repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
nurcahyaari/Kite
src/domain/generator/appnew.go
package generator import ( "errors" "fmt" "go/parser" "github.com/nurcahyaari/kite/infrastructure/database" "github.com/nurcahyaari/kite/internal/templates/misctemplate" "github.com/nurcahyaari/kite/internal/utils" "github.com/nurcahyaari/kite/internal/utils/ast" "github.com/nurcahyaari/kite/internal/utils/pkg" "github.com/nurcahyaari/kite/src/domain/configgen" "github.com/nurcahyaari/kite/src/domain/dbgen" "github.com/nurcahyaari/kite/src/domain/domaingen" "github.com/nurcahyaari/kite/src/domain/envgen" "github.com/nurcahyaari/kite/src/domain/infrastructuregen" "github.com/nurcahyaari/kite/src/domain/internalgen" "github.com/nurcahyaari/kite/src/domain/miscgen" "github.com/nurcahyaari/kite/src/domain/protocolgen" "github.com/nurcahyaari/kite/src/domain/srcgen" "github.com/nurcahyaari/kite/src/domain/wiregen" ) type AppGenNew interface { CreateNewApp(dto AppNewDto) error createMainApp(dto AppNewDto) error rollback(path string) } type AppGenNewImpl struct { fs database.FileSystem configGen configgen.ConfigGen envGen envgen.EnvGen wireGen wiregen.WireGen internalGen internalgen.InternalGen infrastructureGen infrastructuregen.InfrastructureGen srcGen srcgen.SrcGen domainGen domaingen.DomainGen gitignoreGen miscgen.GitIgnoreGen makefileGen miscgen.MakefileGen } func NewApp( fs database.FileSystem, configGen configgen.ConfigGen, envGen envgen.EnvGen, wireGen wiregen.WireGen, internalGen internalgen.InternalGen, infrastructureGen infrastructuregen.InfrastructureGen, srcGen srcgen.SrcGen, domainGen domaingen.DomainGen, gitignoreGen miscgen.GitIgnoreGen, makefileGen miscgen.MakefileGen, ) *AppGenNewImpl { return &AppGenNewImpl{ fs: fs, configGen: configGen, envGen: envGen, wireGen: wireGen, internalGen: internalGen, infrastructureGen: infrastructureGen, srcGen: srcGen, domainGen: domainGen, gitignoreGen: gitignoreGen, makefileGen: makefileGen, } } func (s AppGenNewImpl) CreateNewApp(dto AppNewDto) error { // creational flow // create top level file such as (.env, .env.example, main.go, wire.go, gitignore, gitinit, go.mod) // create config modules // create internal modules such as (protocols, logger, utils) // create infrastructure modules // create src moduels if !s.fs.IsFolderEmpty(dto.ProjectPath) && s.fs.IsFolderExists(dto.ProjectPath) { return errors.New("the folder is not empty") } if utils.IsFolderHasGoMod(dto.ProjectPath) { return errors.New("the folder already had go.mod") } s.fs.CreateFolderIfNotExists(dto.ProjectPath) // init go.mod err := utils.GoModInit(dto.ProjectPath, dto.GoModName) if err != nil { return err } err = utils.Gitinit(dto.ProjectPath) if err != nil { return err } // setup all path configPath := utils.ConcatDirPath(dto.ProjectPath, "config") internalPath := utils.ConcatDirPath(dto.ProjectPath, "internal") infrastructurePath := utils.ConcatDirPath(dto.ProjectPath, "infrastructure") srcPath := utils.ConcatDirPath(dto.ProjectPath, "src") // create file in project path dir level err = s.envGen.CreateEnvFile(dto.ProjectPath) if err != nil { return err } err = s.envGen.CreateEnvExampleFile(dto.ProjectPath) if err != nil { return err } err = s.wireGen.CreateWireFiles(wiregen.WireDto{ ProjectPath: dto.ProjectPath, GomodName: dto.GoModName, }) if err != nil { return err } miscDto := miscgen.MiscDto{ ProjectPath: dto.ProjectPath, GomodName: dto.GoModName, } err = s.gitignoreGen.CreateGitignoreFile(miscDto) if err != nil { return err } err = s.makefileGen.CreateMakefilefile(miscDto) if err != nil { return err } err = s.createMainApp(dto) if err != nil { return err } // create config module configGenDto := configgen.ConfigDto{ ConfigPath: configPath, AppName: dto.Name, } err = s.configGen.CreateConfigDir(configGenDto) if err != nil { return err } err = s.configGen.CreateConfigFile(configGenDto) if err != nil { return err } // create internal module internalDto := internalgen.InternalDto{ Path: internalPath, ProjectPath: dto.ProjectPath, GomodName: dto.GoModName, } err = s.internalGen.CreateInternalDir(internalDto) if err != nil { return err } err = s.internalGen.CreateInternalModules(internalDto) if err != nil { return err } // create infrastructure module infrastructureDto := infrastructuregen.InfrastructureDto{ GomodName: dto.GoModName, DatabaseType: dbgen.DbMysql, InfrastructurePath: infrastructurePath, ProjectPath: dto.ProjectPath, } err = s.infrastructureGen.CreateInfrastructureDir(infrastructureDto) if err != nil { return err } err = s.infrastructureGen.GenerateInfrastructure(infrastructureDto) if err != nil { return err } // create src module srcDto := srcgen.SrcDto{ Path: srcPath, GomodName: dto.GoModName, ProtocolType: protocolgen.NewProtocolType(dto.ProtocolType), } err = s.srcGen.CreateSrcDirectory(srcDto) if err != nil { return err } err = s.installPackage() if err != nil { return err } return nil } func (s AppGenNewImpl) createMainApp(dto AppNewDto) error { templateNew := misctemplate.NewMainTemplate() mainTemplate, err := templateNew.Render() if err != nil { return err } // TODO: remove this // since I don't know how to add new line with ast standard lib, so I use this mainTemplate = fmt.Sprintf("\n%s", mainTemplate) mainAbstractCode := ast.NewAbstractCode(mainTemplate, parser.ParseComments) mainAbstractCode.AddImport(ast.ImportSpec{ Path: "\"context\"", }) mainAbstractCode.AddImport(ast.ImportSpec{ Path: fmt.Sprintf("\"%s/config\"", dto.GoModName), }) mainAbstractCode.AddImport(ast.ImportSpec{ Path: fmt.Sprintf("\"%s/internal/graceful\"", dto.GoModName), }) mainAbstractCode.AddImport(ast.ImportSpec{ Path: fmt.Sprintf("\"%s/internal/logger\"", dto.GoModName), }) mainAbstractCode.AddCommentOutsideFunction(ast.Comment{ Value: "//go:generate go run github.com/google/wire/cmd/wire", }) mainAbstractCode.AddCommentOutsideFunction(ast.Comment{ Value: "//go:generate go run github.com/swaggo/swag/cmd/swag init", }) err = mainAbstractCode.RebuildCode() if err != nil { return err } mainTemplate = mainAbstractCode.GetCode() err = s.fs.CreateFileIfNotExists(dto.ProjectPath, "main.go", mainTemplate) if err != nil { return err } return nil } func (s AppGenNewImpl) installPackage() error { appPkg := pkg.AppPackages{ Packages: []string{ "github.com/rs/zerolog", "github.com/spf13/viper", "github.com/go-sql-driver/mysql", "github.com/jmoiron/sqlx", "github.com/go-chi/chi/v5", "github.com/go-chi/cors", "github.com/golang-jwt/jwt", "github.com/google/wire", "github.com/google/wire/cmd/wire", "github.com/swaggo/swag/cmd/swag", "github.com/swaggo/http-swagger", "github.com/nurcahyaari/sqlabst", }, } return appPkg.InstallPackage() } func (s AppGenNewImpl) rollback(path string) { s.fs.DeleteFolder(path) }
object-oriented-human/competitive
HackerRank/C++/cpp-lower-bound.cpp
<filename>HackerRank/C++/cpp-lower-bound.cpp<gh_stars>1-10 #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n, q, y; cin >> n; vector<int> v(n); for (int i = 0; i < n; i++) { cin >> v[i]; } cin >> q; for (int i = 0; i < q; i++) { cin >> y; if (*lower_bound(v.begin(), v.end(), y) == y) { cout << "Yes " << lower_bound(v.begin(), v.end(), y) - v.begin() + 1 << endl; } else { cout << "No " << lower_bound(v.begin(), v.end(), y) - v.begin() + 1 << endl; } } return 0; }
juitem/ONE
compiler/luci/pass/src/SubstituteSplitVToSplitPass.cpp
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. 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 "luci/Pass/SubstituteSplitVToSplitPass.h" #include <loco.h> #include <luci/IR/CircleNodes.h> #include <luci/Profile/CircleNodeOrigin.h> namespace { void copy_quantparam(luci::CircleNode *dst, const luci::CircleNode *src) { auto q = src->quantparam(); if (q == nullptr) dst->quantparam(nullptr); else dst->quantparam(std::make_unique<luci::CircleQuantParam>(*q)); } // SplitV is substituted to Split if the contents of size_splits are all same // For example, // size_splits = [32, 32] -> substitute // size_splits = [31, 33] -> do not substitute bool resolve_splitv(luci::CircleSplitV *sv) { auto size_splits = dynamic_cast<luci::CircleConst *>(sv->size_splits()); if (not size_splits) return false; if (size_splits->dtype() != loco::DataType::S32) return false; auto num_split = size_splits->size<loco::DataType::S32>(); if (static_cast<int32_t>(num_split) != sv->num_split()) return false; if (num_split < 1) return false; // Check the contents of size_splits are all same auto first_size = size_splits->at<loco::DataType::S32>(0); for (uint32_t i = 1; i < num_split; i++) { if (first_size != size_splits->at<loco::DataType::S32>(i)) return false; } auto graph = sv->graph(); auto split_node = graph->nodes()->create<luci::CircleSplit>(); split_node->input(sv->input()); split_node->split_dim(sv->split_dim()); split_node->num_split(sv->num_split()); split_node->name(sv->name()); copy_quantparam(split_node, sv); luci::add_origin(split_node, luci::get_origin(sv)); auto succs = loco::succs(sv); for (auto succ : succs) { auto svo = loco::must_cast<luci::CircleSplitVOut *>(succ); auto so_node = graph->nodes()->create<luci::CircleSplitOut>(); so_node->input(split_node); so_node->index(svo->index()); so_node->name(svo->name()); copy_quantparam(so_node, svo); luci::add_origin(so_node, luci::get_origin(svo)); replace(svo).with(so_node); } return true; } } // namespace namespace luci { /** * EXAMPLE (SplitV with num_split = 2) * * BEFORE * [CircleNode] * | * [CircleSplitV] (size_splits and split_dim are ignored) * / \ * [CircleSplitVOut] [CircleSplitVOut] * | | * [CircleNode] [CircleNode] * * AFTER * [CircleNode] * / \ * [CircleSplit] [CircleSplitV] (dead) * / \ \ * [CircleSplitOut] [CircleSplitOut] [CircleSplitVOut] * 2 (dead) * | | * [CircleNode] [CircleNode] */ bool SubstituteSplitVToSplitPass::run(loco::Graph *g) { bool changed = false; for (auto node : loco::active_nodes(loco::output_nodes(g))) { if (auto sv = dynamic_cast<luci::CircleSplitV *>(node)) { if (resolve_splitv(sv)) changed = true; } } return changed; } } // namespace luci
harishsharma/junk
src/main/java/hackerrank/CutTree.java
package hackerrank; /** * https://www.hackerrank.com/challenges/cuttree * * @author harish.sharma * */ public class CutTree { }
shopstic/chopsticks
chopsticks-sample/src/main/scala/dev/chopsticks/sample/kvdb/MultiBackendSampleDb.scala
package dev.chopsticks.sample.kvdb import java.time.Instant import dev.chopsticks.kvdb.{ColumnFamilySet, KvdbDefinition, KvdbMaterialization} import dev.chopsticks.kvdb.api.KvdbDatabaseApi import dev.chopsticks.kvdb.codec.ValueSerdes import dev.chopsticks.kvdb.fdb.FdbMaterialization import dev.chopsticks.kvdb.fdb.FdbMaterialization.{KeyspaceWithVersionstampKey, KeyspaceWithVersionstampValue} import dev.chopsticks.kvdb.rocksdb.RocksdbColumnFamilyConfig.PrefixedScanPattern import dev.chopsticks.kvdb.rocksdb.{RocksdbColumnFamilyConfig, RocksdbColumnFamilyOptionsMap, RocksdbMaterialization} import dev.chopsticks.kvdb.codec.KeyPrefix object MultiBackendSampleDb { object Definition extends KvdbDefinition { final case class TestKey(name: String, time: Instant, version: Int) object TestKey { // Optional for absolute performance implicit lazy val p1 = KeyPrefix[String, TestKey] implicit lazy val p2 = KeyPrefix[(String, Instant), TestKey] } final case class TestValue(quantity: Long, amount: Double) trait Default extends BaseCf[TestKey, TestValue] trait Foo extends BaseCf[TestKey, TestValue] trait Bar extends BaseCf[TestKey, TestValue] type CfSet = Default with Foo with Bar trait DbStorage extends KvdbMaterialization[BaseCf, CfSet] { def default: Default def foo: Foo def bar: Bar override def columnFamilySet: ColumnFamilySet[BaseCf, CfSet] = ColumnFamilySet[BaseCf] .of(default) .and(foo) .and(bar) } trait FdbStorage extends DbStorage with FdbMaterialization[BaseCf] { override def keyspacesWithVersionstampKey: Set[KeyspaceWithVersionstampKey[BaseCf]] = Set.empty override def keyspacesWithVersionstampValue: Set[KeyspaceWithVersionstampValue[BaseCf]] = Set.empty } trait RocksdbStorage extends DbStorage with RocksdbMaterialization[BaseCf, CfSet] { override def defaultColumnFamily: BaseCf[_, _] = default override def columnFamilyConfigMap: RocksdbColumnFamilyOptionsMap[BaseCf, CfSet] = { import squants.information.InformationConversions._ import eu.timepit.refined.auto._ val cfConfig = RocksdbColumnFamilyConfig( memoryBudget = 1.mib, blockCache = 1.mib, blockSize = 8.kib, writeBufferCount = 4 ).toOptions(PrefixedScanPattern(1)) RocksdbColumnFamilyOptionsMap[BaseCf] .of(default, cfConfig) .and(foo, cfConfig) .and(bar, cfConfig) } } sealed trait DbService { def api: KvdbDatabaseApi[BaseCf] def storage: DbStorage } final case class FdbService(api: KvdbDatabaseApi[BaseCf], storage: FdbStorage) extends DbService final case class RocksdbService(api: KvdbDatabaseApi[BaseCf], storage: RocksdbStorage) extends DbService } object Backends { import Definition._ object fdbStorage extends FdbStorage { import dev.chopsticks.kvdb.codec.fdb_key._ implicit val valueSerdes: ValueSerdes[TestValue] = ValueSerdes.fromKeySerdes object default extends Default object foo extends Foo object bar extends Bar } object rocksdbStorage extends RocksdbStorage { import dev.chopsticks.kvdb.codec.berkeleydb_key._ implicit val valueSerdes: ValueSerdes[TestValue] = ValueSerdes.fromKeySerdes object default extends Default object foo extends Foo object bar extends Bar } } }
shettyh/azure-sdk-for-java
sdk/keyvault/azure-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClient.java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.security.keyvault.keys.cryptography; import com.azure.core.exception.HttpResponseException; import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.HttpPipeline; import com.azure.core.http.rest.Response; import com.azure.core.implementation.RestProxy; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceClient; import com.azure.core.annotation.ServiceMethod; import com.azure.core.implementation.util.FluxUtil; import com.azure.core.implementation.util.ImplUtils; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; import com.azure.security.keyvault.keys.cryptography.models.KeyUnwrapResult; import com.azure.security.keyvault.keys.cryptography.models.KeyWrapResult; import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; import com.azure.security.keyvault.keys.cryptography.models.SignResult; import com.azure.security.keyvault.keys.cryptography.models.VerifyResult; import com.azure.security.keyvault.keys.models.Key; import com.azure.security.keyvault.keys.models.webkey.JsonWebKey; import com.azure.security.keyvault.keys.models.webkey.KeyOperation; import reactor.core.publisher.Mono; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.Objects; import static com.azure.core.implementation.util.FluxUtil.withContext; /** * The CryptographyAsyncClient provides asynchronous methods to perform cryptographic operations using asymmetric and * symmetric keys. The client supports encrypt, decrypt, wrap key, unwrap key, sign and verify operations using the * configured key. * * <p><strong>Samples to construct the sync client</strong></p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.instantiation} * * @see CryptographyClientBuilder */ @ServiceClient(builder = CryptographyClientBuilder.class, isAsync = true, serviceInterfaces = CryptographyService.class) public class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https://vault.azure.net/.default"; JsonWebKey key; private final CryptographyService service; private final CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param key the JsonWebKey to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline) { Objects.requireNonNull(key); if (!key.isValid()) { throw new IllegalArgumentException("Json Web Key is not valid"); } if (key.getKeyOps() == null) { throw new IllegalArgumentException("Json Web Key's key operations property is not configured"); } if (key.getKty() == null) { throw new IllegalArgumentException("Json Web Key's key type property is not configured"); } this.key = key; service = RestProxy.create(CryptographyService.class, pipeline); if (!Strings.isNullOrEmpty(key.getKid())) { unpackAndValidateId(key.getKid()); cryptographyServiceClient = new CryptographyServiceClient(key.getKid(), service); } else { cryptographyServiceClient = null; } initializeCryptoClients(); } /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param kid THe Azure Key vault key identifier to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(String kid, HttpPipeline pipeline) { unpackAndValidateId(kid); service = RestProxy.create(CryptographyService.class, pipeline); cryptographyServiceClient = new CryptographyServiceClient(kid, service); this.key = null; } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } switch (key.getKty()) { case RSA: case RSA_HSM: localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); break; case EC: case EC_HSM: localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); break; case OCT: localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); break; default: throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The Json Web Key Type: %s is not supported.", key.getKty().toString()))); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse} * * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the requested * {@link Key key}. * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Key>> getKeyWithResponse() { return withContext(context -> getKeyWithResponse(context)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey} * * @return A {@link Mono} containing the requested {@link Key key}. * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Key> getKey() { return getKeyWithResponse().flatMap(FluxUtil::toMono); } Mono<Response<Key>> getKeyWithResponse(Context context) { return cryptographyServiceClient.getKey(context); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public * portion of the key is used for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plaintext}. Possible values for assymetric keys include: * {@link EncryptionAlgorithm#RSA1_5 RSA1_5}, {@link EncryptionAlgorithm#RSA_OAEP RSA_OAEP} and * {@link EncryptionAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. * * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128CBC A128CBC}, * {@link EncryptionAlgorithm#A128CBC_HS256 A128CBC-HS256}, {@link EncryptionAlgorithm#A192CBC A192CBC}, * {@link EncryptionAlgorithm#A192CBC_HS384 A192CBC-HS384}, {@link EncryptionAlgorithm#A256CBC A256CBC} and * {@link EncryptionAlgorithm#A256CBC_HS512 A256CBC-HS512}</p> * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt#EncryptionAlgorithm-byte} * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult#getCipherText() cipher text} * contains the encrypted content. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return withContext(context -> encrypt(algorithm, plaintext, context, null, null)); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public * portion of the key is used for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the * specified {@code plaintext}. Possible values for assymetric keys include: * {@link EncryptionAlgorithm#RSA1_5 RSA1_5}, {@link EncryptionAlgorithm#RSA_OAEP RSA_OAEP} and * {@link EncryptionAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. * * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128CBC A128CBC}, {@link * EncryptionAlgorithm#A128CBC_HS256 A128CBC-HS256}, {@link EncryptionAlgorithm#A192CBC A192CBC}, {@link * EncryptionAlgorithm#A192CBC_HS384 A192CBC-HS384}, {@link EncryptionAlgorithm#A256CBC A256CBC} and * {@link EncryptionAlgorithm#A256CBC_HS512 A256CBC-HS512} </p> * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when * a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt#EncryptionAlgorithm-byte-byte-byte} * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult#getCipherText() cipher text} * contains the encrypted content. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return withContext(context -> encrypt(algorithm, plaintext, context, iv, authenticationData)); } Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) { Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.encrypt(algorithm, plaintext, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.ENCRYPT)) { return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is missing " + "permission/not supported for key with id %s", key.getKid()))); } return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to * be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the * keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the * specified encrypted content. Possible values for assymetric keys include: * {@link EncryptionAlgorithm#RSA1_5 RSA1_5}, {@link EncryptionAlgorithm#RSA_OAEP RSA_OAEP} and {@link * EncryptionAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. * * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128CBC A128CBC}, * {@link EncryptionAlgorithm#A128CBC_HS256 A128CBC-HS256}, {@link EncryptionAlgorithm#A192CBC A192CBC}, * {@link EncryptionAlgorithm#A192CBC_HS384 A192CBC-HS384}, {@link * EncryptionAlgorithm#A256CBC A256CBC} and {@link EncryptionAlgorithm#A256CBC_HS512 A256CBC-HS512} </p> * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt#EncryptionAlgorithm-byte} * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @return A {@link Mono} containing the decrypted blob. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return withContext(context -> decrypt(algorithm, cipherText, null, null, null, context)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to * be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the * keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the * specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm#RSA1_5 RSA1_5}, {@link EncryptionAlgorithm#RSA_OAEP * RSA_OAEP} and {@link EncryptionAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. * Possible values for symmetric keys include: {@link EncryptionAlgorithm#A128CBC A128CBC}, {@link * EncryptionAlgorithm#A128CBC_HS256 A128CBC-HS256}, * {@link EncryptionAlgorithm#A192CBC A192CBC}, {@link EncryptionAlgorithm#A192CBC_HS384 A192CBC-HS384}, {@link * EncryptionAlgorithm#A256CBC A256CBC} and {@link EncryptionAlgorithm#A256CBC_HS512 A256CBC-HS512} </p> * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content * details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt#EncryptionAlgorithm-byte-byte-byte-byte} * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @param iv The initialization vector. * @param authenticationData The authentication data. * @param authenticationTag The authentication tag. * @return A {@link Mono} containing the decrypted blob. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { return withContext(context -> decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, context)); } Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context) { Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.decrypt(algorithm, cipherText, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.DECRYPT)) { return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for " + "key with id %s", key.getKid()))); } return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the * signature from the digest. Possible values include: * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 E384}, * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES246K}, * {@link SignatureAlgorithm#PS256 PS256}, {@link SignatureAlgorithm#RS384 RS384}, * {@link SignatureAlgorithm#RS512 RS512}, {@link SignatureAlgorithm#RS256 RS256}, * {@link SignatureAlgorithm#RS384 RS384} and {@link SignatureAlgorithm#RS512 RS512}</p> * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign#SignatureAlgorithm-byte} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult#getSignature() signature} contains * the created signature. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code digest} is null. */ public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { return withContext(context -> sign(algorithm, digest, context)); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key " + "with id %s", key.getKid()))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric * keys. In case of asymmetric keys public portion of the key is used to verify the signature . This operation * requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 E384}, {@link SignatureAlgorithm#ES512 * ES512}, {@link SignatureAlgorithm#ES256K ES246K}, {@link SignatureAlgorithm#PS256 PS256}, {@link * SignatureAlgorithm#RS384 RS384}, {@link SignatureAlgorithm#RS512 RS512}, {@link SignatureAlgorithm#RS256 RS256}, * {@link SignatureAlgorithm#RS384 RS384} and {@link SignatureAlgorithm#RS512 RS512}</p> * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify#SignatureAlgorithm-byte-byte} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null. */ public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return withContext(context -> verify(algorithm, digest, signature, context)); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for " + "key with id %s", key.getKid()))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified * key content. Possible values include: * {@link KeyWrapAlgorithm#RSA1_5 RSA1_5}, {@link KeyWrapAlgorithm#RSA_OAEP RSA_OAEP} and {@link * KeyWrapAlgorithm#RSA_OAEP_256 RSA_OAEP_256}</p> * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a * response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey#KeyWrapAlgorithm-byte} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult#getEncryptedKey() encrypted * key} contains the wrapped key result. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code key} is null. */ public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { return withContext(context -> wrapKey(algorithm, key, context)); } Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for " + "key with id %s", this.key.getKid()))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is * the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey * permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the * specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm#RSA1_5 RSA1_5}, {@link KeyWrapAlgorithm#RSA_OAEP RSA_OAEP} and {@link * KeyWrapAlgorithm#RSA_OAEP_256 RSA_OAEP_256}. * Possible values for symmetric keys include: {@link KeyWrapAlgorithm#A128KW A128KW}, {@link * KeyWrapAlgorithm#A192KW A192KW} and {@link KeyWrapAlgorithm#A256KW A256KW}</p> * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a * response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey#KeyWrapAlgorithm-byte} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @return A {@link Mono} containing a the unwrapped key content. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null. */ public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed " + "for key with id %s", this.key.getKid()))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric * and symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. * Possible values include: * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 E384}, {@link SignatureAlgorithm#ES512 * ES512}, {@link SignatureAlgorithm#ES256K ES246K}, {@link SignatureAlgorithm#PS256 PS256}, * {@link SignatureAlgorithm#RS384 RS384}, {@link SignatureAlgorithm#RS512 RS512}, {@link * SignatureAlgorithm#RS256 RS256}, {@link SignatureAlgorithm#RS384 RS384} and * {@link SignatureAlgorithm#RS512 RS512}</p> * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response * has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData#SignatureAlgorithm-byte} * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult#getSignature() signature} contains * the created signature. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code data} is null. */ public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { return withContext(context -> signData(algorithm, data, context)); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.SIGN)) { return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key " + "with id %s", this.key.getKid()))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric * keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires * the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the * signature. Possible values include: * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 E384}, {@link SignatureAlgorithm#ES512 * ES512}, {@link SignatureAlgorithm#ES256K ES246K}, {@link SignatureAlgorithm#PS256 PS256}, {@link * SignatureAlgorithm#RS384 RS384}, {@link SignatureAlgorithm#RS512 RS512}, {@link SignatureAlgorithm#RS256 RS256}, * {@link SignatureAlgorithm#RS384 RS384} and {@link SignatureAlgorithm#RS512 RS512}</p> * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the * verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData#SignatureAlgorithm-byte-byte} * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @return The {@link Boolean} indicating the signature verification result. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null. */ public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { return withContext(context -> verifyData(algorithm, data, signature, context)); } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.VERIFY)) { return Mono.error(new UnsupportedOperationException(String.format( "Verify Operation is not allowed for key with id %s", this.key.getKid()))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); } private void unpackAndValidateId(String keyId) { if (ImplUtils.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid")); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + "://" + url.getHost(); String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); if (Strings.isNullOrEmpty(endpoint)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key endpoint in key id is invalid")); } else if (Strings.isNullOrEmpty(keyName)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key name in key id is invalid")); } else if (Strings.isNullOrEmpty(version)) { throw logger.logExceptionAsError(new IllegalArgumentException("Key version in key id is invalid")); } } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed", e)); } } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private boolean ensureValidKeyAvailable() { boolean keyAvailableLocally = true; if (this.key == null) { try { this.key = getKey().block().getKeyMaterial(); keyAvailableLocally = this.key.isValid(); initializeCryptoClients(); } catch (HttpResponseException | NullPointerException e) { logger.info("Failed to retrieve key from key vault"); keyAvailableLocally = false; } } return keyAvailableLocally; } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } }
xlf999/AdsDemo
MobGiAdSDK/AggregationSDK/NativeAds/NativeAdDetailsInfo.h
<filename>MobGiAdSDK/AggregationSDK/NativeAds/NativeAdDetailsInfo.h // // NativeAdDetailsInfo.h // NativePolymerization // // Created by alan.xia on 2018/1/18. // Copyright © 2018年 com.idreamsky. All rights reserved. // /*该类用于展示的时候传入一些属性设置*/ #import <Foundation/Foundation.h> @interface NativeAdDetailsInfo : NSObject //按实际类型设置,游戏类型传YES,应用类型传NO,如果传错类型,会影响展示和点击跳转 @property(nonatomic,assign) BOOL isGame; @end
woohoou/aws-sdk-cpp
aws-cpp-sdk-glue/include/aws/glue/model/Classifier.h
<gh_stars>1-10 /* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/glue/Glue_EXPORTS.h> #include <aws/glue/model/GrokClassifier.h> #include <aws/glue/model/XMLClassifier.h> #include <aws/glue/model/JsonClassifier.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace Glue { namespace Model { /** * <p>Classifiers are written in Python and triggered during a crawl task. You can * write your own classifiers to best categorize your data sources and specify the * appropriate schemas to use for them. A classifier checks whether a given file is * in a format it can handle, and if it is, the classifier creates a schema in the * form of a <code>StructType</code> object that matches that data format.</p> <p>A * classifier can be a <code>grok</code> classifier, an XML classifier, or a JSON * classifier, asspecified in one of the fields in the <code>Classifier</code> * object.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/Classifier">AWS API * Reference</a></p> */ class AWS_GLUE_API Classifier { public: Classifier(); Classifier(const Aws::Utils::Json::JsonValue& jsonValue); Classifier& operator=(const Aws::Utils::Json::JsonValue& jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>A <code>GrokClassifier</code> object.</p> */ inline const GrokClassifier& GetGrokClassifier() const{ return m_grokClassifier; } /** * <p>A <code>GrokClassifier</code> object.</p> */ inline void SetGrokClassifier(const GrokClassifier& value) { m_grokClassifierHasBeenSet = true; m_grokClassifier = value; } /** * <p>A <code>GrokClassifier</code> object.</p> */ inline void SetGrokClassifier(GrokClassifier&& value) { m_grokClassifierHasBeenSet = true; m_grokClassifier = std::move(value); } /** * <p>A <code>GrokClassifier</code> object.</p> */ inline Classifier& WithGrokClassifier(const GrokClassifier& value) { SetGrokClassifier(value); return *this;} /** * <p>A <code>GrokClassifier</code> object.</p> */ inline Classifier& WithGrokClassifier(GrokClassifier&& value) { SetGrokClassifier(std::move(value)); return *this;} /** * <p>An <code>XMLClassifier</code> object.</p> */ inline const XMLClassifier& GetXMLClassifier() const{ return m_xMLClassifier; } /** * <p>An <code>XMLClassifier</code> object.</p> */ inline void SetXMLClassifier(const XMLClassifier& value) { m_xMLClassifierHasBeenSet = true; m_xMLClassifier = value; } /** * <p>An <code>XMLClassifier</code> object.</p> */ inline void SetXMLClassifier(XMLClassifier&& value) { m_xMLClassifierHasBeenSet = true; m_xMLClassifier = std::move(value); } /** * <p>An <code>XMLClassifier</code> object.</p> */ inline Classifier& WithXMLClassifier(const XMLClassifier& value) { SetXMLClassifier(value); return *this;} /** * <p>An <code>XMLClassifier</code> object.</p> */ inline Classifier& WithXMLClassifier(XMLClassifier&& value) { SetXMLClassifier(std::move(value)); return *this;} /** * <p>A <code>JsonClassifier</code> object.</p> */ inline const JsonClassifier& GetJsonClassifier() const{ return m_jsonClassifier; } /** * <p>A <code>JsonClassifier</code> object.</p> */ inline void SetJsonClassifier(const JsonClassifier& value) { m_jsonClassifierHasBeenSet = true; m_jsonClassifier = value; } /** * <p>A <code>JsonClassifier</code> object.</p> */ inline void SetJsonClassifier(JsonClassifier&& value) { m_jsonClassifierHasBeenSet = true; m_jsonClassifier = std::move(value); } /** * <p>A <code>JsonClassifier</code> object.</p> */ inline Classifier& WithJsonClassifier(const JsonClassifier& value) { SetJsonClassifier(value); return *this;} /** * <p>A <code>JsonClassifier</code> object.</p> */ inline Classifier& WithJsonClassifier(JsonClassifier&& value) { SetJsonClassifier(std::move(value)); return *this;} private: GrokClassifier m_grokClassifier; bool m_grokClassifierHasBeenSet; XMLClassifier m_xMLClassifier; bool m_xMLClassifierHasBeenSet; JsonClassifier m_jsonClassifier; bool m_jsonClassifierHasBeenSet; }; } // namespace Model } // namespace Glue } // namespace Aws
liufangqi/hudi
hudi-common/src/main/java/org/apache/hudi/common/table/timeline/dto/FileSliceDTO.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hudi.common.table.timeline.dto; import org.apache.hudi.common.model.FileSlice; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.stream.Collectors; /** * The data transfer object of file slice. */ @JsonIgnoreProperties(ignoreUnknown = true) public class FileSliceDTO { @JsonProperty("baseFile") BaseFileDTO baseFile; @JsonProperty("logFiles") List<LogFileDTO> logFiles; @JsonProperty("partition") private String partitionPath; @JsonProperty("fileId") private String fileId; @JsonProperty("baseInstant") private String baseInstantTime; public static FileSliceDTO fromFileSlice(FileSlice slice) { FileSliceDTO dto = new FileSliceDTO(); dto.partitionPath = slice.getPartitionPath(); dto.baseInstantTime = slice.getBaseInstantTime(); dto.fileId = slice.getFileId(); dto.baseFile = slice.getBaseFile().map(BaseFileDTO::fromHoodieBaseFile).orElse(null); dto.logFiles = slice.getLogFiles().map(LogFileDTO::fromHoodieLogFile).collect(Collectors.toList()); return dto; } public static FileSlice toFileSlice(FileSliceDTO dto) { FileSlice slice = new FileSlice(dto.partitionPath, dto.baseInstantTime, dto.fileId); slice.setBaseFile(BaseFileDTO.toHoodieBaseFile(dto.baseFile)); dto.logFiles.stream().forEach(lf -> slice.addLogFile(LogFileDTO.toHoodieLogFile(lf))); return slice; } }
walesey/go-bundle
generator/test/input13_output.js
var i = React.createElement("div", null); var j = React.createElement("div", { prop: "value" }); var Message = React.createElement(Hello, { name: "World" }); React.createElement("div", null); React.createElement("div", null, "Hello"); React.createElement("div", null, React.createElement("div", null));
alwyn/intellij-community
python/educational-core/src/com/jetbrains/edu/learning/core/EduAnswerPlaceholderPainter.java
<gh_stars>0 package com.jetbrains.edu.learning.core; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.impl.DocumentImpl; import com.intellij.openapi.editor.markup.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.ui.JBColor; import com.intellij.ui.SimpleTextAttributes; import com.jetbrains.edu.learning.StudyUtils; import com.jetbrains.edu.learning.courseFormat.AnswerPlaceholder; import com.jetbrains.edu.learning.courseFormat.TaskFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.List; public class EduAnswerPlaceholderPainter { //it should be the lowest highlighting layer, otherwise selection and other effects are not visible public static final int PLACEHOLDERS_LAYER = 0; private EduAnswerPlaceholderPainter() { } public static void drawAnswerPlaceholder(@NotNull final Editor editor, @NotNull final AnswerPlaceholder placeholder, @NotNull final JBColor color) { EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); final TextAttributes textAttributes = new TextAttributes(scheme.getDefaultForeground(), scheme.getDefaultBackground(), null, EffectType.BOXED, Font.PLAIN); textAttributes.setEffectColor(color); int startOffset = placeholder.getOffset(); if (startOffset == -1) { return; } final int length = placeholder.isActive() ? placeholder.getRealLength() : placeholder.getVisibleLength(placeholder.getActiveSubtaskIndex()); Pair<Integer, Integer> offsets = StudyUtils.getPlaceholderOffsets(placeholder, editor.getDocument()); startOffset = offsets.first; int endOffset = offsets.second; if (placeholder.isActive()) { drawAnswerPlaceholder(editor, startOffset, endOffset, textAttributes, PLACEHOLDERS_LAYER); } else if (!placeholder.getUseLength() && length != 0) { drawAnswerPlaceholderFromPrevStep(editor, startOffset, endOffset); } } public static void drawAnswerPlaceholder(@NotNull Editor editor, int start, int end, @Nullable TextAttributes textAttributes, int placeholdersLayer) { final Project project = editor.getProject(); assert project != null; if (start == -1) { return; } RangeHighlighter highlighter = editor.getMarkupModel().addRangeHighlighter(start, end, placeholdersLayer, textAttributes, HighlighterTargetArea.EXACT_RANGE); highlighter.setGreedyToLeft(true); highlighter.setGreedyToRight(true); } public static void drawAnswerPlaceholderFromPrevStep(@NotNull Editor editor, int start, int end) { EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); Color color = scheme.getColor(EditorColors.TEARLINE_COLOR); SimpleTextAttributes attributes = SimpleTextAttributes.GRAY_ATTRIBUTES; final TextAttributes textAttributes = new TextAttributes(attributes.getFgColor(), color, null, null, attributes.getFontStyle()); drawAnswerPlaceholder(editor, start, end, textAttributes, HighlighterLayer.LAST); } public static void createGuardedBlock(Editor editor, List<RangeMarker> blocks, int start, int end) { RangeHighlighter rh = editor.getMarkupModel() .addRangeHighlighter(start, end, PLACEHOLDERS_LAYER, null, HighlighterTargetArea.EXACT_RANGE); blocks.add(rh); } public static void createGuardedBlocks(@NotNull final Editor editor, TaskFile taskFile) { for (AnswerPlaceholder answerPlaceholder : taskFile.getAnswerPlaceholders()) { createGuardedBlocks(editor, answerPlaceholder); } } public static void createGuardedBlocks(@NotNull final Editor editor, AnswerPlaceholder placeholder) { Document document = editor.getDocument(); if (document instanceof DocumentImpl) { DocumentImpl documentImpl = (DocumentImpl)document; List<RangeMarker> blocks = documentImpl.getGuardedBlocks(); Pair<Integer, Integer> offsets = StudyUtils.getPlaceholderOffsets(placeholder, editor.getDocument()); Integer start = offsets.first; Integer end = offsets.second; if (start != 0) { createGuardedBlock(editor, blocks, start - 1, start); } if (end != document.getTextLength()) { createGuardedBlock(editor, blocks, end, end + 1); } } } }
RexTremendaeMajestatis/QREAL
qrmc/classes/type.h
<filename>qrmc/classes/type.h /* Copyright 2007-2016 QReal Research Group, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <QtCore/QMap> #include <QtCore/QString> #include "qrmc/utils/defs.h" #include <qrrepo/repoApi.h> namespace qrmc { class Property; class Diagram; /// Virtual base class of all metatypes supported by metaeditor. class Type { public: /// Constructor. /// @param isResolved - true, if type is already resolved. /// @param diagram - diagram to which this type belongs to. /// @param api - repository with metamodel. /// @param id - id of a type in repository. Type(bool isResolved, const Diagram &diagram, const qrRepo::LogicalRepoApi &api, const qReal::Id &id); virtual ~Type(); /// Provides copy of this type. /// Ownership passed to the caller. virtual Type* clone() const = 0; /// Resolves inheritance by copying properties of a parent to this type. virtual bool resolve() = 0; /// Initializes this type in a given context (context is like namespace). virtual bool init(const QString &context); /// Returns true if this type is currently in "resolving" status. virtual bool isResolving() const; /// Returns true if this type is graphical (i.e. can be drawn by editor). virtual bool isGraphicalType() const = 0; /// Returns true if this type is already resolved. virtual bool isResolved() const; /// Debug print method. virtual void print() = 0; /// Returns name of the type. virtual QString name() const; /// Returns mouse gesture path of this type. virtual QString path() const; /// Returns fully qualified name (context + name). virtual QString qualifiedName() const; /// Returns displayed name of a type. virtual QString displayedName() const; /// Returns context to which this type belongs to originally (may differ from context when type was copied /// by "include"). virtual QString nativeContext() const; /// Returns diagram this type belongs to. virtual const Diagram &diagram() const; /// Returns all properties of this type. Does not transfer ownership. virtual const QMap<QString, Property*> &properties() const; /// Sets a name of this type. virtual void setName(const QString &name); /// Sets a diagram this type belongs to. virtual void setDiagram(Diagram &diagram); /// Sets new context for this type. virtual void setContext(const QString &newContext); /// Sets displayed name of this type. virtual void setDisplayedName(const QString &displayedName); virtual QString generateNames(const QString &lineTemplate) const; virtual QString generateMouseGestures(const QString &lineTemplate) const; virtual QString generateProperties(const QString &lineTemplate) const = 0; virtual QString generatePropertyDefaults(const QString &lineTemplate) const = 0; virtual QString generatePropertyDisplayedNames(const QString &lineTemplate) const = 0; virtual QString generateElementDescription(const QString &lineTemplate) const = 0; virtual QString generateReferenceProperties(const QString &lineTemplate) const = 0; virtual QString generatePortTypes(const QString &lineTemplate) const = 0; virtual QString generatePropertyName(const QString &lineTemplate) const = 0; virtual QString generateParents(const QString &lineTemplate) const = 0; virtual QString generateContainers(const QString &lineTemplate) const = 0; virtual QString generateConnections(const QString &lineTemplate) const = 0; virtual QString generateUsages(const QString &lineTemplate) const = 0; virtual QString generateFactory(const QString &lineTemplate) const; virtual QString generateIsNodeOrEdge(const QString &lineTemplate) const = 0; virtual QString generateEnums(const QString &lineTemplate) const = 0; virtual QString generatePossibleEdges(const QString &lineTemplate) const = 0; virtual QString generateNodeClass(const QString &classTemplate) = 0; virtual QString generateEdgeClass(const QString &classTemplate) const = 0; virtual QString generateResourceLine(const QString &classTemplate) const = 0; protected: /// Copies all fields of this type to a given type. virtual void copyFields(Type *type) const; /// Map of all properties of a type. /// Has ownership. QMap<QString, Property*> mProperties; /// Flag that becomes true if this type is resolved. bool mResolvingFinished = false; /// Diagram this type belongs to. /// Does not have ownership. const Diagram *mDiagram; /// Id of this type in repository. const qReal::Id mId; /// Repository with metamodel. const qrRepo::LogicalRepoApi &mApi; /// Metatype name. QString mName; /// Context if metatype. e.g. Kernel::Node: Node - name, Kernel - context. QString mContext; /// Native context, doesn't change on import and is used for element resolving. QString mNativeContext; /// Name of this type as it is displayed to user. QString mDisplayedName; /// Mouse gesture path. QString mPath; }; }
RollingSoftware/L2J_HighFive_Hardcore
l2j_datapack/dist/game/data/scripts/quests/Q00284_MuertosFeather/Q00284_MuertosFeather.java
<reponame>RollingSoftware/L2J_HighFive_Hardcore /* * Copyright (C) 2004-2016 L2J DataPack * * This file is part of L2J DataPack. * * L2J DataPack is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * L2J DataPack is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package quests.Q00284_MuertosFeather; import java.util.HashMap; import java.util.Map; import com.l2jserver.gameserver.model.actor.L2Npc; import com.l2jserver.gameserver.model.actor.instance.L2PcInstance; import com.l2jserver.gameserver.model.quest.Quest; import com.l2jserver.gameserver.model.quest.QuestState; /** * Muertos Feather (284). * @author xban1x */ public final class Q00284_MuertosFeather extends Quest { // NPC private static final int TREVOR = 32166; // Item private static final int MUERTOS_FEATHER = 9748; // Monsters private static final Map<Integer, Double> MOB_DROP_CHANCE = new HashMap<>(); static { MOB_DROP_CHANCE.put(22239, 0.500); // Muertos Guard MOB_DROP_CHANCE.put(22240, 0.533); // Muertos Scout MOB_DROP_CHANCE.put(22242, 0.566); // Muertos Warrior MOB_DROP_CHANCE.put(22243, 0.600); // Muertos Captain MOB_DROP_CHANCE.put(22245, 0.633); // Muertos Lieutenant MOB_DROP_CHANCE.put(22246, 0.633); // Muertos Commander } // Misc private static final int MIN_LVL = 11; public Q00284_MuertosFeather() { super(284, Q00284_MuertosFeather.class.getSimpleName(), "Muertos Feather"); addStartNpc(TREVOR); addTalkId(TREVOR); addKillId(MOB_DROP_CHANCE.keySet()); registerQuestItems(MUERTOS_FEATHER); } @Override public String onAdvEvent(String event, L2Npc npc, L2PcInstance player) { final QuestState qs = getQuestState(player, false); String html = null; if (qs == null) { return html; } switch (event) { case "32166-03.htm": { qs.startQuest(); html = event; break; } case "32166-06.html": { html = event; break; } case "32166-08.html": { if (hasQuestItems(player, MUERTOS_FEATHER)) { giveAdena(player, getQuestItemsCount(player, MUERTOS_FEATHER) * 45, true); takeItems(player, MUERTOS_FEATHER, -1); html = event; } else { html = "32166-07.html"; } break; } case "32166-09.html": { qs.exitQuest(true, true); html = event; break; } } return html; } @Override public String onKill(L2Npc npc, L2PcInstance killer, boolean isSummon) { final QuestState qs = getRandomPartyMemberState(killer, 1, 3, npc); if (qs != null) { giveItemRandomly(qs.getPlayer(), npc, MUERTOS_FEATHER, 1, 0, MOB_DROP_CHANCE.get(npc.getId()), true); } return super.onKill(npc, killer, isSummon); } @Override public String onTalk(L2Npc npc, L2PcInstance player) { final QuestState qs = getQuestState(player, true); String html = getNoQuestMsg(player); if (qs.isCreated()) { html = ((player.getLevel() >= MIN_LVL) ? "32166-01.htm" : "32166-02.htm"); } else if (qs.isStarted()) { html = (hasQuestItems(player, MUERTOS_FEATHER) ? "32166-05.html" : "32166-04.html"); } return html; } }
zeyuanxy/LeetCode
vol5/add-and-search-word-data-structure-design/add-and-search-word-data-structure-design.cpp
<reponame>zeyuanxy/LeetCode<gh_stars>1-10 /* * @Author: <NAME> * @Date: 2015-11-05 00:18:39 * @Last Modified by: <NAME> * @Last Modified time: 2015-11-05 00:18:57 */ class TrieNode { public: // Initialize your data structure here. TrieNode() : children(26, NULL), isWord(false) { } vector<TrieNode*> children; bool isWord; }; class WordDictionary { private: TrieNode* root; bool recursive_serach(TrieNode* p, string word) { if (word.length() == 0) { return p->isWord; } char c = word[0]; if (c != '.') { if (!p->children[c - 'a']) { return false; } return recursive_serach(p->children[c - 'a'], word.substr(1)); } else { bool ret = false; for (char x = 'a'; x <= 'z'; ++x) { if (!p->children[x - 'a']) { continue; } ret |= recursive_serach(p->children[x - 'a'], word.substr(1)); if (ret) { return true; } } } return false; } public: WordDictionary() { root = new TrieNode(); } // Adds a word into the data structure. void addWord(string word) { TrieNode* p = root; for (auto c : word) { if (!p->children[c - 'a']) { p->children[c - 'a'] = new TrieNode(); } p = p->children[c - 'a']; } p->isWord = true; } // Returns if the word is in the data structure. A word could // contain the dot character '.' to represent any one letter. bool search(string word) { return recursive_serach(root, word); } }; // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary; // wordDictionary.addWord("word"); // wordDictionary.search("pattern");
AlexWayfer/sentry
tests/sentry/web/frontend/test_unsubscribe_issue_notifications.py
from __future__ import absolute_import from sentry.testutils import TestCase from sentry.models import GroupSubscription from sentry.utils.linksign import generate_signed_link class UnsubscribeIssueNotificationsTest(TestCase): def test_renders(self): group = self.create_group() path = generate_signed_link( user=self.user, viewname='sentry-account-email-unsubscribe-issue', args=[group.id], ) resp = self.client.get(path) assert resp.status_code == 200 def test_process(self): group = self.create_group() path = generate_signed_link( user=self.user, viewname='sentry-account-email-unsubscribe-issue', args=[group.id], ) resp = self.client.post(path, data={'op': 'unsubscribe'}) assert resp.status_code == 302 assert GroupSubscription.objects.filter( user=self.user, group=group, is_active=False, ).exists() def test_no_access(self): user = self.create_user('<EMAIL>') group = self.create_group() path = generate_signed_link( user=user, viewname='sentry-account-email-unsubscribe-issue', args=[group.id], ) resp = self.client.get(path) assert resp.status_code == 404 def test_invalid_issue(self): path = generate_signed_link( user=self.user, viewname='sentry-account-email-unsubscribe-issue', args=[13413434], ) resp = self.client.get(path) assert resp.status_code == 404
bitbrain/beansjam-2017
core/src/tv/rocketbeans/supermafiosi/minigame/roulette/RouletteMiniGame.java
package tv.rocketbeans.supermafiosi.minigame.roulette; import java.util.ArrayList; import java.util.List; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.utils.Align; import aurelienribon.tweenengine.BaseTween; import aurelienribon.tweenengine.Tween; import aurelienribon.tweenengine.TweenCallback; import aurelienribon.tweenengine.TweenEquations; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable; import de.bitbrain.braingdx.GameContext; import de.bitbrain.braingdx.assets.SharedAssetManager; import de.bitbrain.braingdx.audio.AudioManager; import de.bitbrain.braingdx.graphics.renderer.SpriteRenderer; import de.bitbrain.braingdx.tweens.ActorTween; import de.bitbrain.braingdx.tweens.GameObjectTween; import de.bitbrain.braingdx.tweens.SharedTweenManager; import de.bitbrain.braingdx.world.GameObject; import tv.rocketbeans.supermafiosi.SuperMafiosiGame; import tv.rocketbeans.supermafiosi.assets.Asset; import tv.rocketbeans.supermafiosi.assets.AssetUtils; import tv.rocketbeans.supermafiosi.core.Dialog; import tv.rocketbeans.supermafiosi.core.DialogManager.DialogManagerListener; import tv.rocketbeans.supermafiosi.core.Mafiosi; import tv.rocketbeans.supermafiosi.core.MafiosiGameContext; import tv.rocketbeans.supermafiosi.i18n.Message; import tv.rocketbeans.supermafiosi.minigame.AbstractMiniGame; import tv.rocketbeans.supermafiosi.screens.CongratulationsScreen; import tv.rocketbeans.supermafiosi.screens.GameOverScreen; import tv.rocketbeans.supermafiosi.ui.Styles; import tv.rocketbeans.supermafiosi.ui.Toast; /** * In this final mini game the players need to pull the trigger in round robin. The chances are * higher for a shot if more bullets are loaded. */ public class RouletteMiniGame extends AbstractMiniGame { private static final String[] DEATH_WISHES = { Message.MINIGAME_ROULETTE_DEATHWISH_1, Message.MINIGAME_ROULETTE_DEATHWISH_2, Message.MINIGAME_ROULETTE_DEATHWISH_3, Message.MINIGAME_ROULETTE_DEATHWISH_4, Message.MINIGAME_ROULETTE_DEATHWISH_5 }; private final MafiosiGameContext context; private final GameContext gameContext; private final List<Mafiosi> deadMafiosis = new ArrayList<Mafiosi>(); private List<Mafiosi> remainingCandidates; private Mafiosi mafiosi; private boolean waitingForPlayerConfirmation; private GameObject rouletteBackground; private GameObject ronaldtrumpfroulette; private GameObject tronroulette; private GameObject sanchezroulette; private GameObject ronaldtrumpfwafferoulette; private GameObject tronwafferoulette; private GameObject sanchezwafferoulette; private Image boom; private DialogManagerListener dialogListener = new DialogManagerListener() { @Override public void afterLastDialog() { System.out.println("After last dialog!"); if (waitingForPlayerConfirmation) { System.out.println("waiting for player confirmation..."); return; } setRouletteAnimation(mafiosi); Tween.call(new TweenCallback() { @Override public void onEvent(int arg0, BaseTween<?> arg1) { pullTrigger(); } }).delay(2f).start(SharedTweenManager.getInstance()); } @Override public void onDialog(Dialog dialog) { } }; private Label confirmationLabel; private final SuperMafiosiGame game; public RouletteMiniGame(SuperMafiosiGame game, MafiosiGameContext context, GameContext gameContext) { this.context = context; this.gameContext = gameContext; this.game = game; } @Override public void initialise() { System.out.println("Initialise..."); context.getDialogManager().addListener(dialogListener); remainingCandidates = new ArrayList<Mafiosi>(context.getCandidates()); AudioManager.getInstance().fadeOutMusic(Asset.Music.MENU_CHAR_SELECT_MAIN, 4f); AudioManager.getInstance().fadeOutMusic(Asset.Music.AUDIANCE_HAPPY, 8f); AudioManager.getInstance().fadeInMusic(Asset.Music.MENU_MINIGAME_ROULETTE_MUSIC_MAIN); nextPlayer(); } public void setBoom() { if (boom == null) { boom = new Image(new SpriteDrawable(new Sprite(SharedAssetManager.getInstance().get(Asset.Textures.BOOM, Texture.class)))); Vector2 boomdim = AssetUtils.getDimensionOfTexture(Asset.Textures.ROAST_BATTLE_LOGO); boom.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); boom.setPosition(0, 0); gameContext.getStage().addActor(boom); } boom.setVisible(true); Tween.call(new TweenCallback() { @Override public void onEvent(int i, BaseTween<?> bt) { boom.setVisible(false); boom.getColor().a = 0f; } }).delay(2).start(gameContext.getTweenManager()); } public void setRouletteAnimation(Mafiosi mafiosi) { this.mafiosi.setActive(mafiosi == null); System.out.println("mafiosi: " + mafiosi); if (rouletteBackground == null) { rouletteBackground = gameContext.getGameWorld().addObject(); rouletteBackground.setType("RouletteBG"); rouletteBackground.setPosition(0, 0); rouletteBackground.setDimensions(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); rouletteBackground.getColor().a = 0f; gameContext.getRenderManager().register("RouletteBG", new SpriteRenderer(Asset.Textures.ROULETTE_BG)); ronaldtrumpfroulette = createRouletteHeadAnimation(Asset.Textures.RONALD_ROULETTE, "RonaldTrumpfRoulette"); tronroulette = createRouletteHeadAnimation(Asset.Textures.TRON_ROULETTE, "LerryRoulette"); sanchezroulette = createRouletteHeadAnimation(Asset.Textures.SANCHEZ_ROULETTE, "TronRoulette"); ronaldtrumpfwafferoulette = createRouletteWaffeAnimation(Asset.Textures.RONALD_ROULETTE_WEAPON, "Ronaldtrumpfwafferoulette"); tronwafferoulette = createRouletteWaffeAnimation(Asset.Textures.TRON_ROULETTE_WEAPON, "tronwafferoulette"); sanchezwafferoulette = createRouletteWaffeAnimation(Asset.Textures.SANCHEZ_ROULETTE_WEAPON, "sanchezwafferoulette"); } if (mafiosi == null) { rouletteBackground.getColor().a = 0; ronaldtrumpfroulette.getColor().a = 0; tronroulette.getColor().a = 0; sanchezroulette.getColor().a = 0; ronaldtrumpfwafferoulette.getColor().a = 0; tronwafferoulette.getColor().a = 0; sanchezwafferoulette.getColor().a = 0; return; } if (mafiosi.getName().contains("Trumpf")) { rouletteBackground.getColor().a = 1f; ronaldtrumpfroulette.getColor().a = 1f; tronroulette.getColor().a = 0; sanchezroulette.getColor().a = 0; ronaldtrumpfwafferoulette.getColor().a = 1f; tronwafferoulette.getColor().a = 0; sanchezwafferoulette.getColor().a = 0; } if (mafiosi.getName().contains("Jawolta")) { rouletteBackground.getColor().a = 1f; ronaldtrumpfroulette.getColor().a = 0; tronroulette.getColor().a = 1f; sanchezroulette.getColor().a = 0; ronaldtrumpfwafferoulette.getColor().a = 0; tronwafferoulette.getColor().a = 1f; sanchezwafferoulette.getColor().a = 0; } if (mafiosi.getName().contains("Sanchez")) { rouletteBackground.getColor().a = 1f; ronaldtrumpfroulette.getColor().a = 0; tronroulette.getColor().a = 0; sanchezroulette.getColor().a = 1f; ronaldtrumpfwafferoulette.getColor().a = 0; tronwafferoulette.getColor().a = 0; sanchezwafferoulette.getColor().a = 1f; } } public GameObject createRouletteHeadAnimation(String path, String type) { GameObject o = gameContext.getGameWorld().addObject(); o.setType(type); o.setPosition(600, 250); o.setDimensions(Gdx.graphics.getWidth() / 1.5f, Gdx.graphics.getHeight()); o.getColor().a = 0f; o.setZIndex(100); gameContext.getRenderManager().unregister(type); gameContext.getRenderManager().register(type, new SpriteRenderer(path)); return o; } public GameObject createRouletteWaffeAnimation(String path, String type) { GameObject o = gameContext.getGameWorld().addObject(); o.setType(type); o.setPosition(100, 250); o.setDimensions(Gdx.graphics.getWidth() / 2f, Gdx.graphics.getHeight() / 2f); o.getColor().a = 0f; o.setZIndex(101); gameContext.getRenderManager().register(type, new SpriteRenderer(path)); Tween.to(o, GameObjectTween.POS_Y, 0.75f).target(220).repeatYoyo(Tween.INFINITY, 0.75f).ease(TweenEquations.easeNone).start(gameContext.getTweenManager()); return o; } @Override public void cleanup() { context.clearActiveMafiosis(); context.getDialogManager().removeListener(dialogListener); } @Override public void update(float delta) { if (waitingForPlayerConfirmation) { if (Gdx.input.isTouched() || Gdx.input.isKeyPressed(Keys.ANY_KEY)) { System.out.println("Player decided to pull the trigger!"); waitingForPlayerConfirmation = false; gameContext.getTweenManager().killTarget(confirmationLabel); gameContext.getStage().getActors().removeValue(confirmationLabel, true); context.getDialogManager().addDialog(mafiosi.getName(), getRandomDeathWish(), mafiosi.getAvatarId()); context.getDialogManager().nextDialog(); } } } private void nextPlayer() { System.out.println("=== NEW ROUND!!! ==="); // Initialise first candidate to pull the trigger if (mafiosi != null) { mafiosi.setActive(false); } mafiosi = remainingCandidates.remove(0); mafiosi.setActive(true); setRouletteAnimation(null); if (mafiosi.equals(context.getPlayerMafiosi())) { Tween.call(new TweenCallback() { @Override public void onEvent(int arg0, BaseTween<?> arg1) { System.out.println(mafiosi.getName() + " turn (PLAYER)"); confirmationLabel = new Label("PULL THE TRIGGER!!", Styles.LABEL_PULL_THE_TRIGGER); confirmationLabel.setWidth(Gdx.graphics.getWidth()); confirmationLabel.setHeight(Gdx.graphics.getHeight()); confirmationLabel.setAlignment(Align.center); Tween.to(confirmationLabel, ActorTween.SCALE, 0.5f) .target(1.3f) .ease(TweenEquations.easeInCubic) .repeatYoyo(Tween.INFINITY, 0f) .start(gameContext.getTweenManager()); gameContext.getStage().addActor(confirmationLabel); waitingForPlayerConfirmation = true; } }).delay(4f).start(SharedTweenManager.getInstance()); } else { System.out.println(mafiosi.getName() + " turn"); context.getDialogManager().addDialog(mafiosi.getName(), getRandomDeathWish(), mafiosi.getAvatarId()); context.getDialogManager().nextDialog(); } } private void pullTrigger() { System.out.println("Pull the trigger!"); int numberOfBullets = 1; //context.getNumberOfBullets(mafiosi.getName()); boolean mafiosiWillBeDeadForSure = Math.random() > (float) numberOfBullets / (float) context.getNumberOfBulletSlots(); if (mafiosiWillBeDeadForSure) { System.out.println("SHOOT!"); setBoom(); setRouletteAnimation(null); if (mafiosi != null) { if (mafiosi.getName().contains("Trumpf")) { System.out.println("dead trumpf"); gameContext.getRenderManager().unregister(mafiosi.getName()); gameContext.getRenderManager().register(mafiosi.getName(), new SpriteRenderer(Asset.Textures.TRUMPF_DEAD_STAGE)); } if (mafiosi.getName().contains("Jawolta")) { System.out.println("dead Jawolta"); gameContext.getRenderManager().unregister(mafiosi.getName()); gameContext.getRenderManager().register(mafiosi.getName(), new SpriteRenderer(Asset.Textures.TRON_DEAD_STAGE)); } if (mafiosi.getName().contains("Sanchez")) { System.out.println("dead Sanchez"); gameContext.getRenderManager().unregister(mafiosi.getName()); gameContext.getRenderManager().register(mafiosi.getName(), new SpriteRenderer(Asset.Textures.SANCHEZ_DEAD_STAGE)); } shootCurrentPlayer(); SharedAssetManager.getInstance().get(Asset.Sounds.TRIGGER_BULLET, Sound.class).play(1f, (float) (0.7f + Math.random() * 0.5f), 0f); } } else { SharedAssetManager.getInstance().get(Asset.Sounds.TRIGGER_NO_BULLET, Sound.class).play(1f, (float) (0.7f + Math.random() * 0.5f), 0f); Toast.getInstance().doToast("MISS!"); System.out.println("MISS!"); remainingCandidates.add(mafiosi); nextPlayer(); } } private void shootCurrentPlayer() { if (mafiosi.equals(context.getPlayerMafiosi())) { System.out.println("Game over!"); AudioManager.getInstance().fadeOutMusic(Asset.Music.MENU_MINIGAME_ROULETTE_MUSIC_MAIN); gameContext.getScreenTransitions().out(new GameOverScreen(game), 2.5f); } else { deadMafiosis.add(mafiosi); System.out.println(mafiosi + " shot."); if (deadMafiosis.size() >= context.getCandidates().size() - 1) { AudioManager.getInstance().fadeOutMusic(Asset.Music.MENU_MINIGAME_ROULETTE_MUSIC_MAIN); System.out.println("You won!"); gameContext.getScreenTransitions().out(new CongratulationsScreen(game), 1.0f); } else { nextPlayer(); } } } private String getRandomDeathWish() { return DEATH_WISHES[(int) (DEATH_WISHES.length * Math.random())]; } }
jingcao80/Elastos
Sources/Elastos/Packages/Apps/Settings/inc/elastos/droid/settings/deviceinfo/CMiscFilesHandler.h
<filename>Sources/Elastos/Packages/Apps/Settings/inc/elastos/droid/settings/deviceinfo/CMiscFilesHandler.h //========================================================================= // Copyright (C) 2012 The Elastos 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. //========================================================================= #ifndef __ELASTOS_DROID_SETTINGS_DEVICEINFO_CMISCFILESHANDLER_H__ #define __ELASTOS_DROID_SETTINGS_DEVICEINFO_CMISCFILESHANDLER_H__ #include "Elastos.CoreLibrary.Utility.h" #include "_Elastos_Droid_Settings_Deviceinfo_CMiscFilesHandler.h" #include "elastos/droid/app/ListActivity.h" #include "elastos/droid/widget/BaseAdapter.h" using Elastos::Droid::App::IActivity; using Elastos::Droid::App::ListActivity; using Elastos::Droid::Content::IContext; using Elastos::Droid::Os::IBundle; using Elastos::Droid::View::IActionMode; using Elastos::Droid::View::ILayoutInflater; using Elastos::Droid::View::IMenu; using Elastos::Droid::View::IMenuItem; using Elastos::Droid::View::IView; using Elastos::Droid::View::IViewOnClickListener; using Elastos::Droid::View::IViewOnLongClickListener; using Elastos::Droid::View::IViewGroup; using Elastos::Droid::Widget::BaseAdapter; using Elastos::Droid::Widget::ICompoundButton; using Elastos::Droid::Widget::ICompoundButtonOnCheckedChangeListener; using Elastos::Droid::Widget::IListView; using Elastos::Droid::Widget::IMultiChoiceModeListener; using Elastos::IO::IFile; using Elastos::Utility::IList; namespace Elastos { namespace Droid { namespace Settings { namespace Deviceinfo { /** * This class handles the selection and removal of Misc files. */ CarClass(CMiscFilesHandler) , public ListActivity { public: class MemoryMearurementAdapter : public BaseAdapter { private: class GetViewOnCheckedChangeListener : public Object , public ICompoundButtonOnCheckedChangeListener { public: TO_STRING_IMPL("CMiscFilesHandler::MemoryMearurementAdapter::GetViewOnCheckedChangeListener") CAR_INTERFACE_DECL() GetViewOnCheckedChangeListener( /* [in] */ MemoryMearurementAdapter* host, /* [in] */ IListView* listView, /* [in] */ Int32 listPosition); //@Override CARAPI OnCheckedChanged( /* [in] */ ICompoundButton* buttonView, /* [in] */ Boolean isChecked); private: MemoryMearurementAdapter* mHost; AutoPtr<IListView> mListView; Int32 mListPosition; }; class GetOnLongClickListener : public Object , public IViewOnLongClickListener { public: TO_STRING_IMPL("CMiscFilesHandler::MemoryMearurementAdapter::GetOnLongClickListener") CAR_INTERFACE_DECL() GetOnLongClickListener( /* [in] */ MemoryMearurementAdapter* host, /* [in] */ IListView* listView, /* [in] */ Int32 listPosition, /* [in] */ Boolean viewIsChecked); //@Override CARAPI OnLongClick( /* [in] */ IView* v, /* [out] */ Boolean* result); private: MemoryMearurementAdapter* mHost; AutoPtr<IListView> mListView; Int32 mListPosition; Boolean mViewIsChecked; }; class GetOnClickListener : public Object , public IViewOnClickListener { public: TO_STRING_IMPL("CMiscFilesHandler::MemoryMearurementAdapter::GetOnClickListener") CAR_INTERFACE_DECL() GetOnClickListener( /* [in] */ MemoryMearurementAdapter* host, /* [in] */ IListView* listView, /* [in] */ Int32 listPosition, /* [in] */ Boolean viewIsChecked); //@Override CARAPI OnClick( /* [in] */ IView* v); private: MemoryMearurementAdapter* mHost; AutoPtr<IListView> mListView; Int32 mListPosition; Boolean mViewIsChecked; }; public: TO_STRING_IMPL("CMiscFilesHandler::MemoryMearurementAdapter") MemoryMearurementAdapter( /* [in] */ IActivity* activity, /* [in] */ CMiscFilesHandler* host); //@Override CARAPI GetCount( /* [out] */ Int32* result); //@Override CARAPI GetItem( /* [in] */ Int32 position, /* [out] */ IInterface** result); //StorageMeasurement.FileInfo //@Override CARAPI GetItemId( /* [in] */ Int32 position, /* [out] */ Int64* result); CARAPI RemoveAll( /* [in] */ IList* objs); //List<Object> CARAPI_(Int64) GetDataSize(); //@Override CARAPI NotifyDataSetChanged(); //@Override CARAPI GetView( /* [in] */ Int32 position, /* [in] */ IView* convertView, /* [in] */ IViewGroup* parent, /* [out] */ IView** result); private: AutoPtr<IList> mData; //ArrayList<StorageMeasurement.FileInfo> Int64 mDataSize; AutoPtr<IContext> mContext; CMiscFilesHandler* mHost; }; private: class ModeCallback : public Object , public IMultiChoiceModeListener , public IActionModeCallback { public: TO_STRING_IMPL("CMiscFilesHandler::ModeCallback") CAR_INTERFACE_DECL() ModeCallback( /* [in] */ IContext* context, /* [in] */ CMiscFilesHandler* host); CARAPI OnCreateActionMode( /* [in] */ IActionMode* mode, /* [in] */ IMenu* menu, /* [out] */ Boolean* result); CARAPI OnPrepareActionMode( /* [in] */ IActionMode* mode, /* [in] */ IMenu* menu, /* [out] */ Boolean* result); CARAPI OnActionItemClicked( /* [in] */ IActionMode* mode, /* [in] */ IMenuItem* item, /* [out] */ Boolean* result); CARAPI OnDestroyActionMode( /* [in] */ IActionMode* mode); CARAPI OnItemCheckedStateChanged( /* [in] */ IActionMode* mode, /* [in] */ Int32 position, /* [in] */ Int64 id, /* [in] */ Boolean checked); private: // Deletes all files and subdirectories under given dir. // Returns TRUE if all deletions were successful. // If a deletion fails, the method stops attempting to delete and returns FALSE. CARAPI_(Boolean) DeleteDir( /* [in] */ IFile* dir); private: Int32 mDataCount; AutoPtr<IContext> mContext; CMiscFilesHandler* mHost; }; public: TO_STRING_IMPL("CMiscFilesHandler") CMiscFilesHandler(); virtual ~CMiscFilesHandler(); CARAPI constructor(); //@Override CARAPI OnCreate( /* [in] */ IBundle* savedInstanceState); private: static const String TAG; String mNumSelectedFormat; String mNumBytesSelectedFormat; AutoPtr<MemoryMearurementAdapter> mAdapter; AutoPtr<ILayoutInflater> mInflater; }; } // namespace Deviceinfo } // namespace Settings } // namespace Droid } // namespace Elastos #endif //__ELASTOS_DROID_SETTINGS_DEVICEINFO_CMISCFILESHANDLER_H__
Aimee-MacDonald/blauw
src/tests/components/controls/Toolbox.test.js
<reponame>Aimee-MacDonald/blauw<filename>src/tests/components/controls/Toolbox.test.js<gh_stars>0 import React from 'react' import {shallow} from 'enzyme' import {Toolbox} from '../../../components/controls/Toolbox' test('Render closed Toolbox', () => { const navigation = { "bookingSheet":true, "checkout":false, "stock":false, "notes":false, "addRoom":false } const wrapper = shallow(<Toolbox open={false} navigation={navigation} selectedBooking={null} />) expect(wrapper.getElement()).toMatchSnapshot() }) test('Render booking sheet Toolbox', () => { const navigation = { "bookingSheet":true, "checkout":false, "stock":false, "notes":false, "addRoom":false } const wrapper = shallow(<Toolbox open={true} navigation={navigation} selectedBooking={null} />) expect(wrapper.getElement()).toMatchSnapshot() }) test('Render booking sheet Toolbox with a booking selected', () => { const navigation = { "bookingSheet":true, "checkout":false, "stock":false, "notes":false, "addRoom":false } const wrapper = shallow(<Toolbox open={true} navigation={navigation} selectedBooking={'abcd1234'} />) expect(wrapper.getElement()).toMatchSnapshot() }) test(`Render 'edit rooms list' Toolbox`, () => { const navigation = { "bookingSheet":false, "checkout":false, "stock":false, "notes":false, "addRoom":false, "editRoomsList": true } const wrapper = shallow(<Toolbox open={true} navigation={navigation} selectedBooking={null} />) expect(wrapper.getElement()).toMatchSnapshot() })
joschock/mu_plus
MsGraphicsPkg/MsEarlyGraphics/MsEarlyGraphicsCommon.c
<reponame>joschock/mu_plus /** @file These routines are common between Pei and Dxe versions of MsEarlyGraphics. Copyright (c) 2016 - 2018, 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. 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. **/ #include "MsEarlyGraphicsCommon.h" #define MS_EARLY_GRAPHICS_FONT MsUiGetFixedFontGlyphs () #define MS_EARLY_GRAPHICS_CELL_HEIGHT MsUiGetFixedFontHeight () #define MS_EARLY_GRAPHICS_CELL_WIDTH MsUiGetFixedFontWidth () #define MS_EARLY_GRAPHICS_CELL_ADVANCE MsUiGetFixedFontMaxAdvance () #define BITMAP_LEN_1_BIT(Width, Height) (((Width) + 7) / 8 * (Height)) /** Parse all glyph blocks to find a glyph block specified by CharValue. If CharValue = (CHAR16) (-1), collect all default character cell information within this font package and backup its information. @param CharValue Unicode character value, which identifies a glyph block. @param Cell Output cell information of the encoded bitmap. @param GlyphBlock Pointer to the static Glyph Block. @retval EFI_SUCCESS The bitmap data is retrieved successfully. @retval EFI_NOT_FOUND The specified CharValue does not exist in current database. **/ EFI_STATUS FindGlyph ( IN CHAR16 CharValue, OUT EFI_HII_GLYPH_INFO **Cell, OUT UINT8 **GlyphBlock ) { UINT8 *BlockPtr; EFI_HII_GIBT_GLYPHS_BLOCK *BlockGlyphs; UINT16 CharCurrent; UINT16 Length16; UINTN BufferLen; EFI_HII_GLYPH_INFO *DefaultCell; BlockPtr = MS_EARLY_GRAPHICS_FONT; CharCurrent = 1; BufferLen = 0; DefaultCell = NULL; while (*BlockPtr != EFI_HII_GIBT_END) { switch (*BlockPtr) { case EFI_HII_GIBT_DEFAULTS: // // Collect all default character cell information specified by // EFI_HII_GIBT_DEFAULTS. // // AsciiPrint("Ignoring GIBT_DEFAULTS\n"); DefaultCell = &((EFI_HII_GIBT_DEFAULTS_BLOCK *)BlockPtr)->Cell; BlockPtr += sizeof(EFI_HII_GIBT_DEFAULTS_BLOCK); break; case EFI_HII_GIBT_GLYPH_DEFAULT: if (DefaultCell == NULL) { ASSERT(DefaultCell != NULL); return EFI_NOT_FOUND; //mschange - check with MT. What is best way to exit this func } BufferLen = BITMAP_LEN_1_BIT(DefaultCell->Width, DefaultCell->Height); if (CharCurrent == CharValue) { *GlyphBlock = (UINT8 *)((UINTN)BlockPtr + sizeof(EFI_HII_GIBT_GLYPH_DEFAULT_BLOCK) - sizeof(UINT8)); *Cell = DefaultCell; // DumpMemory(*GlyphBlock, 16); return EFI_SUCCESS; } CharCurrent++; BlockPtr += sizeof(EFI_HII_GIBT_GLYPH_DEFAULT_BLOCK) - sizeof(UINT8) + BufferLen; break; case EFI_HII_GIBT_GLYPH: BlockGlyphs = (EFI_HII_GIBT_GLYPHS_BLOCK *)BlockPtr; *Cell = &BlockGlyphs->Cell; BufferLen = BITMAP_LEN_1_BIT(BlockGlyphs->Cell.Width, BlockGlyphs->Cell.Height); if (CharCurrent == CharValue) { *GlyphBlock = (UINT8 *)((UINTN)BlockPtr + sizeof(EFI_HII_GIBT_GLYPH_BLOCK) - sizeof(UINT8)); *Cell = &BlockGlyphs->Cell; //DumpMemory (*GlyphBlock,16); return EFI_SUCCESS; } CharCurrent++; BlockPtr += sizeof(EFI_HII_GIBT_GLYPH_BLOCK) - sizeof(UINT8) + BufferLen; break; case EFI_HII_GIBT_SKIP1: CharCurrent = (UINT16)(CharCurrent + (UINT16)(*(BlockPtr + sizeof(EFI_HII_GLYPH_BLOCK)))); BlockPtr += sizeof(EFI_HII_GIBT_SKIP1_BLOCK); break; case EFI_HII_GIBT_SKIP2: CopyMem(&Length16, BlockPtr + sizeof(EFI_HII_GLYPH_BLOCK), sizeof(UINT16)); CharCurrent = (UINT16)(CharCurrent + Length16); BlockPtr += sizeof(EFI_HII_GIBT_SKIP2_BLOCK); break; default: return EFI_NOT_FOUND; break; } if (CharValue < CharCurrent) { return EFI_NOT_FOUND; } } return EFI_NOT_FOUND; } /** Convert bitmap data of the glyph to blt structure. This is a internal function. @param GlyphBuffer Buffer points to bitmap data of glyph. @param Foreground The color of the "on" pixels in the glyph in the bitmap. @param Background The color of the "off" pixels in the glyph in the bitmap. @param ImageWidth Width of the whole image in pixels. @param BaseLine BaseLine in the line. @param RowWidth The width of the text on the line, in pixels. @param RowHeight The height of the line, in pixels. @param Cell Points to EFI_HII_GLYPH_INFO structure. @param Origin Points to the origin of the output buffer for the displayed character. **/ EFI_STATUS GlyphToBlt ( IN UINT8 *GlyphBuffer, IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL Foreground, IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL Background, IN UINT16 ImageWidth, IN UINT16 BaseLine, IN UINT32 RowWidth, IN UINT32 RowHeight, IN CONST EFI_HII_GLYPH_INFO *Cell, OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Origin ) { UINT16 Xpos; UINT16 Ypos; UINT8 Data; UINT16 Index; UINT16 YposOffset; UINTN OffsetY; EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer; if (GlyphBuffer == NULL || Cell == NULL) { return EFI_INVALID_PARAMETER; } // Move position to the left-top corner of char. // BltBuffer = Origin + Cell->OffsetX - (Cell->OffsetY + Cell->Height) * ImageWidth; YposOffset = (UINT16)(BaseLine - (Cell->OffsetY + Cell->Height)); // // The glyph's upper left hand corner pixel is the most significant bit of the // first bitmap byte. // for (Ypos = 0; Ypos < Cell->Height && ((UINTN)(Ypos + YposOffset) < RowHeight); Ypos++) { OffsetY = BITMAP_LEN_1_BIT(Cell->Width, Ypos); // // All bits in these bytes are meaningful. // for (Xpos = 0; Xpos < Cell->Width / 8; Xpos++) { Data = *(GlyphBuffer + OffsetY + Xpos); for (Index = 0; Index < 8 && ((UINTN)(Xpos * 8 + Index + Cell->OffsetX) < RowWidth); Index++) { if ((Data & (1 << (8 - Index - 1))) != 0) { BltBuffer[Ypos * ImageWidth + Xpos * 8 + Index] = Foreground; } else { BltBuffer[Ypos * ImageWidth + Xpos * 8 + Index] = Background; } } } if (Cell->Width % 8 != 0) { // // There are some padding bits in this byte. Ignore them. // Data = *(GlyphBuffer + OffsetY + Xpos); for (Index = 0; Index < Cell->Width % 8 && ((UINTN)(Xpos * 8 + Index + Cell->OffsetX) < RowWidth); Index++) { if ((Data & (1 << (8 - Index - 1))) != 0) { BltBuffer[Ypos * ImageWidth + Xpos * 8 + Index] = Foreground; } else { BltBuffer[Ypos * ImageWidth + Xpos * 8 + Index] = Background; } } } // end of if (Width % 8...) } // end of for (Ypos=0...) return EFI_SUCCESS; } /** SimpleBlt @param This Pointer to MS_EARLY_GRAPHICS_PROTOCOL @param Image Pointer to bitmap @param DestinationX X location to display the bitmatp @param DestinationY Y location to display the bitmap @param Width Width of bitmap @param Height Height of bitmap @return EFI_STATUS Blt successful */ EFI_STATUS EFIAPI SimpleBlt ( IN MS_EARLY_GRAPHICS_PROTOCOL *this, IN CONST EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Image, IN UINT32 DestinationX, IN UINT32 DestinationY, IN UINT32 Width, IN UINT32 Height ) { UINT32 Row; UINT32 *Dest; UINT32 *Src = (UINT32 *)Image; this->UpdateFrameBufferBase(this); // if (this->Mode->Info->PixelFormat != PixelBlueGreenRedReserved8BitPerColor) { // DEBUG((DEBUG_ERROR,__FUNCTION__ " Invalid Pixel formal %d",this->Mode->Info->PixelFormat)); // return EFI_DEVICE_ERROR; // } // FrameBuffer has to be in low 4GB to work in PEI anyway. Allw full 64 bit memory address in DXE Dest = (UINT32 *)((UINTN)this->Mode->FrameBufferBase + DestinationX *sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL) + DestinationY * this->Mode->Info->PixelsPerScanLine * sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL)); for (Row = 0; Row < Height; Row++) { CopyMem(Dest, Src, Width * sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL)); Src = Src + Width; Dest = Dest + this->Mode->Info->PixelsPerScanLine; } return EFI_SUCCESS; } /** SimpleFill @param this Pointer to MS_EARLY_GRAPHICS_PROTOCOL @param Image Pointer to bitmap @param DestinationX X location to display the bitmatp @param DestinationY Y location to display the bitmap @param Width Width of bitmap @param Height Height of bitmap @return EFI_STATUS Blt successful */ EFI_STATUS EFIAPI SimpleFill( IN MS_EARLY_GRAPHICS_PROTOCOL *this, IN UINT32 Color, IN UINT32 DestinationX, IN UINT32 DestinationY, IN UINT32 Width, IN UINT32 Height ) { UINT32 Row; UINT32 *p; this->UpdateFrameBufferBase(this); // if (this->Mode->Info->PixelFormat != PixelBlueGreenRedReserved8BitPerColor) { // DEBUG((DEBUG_ERROR,__FUNCTION__ " Invalid Pixed formal %d",this->Mode->Info->PixelFormat)); // return EFI_DEVICE_ERROR; // } // FrameBuffer has to be in low 4GB to work in PEI anyway. p = (UINT32 *)((UINTN)this->Mode->FrameBufferBase + DestinationX * sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL) + DestinationY * this->Mode->Info->PixelsPerScanLine * sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL)); for (Row = 0; Row < Height; Row++) { SetMem32(p, Width * sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL), Color); p = p + this->Mode->Info->PixelsPerScanLine; } return EFI_SUCCESS; } /** * Print a line at the row specified. There is no line * wrapping, and \n and other special characters are not * supported. * * @param Row Row to display msg on * @param Column Column to start display of message * @param ForegroundColor Color of text in foreground * @param BackgroundColor Color of background behind text * @param Msg String to display * * @retval EFI_SUCCESS String was written to display */ EFI_STATUS EFIAPI PrintLn( IN MS_EARLY_GRAPHICS_PROTOCOL *this, IN UINT32 Row, IN UINT32 Column, IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL ForegroundColor, IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL BackgroundColor, IN CONST CHAR8 *Msg) { EFI_STATUS Status; OUT EFI_HII_GLYPH_INFO *Cell; OUT UINT8 *GlyphBlock; UINT16 BaseLine; EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BufferPtr; EFI_GRAPHICS_OUTPUT_BLT_PIXEL *ImageBuffer; this->UpdateFrameBufferBase(this); ImageBuffer = AllocatePool (MS_EARLY_GRAPHICS_CELL_HEIGHT * MS_EARLY_GRAPHICS_CELL_ADVANCE * sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL)); if (ImageBuffer == NULL) { return EFI_OUT_OF_RESOURCES; } Status = EFI_SUCCESS; while ('\0' != *Msg) { Status = FindGlyph((UINT8)*Msg, &Cell, &GlyphBlock); // Poor man's CHAR8 to CHAR16 conversion if (!EFI_ERROR(Status)) { BaseLine = Cell->Height + Cell->OffsetY; BufferPtr = ImageBuffer + BaseLine * Cell->Width; Status = GlyphToBlt(GlyphBlock, ForegroundColor, BackgroundColor, Cell->Width, BaseLine, Cell->Width, Cell->Height, Cell, BufferPtr); if (!EFI_ERROR(Status)) { Status = SimpleBlt(this, ImageBuffer, Column * MS_EARLY_GRAPHICS_CELL_WIDTH, Row * MS_EARLY_GRAPHICS_CELL_HEIGHT, Cell->Width, Cell->Height); } } Msg++; Column++; } FreePool (ImageBuffer ); return Status; } /** * GetCellHeight * * * @return UINT32 */ UINT32 EFIAPI GetCellHeight() { return MS_EARLY_GRAPHICS_CELL_HEIGHT; } /** * GetCellWidth * * * @return UINT32 */ UINT32 EFIAPI GetCellWidth() { return MS_EARLY_GRAPHICS_CELL_WIDTH; }
sleyzerzon/soar
Documentation/ManualSource/wikicmd/MoinMoin/parser/text_creole.py
<gh_stars>1-10 # -*- coding: iso-8859-1 -*- """ MoinMoin - Creole wiki markup parser See http://wikicreole.org/ for latest specs. Notes: * No markup allowed in headings. Creole 1.0 does not require us to support this. * No markup allowed in table headings. Creole 1.0 does not require us to support this. * No (non-bracketed) generic url recognition: this is "mission impossible" except if you want to risk lots of false positives. Only known protocols are recognized. * We do not allow ":" before "//" italic markup to avoid urls with unrecognized schemes (like wtf://server/path) triggering italic rendering for the rest of the paragraph. @copyright: 2007 MoinMoin:RadomirDopieralski (creole 0.5 implementation), 2007 MoinMoin:ThomasWaldmann (updates) @license: GNU GPL, see COPYING for details. """ import re import StringIO from MoinMoin import config, wikiutil from MoinMoin.macro import Macro from MoinMoin import config from _creole import Parser as CreoleParser from _creole import Rules as CreoleRules Dependencies = [] _ = lambda x: x class Parser: """ Glue the DocParser and DocEmitter with the MoinMoin current API. """ extensions = ['.creole'] # Enable caching caching = 1 Dependencies = Dependencies quickhelp = _(u"""\ Emphasis:: <<Verbatim(//)>>''italics''<<Verbatim(//)>>; <<Verbatim(**)>>'''bold'''<<Verbatim(**)>>; <<Verbatim(**//)>>'''''bold italics'''''<<Verbatim(//**)>>; <<Verbatim(//)>>''mixed ''<<Verbatim(**)>>'''''bold'''<<Verbatim(**)>> and italics''<<Verbatim(//)>>; Horizontal Rule:: <<Verbatim(----)>> Force Linebreak:: <<Verbatim(\\\\)>> Headings:: = Title 1 =; == Title 2 ==; === Title 3 ===; ==== Title 4 ====; ===== Title 5 =====. Lists:: * bullets; ** sub-bullets; # numbered items; ## numbered sub items. Links:: <<Verbatim([[target]])>>; <<Verbatim([[target|linktext]])>>. Tables:: |= header text | cell text | more cell text |; (!) For more help, see HelpOnEditing or HelpOnCreoleSyntax. """) def __init__(self, raw, request, **kw): """Create a minimal Parser object with required attributes.""" self.request = request self.form = request.form self.raw = raw self.rules = MoinRules(wiki_words=True, url_protocols=config.url_schemas) def format(self, formatter): """Create and call the true parser and emitter.""" document = CreoleParser(self.raw, self.rules).parse() result = Emitter(document, formatter, self.request, Macro(self), self.rules).emit() self.request.write(result) class MoinRules(CreoleRules): # For the link targets: proto = r'http|https|ftp|nntp|news|mailto|telnet|file|irc' extern = r'(?P<extern_addr>(?P<extern_proto>%s):.*)' % proto attach = r''' (?P<attach_scheme> attachment | drawing | image ): (?P<attach_addr> .* ) ''' interwiki = r''' (?P<inter_wiki> [A-Z][a-zA-Z]+ ) : (?P<inter_page> .* ) ''' page = r'(?P<page_name> .* )' def __init__(self, *args, **kwargs): CreoleRules.__init__(self, *args, **kwargs) # for addresses self.addr_re = re.compile('|'.join([self.extern, self.attach, self.interwiki, self.page]), re.X | re.U) class Emitter: """ Generate the output for the document tree consisting of DocNodes. """ def __init__(self, root, formatter, request, macro, rules): self.root = root self.formatter = formatter self.request = request self.form = request.form self.macro = macro self.rules = rules def get_text(self, node): """Try to emit whatever text is in the node.""" try: return node.children[0].content or '' except: return node.content or '' # *_emit methods for emitting nodes of the document: def document_emit(self, node): return self.emit_children(node) def text_emit(self, node): return self.formatter.text(node.content or '') def separator_emit(self, node): return self.formatter.rule() def paragraph_emit(self, node): return ''.join([ self.formatter.paragraph(1), self.emit_children(node), self.formatter.paragraph(0), ]) def bullet_list_emit(self, node): return ''.join([ self.formatter.bullet_list(1), self.emit_children(node), self.formatter.bullet_list(0), ]) def number_list_emit(self, node): return ''.join([ self.formatter.number_list(1), self.emit_children(node), self.formatter.number_list(0), ]) def list_item_emit(self, node): return ''.join([ self.formatter.listitem(1), self.emit_children(node), self.formatter.listitem(0), ]) # Not used # def definition_list_emit(self, node): # return ''.join([ # self.formatter.definition_list(1), # self.emit_children(node), # self.formatter.definition_list(0), # ]) # Not used # def term_emit(self, node): # return ''.join([ # self.formatter.definition_term(1), # self.emit_children(node), # self.formatter.definition_term(0), # ]) # Not used # def definition_emit(self, node): # return ''.join([ # self.formatter.definition_desc(1), # self.emit_children(node), # self.formatter.definition_desc(0), # ]) def table_emit(self, node): return ''.join([ self.formatter.table(1, attrs=getattr(node, 'attrs', '')), self.emit_children(node), self.formatter.table(0), ]) def table_row_emit(self, node): return ''.join([ self.formatter.table_row(1, attrs=getattr(node, 'attrs', '')), self.emit_children(node), self.formatter.table_row(0), ]) def table_cell_emit(self, node): return ''.join([ self.formatter.table_cell(1, attrs=getattr(node, 'attrs', '')), self.emit_children(node), self.formatter.table_cell(0), ]) def table_head_emit(self, node): return ''.join([ self.formatter.rawHTML('<th>'), self.emit_children(node), self.formatter.rawHTML('</th>'), ]) def emphasis_emit(self, node): return ''.join([ self.formatter.emphasis(1), self.emit_children(node), self.formatter.emphasis(0), ]) # Not used # def quote_emit(self, node): # return ''.join([ # self.formatter.rawHTML('<q>'), # self.emit_children(node), # self.formatter.rawHTML('</q>'), # ]) def strong_emit(self, node): return ''.join([ self.formatter.strong(1), self.emit_children(node), self.formatter.strong(0), ]) # Not used # def smiley_emit(self, node): # return self.formatter.smiley(node.content) def header_emit(self, node): text = self.get_text(node) return ''.join([ self.formatter.heading(1, node.level, id=text), self.formatter.text(text), self.formatter.heading(0, node.level), ]) def code_emit(self, node): # XXX The current formatter will replace all spaces with &nbsp;, so we need # to use rawHTML instead, until that is fixed. # return ''.join([ # self.formatter.code(1), # self.formatter.text(node.content or ''), # self.formatter.code(0), # ]) return ''.join([ self.formatter.rawHTML('<tt>'), self.formatter.text(node.content or ''), self.formatter.rawHTML('</tt>'), ]) # Not used # def abbr_emit(self, node): # return ''.join([ # self.formatter.rawHTML('<abbr title="%s">' % node.title), # self.formatter.text(node.content or ''), # self.formatter.rawHTML('</abbr>'), # ]) def link_emit(self, node): target = node.content m = self.rules.addr_re.match(target) if m: if m.group('page_name'): # link to a page word = m.group('page_name') if word.startswith(wikiutil.PARENT_PREFIX): word = word[wikiutil.PARENT_PREFIX_LEN:] elif word.startswith(wikiutil.CHILD_PREFIX): word = "%s/%s" % (self.formatter.page.page_name, word[wikiutil.CHILD_PREFIX_LEN:]) word, anchor = wikiutil.split_anchor(word) return ''.join([ self.formatter.pagelink(1, word, anchor=anchor), self.emit_children(node) or self.formatter.text(target), self.formatter.pagelink(0, word), ]) elif m.group('extern_addr'): # external link address = m.group('extern_addr') proto = m.group('extern_proto') return ''.join([ self.formatter.url(1, address, css=proto), self.emit_children(node) or self.formatter.text(target), self.formatter.url(0), ]) elif m.group('inter_wiki'): # interwiki link wiki = m.group('inter_wiki') page = m.group('inter_page') page, anchor = wikiutil.split_anchor(page) return ''.join([ self.formatter.interwikilink(1, wiki, page, anchor=anchor), self.emit_children(node) or self.formatter.text(page), self.formatter.interwikilink(0), ]) elif m.group('attach_scheme'): # link to an attachment scheme = m.group('attach_scheme') attachment = m.group('attach_addr') url = wikiutil.url_unquote(attachment) text = self.get_text(node) return ''.join([ self.formatter.attachment_link(1, url), self.formatter.text(text), self.formatter.attachment_link(0) ]) return "".join(["[[", self.formatter.text(target), "]]"]) # Not used # def anchor_link_emit(self, node): # return ''.join([ # self.formatter.url(1, node.content, css='anchor'), # self.emit_children(node), # self.formatter.url(0), # ]) def image_emit(self, node): target = node.content text = self.get_text(node) m = self.rules.addr_re.match(target) if m: if m.group('page_name'): # inserted anchors url = wikiutil.url_unquote(target) if target.startswith('#'): return self.formatter.anchordef(url[1:]) # default to images return self.formatter.attachment_image( url, alt=text, html_class='image') elif m.group('extern_addr'): # external link address = m.group('extern_addr') proto = m.group('extern_proto') url = wikiutil.url_unquote(address) return self.formatter.image( src=url, alt=text, html_class='external_image') elif m.group('attach_scheme'): # link to an attachment scheme = m.group('attach_scheme') attachment = m.group('attach_addr') url = wikiutil.url_unquote(attachment) if scheme == 'image': return self.formatter.attachment_image( url, alt=text, html_class='image') elif scheme == 'drawing': url = wikiutil.drawing2fname(url) return self.formatter.attachment_drawing(url, text, alt=text) else: pass elif m.group('inter_wiki'): # interwiki link pass # return "".join(["{{", self.formatter.text(target), "}}"]) url = wikiutil.url_unquote(node.content) return self.formatter.attachment_inlined(url, text) # Not used # def drawing_emit(self, node): # url = wikiutil.url_unquote(node.content) # text = self.get_text(node) # return self.formatter.attachment_drawing(url, text) # Not used # def figure_emit(self, node): # text = self.get_text(node) # url = wikiutil.url_unquote(node.content) # return ''.join([ # self.formatter.rawHTML('<div class="figure">'), # self.get_image(url, text), self.emit_children(node), # self.formatter.rawHTML('</div>'), # ]) # Not used # def bad_link_emit(self, node): # return self.formatter.text(''.join([ # '[[', # node.content or '', # ']]', # ])) def macro_emit(self, node): macro_name = node.content args = node.args return self.formatter.macro(self.macro, macro_name, args) # Not used # def section_emit(self, node): # return ''.join([ # self.formatter.rawHTML( # '<div class="%s" style="%s">' % (node.sect, node.style)), # self.emit_children(node), # self.formatter.rawHTML('</div>'), # ]) def break_emit(self, node): return self.formatter.linebreak(preformatted=0) # Not used # def blockquote_emit(self, node): # return ''.join([ # self.formatter.rawHTML('<blockquote>'), # self.emit_children(node), # self.formatter.rawHTML('</blockquote>'), # ]) def preformatted_emit(self, node): parser_name = getattr(node, 'sect', '') if parser_name: # The formatter.parser will *sometimes* just return the result # and *sometimes* try to write it directly. We need to take both # cases into account! lines = node.content.split(u'\n') buf = StringIO.StringIO() try: try: self.request.redirect(buf) ret = self.formatter.parser(parser_name, lines) finally: self.request.redirect() buf.flush() writ = buf.getvalue() buf.close() return ret + writ except wikiutil.PluginMissingError: pass return ''.join([ self.formatter.preformatted(1), self.formatter.text(node.content), self.formatter.preformatted(0), ]) def default_emit(self, node): """Fallback function for emitting unknown nodes.""" return ''.join([ self.formatter.preformatted(1), self.formatter.text('<%s>\n' % node.kind), self.emit_children(node), self.formatter.preformatted(0), ]) def emit_children(self, node): """Emit all the children of a node.""" return ''.join([self.emit_node(child) for child in node.children]) def emit_node(self, node): """Emit a single node.""" emit = getattr(self, '%s_emit' % node.kind, self.default_emit) return emit(node) def emit(self): """Emit the document represented by self.root DOM tree.""" # Try to disable 'smart' formatting if possible magic_save = getattr(self.formatter, 'no_magic', False) self.formatter.no_magic = True output = '\n'.join([ self.emit_node(self.root), ]) # restore 'smart' formatting if it was set self.formatter.no_magic = magic_save return output del _
melodyyangaws/arc
src/test/scala/ai/tripl/arc/validate/SQLValidateSuite.scala
<gh_stars>100-1000 package ai.tripl.arc import java.net.URI import org.scalatest.FunSuite import org.scalatest.BeforeAndAfter import org.apache.commons.io.FileUtils import org.apache.commons.io.IOUtils import org.apache.spark.sql._ import org.apache.spark.sql.functions._ import ai.tripl.arc.api._ import ai.tripl.arc.api.API._ import ai.tripl.arc.config._ import ai.tripl.arc.util._ class SQLValidateSuite extends FunSuite with BeforeAndAfter { var session: SparkSession = _ var testName = "" var testURI = FileUtils.getTempDirectoryPath() val signature = "SQLValidate requires query to return 1 row with [outcome: boolean, message: string] signature." before { implicit val spark = SparkSession .builder() .master("local[*]") .config("spark.ui.port", "9999") .appName("Arc Test") .getOrCreate() spark.sparkContext.setLogLevel("INFO") // set for deterministic timezone spark.conf.set("spark.sql.session.timeZone", "UTC") session = spark } after { session.stop } test("SQLValidate: end-to-end") { implicit val spark = session implicit val logger = TestUtils.getLogger() implicit val arcContext = TestUtils.getARCContext() val conf = s"""{ "stages": [ { "type": "SQLValidate", "name": "test", "description": "test", "environments": [ "production", "test" ], "inputURI": "${getClass.getResource("/conf/sql/").toString}/basic.sql", "sqlParams": { "placeholder": "value", } } ] }""" val pipelineEither = ArcPipeline.parseConfig(Left(conf), arcContext) pipelineEither match { case Left(err) => fail(err.toString) case Right((pipeline, _)) => ARC.run(pipeline)(spark, logger, arcContext) } } test("SQLValidate: end-to-end inline sql") { implicit val spark = session implicit val logger = TestUtils.getLogger() implicit val arcContext = TestUtils.getARCContext() val conf = s"""{ "stages": [ { "type": "SQLValidate", "name": "test", "description": "test", "environments": [ "production", "test" ], "sql": "SELECT TRUE, '$${placeholder}'", "sqlParams": { "placeholder": "value", } } ] }""" val pipelineEither = ArcPipeline.parseConfig(Left(conf), arcContext) pipelineEither match { case Left(err) => fail(err.toString) case Right((pipeline, _)) => ARC.run(pipeline)(spark, logger, arcContext) } } test("SQLValidate: end-to-end with json array") { implicit val spark = session implicit val logger = TestUtils.getLogger() implicit val arcContext = TestUtils.getARCContext() val conf = s"""{ "stages": [ { "type": "SQLValidate", "name": "test", "description": "test", "environments": [ "production", "test" ], "sql": "SELECT TRUE, TO_JSON(COLLECT_LIST(NAMED_STRUCT('stringKey', 'stringValue', 'numKey', 123)))" } ] }""" val pipelineEither = ArcPipeline.parseConfig(Left(conf), arcContext) pipelineEither match { case Left(err) => fail(err.toString) case Right((pipeline, _)) => ARC.run(pipeline)(spark, logger, arcContext) } } test("SQLValidate: true, null") { implicit val spark = session import spark.implicits._ implicit val logger = TestUtils.getLogger() implicit val arcContext = TestUtils.getARCContext() validate.SQLValidateStage.execute( validate.SQLValidateStage( plugin=new validate.SQLValidate, id=None, name=testName, description=None, inputURI=Option(new URI(testURI)), sql="SELECT true, null", sqlParams=Map.empty, params=Map.empty ) ) } test("SQLValidate: true, string") { implicit val spark = session import spark.implicits._ implicit val logger = TestUtils.getLogger() implicit val arcContext = TestUtils.getARCContext() validate.SQLValidateStage.execute( validate.SQLValidateStage( plugin=new validate.SQLValidate, id=None, name=testName, description=None, inputURI=Option(new URI(testURI)), sql="SELECT true, 'message'", sqlParams=Map.empty, params=Map.empty ) ) } test("SQLValidate: true, json") { implicit val spark = session import spark.implicits._ implicit val logger = TestUtils.getLogger() implicit val arcContext = TestUtils.getARCContext() validate.SQLValidateStage.execute( validate.SQLValidateStage( plugin=new validate.SQLValidate, id=None, name=testName, description=None, inputURI=Option(new URI(testURI)), sql="""SELECT true, '{"stringKey": "stringValue", "numKey": 123}'""", sqlParams=Map.empty, params=Map.empty ) ) } test("SQLValidate: false, null") { implicit val spark = session import spark.implicits._ implicit val logger = TestUtils.getLogger() implicit val arcContext = TestUtils.getARCContext() val thrown = intercept[Exception with DetailException] { validate.SQLValidateStage.execute( validate.SQLValidateStage( plugin=new validate.SQLValidate, id=None, name=testName, description=None, inputURI=Option(new URI(testURI)), sql="SELECT false, null", sqlParams=Map.empty, params=Map.empty ) ) } assert(thrown.getMessage === "SQLValidate failed with message: 'null'.") } test("SQLValidate: false, string") { implicit val spark = session import spark.implicits._ implicit val logger = TestUtils.getLogger() implicit val arcContext = TestUtils.getARCContext() val thrown = intercept[Exception with DetailException] { validate.SQLValidateStage.execute( validate.SQLValidateStage( plugin=new validate.SQLValidate, id=None, name=testName, description=None, inputURI=Option(new URI(testURI)), sql="SELECT false, 'this is my message'", sqlParams=Map.empty, params=Map.empty ) ) } assert(thrown.getMessage === "SQLValidate failed with message: 'this is my message'.") } test("SQLValidate: false, json") { implicit val spark = session import spark.implicits._ implicit val logger = TestUtils.getLogger() implicit val arcContext = TestUtils.getARCContext() val thrown = intercept[Exception with DetailException] { validate.SQLValidateStage.execute( validate.SQLValidateStage( plugin=new validate.SQLValidate, id=None, name=testName, description=None, inputURI=Option(new URI(testURI)), sql="""SELECT false, TO_JSON(NAMED_STRUCT('stringKey', 'stringValue', 'numKey', 123))""", sqlParams=Map.empty, params=Map.empty ) ) } assert(thrown.getMessage === """SQLValidate failed with message: '{"stringKey":"stringValue","numKey":123}'.""") } test("SQLValidate: string, boolean") { implicit val spark = session import spark.implicits._ implicit val logger = TestUtils.getLogger() implicit val arcContext = TestUtils.getARCContext() val thrown = intercept[Exception with DetailException] { validate.SQLValidateStage.execute( validate.SQLValidateStage( plugin=new validate.SQLValidate, id=None, name=testName, description=None, inputURI=Option(new URI(testURI)), sql="SELECT 'string', true", sqlParams=Map.empty, params=Map.empty ) ) } assert(thrown.getMessage === s"${signature} Query returned 1 rows of type [string, boolean].") } test("SQLValidate: rows != 1") { implicit val spark = session import spark.implicits._ implicit val logger = TestUtils.getLogger() implicit val arcContext = TestUtils.getARCContext() val thrown0 = intercept[Exception with DetailException] { validate.SQLValidateStage.execute( validate.SQLValidateStage( plugin=new validate.SQLValidate, id=None, name=testName, description=None, inputURI=Option(new URI(testURI)), sql="SELECT true, 'message' WHERE false", sqlParams=Map.empty, params=Map.empty ) ) } assert(thrown0.getMessage === s"${signature} Query returned 0 rows of type [boolean, string].") val thrown1 = intercept[Exception with DetailException] { validate.SQLValidateStage.execute( validate.SQLValidateStage( plugin=new validate.SQLValidate, id=None, name=testName, description=None, inputURI=Option(new URI(testURI)), sql="SELECT true, 'message' UNION ALL SELECT true, 'message'", sqlParams=Map.empty, params=Map.empty ) ) } assert(thrown1.getMessage === s"${signature} Query returned 2 rows of type [boolean, string].") } test("SQLValidate: columns != 2") { implicit val spark = session import spark.implicits._ implicit val logger = TestUtils.getLogger() implicit val arcContext = TestUtils.getARCContext() val thrown0 = intercept[Exception with DetailException] { validate.SQLValidateStage.execute( validate.SQLValidateStage( plugin=new validate.SQLValidate, id=None, name=testName, description=None, inputURI=Option(new URI(testURI)), sql="SELECT true", sqlParams=Map.empty, params=Map.empty ) ) } assert(thrown0.getMessage === s"${signature} Query returned 1 rows of type [boolean].") val thrown1 = intercept[Exception with DetailException] { validate.SQLValidateStage.execute( validate.SQLValidateStage( plugin=new validate.SQLValidate, id=None, name=testName, description=None, inputURI=Option(new URI(testURI)), sql="SELECT true, 'message', true", sqlParams=Map.empty, params=Map.empty ) ) } assert(thrown1.getMessage === s"${signature} Query returned 1 rows of type [boolean, string, boolean].") } test("SQLValidate: sqlParams") { implicit val spark = session import spark.implicits._ implicit val logger = TestUtils.getLogger() implicit val arcContext = TestUtils.getARCContext() validate.SQLValidateStage.execute( validate.SQLValidateStage( plugin=new validate.SQLValidate, id=None, name=testName, description=None, inputURI=Option(new URI(testURI)), sql="""SELECT 0.1 > ${threshold}, 'message'""", sqlParams=Map("threshold" -> "0.05"), params=Map.empty ) ) val thrown = intercept[Exception with DetailException] { validate.SQLValidateStage.execute( validate.SQLValidateStage( plugin=new validate.SQLValidate, id=None, name=testName, description=None, inputURI=Option(new URI(testURI)), sql="""SELECT 0.01 > ${threshold}, 'message'""", sqlParams=Map("threshold" -> "0.05"), params=Map.empty ) ) } assert(thrown.getMessage === s"SQLValidate failed with message: 'message'.") } test("SQLValidate: No rows") { implicit val spark = session import spark.implicits._ implicit val logger = TestUtils.getLogger() implicit val arcContext = TestUtils.getARCContext() val thrown = intercept[Exception with DetailException] { validate.SQLValidateStage.execute( validate.SQLValidateStage( plugin=new validate.SQLValidate, id=None, name=testName, description=None, inputURI=Option(new URI(testURI)), sql="SELECT CAST(NULL AS BOOLEAN), CAST(NULL AS STRING)", sqlParams=Map.empty, params=Map.empty ) ) } assert(thrown.getMessage === s"SQLValidate requires query to return 1 row with [outcome: boolean, message: string] signature. Query returned [null, null].") } }
cohadar/codereplicator
src/cohadar/tools/replicator/engine/CompositeAlgorithm.java
package cohadar.tools.replicator.engine; import java.util.regex.Pattern; /** * call order: * setSmartList * setVerbatimList * */ public class CompositeAlgorithm extends Composite { protected final int MAX_SEPARATOR_LENGTH = 5; protected String[] smartList; protected String[] verbatimList; protected Pattern smartPattern; protected Pattern verbatimPattern; public int setSmartList(String[] smartList) { this.smartList = null; this.smartPattern = null; if (smartList == null || smartList.length == 0) { return 0; } if (Text.isBlank(smartList[0])) { for (String s : smartList) { if (!Text.isBlank(s)) { return Composite.BLANK_SMART; } } } else { for (int i = 0; i < smartList.length; i++) { smartList[i] = Text.clowerCase(smartList[i]); } if (smartList[0].contains(Text.UNDERSCORE) == false) { for (String s : smartList) { if (s.contains(Text.UNDERSCORE)) { return Composite.UNDERSCORES; } } } String regexp = Text.regExp(smartList[0], MAX_SEPARATOR_LENGTH); this.smartPattern = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE); this.smartList = smartList; } return 0; } public int setVerbatimList(String[] verbatimList) { this.verbatimList = null; this.verbatimPattern = null; if (verbatimList == null || verbatimList.length == 0) { return 0; } if (Text.isBlank(verbatimList[0])) { for (String s : verbatimList) { if (!Text.isBlank(s)) { return Composite.BLANK_VERBATIM; } } } else { this.verbatimList = verbatimList; this.verbatimPattern = Pattern.compile(verbatimList[0], Pattern.LITERAL); } return 0; } }
ryandesign/yap
packages/myddas/myddas_initialization.c
<filename>packages/myddas/myddas_initialization.c #include <stdio.h> #include <stdlib.h> #include "Yap.h" #include "myddas.h" #ifdef MYDDAS_STATS #include "myddas_statistics.h" #endif MYDDAS_GLOBAL myddas_init_initialize_myddas(void) { MYDDAS_GLOBAL global = NULL; /* We cannot call MYDDAS_MALLOC were because the global register isn't yet initialized */ global = (MYDDAS_GLOBAL)malloc(sizeof(struct myddas_global)); #ifdef DEBUGX printf("MALLOC %p %s %d\n", global, __FILE__, __LINE__); #endif global->myddas_top_connections = NULL; #ifdef MYDDAS_TOP_LEVEL global->myddas_top_level_connection = NULL; #endif #ifdef MYDDAS_STATS global->myddas_statistics = (MYDDAS_GLOBAL_STATS)malloc(sizeof(struct myddas_global_stats)); #ifdef DEBUG printf("MALLOC %p %s %d\n", global->myddas_statistics, __FILE__, __LINE__); #endif global->myddas_statistics->stats = NULL; #endif #ifdef DEBUG /* We first malloc for this struct and the stats struct */ #ifdef MYDDAS_STATS global->malloc_called = 2; global->memory_allocated = sizeof(struct myddas_global) + sizeof(struct myddas_global_stats); #else global->malloc_called = 1; global->memory_allocated = sizeof(struct myddas_global); #endif /* MYDDAS_STATS */ global->free_called = 0; global->memory_freed = 0; #endif return global; } /* Inserts the new node on the front of the list */ MYDDAS_UTIL_CONNECTION myddas_init_initialize_connection(void *conn, void *enviromment, MYDDAS_API api, MYDDAS_UTIL_CONNECTION next) { CACHE_REGS MYDDAS_UTIL_CONNECTION new = NULL; MYDDAS_MALLOC(new, struct myddas_list_connection); if (new == NULL) { return NULL; } new->api = api; new->predicates = NULL; new->connection = conn; new->odbc_enviromment = enviromment; /* It saves n queries, doing at once n+1 queries */ new->total_number_queries = 0; // Default new->actual_number_queries = 0; new->queries = NULL; /* List integrity */ new->next = next; new->previous = NULL; /* If there's already at least one node on the list */ if (next != NULL) next->previous = new; #ifdef MYDDAS_STATS new->stats = NULL; new->stats = myddas_stats_initialize_connection_stats(); #endif return new; } MYDDAS_UTIL_PREDICATE myddas_init_initialize_predicate(const char *pred_name, int pred_arity, const char *pred_module, MYDDAS_UTIL_PREDICATE next) { CACHE_REGS MYDDAS_UTIL_PREDICATE new = NULL; MYDDAS_MALLOC(new, struct myddas_list_preds); if (new == NULL) { return NULL; } new->pred_name = pred_name; new->pred_arity = pred_arity; new->pred_module = pred_module; /* List integrity */ new->next = next; new->previous = NULL; /* If there's already at least one node on the list */ if (next != NULL) next->previous = new; return new; }
nistefan/cmssw
DataFormats/EcalDetId/src/ESDetId.cc
#include "DataFormats/EcalDetId/interface/ESDetId.h" #include "FWCore/Utilities/interface/Exception.h" #include <ostream> void ESDetId::verify( int strip, int ixs, int iys, int plane, int iz ) { if( !validDetId( strip, ixs, iys, plane, iz) ) throw cms::Exception("InvalidDetId") << "ESDetId: Cannot create object. Indexes out of bounds \n" << " strip = " << strip << " x = " << ixs << " y = " << iys << "\n" << " plane = " << plane << " z = " << iz << " hxy = " << (1==plane?hxy1[ixs-1][iys-1]:hxy2[ixs-1][iys-1]) << "\n"; } bool ESDetId::validDetId( int istrip, int ixs, int iys, int iplane, int iz ) { return ( !( ( istrip < ISTRIP_MIN ) || ( istrip > ISTRIP_MAX ) || ( ixs < IX_MIN ) || ( ixs > IX_MAX ) || ( iys < IY_MIN ) || ( iys > IY_MAX ) || ( abs( iz ) != 1 ) || ( iplane < PLANE_MIN ) || ( iplane > PLANE_MAX ) || ( ( 1 == iplane ) && 0 == hxy1[ixs-1][iys-1] ) || ( ( 2 == iplane ) && 0 == hxy2[ixs-1][iys-1] ) ) ) ; } int ESDetId::hashedIndex() const { const int ia ( 1 == zside() ? 2 : 1 ) ; const int ib ( plane() ) ; const int ix ( six() ) ; const int iy ( siy() ) ; const int ic ( 1 == ib ? hxy1[ ix - 1 ][ iy - 1 ] : hxy2[ ix - 1 ][ iy - 1 ] ) ; const int id ( strip() ) ; return ( ( ia - 1 )*kLb + ( ib - 1 )*kLc + ( ic - 1 )*kLd + id - 1 ) ; } ESDetId ESDetId::unhashIndex( int hi ) { if( validHashIndex( hi ) ) { const int id ( hi%kLd + 1 ) ; const int nd ( hi - id + 1 ) ; const int ic ( ( nd%kLc )/kLd + 1 ) ; const int nc ( nd - ( ic - 1 )*kLd ) ; const int ib ( ( nc%kLb )/kLc + 1 ) ; const int nb ( nc - ( ib - 1 )*kLc ) ; const int ia ( nb/kLb + 1 );// + 1 ) ; const int st ( id ) ; const int pl ( ib ) ; int ix ; int iy ; const int ic1 ( ic - 1 ) ; if( 1 == pl ) { ix = hx1[ ic1 ] ; iy = hy1[ ic1 ] ; } else { ix = hx2[ ic1 ] ; iy = hy2[ ic1 ] ; } const int iz ( 1 == ia ? -1 : 1 ) ; return ESDetId( st, ix, iy, pl, iz ) ; } else { return ESDetId() ; } } std::ostream& operator<<(std::ostream& s,const ESDetId& id) { return s << "(ES z=" << id.zside() << " plane " << id.plane() << " " << id.six() << ':' << id.siy() << " " << id.strip() << ')' << " hashIndex = "; // << id.hashedIndex() ; } const unsigned short ESDetId::hxy1[ kXMAX ][ kYMAX ] = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } , //1 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } , //2 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } , //3 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 0, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 0, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 0, 0, 0, 0, 0, 0, 0 } ,//6 { 0, 0, 0, 0, 0, 0, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 0, 0, 0, 0 } , { 0, 0, 0, 0, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 0, 0, 0, 0 } , { 0, 0, 0, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 0, 0, 0 } ,//10 { 0, 0, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 0, 0 } , { 0, 0, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 0, 0 } , { 0, 0, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 0, 0 } , { 0, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 0, 0, 0, 0, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 0 } , { 0, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 0, 0, 0, 0, 0, 0, 0, 0, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 0 } ,//15 { 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428 } , { 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456 } , { 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484 } , { 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510 } , { 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536 } , { 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562 } , { 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588 } , { 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616 } , { 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644 } , { 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674 } , { 0, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 0, 0, 0, 0, 0, 0, 0, 0, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 0 } , { 0, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 0, 0, 0, 0, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 0 } , { 0, 0, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 0, 0 } , { 0, 0, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 0, 0 } , { 0, 0, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 0, 0 } , { 0, 0, 0, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 0, 0, 0 } , { 0, 0, 0, 0, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 0, 0, 0, 0 } , { 0, 0, 0, 0, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 0, 999, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 0, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 0, 0, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; const unsigned short ESDetId::hxy2[ kXMAX ][ kYMAX ] = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 0, 0, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 0, 0, 0, 0 } , { 0, 0, 0, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 0, 0, 0 } , { 0, 0, 0, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 0, 0, 0 } , { 0, 0, 0, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 0, 0, 0 } , { 0, 0, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 0, 0 } , { 0, 0, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 0, 0, 0, 0, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 0, 0 } , { 0, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 0, 0, 0, 0, 0, 0, 0, 0, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 0 } , { 0, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 0 } , { 0, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 0 } , { 0, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 0 } , { 0, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 0 } , { 0, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 0 } , { 0, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 0 } , { 0, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 0 } , { 0, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 0 } , { 0, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 0 } , { 0, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 0 } , { 0, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 0, 0, 0, 0, 0, 0, 0, 0, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 0 } , { 0, 0, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 0, 0, 0, 0, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 0, 0 } , { 0, 0, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 0, 0 } , { 0, 0, 0, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 0, 0, 0 } , { 0, 0, 0, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 0, 0, 0 } , { 0, 0, 0, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 0, 0, 0 } , { 0, 0, 0, 0, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 0, 0, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } , { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; const unsigned short ESDetId::hx1[ kXYMAX ] = { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39 }; const unsigned short ESDetId::hy1[ kXYMAX ] = { 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 }; const unsigned short ESDetId::hx2[ kXYMAX ] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40 }; const unsigned short ESDetId::hy2[ kXYMAX ] = { 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 };
copasi/copasi-dependencies
src/libSBML/src/sbml/packages/render/util/RenderUtilities.h
<filename>src/libSBML/src/sbml/packages/render/util/RenderUtilities.h /** * @file RenderUtilities.h * @brief Definition of RenderUtilities, a class of utility functions for the render package * @author <NAME> * *<!--------------------------------------------------------------------------- * This file is part of libSBML. Please visit http://sbml.org for more * information about SBML, and the latest version of libSBML. * * Copyright (C) 2020 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. University of Heidelberg, Heidelberg, Germany * 3. University College London, London, UK * * Copyright (C) 2019 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. University of Heidelberg, Heidelberg, Germany * * Copyright (C) 2013-2018 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * 3. University of Heidelberg, Heidelberg, Germany * * Copyright (C) 2009-2013 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation. A copy of the license agreement is provided * in the file named "LICENSE.txt" included with this software distribution * and also available online as http://sbml.org/software/libsbml/license.html *------------------------------------------------------------------------- --> */ #ifndef RenderUtilities_h #define RenderUtilities_h #include <sbml/common/extern.h> #include <sbml/packages/render/common/RenderExtensionTypes.h> LIBSBML_CPP_NAMESPACE_BEGIN class ListOfLayouts; class Layout; class XMLNode; /* * This method adds a correction term to text elements from the old spec so that the text placement * is improved. */ LIBSBML_EXTERN void fixTextElements(RenderGroup* pGroup,RelAbsVector fontSize=RelAbsVector(0.0,0.0)); /* * This method adds a correction term to text elements from the old spec so that the text placement * is improved. */ LIBSBML_EXTERN void fixTextElements(RenderInformationBase* pRenderInfo); /* * This method adds a correction term to text elements from the old spec so that the text placement * is improved. */ LIBSBML_EXTERN void fixTextElements(LocalRenderInformation* pRenderInfo); /* * This method adds a correction term to text elements from the old spec so that the text placement * is improved. */ LIBSBML_EXTERN void fixTextElements(GlobalRenderInformation* pRenderInfo); /* * takes an annotation that has been read into the model * identifies the listOfLayouts element and creates a List of * Layouts from the annotation */ LIBSBML_EXTERN void parseGlobalRenderAnnotation(XMLNode * annotation, ListOfLayouts* pLOL); /* * Takes an XMLNode and tries to find the render information annotation node and deletes it if it was found. */ LIBSBML_EXTERN XMLNode* deleteGlobalRenderAnnotation(XMLNode* pAnnotation); /* * Creates an XMLNode that represents the layouts of the model from the given Model object. */ LIBSBML_EXTERN XMLNode* parseGlobalRenderInformation(const ListOfLayouts* pList); LIBSBML_EXTERN XMLNode* deleteLocalRenderAnnotation(XMLNode* pAnnotation); LIBSBML_EXTERN XMLNode* parseLocalRenderInformation(const Layout* pLayout); LIBSBML_EXTERN void parseLocalRenderAnnotation(XMLNode * annotation, Layout* pLayout); LIBSBML_CPP_NAMESPACE_END #endif
flyingkraken/telebook-frontend
src/config/environment.dev.js
<reponame>flyingkraken/telebook-frontend<filename>src/config/environment.dev.js export const environment = { firebase: { apiKey: "<KEY>", authDomain: "telebook-107e4.firebaseapp.com", databaseURL: "https://telebook-107e4.firebaseio.com", projectId: "telebook-107e4", storageBucket: "telebook-107e4.appspot.com", messagingSenderId: "589435912037", appId: "1:589435912037:web:d5da8d43237cbde87aeb8c" };, settings: { enabledOAuthLogin: true, appName: 'Telebook', defaultProfileCover: 'https://firebasestorage.googleapis.com/v0/b/open-social-33d92.appspot.com/o/images%2F751145a1-9488-46fd-a97e-04018665a6d3.JPG?alt=media&token=<PASSWORD>' }, theme: { primaryColor: '#00b1b3', secondaryColor: '#4d545d' } }
Cregrant/SmaliScissors
patcher/src/main/java/com/github/cregrant/smaliscissors/engine/Regex.java
package com.github.cregrant.smaliscissors.engine; import java.util.ArrayList; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; class Regex { static ArrayList<String> matchMultiLines(Pattern readyPattern, CharSequence content, String mode) { Matcher matcher = readyPattern.matcher(content); ArrayList<String> matchedArr = new ArrayList<>(); while (matcher.find()) { for (int i = 1; i <= matcher.groupCount(); ++i) { String textMatched = matcher.group(i); switch (mode) { case "": case "rules": case "replace": matchedArr.add(textMatched); break; case "assign": matchedArr.addAll(Arrays.asList(textMatched.split("\\R"))); break; case "target": for (String str : textMatched.split("\\R")) { str = str.replace("*/*", "*"); if (Prefs.isWindows) str = str.replace("/", "\\\\"); matchedArr.add(globToRegex(str)); } break; } } } return matchedArr; } static String matchSingleLine(Pattern readyPattern, CharSequence content) { Matcher matcher = readyPattern.matcher(content); if (matcher.find()) { if (matcher.groupCount()==0) return matcher.group(0); return matcher.group(1); } return null; } static String getEndOfPath(String path) { int last; if (Prefs.isWindows) last = path.lastIndexOf('\\')+1; else last = path.lastIndexOf('/')+1; if (last == 0) return path; return path.substring(last); } private static String globToRegex(String line) { line = line.trim(); int strLen = line.length(); StringBuilder sb = new StringBuilder(strLen); boolean escaping = false; int inBraces = 0; char prevChar = 0; for (char currentChar : line.toCharArray()) { switch (currentChar) { case '*': if (escaping) sb.append("\\*"); else if (currentChar != prevChar) sb.append(".*"); escaping = false; break; case '?': if (escaping) sb.append("\\?"); else sb.append('.'); escaping = false; break; //case '.': case '(': case ')': case '+': case '|': case '^': case '$': case '@': case '%': sb.append('\\'); sb.append(currentChar); escaping = false; break; case '\\': if (escaping) { sb.append("\\\\"); escaping = false; } else escaping = true; break; case '{': if (escaping) sb.append("\\{"); else { sb.append('('); inBraces++; } escaping = false; break; case '}': if (inBraces > 0 && !escaping) { sb.append(')'); inBraces--; } else if (escaping) sb.append("\\}"); else sb.append("}"); escaping = false; break; case ',': if (inBraces > 0 && !escaping) sb.append('|'); else if (escaping) sb.append("\\,"); else sb.append(","); break; default: escaping = false; sb.append(currentChar); } prevChar = currentChar; } return sb.toString(); } }
Pixelated-Project/aosp-android-jar
android-31/src/com/android/internal/os/MemoryPowerCalculator.java
package com.android.internal.os; import android.os.BatteryConsumer; import android.os.BatteryStats; import android.os.BatteryUsageStats; import android.os.BatteryUsageStatsQuery; import android.os.UserHandle; import android.util.LongSparseArray; import android.util.SparseArray; import java.util.List; public class MemoryPowerCalculator extends PowerCalculator { public static final String TAG = "MemoryPowerCalculator"; private final UsageBasedPowerEstimator[] mPowerEstimators; public MemoryPowerCalculator(PowerProfile profile) { int numBuckets = profile.getNumElements(PowerProfile.POWER_MEMORY); mPowerEstimators = new UsageBasedPowerEstimator[numBuckets]; for (int i = 0; i < numBuckets; i++) { mPowerEstimators[i] = new UsageBasedPowerEstimator( profile.getAveragePower(PowerProfile.POWER_MEMORY, i)); } } @Override public void calculate(BatteryUsageStats.Builder builder, BatteryStats batteryStats, long rawRealtimeUs, long rawUptimeUs, BatteryUsageStatsQuery query) { final long durationMs = calculateDuration(batteryStats, rawRealtimeUs, BatteryStats.STATS_SINCE_CHARGED); final double powerMah = calculatePower(batteryStats, rawRealtimeUs, BatteryStats.STATS_SINCE_CHARGED); builder.getAggregateBatteryConsumerBuilder( BatteryUsageStats.AGGREGATE_BATTERY_CONSUMER_SCOPE_DEVICE) .setUsageDurationMillis(BatteryConsumer.POWER_COMPONENT_MEMORY, durationMs) .setConsumedPower(BatteryConsumer.POWER_COMPONENT_MEMORY, powerMah); } @Override public void calculate(List<BatterySipper> sippers, BatteryStats batteryStats, long rawRealtimeUs, long rawUptimeUs, int statsType, SparseArray<UserHandle> asUsers) { final long durationMs = calculateDuration(batteryStats, rawRealtimeUs, statsType); final double powerMah = calculatePower(batteryStats, rawRealtimeUs, statsType); BatterySipper memory = new BatterySipper(BatterySipper.DrainType.MEMORY, null, 0); memory.usageTimeMs = durationMs; memory.usagePowerMah = powerMah; memory.sumPower(); if (memory.totalPowerMah > 0) { sippers.add(memory); } } private long calculateDuration(BatteryStats batteryStats, long rawRealtimeUs, int statsType) { long usageDurationMs = 0; LongSparseArray<? extends BatteryStats.Timer> timers = batteryStats.getKernelMemoryStats(); for (int i = 0; i < timers.size() && i < mPowerEstimators.length; i++) { usageDurationMs += mPowerEstimators[i].calculateDuration(timers.valueAt(i), rawRealtimeUs, statsType); } return usageDurationMs; } private double calculatePower(BatteryStats batteryStats, long rawRealtimeUs, int statsType) { double powerMah = 0; LongSparseArray<? extends BatteryStats.Timer> timers = batteryStats.getKernelMemoryStats(); for (int i = 0; i < timers.size() && i < mPowerEstimators.length; i++) { UsageBasedPowerEstimator estimator = mPowerEstimators[(int) timers.keyAt(i)]; final long usageDurationMs = estimator.calculateDuration(timers.valueAt(i), rawRealtimeUs, statsType); powerMah += estimator.calculatePower(usageDurationMs); } return powerMah; } }
AdilIqbal95/Career_App
react-client/src/temp_data.js
<gh_stars>0 const data = [ { Company: "Noodles4Poodles Inc.", Role: "Junior Noodle Farmer", Description: "We need somone to farm noodles for poodles with 5 years noodle consumption experience and Owns a poodle" }, { Company: "HungryFor.app.les", Role: "Frontend Developer", Description: "Looking for a experieced developer to handle development of our new website! Require 10 years React experience and must be hungry for apples" } ] module.exports = data;
yuanboshe/Nebula
src/actor/context/Context.cpp
/******************************************************************************* * Project: Nebula * @file Context.cpp * @brief * @author Bwar * @date: 2019年2月16日 * @note * Modify history: ******************************************************************************/ #include "Context.hpp" namespace neb { Context::Context() : Actor(ACT_CONTEXT, gc_dNoTimeout), m_pChannel(nullptr) { } Context::Context(std::shared_ptr<SocketChannel> pChannel) : Actor(ACT_CONTEXT, gc_dNoTimeout), m_pChannel(pChannel) { } Context::~Context() { } } /* namespace neb */
haohaibo/learn
C++/Cpp-Concurrency-in-Action/listing_7.19.cpp
template <typename T> class lock_free_queue { private: static void free_external_counter(counted_node_ptr& old_node_ptr) { node* const ptr = old_node_ptr.ptr; int const count_increase = old_node_ptr.external_count - 2; node_counter old_counter = ptr->count.load(std::memory_order_relaxed); node_counter new_counter; do { new_counter = old_counter; --new_counter.external_counters; new_counter.internal_count += count_increase; } while (!ptr->count.compare_exchange_strong(old_counter, new_counter, std::memory_order_acquire, std::memory_order_relaxed)); if (!new_counter.internal_count && !new_counter.external_counters) { delete ptr; } } };
ht1131589588/react-ssr
client/index.js
import React from 'react' import ReactDom from 'react-dom' import { BrowserRouter, Route, Switch } from 'react-router-dom' import { Provider } from 'react-redux' import routes from '../src/App' import Header from '../src/components/Header' import { getClientStore } from '../src/store' const Root = ( <Provider store={getClientStore()}> <BrowserRouter> <Header /> <Switch> {routes.map(route => ( <Route {...route} /> ))} </Switch> </BrowserRouter> </Provider> ) if (window.__context) { ReactDom.hydrate(Root, document.getElementById('root')) } else { ReactDom.render(Root, document.getElementById('root')) }
seedhartha/revan
src/scene/node.h
/* * Copyright (c) 2020-2022 The reone project contributors * * 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 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include "../graphics/aabb.h" #include "types.h" namespace reone { namespace graphics { struct GraphicsServices; } namespace audio { struct AudioServices; } namespace scene { class IUser; class SceneGraph; class SceneNode : boost::noncopyable { public: void addChild(SceneNode &node); void removeChild(SceneNode &node); void removeAllChildren(); virtual void update(float dt); virtual void drawLeafs(const std::vector<SceneNode *> &leafs) { } bool isEnabled() const { return _enabled; } bool isCullable() const { return _cullable; } bool isCulled() const { return _culled; } bool isPoint() const { return _point; } glm::vec3 getOrigin() const; glm::vec2 getOrigin2D() const; float getDistanceTo(const glm::vec3 &point) const; float getDistanceTo(const SceneNode &other) const; float getSquareDistanceTo(const glm::vec3 &point) const; float getSquareDistanceTo(const SceneNode &other) const; float getSquareDistanceTo2D(const glm::vec2 &point) const; glm::vec3 getWorldCenterOfAABB() const; SceneNodeType type() const { return _type; } SceneNode *parent() { return _parent; } const SceneNode *parent() const { return _parent; } const std::unordered_set<SceneNode *> &children() const { return _children; } const graphics::AABB &aabb() const { return _aabb; } IUser *user() { return _user; } const IUser *user() const { return _user; } void setUser(IUser &user) { _user = &user; } // Flags void setEnabled(bool enabled) { _enabled = enabled; } void setCullable(bool cullable) { _cullable = cullable; } void setCulled(bool culled) { _culled = culled; } // END Flags // Transformations const glm::mat4 &localTransform() const { return _localTransform; } const glm::mat4 &absoluteTransform() const { return _absTransform; } const glm::mat4 &absoluteTransformInverse() const { return _absTransformInv; } void setLocalTransform(glm::mat4 transform); // END Transformations protected: SceneNodeType _type; SceneGraph &_sceneGraph; graphics::GraphicsServices &_graphicsSvc; audio::AudioServices &_audioSvc; SceneNode *_parent {nullptr}; std::unordered_set<SceneNode *> _children; graphics::AABB _aabb; IUser *_user {nullptr}; // Flags bool _enabled {true}; bool _cullable {false}; /**< can this node be frustum- or distance-culled? */ bool _culled {false}; /**< has this node been frustum- or distance-culled? */ bool _point {true}; /**< is this node represented by a single point? */ // END Flags // Transformations glm::mat4 _localTransform {1.0f}; glm::mat4 _absTransform {1.0f}; glm::mat4 _absTransformInv {1.0f}; // END Transformations SceneNode( SceneNodeType type, SceneGraph &sceneGraph, graphics::GraphicsServices &graphicsSvc, audio::AudioServices &audioSvc) : _type(type), _sceneGraph(sceneGraph), _graphicsSvc(graphicsSvc), _audioSvc(audioSvc) { } void computeAbsoluteTransforms(); virtual void onAbsoluteTransformChanged() {} }; } // namespace scene } // namespace reone
iamhi/on-path-fe
externalcontent.config.js
module.exports = { source: "http://localhost:3002/public/hi-zone-fe/content/", destination: './dist/assets/content/', files: [ { filename: "about-content.json", }, { filename: "application-content.json", }, { filename: "current-focus-content.json", }, { filename: "social-media-content.json", }, { filename: "spotify-content.json", }, ], };
IsraelyFlightSimulator/Negev-Storm
SOURCES/ui/include/te_include.h
#define TACTICAL_GROUP 3000
XYGDeveloper/GlobalFrog
Common/Global/CZCountDownView.h
<reponame>XYGDeveloper/GlobalFrog // // CZCountDownView.h // countDownDemo // // Created by 孔凡列 on 15/12/9. // Copyright © 2015年 czebd. All rights reserved. // #import <UIKit/UIKit.h> typedef void(^TimerStopBlock)(); @interface CZCountDownView : UIView // 时间戳 @property (nonatomic,assign)NSInteger timestamp; // 背景 @property (nonatomic,copy)NSString *leftTitle; // 时间停止后回调 @property (nonatomic,copy)TimerStopBlock timerStopBlock; /** * 创建单例对象 */ + (instancetype)cz_shareCountDown;// 工程中使用的倒计时是唯一的 /** * 创建非单例对象 */ + (instancetype)cz_countDown; // 工程中倒计时不是唯一的 @end
hugmyndakassi/ghidra-kaiju
src/main/java/kaiju/tools/ghihorn/display/GhiHornController.java
<filename>src/main/java/kaiju/tools/ghihorn/display/GhiHornController.java package kaiju.tools.ghihorn.display; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.beans.PropertyChangeEvent; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.border.BevelBorder; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import com.google.common.base.VerifyException; import ghidra.program.model.address.Address; import ghidra.util.Msg; import kaiju.tools.ghihorn.GhiHornPlugin; import kaiju.tools.ghihorn.GhiHornifierBuilder; import kaiju.tools.ghihorn.answer.format.GhiHornDisplaySettings; import kaiju.tools.ghihorn.answer.format.GhiHornOutputFormatter; import kaiju.tools.ghihorn.cmd.GhiHornCommand; import kaiju.tools.ghihorn.cmd.GhiHornCommandListener; import kaiju.tools.ghihorn.decompiler.GhiHornParallelDecompiler; import kaiju.tools.ghihorn.display.graph.GhiHornAnswerGraphComponent; import kaiju.tools.ghihorn.hornifer.GhiHornCommandEvent; import kaiju.tools.ghihorn.hornifer.GhiHornifier; import kaiju.tools.ghihorn.hornifer.horn.GhiHornAnswer; import kaiju.tools.ghihorn.z3.GhiHornFixedpointStatus; import kaiju.tools.ghihorn.z3.GhiHornZ3Parameters; /** * Common properties for Horn displays */ public abstract class GhiHornController implements GhiHornCommandListener { protected final GhiHornPlugin plugin; protected Address entryPointAddress; private GhiHornAnswer currentResult; private final String name; private Map<GhiHornCommandEvent, String> eventConfig; private GhiHornZ3Parameters z3Params; // The IDs for properties all displays must handle protected String updateMessageID; protected String terminateMessageID; protected String resultMessageID; protected Set<GhiHornCommand> cmdList; protected GhiHornDisplaySettings displaySettings; protected GhiHornController(final String n, final GhiHornPlugin p) { this.name = n; this.plugin = p; this.displaySettings = new GhiHornDisplaySettings(); this.eventConfig = new HashMap<>(); this.cmdList = ConcurrentHashMap.newKeySet(); this.entryPointAddress = Address.NO_ADDRESS; // Initialize specific tools initialize(); } @Override public Map<GhiHornCommandEvent, String> getCommandEvents() { return this.eventConfig; } @Override public void registerCommandEvent(final String id, final GhiHornCommandEvent evt) { eventConfig.put(evt, id); } /** * @param displaySettings the displaySettings to set */ public void setDisplaySettings(GhiHornDisplaySettings displaySettings) { this.displaySettings = displaySettings; } public String getName() { return name; } /** * Receive events from the ApiAnalyzer commands, either log or output */ @Override public void propertyChange(PropertyChangeEvent evt) { final String propName = evt.getPropertyName(); if (propName.equalsIgnoreCase(eventConfig.get(GhiHornCommandEvent.StatusMessage))) { String update = (String) evt.getNewValue(); status(update); } else if (propName.equalsIgnoreCase(eventConfig.get(GhiHornCommandEvent.Completed))) { GhiHornCommand endedCmd = (GhiHornCommand) evt.getNewValue(); cmdList.remove(endedCmd); // If there are no further commands to process, then terminate if (cmdList.isEmpty()) { this.plugin.getProvider().endAnalysis(false); status(getControllerName() + " completed."); } } else if (propName.equalsIgnoreCase(eventConfig.get(GhiHornCommandEvent.Cancelled))) { GhiHornCommand endedCmd = (GhiHornCommand) evt.getNewValue(); cmdList.remove(endedCmd); // If there are no further commands to process, then terminate if (cmdList.isEmpty()) { this.plugin.getProvider().endAnalysis(false); this.plugin.cancel(); status(getControllerName() + " completed."); } } else if (propName.equalsIgnoreCase(eventConfig.get(GhiHornCommandEvent.ResultReady))) { this.currentResult = (GhiHornAnswer) evt.getNewValue(); result(currentResult); } else { Msg.info(this, "Unknown event received: " + propName); } } /** * Present the results as a graph * * @param newGraph * @param mon * @return */ protected JPanel installAnswerAsGraph(final GhiHornAnswer result) throws Exception { GhiHornAnswerGraphComponent graph = new GhiHornAnswerGraphComponent(plugin, result.answerGraph); if (displaySettings == null) { displaySettings = new GhiHornDisplaySettings(); } graph.build(displaySettings); return graph.getComponent(); } /** * Install the result as text * * @param result * @return * @throws Exception */ protected JPanel installResultsAsText(final GhiHornAnswer result) throws Exception { JTextPane textPane = new JTextPane(); SimpleAttributeSet attributeSet = new SimpleAttributeSet(); Font font = new Font("Monospaced", Font.BOLD, 12); textPane.setFont(font); if (result.status == GhiHornFixedpointStatus.Satisfiable) { StyleConstants.setForeground(attributeSet, Color.blue); } else if (result.status == GhiHornFixedpointStatus.Unsatisfiable) { StyleConstants.setForeground(attributeSet, Color.red); } textPane.setCharacterAttributes(attributeSet, true); if (result.answerGraph != null) { String graphTxt = result.answerGraph.format(GhiHornOutputFormatter.create(displaySettings)); textPane.setText(graphTxt); } return new JPanel(new BorderLayout()) { { setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); add(new JScrollPane(textPane), BorderLayout.CENTER); } }; } public void refresh() { result(currentResult); } public boolean executeCommands() throws Exception { reset(); List<Map<String, Object>> cmdParametersList = getCommandParameters(); final GhiHornParallelDecompiler parallelDecompiler = new GhiHornParallelDecompiler(this.plugin.getTool()); for (Map<String, Object> parameters : cmdParametersList) { try { GhiHornifierBuilder hornBuilder = new GhiHornifierBuilder(getName()) .withDecompiler(parallelDecompiler) .withApiDatabase(plugin.getApiDatabase()) .withEntryPoint(entryPointAddress) .withZ3Params(z3Params) .withParameters(parameters); GhiHornifier hornifier = hornBuilder.build(); GhiHornCommand cmd = new GhiHornCommand(name, hornifier); cmd.addCommandListener(this); // Each command gets it's own hornifier to simplify threading issues plugin.execute(cmd); cmdList.add(cmd); } catch (VerifyException ve) { status("Improperly configured command"); return false; } catch (Exception e) { e.printStackTrace(); } } // True if any commands are executing return !cmdList.isEmpty(); } public void setEntryPoint(Address entryAddress) { this.entryPointAddress = entryAddress; } public void addZ3Parameters(GhiHornZ3Parameters z3Params) { if (z3Params != null) { this.z3Params = z3Params; } } /////////////////////////////////////////////////////////////////////////////////////////////// //// //// The API that specifc tools must implement //// /////////////////////////////////////////////////////////////////////////////////////////////// public abstract void initialize(); public abstract List<Map<String, Object>> getCommandParameters() throws Exception; public abstract void enable(); public abstract void disable(); public abstract void result(GhiHornAnswer result); public abstract void status(String message); public abstract List<GhiHornAnswer> getResults(boolean includeErrors); public abstract void reset(); public abstract JComponent getMainComponent(); public abstract String getControllerName(); public abstract GhiHornifier getHornifiier(); }
kyowill/hbase-0.1
src/java/org/apache/hadoop/hbase/hql/generated/HQLParserTokenManager.java
/* Generated By:JavaCC: Do not edit this line. HQLParserTokenManager.java */ package org.apache.hadoop.hbase.hql.generated; /** * Copyright 2007 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; import java.io.StringReader; import java.io.Reader; import java.io.Writer; import java.net.URLEncoder; import java.io.UnsupportedEncodingException; import org.apache.hadoop.hbase.hql.*; public class HQLParserTokenManager implements HQLParserConstants { public java.io.PrintStream debugStream = System.out; public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; } private final int jjStopStringLiteralDfa_0(int pos, long active0, long active1) { switch (pos) { case 0: if ((active0 & 0x3fffcc0fffffffe0L) != 0L) { jjmatchedKind = 62; return 1; } return -1; case 1: if ((active0 & 0x3fefc407fff9bfe0L) != 0L) { if (jjmatchedPos != 1) { jjmatchedKind = 62; jjmatchedPos = 1; } return 1; } if ((active0 & 0x10080800064000L) != 0L) return 1; return -1; case 2: if ((active0 & 0x37ffc003efff3fe0L) != 0L) { jjmatchedKind = 62; jjmatchedPos = 2; return 1; } if ((active0 & 0x800040410008000L) != 0L) return 1; return -1; case 3: if ((active0 & 0x37fdc003ebfa28c0L) != 0L) { if (jjmatchedPos != 3) { jjmatchedKind = 62; jjmatchedPos = 3; } return 1; } if ((active0 & 0x2000004051720L) != 0L) return 1; return -1; case 4: if ((active0 & 0x17b9c001e1f22a00L) != 0L) { if (jjmatchedPos != 4) { jjmatchedKind = 62; jjmatchedPos = 4; } return 1; } if ((active0 & 0x204400020a0800c0L) != 0L) return 1; return -1; case 5: if ((active0 & 0x1008000020720800L) != 0L) return 1; if ((active0 & 0x7f1c001c1802200L) != 0L) { jjmatchedKind = 62; jjmatchedPos = 5; return 1; } return -1; case 6: if ((active0 & 0x800000L) != 0L) return 1; if ((active0 & 0x7f1c001c1002200L) != 0L) { jjmatchedKind = 62; jjmatchedPos = 6; return 1; } return -1; case 7: if ((active0 & 0x200000001002200L) != 0L) return 1; if ((active0 & 0x5f1c001c0000000L) != 0L) { jjmatchedKind = 62; jjmatchedPos = 7; return 1; } return -1; case 8: if ((active0 & 0x10000080000000L) != 0L) return 1; if ((active0 & 0x5e1c00140000000L) != 0L) { jjmatchedKind = 62; jjmatchedPos = 8; return 1; } return -1; case 9: if ((active0 & 0x800000000000L) != 0L) return 1; if ((active0 & 0x5e1400140000000L) != 0L) { jjmatchedKind = 62; jjmatchedPos = 9; return 1; } return -1; case 10: if ((active0 & 0x521000000000000L) != 0L) return 1; if ((active0 & 0xc0400140000000L) != 0L) { jjmatchedKind = 62; jjmatchedPos = 10; return 1; } return -1; case 11: if ((active0 & 0x400100000000L) != 0L) return 1; if ((active0 & 0xc0000040000000L) != 0L) { jjmatchedKind = 62; jjmatchedPos = 11; return 1; } return -1; case 12: if ((active0 & 0xc0000040000000L) != 0L) { jjmatchedKind = 62; jjmatchedPos = 12; return 1; } return -1; case 13: if ((active0 & 0x40000000L) != 0L) return 1; if ((active0 & 0xc0000000000000L) != 0L) { jjmatchedKind = 62; jjmatchedPos = 13; return 1; } return -1; case 14: if ((active0 & 0xc0000000000000L) != 0L) { jjmatchedKind = 62; jjmatchedPos = 14; return 1; } return -1; case 15: if ((active0 & 0xc0000000000000L) != 0L) { jjmatchedKind = 62; jjmatchedPos = 15; return 1; } return -1; case 16: if ((active0 & 0xc0000000000000L) != 0L) { jjmatchedKind = 62; jjmatchedPos = 16; return 1; } return -1; case 17: if ((active0 & 0xc0000000000000L) != 0L) { jjmatchedKind = 62; jjmatchedPos = 17; return 1; } return -1; case 18: if ((active0 & 0xc0000000000000L) != 0L) { jjmatchedKind = 62; jjmatchedPos = 18; return 1; } return -1; case 19: if ((active0 & 0x80000000000000L) != 0L) { jjmatchedKind = 62; jjmatchedPos = 19; return 1; } if ((active0 & 0x40000000000000L) != 0L) return 1; return -1; default : return -1; } } private final int jjStartNfa_0(int pos, long active0, long active1) { return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0, active1), pos + 1); } private final int jjStopAtPos(int pos, int kind) { jjmatchedKind = kind; jjmatchedPos = pos; return pos + 1; } private final int jjStartNfaWithStates_0(int pos, int kind, int state) { jjmatchedKind = kind; jjmatchedPos = pos; try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return pos + 1; } return jjMoveNfa_0(state, pos + 1); } private final int jjMoveStringLiteralDfa0_0() { switch(curChar) { case 33: return jjMoveStringLiteralDfa1_0(0x100000000000L); case 40: return jjStopAtPos(0, 37); case 41: return jjStopAtPos(0, 38); case 42: return jjStopAtPos(0, 45); case 44: return jjStopAtPos(0, 36); case 59: return jjStopAtPos(0, 68); case 60: return jjStopAtPos(0, 41); case 61: return jjStopAtPos(0, 39); case 62: return jjStopAtPos(0, 40); case 65: case 97: return jjMoveStringLiteralDfa1_0(0x800000400000040L); case 66: case 98: return jjMoveStringLiteralDfa1_0(0x24000000000000L); case 67: case 99: return jjMoveStringLiteralDfa1_0(0x3041000040000880L); case 68: case 100: return jjMoveStringLiteralDfa1_0(0x901600L); case 69: case 101: return jjMoveStringLiteralDfa1_0(0x410000L); case 70: case 102: return jjMoveStringLiteralDfa1_0(0x4004000L); case 72: case 104: return jjMoveStringLiteralDfa1_0(0x20L); case 73: case 105: return jjMoveStringLiteralDfa1_0(0x10080000060000L); case 74: case 106: return jjMoveStringLiteralDfa1_0(0x8000L); case 76: case 108: return jjMoveStringLiteralDfa1_0(0x200000000L); case 77: case 109: return jjMoveStringLiteralDfa1_0(0xc00000000000L); case 78: case 110: return jjMoveStringLiteralDfa1_0(0x602040100000000L); case 79: case 111: return jjMoveStringLiteralDfa1_0(0x800000000L); case 82: case 114: return jjMoveStringLiteralDfa1_0(0x88000010000000L); case 83: case 115: return jjMoveStringLiteralDfa1_0(0x1200100L); case 84: case 116: return jjMoveStringLiteralDfa1_0(0x80082000L); case 85: case 117: return jjMoveStringLiteralDfa1_0(0x8000000L); case 86: case 118: return jjMoveStringLiteralDfa1_0(0x100000020000000L); case 87: case 119: return jjMoveStringLiteralDfa1_0(0x2000000L); default : return jjMoveNfa_0(0, 0); } } private final int jjMoveStringLiteralDfa1_0(long active0) { try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(0, active0, 0L); return 1; } switch(curChar) { case 61: if ((active0 & 0x100000000000L) != 0L) return jjStopAtPos(1, 44); break; case 65: case 97: return jjMoveStringLiteralDfa2_0(active0, 0xc00020088000L); case 68: case 100: return jjMoveStringLiteralDfa2_0(active0, 0x800000000000000L); case 69: case 101: return jjMoveStringLiteralDfa2_0(active0, 0x188000000300620L); case 72: case 104: return jjMoveStringLiteralDfa2_0(active0, 0x1000000002000100L); case 73: case 105: return jjMoveStringLiteralDfa2_0(active0, 0x280800000L); case 76: case 108: return jjMoveStringLiteralDfa2_0(active0, 0x240000000000c0L); case 78: case 110: if ((active0 & 0x80000000000L) != 0L) { jjmatchedKind = 43; jjmatchedPos = 1; } return jjMoveStringLiteralDfa2_0(active0, 0x10000408460000L); case 79: case 111: return jjMoveStringLiteralDfa2_0(active0, 0x2043040050000000L); case 82: case 114: if ((active0 & 0x800000000L) != 0L) return jjStartNfaWithStates_0(1, 35, 1); return jjMoveStringLiteralDfa2_0(active0, 0x4003800L); case 83: case 115: if ((active0 & 0x4000L) != 0L) return jjStartNfaWithStates_0(1, 14, 1); break; case 84: case 116: return jjMoveStringLiteralDfa2_0(active0, 0x1000000L); case 85: case 117: return jjMoveStringLiteralDfa2_0(active0, 0x600000100000000L); case 88: case 120: return jjMoveStringLiteralDfa2_0(active0, 0x10000L); default : break; } return jjStartNfa_0(0, active0, 0L); } private final int jjMoveStringLiteralDfa2_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(0, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(1, active0, 0L); return 2; } switch(curChar) { case 95: return jjMoveStringLiteralDfa3_0(active0, 0x10000000000000L); case 65: case 97: return jjMoveStringLiteralDfa3_0(active0, 0x1000000001400000L); case 66: case 98: return jjMoveStringLiteralDfa3_0(active0, 0x80000L); case 67: case 99: return jjMoveStringLiteralDfa3_0(active0, 0x108000000000000L); case 68: case 100: if ((active0 & 0x400000000L) != 0L) return jjStartNfaWithStates_0(2, 34, 1); else if ((active0 & 0x800000000000000L) != 0L) return jjStartNfaWithStates_0(2, 59, 1); break; case 69: case 101: return jjMoveStringLiteralDfa3_0(active0, 0x2000880L); case 73: case 105: return jjMoveStringLiteralDfa3_0(active0, 0x10000L); case 76: case 108: return jjMoveStringLiteralDfa3_0(active0, 0x60300020L); case 77: case 109: return jjMoveStringLiteralDfa3_0(active0, 0x601000380000000L); case 78: case 110: return jjMoveStringLiteralDfa3_0(active0, 0x2000000000000L); case 79: case 111: return jjMoveStringLiteralDfa3_0(active0, 0x24000004001100L); case 82: case 114: if ((active0 & 0x8000L) != 0L) return jjStartNfaWithStates_0(2, 15, 1); break; case 83: case 115: return jjMoveStringLiteralDfa3_0(active0, 0x820600L); case 84: case 116: if ((active0 & 0x40000000000L) != 0L) return jjStartNfaWithStates_0(2, 42, 1); return jjMoveStringLiteralDfa3_0(active0, 0x80000008040040L); case 85: case 117: return jjMoveStringLiteralDfa3_0(active0, 0x2040000000002000L); case 87: case 119: if ((active0 & 0x10000000L) != 0L) return jjStartNfaWithStates_0(2, 28, 1); break; case 88: case 120: return jjMoveStringLiteralDfa3_0(active0, 0xc00000000000L); default : break; } return jjStartNfa_0(1, active0, 0L); } private final int jjMoveStringLiteralDfa3_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(1, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(2, active0, 0L); return 3; } switch(curChar) { case 95: return jjMoveStringLiteralDfa4_0(active0, 0x600c00100000000L); case 65: case 97: return jjMoveStringLiteralDfa4_0(active0, 0x800880L); case 66: case 98: return jjMoveStringLiteralDfa4_0(active0, 0x400000L); case 67: case 99: if ((active0 & 0x400L) != 0L) { jjmatchedKind = 10; jjmatchedPos = 3; } return jjMoveStringLiteralDfa4_0(active0, 0x4000000000200L); case 69: case 101: if ((active0 & 0x2000000000000L) != 0L) return jjStartNfaWithStates_0(3, 49, 1); return jjMoveStringLiteralDfa4_0(active0, 0x80320040L); case 73: case 105: return jjMoveStringLiteralDfa4_0(active0, 0x208000000L); case 76: case 108: return jjMoveStringLiteralDfa4_0(active0, 0x80000L); case 77: case 109: if ((active0 & 0x4000000L) != 0L) return jjStartNfaWithStates_0(3, 26, 1); return jjMoveStringLiteralDfa4_0(active0, 0x10000000000000L); case 78: case 110: return jjMoveStringLiteralDfa4_0(active0, 0x3040000000002000L); case 79: case 111: if ((active0 & 0x40000L) != 0L) return jjStartNfaWithStates_0(3, 18, 1); return jjMoveStringLiteralDfa4_0(active0, 0xa8000000000000L); case 80: case 112: if ((active0 & 0x20L) != 0L) return jjStartNfaWithStates_0(3, 5, 1); else if ((active0 & 0x1000L) != 0L) return jjStartNfaWithStates_0(3, 12, 1); return jjMoveStringLiteralDfa4_0(active0, 0x1000000000000L); case 82: case 114: return jjMoveStringLiteralDfa4_0(active0, 0x3000000L); case 84: case 116: if ((active0 & 0x10000L) != 0L) return jjStartNfaWithStates_0(3, 16, 1); return jjMoveStringLiteralDfa4_0(active0, 0x100000000000000L); case 85: case 117: return jjMoveStringLiteralDfa4_0(active0, 0x60000000L); case 87: case 119: if ((active0 & 0x100L) != 0L) return jjStartNfaWithStates_0(3, 8, 1); break; default : break; } return jjStartNfa_0(2, active0, 0L); } private final int jjMoveStringLiteralDfa4_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(2, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(3, active0, 0L); return 4; } switch(curChar) { case 66: case 98: return jjMoveStringLiteralDfa5_0(active0, 0x800000L); case 67: case 99: return jjMoveStringLiteralDfa5_0(active0, 0x202000L); case 69: case 101: if ((active0 & 0x80000L) != 0L) return jjStartNfaWithStates_0(4, 19, 1); else if ((active0 & 0x2000000L) != 0L) return jjStartNfaWithStates_0(4, 25, 1); return jjMoveStringLiteralDfa5_0(active0, 0x410000020000000L); case 71: case 103: return jjMoveStringLiteralDfa5_0(active0, 0x1000000000000000L); case 72: case 104: return jjMoveStringLiteralDfa5_0(active0, 0x200000000000000L); case 75: case 107: if ((active0 & 0x4000000000000L) != 0L) return jjStartNfaWithStates_0(4, 50, 1); break; case 76: case 108: if ((active0 & 0x8000000L) != 0L) return jjStartNfaWithStates_0(4, 27, 1); return jjMoveStringLiteralDfa5_0(active0, 0x800000400000L); case 77: case 109: return jjMoveStringLiteralDfa5_0(active0, 0x20000040000000L); case 79: case 111: return jjMoveStringLiteralDfa5_0(active0, 0x100000000000000L); case 82: case 114: if ((active0 & 0x40L) != 0L) return jjStartNfaWithStates_0(4, 6, 1); else if ((active0 & 0x80L) != 0L) return jjStartNfaWithStates_0(4, 7, 1); return jjMoveStringLiteralDfa5_0(active0, 0x9000000020200L); case 83: case 115: return jjMoveStringLiteralDfa5_0(active0, 0x80000000L); case 84: case 116: if ((active0 & 0x200000000L) != 0L) return jjStartNfaWithStates_0(4, 33, 1); else if ((active0 & 0x2000000000000000L) != 0L) { jjmatchedKind = 61; jjmatchedPos = 4; } return jjMoveStringLiteralDfa5_0(active0, 0x40000001100800L); case 85: case 117: return jjMoveStringLiteralDfa5_0(active0, 0x80000000000000L); case 86: case 118: return jjMoveStringLiteralDfa5_0(active0, 0x400100000000L); default : break; } return jjStartNfa_0(3, active0, 0L); } private final int jjMoveStringLiteralDfa5_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(3, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(4, active0, 0L); return 5; } switch(curChar) { case 65: case 97: return jjMoveStringLiteralDfa6_0(active0, 0x200000000002000L); case 67: case 99: return jjMoveStringLiteralDfa6_0(active0, 0x80000000000000L); case 68: case 100: if ((active0 & 0x8000000000000L) != 0L) return jjStartNfaWithStates_0(5, 51, 1); break; case 69: case 101: if ((active0 & 0x800L) != 0L) return jjStartNfaWithStates_0(5, 11, 1); else if ((active0 & 0x100000L) != 0L) return jjStartNfaWithStates_0(5, 20, 1); else if ((active0 & 0x400000L) != 0L) return jjStartNfaWithStates_0(5, 22, 1); else if ((active0 & 0x1000000000000000L) != 0L) return jjStartNfaWithStates_0(5, 60, 1); return jjMoveStringLiteralDfa6_0(active0, 0x1c00100000000L); case 70: case 102: return jjMoveStringLiteralDfa6_0(active0, 0x20000000000000L); case 73: case 105: return jjMoveStringLiteralDfa6_0(active0, 0x40000001000200L); case 76: case 108: return jjMoveStringLiteralDfa6_0(active0, 0x800000L); case 77: case 109: return jjMoveStringLiteralDfa6_0(active0, 0x10000000000000L); case 78: case 110: return jjMoveStringLiteralDfa6_0(active0, 0x400000040000000L); case 82: case 114: return jjMoveStringLiteralDfa6_0(active0, 0x100000000000000L); case 83: case 115: if ((active0 & 0x20000000L) != 0L) return jjStartNfaWithStates_0(5, 29, 1); break; case 84: case 116: if ((active0 & 0x20000L) != 0L) return jjStartNfaWithStates_0(5, 17, 1); else if ((active0 & 0x200000L) != 0L) return jjStartNfaWithStates_0(5, 21, 1); return jjMoveStringLiteralDfa6_0(active0, 0x80000000L); default : break; } return jjStartNfa_0(4, active0, 0L); } private final int jjMoveStringLiteralDfa6_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(4, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(5, active0, 0L); return 6; } switch(curChar) { case 95: return jjMoveStringLiteralDfa7_0(active0, 0x100000000000000L); case 65: case 97: return jjMoveStringLiteralDfa7_0(active0, 0x80000000L); case 66: case 98: return jjMoveStringLiteralDfa7_0(active0, 0x200L); case 69: case 101: if ((active0 & 0x800000L) != 0L) return jjStartNfaWithStates_0(6, 23, 1); break; case 70: case 102: return jjMoveStringLiteralDfa7_0(active0, 0x40000000L); case 72: case 104: return jjMoveStringLiteralDfa7_0(active0, 0x80000000000000L); case 73: case 105: return jjMoveStringLiteralDfa7_0(active0, 0x20000000000000L); case 78: case 110: return jjMoveStringLiteralDfa7_0(active0, 0x40800001000000L); case 79: case 111: return jjMoveStringLiteralDfa7_0(active0, 0x10000000000000L); case 82: case 114: return jjMoveStringLiteralDfa7_0(active0, 0x400100000000L); case 83: case 115: return jjMoveStringLiteralDfa7_0(active0, 0x201000000000000L); case 84: case 116: return jjMoveStringLiteralDfa7_0(active0, 0x400000000002000L); default : break; } return jjStartNfa_0(5, active0, 0L); } private final int jjMoveStringLiteralDfa7_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(5, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(6, active0, 0L); return 7; } switch(curChar) { case 65: case 97: return jjMoveStringLiteralDfa8_0(active0, 0x40000000L); case 69: case 101: if ((active0 & 0x200L) != 0L) return jjStartNfaWithStates_0(7, 9, 1); else if ((active0 & 0x2000L) != 0L) return jjStartNfaWithStates_0(7, 13, 1); return jjMoveStringLiteralDfa8_0(active0, 0x80000000000000L); case 71: case 103: if ((active0 & 0x1000000L) != 0L) return jjStartNfaWithStates_0(7, 24, 1); return jjMoveStringLiteralDfa8_0(active0, 0x40800000000000L); case 72: case 104: if ((active0 & 0x200000000000000L) != 0L) return jjStartNfaWithStates_0(7, 57, 1); break; case 76: case 108: return jjMoveStringLiteralDfa8_0(active0, 0x20000000000000L); case 77: case 109: return jjMoveStringLiteralDfa8_0(active0, 0x80000000L); case 82: case 114: return jjMoveStringLiteralDfa8_0(active0, 0x410000000000000L); case 83: case 115: return jjMoveStringLiteralDfa8_0(active0, 0x101400100000000L); default : break; } return jjStartNfa_0(6, active0, 0L); } private final int jjMoveStringLiteralDfa8_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(6, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(7, active0, 0L); return 8; } switch(curChar) { case 95: return jjMoveStringLiteralDfa9_0(active0, 0x40000000000000L); case 68: case 100: return jjMoveStringLiteralDfa9_0(active0, 0x80000000000000L); case 73: case 105: return jjMoveStringLiteralDfa9_0(active0, 0x501400100000000L); case 77: case 109: return jjMoveStringLiteralDfa9_0(active0, 0x40000000L); case 80: case 112: if ((active0 & 0x80000000L) != 0L) return jjStartNfaWithStates_0(8, 31, 1); break; case 84: case 116: return jjMoveStringLiteralDfa9_0(active0, 0x20800000000000L); case 89: case 121: if ((active0 & 0x10000000000000L) != 0L) return jjStartNfaWithStates_0(8, 52, 1); break; default : break; } return jjStartNfa_0(7, active0, 0L); } private final int jjMoveStringLiteralDfa9_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(7, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(8, active0, 0L); return 9; } switch(curChar) { case 95: return jjMoveStringLiteralDfa10_0(active0, 0x80000000000000L); case 66: case 98: return jjMoveStringLiteralDfa10_0(active0, 0x40000000000000L); case 69: case 101: return jjMoveStringLiteralDfa10_0(active0, 0x420000000000000L); case 72: case 104: if ((active0 & 0x800000000000L) != 0L) return jjStartNfaWithStates_0(9, 47, 1); break; case 73: case 105: return jjMoveStringLiteralDfa10_0(active0, 0x40000000L); case 79: case 111: return jjMoveStringLiteralDfa10_0(active0, 0x1400100000000L); case 90: case 122: return jjMoveStringLiteralDfa10_0(active0, 0x100000000000000L); default : break; } return jjStartNfa_0(8, active0, 0L); } private final int jjMoveStringLiteralDfa10_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(8, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(9, active0, 0L); return 10; } switch(curChar) { case 66: case 98: return jjMoveStringLiteralDfa11_0(active0, 0x80000000000000L); case 69: case 101: if ((active0 & 0x100000000000000L) != 0L) return jjStartNfaWithStates_0(10, 56, 1); break; case 76: case 108: return jjMoveStringLiteralDfa11_0(active0, 0x40000040000000L); case 78: case 110: if ((active0 & 0x1000000000000L) != 0L) return jjStartNfaWithStates_0(10, 48, 1); return jjMoveStringLiteralDfa11_0(active0, 0x400100000000L); case 82: case 114: if ((active0 & 0x20000000000000L) != 0L) return jjStartNfaWithStates_0(10, 53, 1); break; case 83: case 115: if ((active0 & 0x400000000000000L) != 0L) return jjStartNfaWithStates_0(10, 58, 1); break; default : break; } return jjStartNfa_0(9, active0, 0L); } private final int jjMoveStringLiteralDfa11_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(9, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(10, active0, 0L); return 11; } switch(curChar) { case 73: case 105: return jjMoveStringLiteralDfa12_0(active0, 0x40000000L); case 76: case 108: return jjMoveStringLiteralDfa12_0(active0, 0x80000000000000L); case 79: case 111: return jjMoveStringLiteralDfa12_0(active0, 0x40000000000000L); case 83: case 115: if ((active0 & 0x100000000L) != 0L) return jjStartNfaWithStates_0(11, 32, 1); else if ((active0 & 0x400000000000L) != 0L) return jjStartNfaWithStates_0(11, 46, 1); break; default : break; } return jjStartNfa_0(10, active0, 0L); } private final int jjMoveStringLiteralDfa12_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(10, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(11, active0, 0L); return 12; } switch(curChar) { case 69: case 101: return jjMoveStringLiteralDfa13_0(active0, 0x40000000L); case 79: case 111: return jjMoveStringLiteralDfa13_0(active0, 0xc0000000000000L); default : break; } return jjStartNfa_0(11, active0, 0L); } private final int jjMoveStringLiteralDfa13_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(11, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(12, active0, 0L); return 13; } switch(curChar) { case 77: case 109: return jjMoveStringLiteralDfa14_0(active0, 0x40000000000000L); case 79: case 111: return jjMoveStringLiteralDfa14_0(active0, 0x80000000000000L); case 83: case 115: if ((active0 & 0x40000000L) != 0L) return jjStartNfaWithStates_0(13, 30, 1); break; default : break; } return jjStartNfa_0(12, active0, 0L); } private final int jjMoveStringLiteralDfa14_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(12, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(13, active0, 0L); return 14; } switch(curChar) { case 70: case 102: return jjMoveStringLiteralDfa15_0(active0, 0x40000000000000L); case 77: case 109: return jjMoveStringLiteralDfa15_0(active0, 0x80000000000000L); default : break; } return jjStartNfa_0(13, active0, 0L); } private final int jjMoveStringLiteralDfa15_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(13, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(14, active0, 0L); return 15; } switch(curChar) { case 70: case 102: return jjMoveStringLiteralDfa16_0(active0, 0x80000000000000L); case 73: case 105: return jjMoveStringLiteralDfa16_0(active0, 0x40000000000000L); default : break; } return jjStartNfa_0(14, active0, 0L); } private final int jjMoveStringLiteralDfa16_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(14, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(15, active0, 0L); return 16; } switch(curChar) { case 73: case 105: return jjMoveStringLiteralDfa17_0(active0, 0x80000000000000L); case 76: case 108: return jjMoveStringLiteralDfa17_0(active0, 0x40000000000000L); default : break; } return jjStartNfa_0(15, active0, 0L); } private final int jjMoveStringLiteralDfa17_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(15, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(16, active0, 0L); return 17; } switch(curChar) { case 76: case 108: return jjMoveStringLiteralDfa18_0(active0, 0x80000000000000L); case 84: case 116: return jjMoveStringLiteralDfa18_0(active0, 0x40000000000000L); default : break; } return jjStartNfa_0(16, active0, 0L); } private final int jjMoveStringLiteralDfa18_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(16, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(17, active0, 0L); return 18; } switch(curChar) { case 69: case 101: return jjMoveStringLiteralDfa19_0(active0, 0x40000000000000L); case 84: case 116: return jjMoveStringLiteralDfa19_0(active0, 0x80000000000000L); default : break; } return jjStartNfa_0(17, active0, 0L); } private final int jjMoveStringLiteralDfa19_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(17, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(18, active0, 0L); return 19; } switch(curChar) { case 69: case 101: return jjMoveStringLiteralDfa20_0(active0, 0x80000000000000L); case 82: case 114: if ((active0 & 0x40000000000000L) != 0L) return jjStartNfaWithStates_0(19, 54, 1); break; default : break; } return jjStartNfa_0(18, active0, 0L); } private final int jjMoveStringLiteralDfa20_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(18, old0, 0L); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(19, active0, 0L); return 20; } switch(curChar) { case 82: case 114: if ((active0 & 0x80000000000000L) != 0L) return jjStartNfaWithStates_0(20, 55, 1); break; default : break; } return jjStartNfa_0(19, active0, 0L); } private final void jjCheckNAdd(int state) { if (jjrounds[state] != jjround) { jjstateSet[jjnewStateCnt++] = state; jjrounds[state] = jjround; } } private final void jjAddStates(int start, int end) { do { jjstateSet[jjnewStateCnt++] = jjnextStates[start]; } while (start++ != end); } private final void jjCheckNAddTwoStates(int state1, int state2) { jjCheckNAdd(state1); jjCheckNAdd(state2); } private final void jjCheckNAddStates(int start, int end) { do { jjCheckNAdd(jjnextStates[start]); } while (start++ != end); } private final void jjCheckNAddStates(int start) { jjCheckNAdd(jjnextStates[start]); jjCheckNAdd(jjnextStates[start + 1]); } static final long[] jjbitVec0 = { 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL }; private final int jjMoveNfa_0(int startState, int curPos) { int[] nextStates; int startsAt = 0; jjnewStateCnt = 32; int i = 1; jjstateSet[0] = startState; int j, kind = 0x7fffffff; for (;;) { if (++jjround == 0x7fffffff) ReInitRounds(); if (curChar < 64) { long l = 1L << curChar; MatchLoop: do { switch(jjstateSet[--i]) { case 0: if ((0x3ff000000000000L & l) != 0L) { if (kind > 63) kind = 63; jjCheckNAddStates(0, 6); } else if ((0x400e00000000000L & l) != 0L) { if (kind > 62) kind = 62; jjCheckNAdd(1); } else if (curChar == 39) jjCheckNAddStates(7, 9); else if (curChar == 34) jjCheckNAdd(8); if (curChar == 46) jjCheckNAdd(3); break; case 1: if ((0x7ffe00000000000L & l) == 0L) break; if (kind > 62) kind = 62; jjCheckNAdd(1); break; case 2: if (curChar == 46) jjCheckNAdd(3); break; case 3: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 64) kind = 64; jjCheckNAddTwoStates(3, 4); break; case 5: if ((0x280000000000L & l) != 0L) jjCheckNAdd(6); break; case 6: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 64) kind = 64; jjCheckNAdd(6); break; case 7: if (curChar == 34) jjCheckNAdd(8); break; case 8: if ((0xfffffffbffffffffL & l) != 0L) jjCheckNAddTwoStates(8, 9); break; case 9: if (curChar == 34 && kind > 66) kind = 66; break; case 10: if (curChar == 39) jjCheckNAddStates(7, 9); break; case 11: if ((0xffffff7fffffffffL & l) != 0L) jjCheckNAddStates(7, 9); break; case 12: if (curChar == 39) jjCheckNAddStates(10, 12); break; case 13: if (curChar == 39) jjstateSet[jjnewStateCnt++] = 12; break; case 14: if ((0xffffff7fffffffffL & l) != 0L) jjCheckNAddStates(10, 12); break; case 15: if (curChar == 39 && kind > 67) kind = 67; break; case 16: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 63) kind = 63; jjCheckNAddStates(0, 6); break; case 17: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 63) kind = 63; jjCheckNAdd(17); break; case 18: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(18, 19); break; case 19: if (curChar == 46) jjCheckNAdd(20); break; case 20: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 64) kind = 64; jjCheckNAddTwoStates(20, 21); break; case 22: if ((0x280000000000L & l) != 0L) jjCheckNAdd(23); break; case 23: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 64) kind = 64; jjCheckNAdd(23); break; case 24: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(24, 25); break; case 26: if ((0x280000000000L & l) != 0L) jjCheckNAdd(27); break; case 27: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 64) kind = 64; jjCheckNAdd(27); break; case 28: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 64) kind = 64; jjCheckNAddTwoStates(28, 29); break; case 30: if ((0x280000000000L & l) != 0L) jjCheckNAdd(31); break; case 31: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 64) kind = 64; jjCheckNAdd(31); break; default : break; } } while(i != startsAt); } else if (curChar < 128) { long l = 1L << (curChar & 077); MatchLoop: do { switch(jjstateSet[--i]) { case 0: case 1: if ((0x47fffffe87fffffeL & l) == 0L) break; if (kind > 62) kind = 62; jjCheckNAdd(1); break; case 4: if ((0x2000000020L & l) != 0L) jjAddStates(13, 14); break; case 8: jjAddStates(15, 16); break; case 11: jjCheckNAddStates(7, 9); break; case 14: jjCheckNAddStates(10, 12); break; case 21: if ((0x2000000020L & l) != 0L) jjAddStates(17, 18); break; case 25: if ((0x2000000020L & l) != 0L) jjAddStates(19, 20); break; case 29: if ((0x2000000020L & l) != 0L) jjAddStates(21, 22); break; default : break; } } while(i != startsAt); } else { int i2 = (curChar & 0xff) >> 6; long l2 = 1L << (curChar & 077); MatchLoop: do { switch(jjstateSet[--i]) { case 8: if ((jjbitVec0[i2] & l2) != 0L) jjAddStates(15, 16); break; case 11: if ((jjbitVec0[i2] & l2) != 0L) jjCheckNAddStates(7, 9); break; case 14: if ((jjbitVec0[i2] & l2) != 0L) jjCheckNAddStates(10, 12); break; default : break; } } while(i != startsAt); } if (kind != 0x7fffffff) { jjmatchedKind = kind; jjmatchedPos = curPos; kind = 0x7fffffff; } ++curPos; if ((i = jjnewStateCnt) == (startsAt = 32 - (jjnewStateCnt = startsAt))) return curPos; try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return curPos; } } } static final int[] jjnextStates = { 17, 18, 19, 24, 25, 28, 29, 11, 13, 15, 13, 14, 15, 5, 6, 8, 9, 22, 23, 26, 27, 30, 31, }; public static final String[] jjstrLiteralImages = { "", null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, "\54", "\50", "\51", "\75", "\76", "\74", null, null, "\41\75", "\52", null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, "\73", }; public static final String[] lexStateNames = { "DEFAULT", }; static final long[] jjtoToken = { 0xffffffffffffffe1L, 0x1dL, }; static final long[] jjtoSkip = { 0x1eL, 0x0L, }; protected SimpleCharStream input_stream; private final int[] jjrounds = new int[32]; private final int[] jjstateSet = new int[64]; protected char curChar; public HQLParserTokenManager(SimpleCharStream stream){ if (SimpleCharStream.staticFlag) throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer."); input_stream = stream; } public HQLParserTokenManager(SimpleCharStream stream, int lexState){ this(stream); SwitchTo(lexState); } public void ReInit(SimpleCharStream stream) { jjmatchedPos = jjnewStateCnt = 0; curLexState = defaultLexState; input_stream = stream; ReInitRounds(); } private final void ReInitRounds() { int i; jjround = 0x80000001; for (i = 32; i-- > 0;) jjrounds[i] = 0x80000000; } public void ReInit(SimpleCharStream stream, int lexState) { ReInit(stream); SwitchTo(lexState); } public void SwitchTo(int lexState) { if (lexState >= 1 || lexState < 0) throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); else curLexState = lexState; } protected Token jjFillToken() { Token t = Token.newToken(jjmatchedKind); t.kind = jjmatchedKind; String im = jjstrLiteralImages[jjmatchedKind]; t.image = (im == null) ? input_stream.GetImage() : im; t.beginLine = input_stream.getBeginLine(); t.beginColumn = input_stream.getBeginColumn(); t.endLine = input_stream.getEndLine(); t.endColumn = input_stream.getEndColumn(); return t; } int curLexState = 0; int defaultLexState = 0; int jjnewStateCnt; int jjround; int jjmatchedPos; int jjmatchedKind; public Token getNextToken() { int kind; Token specialToken = null; Token matchedToken; int curPos = 0; EOFLoop : for (;;) { try { curChar = input_stream.BeginToken(); } catch(java.io.IOException e) { jjmatchedKind = 0; matchedToken = jjFillToken(); return matchedToken; } try { input_stream.backup(0); while (curChar <= 32 && (0x100002600L & (1L << curChar)) != 0L) curChar = input_stream.BeginToken(); } catch (java.io.IOException e1) { continue EOFLoop; } jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_0(); if (jjmatchedKind != 0x7fffffff) { if (jjmatchedPos + 1 < curPos) input_stream.backup(curPos - jjmatchedPos - 1); if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) { matchedToken = jjFillToken(); return matchedToken; } else { continue EOFLoop; } } int error_line = input_stream.getEndLine(); int error_column = input_stream.getEndColumn(); String error_after = null; boolean EOFSeen = false; try { input_stream.readChar(); input_stream.backup(1); } catch (java.io.IOException e1) { EOFSeen = true; error_after = curPos <= 1 ? "" : input_stream.GetImage(); if (curChar == '\n' || curChar == '\r') { error_line++; error_column = 0; } else error_column++; } if (!EOFSeen) { input_stream.backup(1); error_after = curPos <= 1 ? "" : input_stream.GetImage(); } throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); } } }
messyKassaye/my_stock
resources/js/auth/company/components/company/CompanyHome.js
<gh_stars>0 import React,{useEffect,useState} from 'react' import {useDispatch,useSelector} from 'react-redux' import HorizontalLoader from '../../../../loaders/HorizontalLoader' import {index} from '../../../../state/AppAction' import CompanyStyle from './styles/CompanyStyle' import CompanyRegistration from './forms/RegisterNewCompany' import CompanyDashboard from './CompanyDashboard' function CompanyHome(){ const classes = CompanyStyle() const loading = useSelector(state=>state.authReducer.userData.loading) const user = useSelector(state=>state.authReducer.userData.user) return( <div> { loading ? ( <HorizontalLoader/> ) : ( <div> { user.data.company.length<=0 ? ( <CompanyRegistration creation={'first_creation'}/> ) : ( <CompanyDashboard/> ) } </div> ) } </div> ) } export default CompanyHome
joba-sprd/rAppid.js
js/lib/flow.js
/*! * flow.js JavaScript Library v0.2.5 * https://github.com/it-ony/flow.js * * Copyright 2012, <NAME> * Licensed under the MIT license. * https://raw.github.com/it-ony/flow.js/master/LICENSE * * Date: Mon Mar 12 2012 12:36:34 GMT+0100 (CET) */ (function (exports) { "use strict"; var Flow = function (context) { this.$context = context || { actions: [], vars: {} }; }; var flow = function () { return new Flow(); }; /** * * @param {String} [name] variable name * @param {Function} fn function to execute * fn - function() {} // syncron * fn - function(cb) {} // asyncron */ Flow.prototype.seq = function (name, fn) { if (name instanceof Function) { fn = name; name = null; } if (!fn) { throw "Sequence action not defined"; } var self = this; this.$context.actions.push(function (cb) { var sync_end = false, returned = false; var setDataAndReturn = function (err, data, end) { if (!err && name) { // save result to var self.$context.vars[name] = data; } if (returned) { return; } returned = true; cb(err, end); }; /** * @param err * @param data */ var thisArg = function (err, data) { setDataAndReturn(err, data, false); }; thisArg.vars = self.$context.vars; if (fn.length) { // end for async case thisArg.end = function (err, data) { // end setDataAndReturn(err, data, true); }; try { fn.call(thisArg, thisArg); } catch (e) { setDataAndReturn(e, null); } } else { // sync thisArg.end = function () { sync_end = true; }; try { setDataAndReturn(null, fn.call(thisArg), sync_end); } catch (e) { setDataAndReturn(e, null, sync_end); } } } ); return this; }; var ParallelAction = function (name, fn) { if (!fn) { throw "Parallel action not defined"; } return function (parallelInstance, context, results, parallelFinishedCallback) { var sync_end = false; var setDataAndReturn = function (err, data, end) { if (!err && name) { // save result to tmp. var results[name] = data; } parallelFinishedCallback(parallelInstance, err, end); }; var thisArg = function (err, data) { setDataAndReturn(err, data, false); }; thisArg.vars = context.vars; if (fn.length) { // async thisArg.end = function (err, data) { // end setDataAndReturn(err, data, true); }; try { fn.call(thisArg, thisArg); } catch (e) { setDataAndReturn(e, null); } } else { // sync thisArg.end = function () { sync_end = true; }; try { setDataAndReturn(null, fn.call(thisArg), sync_end); } catch (e) { setDataAndReturn(e, null, sync_end); } } }; }; /** * Executes the given functions parallel * * @param {Object|Array} fns * {Object} fns - keys will be variable name for returned value */ Flow.prototype.par = function (fns) { if (arguments.length > 1) { // parallel functions given comma separated without named return this.par(Array.prototype.slice.call(arguments)); return this; } var self = this, i, key; if (fns) { var parallelActions = []; if (fns instanceof Array) { for (i = 0; i < fns.length; i++) { var fn = fns[i]; parallelActions.push(new ParallelAction(null, fn)); } } else if (fns instanceof Function) { this.par([fns]); } else { for (key in fns) { if (fns.hasOwnProperty(key)) { parallelActions.push(new ParallelAction(key, fns[key])); } } } if (parallelActions.length > 0) { // we got at least one function executing in parallel // push new action this.$context.actions.push(function (cb) { (function (parallelActions, cb) { var results = {}, p; var parallelFinished = function (fn, err, end) { var key; if (!cb) { // callback, already called, because end called multiple times return; } if (err || end) { // some error occurred var cb2 = cb; cb = null; cb2(err, end); } else { var index = parallelActions.indexOf(fn); if (index >= 0 && index < parallelActions.length) { // remove parallel executed function from actions parallelActions.splice(index, 1); } else { cb("Parallel function returned which wasn't part of this parallel actions"); cb = null; return; } if (parallelActions.length === 0) { // copy results to var for (key in results) { if (results.hasOwnProperty(key)) { self.$context.vars[key] = results[key]; } } cb(null, false); cb = null; } } }; // copy array of parallel actions, to avoid array is modified by returning of function // before all functions are started var copyParallelActions = parallelActions.slice(); // start all functions for (p = 0; p < copyParallelActions.length; p++) { // start parallel action var parallelInstance = copyParallelActions[p]; parallelInstance(parallelInstance, self.$context, results, parallelFinished); } }(parallelActions, cb)); }); } } return this; }; /*** * executes the given function for each value in values * @param {Array|Object} values for which fn should be called in parallel, * if object is passed, keys will be var names * @param {Function} fn function which will be executed for each value in values * function(value, [key], [cb]) - the function will be called with the value as first parameter * and optional as second parameter with the callback */ Flow.prototype.parEach = function (values, fn) { values = values || []; if (!(fn instanceof Function)) { throw "2nd argument for parEach needs to be a function"; } var noVars = values instanceof Array, delegates = noVars ? [] : {}; function addDelegate(name, value, key) { if (noVars) { key = value; value = name; name = null; } var parFn; if (fn.length >= 3) { // async with key parFn = function (cb) { this.key = key; fn.call(this, value, key, cb); }; } else if (fn.length == 2) { // async parFn = function (cb) { this.key = key; fn.call(this, value, cb); }; } else { // sync parFn = function () { this.key = key; return fn.call(this, value); }; } if (noVars) { delegates.push(parFn); } else { delegates[name] = parFn; } } if (noVars) { for (var i = 0; i < values.length; i++) { addDelegate(values[i], i); } } else { for (var key in values) { if (values.hasOwnProperty(key)) { addDelegate(key, values[key], key); } } } return this.par(delegates); }; Flow.prototype.seqEach = function (values, fn) { values = values || []; if (!(values instanceof Array)) { throw "values must be an array"; } if (!(fn instanceof Function)) { throw "2nd argument for parEach needs to be a function"; } var self = this; function addSequence(value, i) { var seqFn; if (fn.length >= 3) { // async seqFn = function (cb) { this.key = i; fn.call(this, value, i, cb); }; } else if (fn.length == 2) { // async seqFn = function (cb) { this.key = i; fn.call(this, value, cb); }; } else { // sync seqFn = function () { this.key = i; return fn.call(this, value); }; } self.seq(seqFn); } for (var i = 0; i < values.length; i++) { addSequence(values[i], i); } return this; }; Flow.prototype.exec = function (cb) { var self = this; var callback = function (err, data) { if (cb) { cb(err, data); } }; function flowEnd(err, results) { try { callback(err, results); } catch (e) { // error in exec if (self.errorHandler) { try { self.errorHandler(e); } catch (e) { // error in errorHandler, catch silent } } } } function execNext(index) { if (index < self.$context.actions.length) { // execute action self.$context.actions[index](function (err, end) { if (err || end) { flowEnd(err, self.$context.vars); } else { execNext(index + 1); } }); } else { flowEnd(null, self.$context.vars) } } execNext(0); }; if (typeof console !== "undefined" && console) { var log = (console.warn || console.log); if (log instanceof Function) { Flow.prototype.errorHandler = function (e) { if (e instanceof Error) { log.call(console, [e.message, e.stack]); } else { log.call(console, e); } } } } // global on the server, window in the browser var previous_flow = exports.flow; flow.noConflict = function () { exports.flow = previous_flow; return flow; }; exports.flow = flow; exports.Flow = Flow; }(typeof(exports) === "undefined" ? this : exports));
stackrox/stackrox
ui/apps/platform/src/reducers/network/backend.js
import { combineReducers } from 'redux'; import isEqual from 'lodash/isEqual'; import { createFetchingActionTypes, createFetchingActions } from 'utils/fetchingReduxRoutines'; // Action types export const types = { FETCH_NETWORK_POLICY_GRAPH: createFetchingActionTypes('network/FETCH_NETWORK_POLICY_GRAPH'), FETCH_NETWORK_FLOW_GRAPH: createFetchingActionTypes('network/FETCH_NETWORK_FLOW_GRAPH'), FETCH_NODE_UPDATES: createFetchingActionTypes('network/FETCH_NODE_UPDATES'), APPLY_NETWORK_POLICY_MODIFICATION: createFetchingActionTypes( 'network/APPLY_NETWORK_POLICY_MODIFICATION' ), }; // Actions export const actions = { fetchNetworkPolicyGraph: createFetchingActions(types.FETCH_NETWORK_POLICY_GRAPH), fetchNetworkFlowGraph: createFetchingActions(types.FETCH_NETWORK_FLOW_GRAPH), fetchNodeUpdates: createFetchingActions(types.FETCH_NODE_UPDATES), applyNetworkPolicyModification: createFetchingActions(types.APPLY_NETWORK_POLICY_MODIFICATION), }; // Reducers const networkPolicyGraph = (state = { nodes: [] }, action) => { if (action.type === types.FETCH_NETWORK_POLICY_GRAPH.SUCCESS) { return isEqual(action.response, state) ? state : action.response; } return state; }; const nodeUpdatesEpoch = (state = null, action) => { if (action.type === types.FETCH_NODE_UPDATES.SUCCESS) { return isEqual(action.response.epoch, state) ? state : action.response.epoch; } return state; }; const networkPolicyErrorMessage = (state = '', action) => { if (action.type === types.FETCH_NETWORK_POLICY_GRAPH.FAILURE) { const { message } = action.error.response.data; return message; } if (action.type === types.FETCH_NETWORK_POLICY_GRAPH.SUCCESS) { return ''; } return state; }; const networkFlowErrorMessage = (state = '', action) => { if (action.type === types.FETCH_NETWORK_FLOW_GRAPH.FAILURE) { const { message } = action.error.response.data; return message; } if (action.type === types.FETCH_NETWORK_FLOW_GRAPH.SUCCESS) { return ''; } return state; }; const networkPolicyGraphState = (state = 'INITIAL', action) => { const { type } = action; if (type === types.FETCH_NETWORK_POLICY_GRAPH.REQUEST) { return 'REQUEST'; } if (type === types.FETCH_NETWORK_POLICY_GRAPH.FAILURE) { return 'ERROR'; } if (type === types.FETCH_NETWORK_POLICY_GRAPH.SUCCESS) { return 'SUCCESS'; } return state; }; const networkFlowGraphState = (state = 'INITIAL', action) => { const { type } = action; if (type === types.FETCH_NETWORK_FLOW_GRAPH.REQUEST) { return 'REQUEST'; } if (type === types.FETCH_NETWORK_FLOW_GRAPH.FAILURE) { return 'ERROR'; } if (type === types.FETCH_NETWORK_FLOW_GRAPH.SUCCESS) { return 'SUCCESS'; } return state; }; const networkPolicyApplicationState = (state = 'INITIAL', action) => { const { type } = action; if (type === types.APPLY_NETWORK_POLICY_MODIFICATION.REQUEST) { return 'REQUEST'; } if (type === types.APPLY_NETWORK_POLICY_MODIFICATION.FAILURE) { return 'ERROR'; } if (type === types.APPLY_NETWORK_POLICY_MODIFICATION.SUCCESS) { return 'SUCCESS'; } return state; }; const reducer = combineReducers({ networkPolicyGraph, nodeUpdatesEpoch, networkPolicyErrorMessage, networkFlowErrorMessage, networkPolicyGraphState, networkFlowGraphState, networkPolicyApplicationState, }); // Selectors const getNetworkPolicyGraph = (state) => state.networkPolicyGraph; const getNodeUpdatesEpoch = (state) => state.nodeUpdatesEpoch; const getNetworkPolicyErrorMessage = (state) => state.networkPolicyErrorMessage; const getNetworkFlowErrorMessage = (state) => state.networkFlowErrorMessage; const getNetworkPolicyGraphState = (state) => state.networkPolicyGraphState; const getNetworkFlowGraphState = (state) => state.networkFlowGraphState; const getNetworkPolicyApplicationState = (state) => state.networkPolicyApplicationState; export const selectors = { getNetworkPolicyGraph, getNodeUpdatesEpoch, getNetworkPolicyErrorMessage, getNetworkFlowErrorMessage, getNetworkPolicyGraphState, getNetworkFlowGraphState, getNetworkPolicyApplicationState, }; export default reducer;
etirelli/kie-wb-common
kie-wb-common-screens/kie-wb-common-default-editor/kie-wb-common-default-editor-client/src/test/java/org/kie/workbench/common/screens/defaulteditor/client/editor/NewFileUploaderTest.java
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.screens.defaulteditor.client.editor; import javax.enterprise.event.Event; import com.google.gwtmockito.GwtMock; import com.google.gwtmockito.GwtMockitoTestRunner; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.workbench.common.services.shared.project.KieModuleService; import org.kie.workbench.common.widgets.client.handlers.NewResourcePresenter; import org.kie.workbench.common.widgets.client.handlers.NewResourceSuccessEvent; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.uberfire.backend.vfs.Path; import org.uberfire.client.mvp.PlaceManager; import org.uberfire.ext.widgets.common.client.common.BusyIndicatorView; import org.uberfire.ext.widgets.core.client.editors.defaulteditor.DefaultEditorNewFileUpload; import org.uberfire.mocks.CallerMock; import org.uberfire.mocks.EventSourceMock; import org.uberfire.mvp.Command; import org.uberfire.workbench.category.Others; import org.uberfire.workbench.events.NotificationEvent; import org.uberfire.workbench.type.AnyResourceTypeDefinition; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(GwtMockitoTestRunner.class) public class NewFileUploaderTest { @Mock private PlaceManager placeManager; @GwtMock private DefaultEditorNewFileUpload options; private AnyResourceTypeDefinition resourceType = new AnyResourceTypeDefinition(new Others()); @Mock private BusyIndicatorView busyIndicatorView; @Mock private org.guvnor.common.services.project.model.Package pkg; @Mock private Path pkgResourcesPath; @Mock private NewResourcePresenter presenter; private Event<NewResourceSuccessEvent> newResourceSuccessEventMock = spy(new EventSourceMock<NewResourceSuccessEvent>() { @Override public void fire(final NewResourceSuccessEvent event) { //Do nothing. Default implementation throws an Exception } }); private Event<NotificationEvent> mockNotificationEvent = new EventSourceMock<NotificationEvent>() { @Override public void fire(final NotificationEvent event) { //Do nothing. Default implementation throws an Exception } }; @Mock private KieModuleService moduleService; private NewFileUploader uploader; @Before public void setup() { uploader = new NewFileUploader(placeManager, options, resourceType, busyIndicatorView, new CallerMock<>(moduleService)) { { super.notificationEvent = mockNotificationEvent; super.newResourceSuccessEvent = newResourceSuccessEventMock; } @Override String encode(final String uri) { //Tests don't concern themselves with URI encoding return uri; } }; when(moduleService.resolveDefaultPath(pkg, "txt")).thenReturn(pkgResourcesPath); when(pkgResourcesPath.toURI()).thenReturn("default://p0/src/main/resources"); when(options.getFormFileName()).thenReturn("file.txt"); } @Test public void testCreateFileNameWithExtension() { uploader.create(pkg, "file.txt", presenter); verify(moduleService, times(1)).resolveDefaultPath(pkg, "txt"); verify(busyIndicatorView, times(1)).showBusyIndicator(any(String.class)); verify(options, times(1)).setFileName("file.txt"); verify(options, times(1)).upload(any(Command.class), any(Command.class)); } @Test public void testCreateFileNameWithoutExtension() { uploader.create(pkg, "file", presenter); verify(moduleService, times(1)).resolveDefaultPath(pkg, "txt"); verify(busyIndicatorView, times(1)).showBusyIndicator(any(String.class)); verify(options, times(1)).setFileName("file.txt"); verify(options, times(1)).upload(any(Command.class), any(Command.class)); } @Test public void testCreateSuccess() { final ArgumentCaptor<Command> commandArgumentCaptor = ArgumentCaptor.forClass(Command.class); final ArgumentCaptor<Path> pathArgumentCaptor = ArgumentCaptor.forClass(Path.class); final ArgumentCaptor<NewResourceSuccessEvent> newResourceSuccessEventArgumentCaptor = ArgumentCaptor.forClass(NewResourceSuccessEvent.class); uploader.create(pkg, "file", presenter); verify(moduleService, times(1)).resolveDefaultPath(pkg, "txt"); verify(busyIndicatorView, times(1)).showBusyIndicator(any(String.class)); verify(options, times(1)).upload(commandArgumentCaptor.capture(), any(Command.class)); //Emulate a successful upload final Command command = commandArgumentCaptor.getValue(); assertNotNull(command); command.execute(); verify(busyIndicatorView, times(1)).hideBusyIndicator(); verify(presenter, times(1)).complete(); verify(newResourceSuccessEventMock, times(1)).fire(newResourceSuccessEventArgumentCaptor.capture()); verify(placeManager, times(1)).goTo(pathArgumentCaptor.capture()); //Check navigation final Path routedPath = pathArgumentCaptor.getValue(); assertEquals("default://p0/src/main/resources/file.txt", routedPath.toURI()); final NewResourceSuccessEvent newResourceSuccessEvent = newResourceSuccessEventArgumentCaptor.getValue(); assertEquals("default://p0/src/main/resources/file.txt", newResourceSuccessEvent.getPath().toURI()); } @Test public void testCreateFailure() { final ArgumentCaptor<Command> commandArgumentCaptor = ArgumentCaptor.forClass(Command.class); uploader.create(pkg, "file", presenter); verify(moduleService, times(1)).resolveDefaultPath(pkg, "txt"); verify(busyIndicatorView, times(1)).showBusyIndicator(any(String.class)); verify(options, times(1)).upload(any(Command.class), commandArgumentCaptor.capture()); //Emulate a successful upload final Command command = commandArgumentCaptor.getValue(); assertNotNull(command); command.execute(); verify(busyIndicatorView, times(1)).hideBusyIndicator(); verify(presenter, never()).complete(); verify(placeManager, never()).goTo(any(Path.class)); } @Test public void testNoFileSelected() { when(options.getFormFileName()).thenReturn(null); uploader.create(pkg, "file", presenter); verify(busyIndicatorView, never()).showBusyIndicator(any(String.class)); verify(options, never()).upload(any(Command.class), any(Command.class)); } }
Mararok/EpicWar
src/main/com/mararok/epicwar/command/ListWarCommand.java
/** * EpicWar * The MIT License * Copyright (C) 2015 Mararok <<EMAIL>> */ package com.mararok.epicwar.command; import java.util.Collection; import org.bukkit.command.CommandSender; import com.mararok.epiccore.command.CommandArguments; import com.mararok.epiccore.command.CommandMetadata; import com.mararok.epiccore.misc.MessageBuilder; import com.mararok.epicwar.EpicWarPlugin; import com.mararok.epicwar.War; public class ListWarCommand extends EpicWarCommand { public ListWarCommand(EpicWarPlugin plugin) { super(plugin); setMetadata(CommandMetadata.command("list") .description(getLanguage().getText("command.war.list")) .usage("/ew list") .permission("epicwar.list")); } @Override public boolean onCommand(CommandSender sender, CommandArguments<EpicWarPlugin> arguments) { if (checkPermission(sender)) { Collection<War> wars = getPlugin().getWarManager().findAll(); if (!wars.isEmpty()) { MessageBuilder message = MessageBuilder.message().line(getLanguage().getText("message.war.list.header")); for (War war : wars) { message.line(getLanguage().getFormatedText("message.war.list.row", war.getId(), war.getSettings().name, war.getWorld().getName())); } sender.sendMessage(message.toArray()); } else { sender.sendMessage(getLanguage().getText("message.war.list.empty")); } } return true; } }
pooyaww/Vivado_HLS_Samples
Adaptive_Filter/vhls/step2/lms_filter.h
<reponame>pooyaww/Vivado_HLS_Samples #ifndef LMS_FILTER_H #define LMS_FILTER_H // Includes #include "adaptive_filter.h" class lms_filter: public adaptive_filter { protected: virtual void update_coefs(short* coefs, short* noise_buf, short step_size, short err); public: lms_filter(); ~lms_filter(); }; #endif // LMS_FILTER_H
ks8/conformation
conformation/null_model.py
""" Null model for predicting pairwise distances based on minimum path length between pairs of atoms. """ import itertools import json from logging import Logger import matplotlib.pyplot as plt import numpy as np import os import pickle # noinspection PyUnresolvedReferences from rdkit import Chem # noinspection PyUnresolvedReferences from rdkit.Chem import AllChem, rdMolTransforms, rdmolops from sklearn.model_selection import train_test_split # noinspection PyPackageRequirements from tap import Tap import torch from tqdm import tqdm from conformation.dataloader import DataLoader from conformation.dataset import GraphDataset class Args(Tap): """ System arguments. """ data_dir: str # Path to data directory data_path: str # Path to metadata file uid_path: str # Path to uid file save_dir: str # Directory to save information batch_size: int = 10 # Batch size def null_model(args: Args, logger: Logger) -> None: """ Predict atomic distances for a molecule based on minimum path length between pairs of atoms. :param args: System arguments. :param logger: Logger. :return: None. """ # Set up logger debug, info = logger.debug, logger.info debug("loading data") metadata = json.load(open(args.data_path)) train_metadata, remaining_metadata = train_test_split(metadata, test_size=0.2, random_state=0) validation_metadata, test_metadata = train_test_split(remaining_metadata, test_size=0.5, random_state=0) train_data = GraphDataset(train_metadata) val_data = GraphDataset(validation_metadata) test_data = GraphDataset(test_metadata) train_data_length, val_data_length, test_data_length = len(train_data), len(val_data), len(test_data) debug('train size = {:,} | val size = {:,} | test size = {:,}'.format( train_data_length, val_data_length, test_data_length) ) # Convert to iterator train_data = DataLoader(train_data, args.batch_size) test_data = DataLoader(test_data, args.batch_size) # Loss func and optimizer loss_func = torch.nn.MSELoss() # Uid dictionary uid_dict = pickle.load(open(args.uid_path, "rb")) # Null model 0: use the average inter-atomic distance between all pairs of atoms across all molecules # to predict any pairwise distance # Compute average inter-atomic distance across all atoms and all molecules debug("training null model 0") avg_distances = [] for _, _, files in os.walk(args.data_dir): for f in files: distances = np.load(os.path.join(args.data_dir, f)) avg_distances.append(np.mean(distances[:, 0])) avg_distances = np.array(avg_distances) avg_distance = avg_distances.mean() # Test null model 0 on the test set debug("testing null model 0") with torch.no_grad(): loss_sum, batch_count = 0, 0 for batch in tqdm(test_data, total=len(test_data)): targets = batch.y.unsqueeze(1) preds = torch.zeros_like(targets) # Use the all-atom all-molecule average distance as the prediction for each pair of atoms for i in range(preds.shape[0]): preds[i] = avg_distance loss = loss_func(preds, targets) loss = torch.sqrt_(loss) loss_sum += loss.item() batch_count += 1 loss_avg = loss_sum / batch_count debug("Test error avg = {:.4e}".format(loss_avg)) # Null model 1: compute the average distance between pairs of atoms across all molecules conditioned # on shortest path length, and use that to predict the distance between atoms with a given shortest # path length. debug("training null model 1") true_distances = [] shortest_paths = [] path_dict = dict() with torch.no_grad(): for batch in tqdm(train_data, total=len(train_data)): targets = batch.y[:, 0].unsqueeze(1) targets_aux = targets.cpu().numpy() # Collect the distance between each pair of atoms for i in range(targets_aux.shape[0]): true_distances.append(targets_aux[i][0]) # Compute the shortest path between each pair of atoms for i in range(batch.uid.shape[0]): uid = batch.uid[i].item() # Get the uid smiles = uid_dict[uid] # Access the SMILES via the uid mol = Chem.MolFromSmiles(smiles) # Create a molecule object mol = Chem.AddHs(mol) # Iterate through all pairs of atoms in the molecule and compute the shortest path length for m, n in itertools.combinations(list(np.arange(mol.GetNumAtoms())), 2): shortest_paths.append(len(rdmolops.GetShortestPath(mol, int(m), int(n))) - 1) # Convert the lists of atomic distances and shortest paths to numpy arrays true_distances = np.array(true_distances) shortest_paths = np.array(shortest_paths) # Create a dictionary for which the keys are shortest path lengths and the values are the average # distance between pairs of atoms in the train set which have that shortest path length for i in range(shortest_paths.shape[0]): if shortest_paths[i] in path_dict: path_dict[shortest_paths[i]].append(true_distances[i]) else: path_dict[shortest_paths[i]] = [] path_dict[shortest_paths[i]].append(true_distances[i]) for key in path_dict: path_dict[key] = np.array(path_dict[key]).mean() # Test null model 1 debug("testing null model 1") path_lengths = [] losses = [] loss_func_aux = torch.nn.MSELoss(reduction='none') # Use to analyze individual losses with torch.no_grad(): loss_sum, batch_count = 0, 0 for batch in tqdm(test_data, total=len(test_data)): targets = batch.y[:, 0].unsqueeze(1) preds = [] # Loop through each molecule for i in range(batch.uid.shape[0]): uid = batch.uid[i].item() smiles = uid_dict[uid] mol = Chem.MolFromSmiles(smiles) mol = Chem.AddHs(mol) # Predict distance based on shortest path length for each pair of atoms, keeping track # of both the predictions and the shortest path lengths for m, n in itertools.combinations(list(np.arange(mol.GetNumAtoms())), 2): preds.append(path_dict[len(rdmolops.GetShortestPath(mol, int(m), int(n))) - 1]) path_lengths.append(len(rdmolops.GetShortestPath(mol, int(m), int(n))) - 1) preds = torch.tensor(np.array(preds)).unsqueeze(1) loss = loss_func(preds, targets) loss = torch.sqrt_(loss) loss_aux = torch.sqrt_(loss_func_aux(preds, targets)) loss_aux = loss_aux.cpu().numpy() for i in range(loss_aux.shape[0]): losses.append(loss_aux[i][0]) loss_sum += loss.item() batch_count += 1 loss_avg = loss_sum / batch_count debug("Test error avg = {:.4e}".format(loss_avg)) # Plot loss as a function of shortest path length path_lengths = np.array(path_lengths) losses = np.array(losses) plt.plot(path_lengths, losses, 'bo', markersize=0.5) plt.title("Error vs Path Length") plt.ylabel("|True - Predicted|") plt.xlabel("Shortest Path") plt.savefig(os.path.join(args.save_dir, "null-model-1-error-vs-path")) # Save errors np.save(os.path.join(args.save_dir, "null-model-1-errors"), losses) # # Null model 2: compute the average distance between pairs of atoms across all molecules conditioned # on shortest path length as well as atom types, and use that to predict the distance between atoms with a # given shortest path length and pair of atom types. debug("training null model 2") true_distances = [] shortest_paths = [] path_dict = dict() with torch.no_grad(): for batch in tqdm(train_data, total=len(train_data)): targets = batch.y[:, 0].unsqueeze(1) targets_aux = targets.cpu().numpy() for i in range(targets_aux.shape[0]): true_distances.append(targets_aux[i][0]) for i in range(batch.uid.shape[0]): uid = batch.uid[i].item() smiles = uid_dict[uid] mol = Chem.MolFromSmiles(smiles) mol = Chem.AddHs(mol) # Iterate through all pairs of atoms in the molecule and compute the shortest path length # as well as the atom types, and concatenate that info to create the dictionary key for m, n in itertools.combinations(list(np.arange(mol.GetNumAtoms())), 2): atom_a = str(mol.GetAtoms()[int(m)].GetSymbol()) atom_b = str(mol.GetAtoms()[int(n)].GetSymbol()) path_len = len(rdmolops.GetShortestPath(mol, int(m), int(n))) - 1 key = ''.join(sorted([atom_a, atom_b])) + str(path_len) shortest_paths.append(key) true_distances = np.array(true_distances) for i in range(len(shortest_paths)): if shortest_paths[i] in path_dict: path_dict[shortest_paths[i]].append(true_distances[i]) else: path_dict[shortest_paths[i]] = [true_distances[i]] for key in path_dict: path_dict[key] = np.array(path_dict[key]).mean() # Test null model 2 debug("testing null model 2") path_lengths = [] losses = [] loss_func_aux = torch.nn.MSELoss(reduction='none') with torch.no_grad(): loss_sum, batch_count = 0, 0 for batch in tqdm(test_data, total=len(test_data)): targets = batch.y[:, 0].unsqueeze(1) preds = [] for i in range(batch.uid.shape[0]): uid = batch.uid[i].item() smiles = uid_dict[uid] mol = Chem.MolFromSmiles(smiles) mol = Chem.AddHs(mol) # Predict distance based on shortest path length and atom types for each pair of atoms, # keeping track of both the predictions and the shortest path lengths for m, n in itertools.combinations(list(np.arange(mol.GetNumAtoms())), 2): atom_a = str(mol.GetAtoms()[int(m)].GetSymbol()) atom_b = str(mol.GetAtoms()[int(n)].GetSymbol()) path_len = len(rdmolops.GetShortestPath(mol, int(m), int(n))) - 1 key = ''.join(sorted([atom_a, atom_b])) + str(path_len) preds.append(path_dict[key]) path_lengths.append(path_len) preds = torch.tensor(np.array(preds)).unsqueeze(1) loss = loss_func(preds, targets) loss = torch.sqrt_(loss) loss_aux = torch.sqrt_(loss_func_aux(preds, targets)) loss_aux = loss_aux.cpu().numpy() for i in range(loss_aux.shape[0]): losses.append(loss_aux[i][0]) loss_sum += loss.item() batch_count += 1 loss_avg = loss_sum / batch_count debug("Test error avg = {:.4e}".format(loss_avg)) path_lengths = np.array(path_lengths) losses = np.array(losses) plt.plot(path_lengths, losses, 'bo', markersize=0.5) plt.title("Error vs Path Length") plt.ylabel("|True - Predicted|") plt.xlabel("Shortest Path") plt.savefig(os.path.join(args.save_dir, "null-model-2-error-vs-path")) np.save(os.path.join(args.save_dir, "null-model-2-errors"), losses) # Null model 3: compute the average distance between pairs of atoms across all molecules conditioned # on shortest path length as well as all atom types along that specific path, and use that to predict the distance # between atoms with a given shortest path length and sequence of atom types. debug("training null model 3") null_model_2_path_dict = path_dict true_distances = [] shortest_paths = [] path_dict = dict() with torch.no_grad(): for batch in tqdm(train_data, total=len(train_data)): targets = batch.y[:, 0].unsqueeze(1) targets_aux = targets.cpu().numpy() for i in range(targets_aux.shape[0]): true_distances.append(targets_aux[i][0]) for i in range(batch.uid.shape[0]): uid = batch.uid[i].item() smiles = uid_dict[uid] mol = Chem.MolFromSmiles(smiles) mol = Chem.AddHs(mol) # Iterate through all pairs of atoms in the molecule and compute the shortest path length # as well as the sequence of atom types, and concatenate that info to create the dictionary key for m, n in itertools.combinations(list(np.arange(mol.GetNumAtoms())), 2): atoms = [] path = rdmolops.GetShortestPath(mol, int(m), int(n)) path_len = len(path) - 1 for j in range(path_len + 1): atoms.append(mol.GetAtoms()[path[j]].GetSymbol()) key = ''.join(atoms) shortest_paths.append(key) true_distances = np.array(true_distances) for i in range(len(shortest_paths)): if shortest_paths[i] in path_dict: path_dict[shortest_paths[i]].append(true_distances[i]) else: array = [true_distances[i]] path_dict[shortest_paths[i]] = array path_dict[shortest_paths[i][::-1]] = array for key in path_dict: path_dict[key] = np.array(path_dict[key]).mean() # Test null model 3 debug("testing null model 3") path_lengths = [] losses = [] loss_func_aux = torch.nn.MSELoss(reduction='none') with torch.no_grad(): loss_sum, batch_count = 0, 0 for batch in tqdm(test_data, total=len(test_data)): targets = batch.y[:, 0].unsqueeze(1) preds = [] for i in range(batch.uid.shape[0]): uid = batch.uid[i].item() smiles = uid_dict[uid] mol = Chem.MolFromSmiles(smiles) mol = Chem.AddHs(mol) # Predict distance based on shortest path length and atom types for each pair of atoms, # keeping track of both the predictions and the shortest path lengths for m, n in itertools.combinations(list(np.arange(mol.GetNumAtoms())), 2): atoms = [] path = rdmolops.GetShortestPath(mol, int(m), int(n)) path_len = len(path) - 1 for j in range(path_len + 1): atoms.append(mol.GetAtoms()[path[j]].GetSymbol()) key = ''.join(atoms) if key in shortest_paths: preds.append(path_dict[key]) else: atom_a = str(mol.GetAtoms()[int(m)].GetSymbol()) atom_b = str(mol.GetAtoms()[int(n)].GetSymbol()) path_len = len(rdmolops.GetShortestPath(mol, int(m), int(n))) - 1 key = ''.join(sorted([atom_a, atom_b])) + str(path_len) preds.append(null_model_2_path_dict[key]) path_lengths.append(path_len) preds = torch.tensor(np.array(preds)).unsqueeze(1) loss = loss_func(preds, targets) loss = torch.sqrt_(loss) loss_aux = torch.sqrt_(loss_func_aux(preds, targets)) loss_aux = loss_aux.cpu().numpy() for i in range(loss_aux.shape[0]): losses.append(loss_aux[i][0]) loss_sum += loss.item() batch_count += 1 loss_avg = loss_sum / batch_count debug("Test error avg = {:.4e}".format(loss_avg)) path_lengths = np.array(path_lengths) losses = np.array(losses) plt.plot(path_lengths, losses, 'bo', markersize=0.5) plt.title("Error vs Path Length") plt.ylabel("|True - Predicted|") plt.xlabel("Shortest Path") plt.savefig(os.path.join(args.save_dir, "null-model-3-error-vs-path")) np.save(os.path.join(args.save_dir, "null-model-3-errors"), losses)
randmonkey/kpaas
pkg/service/api/v1/helm/export_release.go
// Copyright 2019 Shanghai JingDuo Information Technology co., Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package helm import ( "github.com/gin-gonic/gin" "helm.sh/helm/v3/pkg/action" "github.com/kpaas-io/kpaas/pkg/utils/log" ) func exportRelease(c *gin.Context, cluster string, namespace string, releaseName string) ( string, error) { logEntry := log.ReqEntry(c). WithField("cluster", cluster).WithField("namespace", namespace).WithField("releaseName", releaseName) logEntry.Debug("getting action config...") exportReleaseConfig, err := generateHelmActionConfig(cluster, namespace, logEntry) if err != nil { logEntry.Warningf("failed to generate configuration for helm action") return "", err } exportReleaseAction := action.NewGet(exportReleaseConfig) releaseContent, err := exportReleaseAction.Run(releaseName) if err != nil { logEntry.WithField("error", err).Warning("failed to run get release action") return "", err } return releaseContent.Manifest, nil }
hbarsnes/compomics-utilities
src/main/java/com/compomics/util/gui/parameters/proteowizard/MsConvertParametersDialog.java
package com.compomics.util.gui.parameters.proteowizard; import com.compomics.util.examples.BareBonesBrowserLaunch; import com.compomics.util.experiment.mass_spectrometry.proteowizard.MsConvertParameters; import com.compomics.util.experiment.mass_spectrometry.proteowizard.ProteoWizardMsFormat; import com.compomics.util.experiment.mass_spectrometry.proteowizard.ProteoWizardFilter; import com.compomics.util.gui.file_handling.FileChooserUtil; import com.compomics.util.gui.renderers.AlignedListCellRenderer; import com.compomics.util.parameters.UtilitiesUserParameters; import java.awt.event.MouseEvent; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import javax.swing.DefaultCellEditor; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; /** * Dialog for the creation and edition of msconvert parameters. * * @author <NAME> */ public class MsConvertParametersDialog extends javax.swing.JDialog { /** * Boolean indicating whether the editing was canceled. */ private boolean canceled = false; /** * Map of the filters to use. */ private HashMap<Integer, String> filters; /** * List of the indexes of the filters to use. */ private ArrayList<Integer> filterIndexes; /** * The selected folder. */ private String lastSelectedFolder = ""; /** * The utilities preferences. */ private UtilitiesUserParameters utilitiesUserParameters; /** * Constructor. * * @param parent the parent frame * @param msConvertParameters initial parameters, ignored if null */ public MsConvertParametersDialog( java.awt.Frame parent, MsConvertParameters msConvertParameters ) { super(parent, true); initComponents(); setUpGUI(msConvertParameters); setLocationRelativeTo(parent); setVisible(true); } /** * Sets up the GUI components. * * @param msConvertParameters parameters to display on the interface, * ignored if null */ private void setUpGUI( MsConvertParameters msConvertParameters ) { filtersTableScrollPane.getViewport().setOpaque(false); filtersTable.getTableHeader().setReorderingAllowed(false); if (msConvertParameters != null) { outputFormatCmb.setSelectedItem(msConvertParameters.getMsFormat()); filters = (HashMap<Integer, String>) msConvertParameters.getFiltersMap().clone(); } else { outputFormatCmb.setSelectedItem(ProteoWizardMsFormat.mzML); filters = new HashMap<>(2); } filterIndexes = new ArrayList<>(filters.keySet()); Collections.sort(filterIndexes); DefaultTableModel tableModel = new FiltersTableModel(); filtersTable.setModel(tableModel); TableColumnModel tableColumnModel = filtersTable.getColumnModel(); tableColumnModel.getColumn(0).setMinWidth(50); tableColumnModel.getColumn(0).setMaxWidth(50); TableColumn filterColumn = tableColumnModel.getColumn(1); filterColumn.setMinWidth(200); filterColumn.setMaxWidth(200); JComboBox comboBox = new JComboBox(ProteoWizardFilter.values()); filterColumn.setCellEditor(new DefaultCellEditor(comboBox)); for (final ProteoWizardFilter tempFilter : ProteoWizardFilter.values()) { JMenuItem tempFilterMenuItem = new javax.swing.JMenuItem(tempFilter.name); tempFilterMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { if (!filters.containsKey(tempFilter.number)) { filters.put(tempFilter.number, ""); updateTable(); } } }); addFilterMenu.add(tempFilterMenuItem); } outputFormatCmb.setRenderer(new AlignedListCellRenderer(SwingConstants.CENTER)); utilitiesUserParameters = UtilitiesUserParameters.loadUserParameters(); if (utilitiesUserParameters.getProteoWizardPath() == null) { int option = JOptionPane.showConfirmDialog( this, "Cannot find ProteoWizard. Do you want to download it now?", "Download ProteoWizard?", JOptionPane.YES_NO_OPTION ); if (option == JOptionPane.YES_OPTION) { openWebPage(); } } // display the current path if (utilitiesUserParameters != null) { installationJTextField.setText(utilitiesUserParameters.getProteoWizardPath()); lastSelectedFolder = utilitiesUserParameters.getProteoWizardPath(); } } /** * Updates the table. */ private void updateTable() { filterIndexes = new ArrayList<>(filters.keySet()); Collections.sort(filterIndexes); ((DefaultTableModel) filtersTable.getModel()).fireTableDataChanged(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { filtersPopupMenu = new javax.swing.JPopupMenu(); removeFilterMenuItem = new javax.swing.JMenuItem(); addFilterMenu = new javax.swing.JMenu(); backgourdPanel = new javax.swing.JPanel(); cancelButton = new javax.swing.JButton(); okButton = new javax.swing.JButton(); msconvertParameters = new javax.swing.JPanel(); outputFormatLbl = new javax.swing.JLabel(); outputFormatCmb = new javax.swing.JComboBox(); filtersLbl = new javax.swing.JLabel(); filtersTableScrollPane = new javax.swing.JScrollPane(); filtersTable = new javax.swing.JTable(); filterHelpLabel = new javax.swing.JLabel(); installationPanel = new javax.swing.JPanel(); installationJTextField = new javax.swing.JTextField(); browseButton = new javax.swing.JButton(); folderHelpLabel = new javax.swing.JLabel(); removeFilterMenuItem.setText("Remove Filter"); removeFilterMenuItem.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { removeFilterMenuItemMouseReleased(evt); } }); filtersPopupMenu.add(removeFilterMenuItem); addFilterMenu.setText("Add Filter"); filtersPopupMenu.add(addFilterMenu); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("MSConvert Settings"); setMinimumSize(new java.awt.Dimension(400, 400)); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); backgourdPanel.setBackground(new java.awt.Color(230, 230, 230)); cancelButton.setText("Cancel"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); okButton.setText("OK"); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); msconvertParameters.setBorder(javax.swing.BorderFactory.createTitledBorder("Settings")); msconvertParameters.setOpaque(false); outputFormatLbl.setText("Output Format"); outputFormatCmb.setMaximumRowCount(10); outputFormatCmb.setModel(new DefaultComboBoxModel(com.compomics.util.experiment.mass_spectrometry.proteowizard.ProteoWizardMsFormat.getDataFormats(null, true))); filtersLbl.setText("Filters (right click in the table to edit)"); filtersTableScrollPane.setOpaque(false); filtersTableScrollPane.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { filtersTableScrollPaneMouseReleased(evt); } }); filtersTable.setModel(new FiltersTableModel()); filtersTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { filtersTableMouseReleased(evt); } }); filtersTableScrollPane.setViewportView(filtersTable); javax.swing.GroupLayout msconvertParametersLayout = new javax.swing.GroupLayout(msconvertParameters); msconvertParameters.setLayout(msconvertParametersLayout); msconvertParametersLayout.setHorizontalGroup( msconvertParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(msconvertParametersLayout.createSequentialGroup() .addContainerGap() .addGroup(msconvertParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(filtersTableScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 682, Short.MAX_VALUE) .addGroup(msconvertParametersLayout.createSequentialGroup() .addComponent(filtersLbl) .addGap(0, 507, Short.MAX_VALUE)) .addGroup(msconvertParametersLayout.createSequentialGroup() .addComponent(outputFormatLbl) .addGap(18, 18, 18) .addComponent(outputFormatCmb, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap()) ); msconvertParametersLayout.setVerticalGroup( msconvertParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, msconvertParametersLayout.createSequentialGroup() .addContainerGap() .addGroup(msconvertParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(outputFormatLbl) .addComponent(outputFormatCmb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(filtersLbl) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(filtersTableScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE) .addContainerGap()) ); filterHelpLabel.setText("<html><a href>Help with the msconvert filters</a></html>"); filterHelpLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { filterHelpLabelMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { filterHelpLabelMouseExited(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { filterHelpLabelMouseReleased(evt); } }); installationPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("ProteoWizard Folder")); installationPanel.setOpaque(false); installationJTextField.setEditable(false); installationJTextField.setToolTipText("The folder containing the PeptideShaker jar file."); browseButton.setText("Browse"); browseButton.setToolTipText("The folder containing the PeptideShaker jar file."); browseButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browseButtonActionPerformed(evt); } }); folderHelpLabel.setFont(folderHelpLabel.getFont().deriveFont((folderHelpLabel.getFont().getStyle() | java.awt.Font.ITALIC))); folderHelpLabel.setText("Please locate the ProteoWizard installation folder"); javax.swing.GroupLayout installationPanelLayout = new javax.swing.GroupLayout(installationPanel); installationPanel.setLayout(installationPanelLayout); installationPanelLayout.setHorizontalGroup( installationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, installationPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(installationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(installationJTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 609, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, installationPanelLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(folderHelpLabel) .addGap(11, 11, 11))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(browseButton) .addContainerGap()) ); installationPanelLayout.setVerticalGroup( installationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(installationPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(installationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(installationJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(browseButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(folderHelpLabel) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout backgourdPanelLayout = new javax.swing.GroupLayout(backgourdPanel); backgourdPanel.setLayout(backgourdPanelLayout); backgourdPanelLayout.setHorizontalGroup( backgourdPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(backgourdPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(backgourdPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(backgourdPanelLayout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(filterHelpLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cancelButton)) .addComponent(msconvertParameters, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(installationPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); backgourdPanelLayout.setVerticalGroup( backgourdPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, backgourdPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(installationPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(msconvertParameters, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(backgourdPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cancelButton) .addComponent(okButton) .addComponent(filterHelpLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(backgourdPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(backgourdPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * Cancel the dialog without saving. * * @param evt */ private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed canceled = true; dispose(); }//GEN-LAST:event_cancelButtonActionPerformed /** * Close the dialog. * * @param evt */ private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed boolean formatCheck = true; ProteoWizardMsFormat selectedFormat = (ProteoWizardMsFormat) outputFormatCmb.getSelectedItem(); if (selectedFormat != ProteoWizardMsFormat.mgf && selectedFormat != ProteoWizardMsFormat.mzML) { int value = JOptionPane.showConfirmDialog( this, "MzML and mgf are the only format compatible with SearchGUI. Proceed anyway?", "Output Format Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE ); if (value == JOptionPane.NO_OPTION) { formatCheck = false; } } if (formatCheck) { utilitiesUserParameters.setProteoWizardPath(installationJTextField.getText()); try { UtilitiesUserParameters.saveUserParameters(utilitiesUserParameters); dispose(); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog( this, "An error occurred while saving the preferences.", "Error", JOptionPane.WARNING_MESSAGE ); } } }//GEN-LAST:event_okButtonActionPerformed /** * Remove an item from the filters. * * @param evt */ private void removeFilterMenuItemMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_removeFilterMenuItemMouseReleased int row = filtersTable.getSelectedRow(); if (row >= 0) { String itemName = filtersTable.getValueAt(row, 1).toString(); ProteoWizardFilter proteoWizardFilter = ProteoWizardFilter.getFilter(itemName); if (proteoWizardFilter != null) { filters.remove(proteoWizardFilter.number); updateTable(); } } }//GEN-LAST:event_removeFilterMenuItemMouseReleased /** * Show the filter popup menu. * * @param evt */ private void filtersTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_filtersTableMouseReleased if (evt != null && filtersTable.rowAtPoint(evt.getPoint()) != -1) { int row = filtersTable.rowAtPoint(evt.getPoint()); filtersTable.setRowSelectionInterval(row, row); } if (evt != null && evt.getButton() == MouseEvent.BUTTON3) { removeFilterMenuItem.setVisible(filtersTable.getSelectedRow() != -1); filtersPopupMenu.show(filtersTable, evt.getX(), evt.getY()); } }//GEN-LAST:event_filtersTableMouseReleased /** * Close the dialog. * * @param evt */ private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing cancelButtonActionPerformed(null); }//GEN-LAST:event_formWindowClosing /** * Change the cursor to a hand icon. * * @param evt */ private void filterHelpLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_filterHelpLabelMouseEntered setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); }//GEN-LAST:event_filterHelpLabelMouseEntered /** * Change the cursor back to the default icon. * * @param evt */ private void filterHelpLabelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_filterHelpLabelMouseExited setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_filterHelpLabelMouseExited /** * Open the msConvert filters helps. * * @param evt */ private void filterHelpLabelMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_filterHelpLabelMouseReleased BareBonesBrowserLaunch.openURL("http://proteowizard.sourceforge.net/tools/filters.html"); }//GEN-LAST:event_filterHelpLabelMouseReleased /** * Open the filter popup menu. * * @param evt */ private void filtersTableScrollPaneMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_filtersTableScrollPaneMouseReleased filtersTableMouseReleased(evt); }//GEN-LAST:event_filtersTableScrollPaneMouseReleased /** * Open a file chooser were the user can select the installation folder. * * @param evt */ private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed File selectedFile = FileChooserUtil.getUserSelectedFolder( this, "ProteoWizard Installation Folder", lastSelectedFolder, "ProteoWizard installation folder", "OK", true ); if (selectedFile != null) { // check if it is a valid folder if (!(new File(selectedFile, "msconvert.exe").exists() || new File(selectedFile, "msconvert").exists())) { JOptionPane.showMessageDialog( this, "The selected folder is not a valid ProteoWizard folder.", "Wrong Folder Selected", JOptionPane.WARNING_MESSAGE ); okButton.setEnabled(false); } else { // assumed to be valid folder lastSelectedFolder = selectedFile.getPath(); installationJTextField.setText(lastSelectedFolder); okButton.setEnabled(true); } } }//GEN-LAST:event_browseButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenu addFilterMenu; private javax.swing.JPanel backgourdPanel; private javax.swing.JButton browseButton; private javax.swing.JButton cancelButton; private javax.swing.JLabel filterHelpLabel; private javax.swing.JLabel filtersLbl; private javax.swing.JPopupMenu filtersPopupMenu; private javax.swing.JTable filtersTable; private javax.swing.JScrollPane filtersTableScrollPane; private javax.swing.JLabel folderHelpLabel; private javax.swing.JTextField installationJTextField; private javax.swing.JPanel installationPanel; private javax.swing.JPanel msconvertParameters; private javax.swing.JButton okButton; private javax.swing.JComboBox outputFormatCmb; private javax.swing.JLabel outputFormatLbl; private javax.swing.JMenuItem removeFilterMenuItem; // End of variables declaration//GEN-END:variables /** * Indicates whether the editing was canceled by the user. * * @return a boolean indicating whether the editing was canceled by the user */ public boolean isCanceled() { return canceled; } /** * Returns the parameters as created by the user. * * @return the parameters as created by the user */ public MsConvertParameters getMsConvertParameters() { MsConvertParameters msConvertParameters = new MsConvertParameters(); msConvertParameters.setMsFormat((ProteoWizardMsFormat) outputFormatCmb.getSelectedItem()); for (Integer filterIndex : filters.keySet()) { msConvertParameters.addFilter(filterIndex, filters.get(filterIndex)); } return msConvertParameters; } /** * Table model for the filters. */ private class FiltersTableModel extends DefaultTableModel { public FiltersTableModel() { } @Override public int getRowCount() { if (filters == null) { return 0; } return filters.size(); } @Override public int getColumnCount() { return 3; } @Override public String getColumnName(int column) { switch (column) { case 0: return " "; case 1: return "Name"; case 2: return "Value"; default: return ""; } } @Override public Object getValueAt(int row, int column) { switch (column) { case 0: return row + 1; case 1: Integer index = filterIndexes.get(row); ProteoWizardFilter proteoWizardFilter = ProteoWizardFilter.getFilter(index); String itemName = proteoWizardFilter.name; return itemName; case 2: index = filterIndexes.get(row); String value = filters.get(index); if (value == null) { value = null; } return value; default: return ""; } } @Override public void setValueAt(Object value, int row, int column) { switch (column) { case 1: Integer index = filterIndexes.get(row); filters.remove(index); ProteoWizardFilter proteoWizardFilter = (ProteoWizardFilter) value; filters.put(proteoWizardFilter.number, ""); break; case 2: index = filterIndexes.get(row); filters.put(index, (String) value); break; } updateTable(); } @Override public Class getColumnClass(int columnIndex) { for (int i = 0; i < getRowCount(); i++) { if (getValueAt(i, columnIndex) != null) { return getValueAt(i, columnIndex).getClass(); } } return String.class; } @Override public boolean isCellEditable(int row, int column) { return column > 0; } } /** * Opens the ProteoWizard web page. */ private void openWebPage() { this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); BareBonesBrowserLaunch.openURL("http://proteowizard.sourceforge.net"); this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } }
cryst-al/novoline
src/net/a90.java
package net; import com.viaversion.viaversion.api.protocol.remapper.PacketRemapper; import com.viaversion.viaversion.api.type.Type; import com.viaversion.viaversion.protocol.packet.PacketWrapperImpl; import net.Zv; final class a90 extends PacketRemapper { public void registerMap() { this.a(Type.STRING); this.a(a90::lambda$registerMap$0); this.a(Type.v); } private static void lambda$registerMap$0(PacketWrapperImpl var0) throws Exception { var0.a(Type.c, Boolean.valueOf(false)); } }
chenshun00/fuck-rpc
fuck-core/src/main/java/top/huzhurong/fuck/spring/bean/ServiceBean.java
package top.huzhurong.fuck.spring.bean; import org.springframework.beans.BeansException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.util.StringUtils; import top.huzhurong.fuck.register.IRegister; import top.huzhurong.fuck.register.zk.ZkRegister; import top.huzhurong.fuck.serialization.ISerialization; import top.huzhurong.fuck.serialization.SerializationFactory; import top.huzhurong.fuck.transaction.Server; import top.huzhurong.fuck.transaction.netty.request.NettyServer; import top.huzhurong.fuck.transaction.support.Provider; import top.huzhurong.fuck.util.NetUtils; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * 单个服务发布 * * @author <EMAIL> * @since 2018/12/1 */ public class ServiceBean implements InitializingBean, ApplicationContextAware, Serializable { private String id; private String interfaceName; private String version; private Integer weight; private IRegister register; private String serialization; private Object impl; private ApplicationContext applicationContext; private ProtocolPort protocolPort; @Override public void afterPropertiesSet() { this.build(); } private void build() { if (register == null) { register = applicationContext.getBean(ZkRegister.class); } if (this.protocolPort == null) { this.protocolPort = this.applicationContext.getBean(ProtocolPort.class); } ISerialization serialization = SerializationFactory.resolve(this.serialization, this.interfaceName); List<Provider> providerList = new ArrayList<>(16); Provider provider = new Provider(); provider.setSerialization(serialization.toString()); provider.setServiceName(interfaceName); provider.setHost(NetUtils.getLocalHost()); provider.setPort(this.protocolPort.getPort()); if (weight == null) { provider.setWeight(1); } else { provider.setWeight(weight); } provider.setVersion(version); providerList.add(provider); //服务注册 register.registerService(providerList); Server server = new NettyServer(serialization, this.applicationContext); server.bind(this.protocolPort.getPort()); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getInterfaceName() { return interfaceName; } public void setInterfaceName(String interfaceName) { this.interfaceName = interfaceName; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public Integer getWeight() { return weight; } public void setWeight(Integer weight) { this.weight = weight; } public IRegister getRegister() { return register; } public void setRegister(IRegister register) { this.register = register; } public String getSerialization() { return serialization; } public void setSerialization(String serialization) { this.serialization = serialization; } public Object getImpl() { return impl; } public void setImpl(Object impl) { this.impl = impl; } public ApplicationContext getApplicationContext() { return applicationContext; } public ProtocolPort getProtocolPort() { return protocolPort; } public void setProtocolPort(ProtocolPort protocolPort) { this.protocolPort = protocolPort; } }
battlesteed/httpRouter
httpRouter-api/src/main/java/steed/router/api/annotation/DocParam.java
package steed.router.api.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import steed.router.api.domain.Parameter; /** * 路径,表明该Processor对应哪个路径 * @author 战马 <EMAIL> */ @Inherited @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface DocParam { public String value() default ""; public int maxLength() default -1; public int minLength() default -1; public boolean require() default Parameter.defaultRequire; }
xeroz/admin-django
apps/competitions/views.py
<reponame>xeroz/admin-django from django.shortcuts import render, HttpResponseRedirect, get_object_or_404 from apps.competitions.models import Competition from apps.competitions.forms import CompetitionForm # Create your views here. def index(request): competitions = Competition.objects.all() data = { 'competitions': competitions, } return render(request, 'competitions/index.html', data) def create(request): if request.method == 'POST': form = CompetitionForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect('/competitions/index') else: form = CompetitionForm() data = {'form': form} return render(request, 'competitions/create.html', data) def teams(request, id): return render(request, 'competitions/teams.html', {}) def edit(request, id): competition = get_object_or_404(Competition, id=id) if request.method == 'POST': form = CompetitionForm( request.POST, request.FILES, instance=competition ) if form.is_valid(): form.save() return HttpResponseRedirect('/competitions/index') else: form = CompetitionForm(instance=competition) data = {'form': form} return render(request, 'competitions/edit.html', data)
brunolauze/MonoNative
MonoNative/mscorlib/System/mscorlib_System_ValueType.cpp
<filename>MonoNative/mscorlib/System/mscorlib_System_ValueType.cpp #include <mscorlib/System/mscorlib_System_ValueType.h> #include <mscorlib/System/mscorlib_System_String.h> #include <mscorlib/System/mscorlib_System_Type.h> namespace mscorlib { namespace System { //Public Methods mscorlib::System::Boolean ValueType::Equals(mscorlib::System::Object obj) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameters__[0] = (MonoObject*)obj; MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "ValueType", 0, NULL, "Equals", __native_object__, 1, __parameter_types__, __parameters__, NULL); return *(mscorlib::System::Boolean*)mono_object_unbox(__result__); } mscorlib::System::Int32 ValueType::GetHashCode() { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "ValueType", 0, NULL, "GetHashCode", __native_object__, 0, NULL, NULL, NULL); return *(mscorlib::System::Int32*)mono_object_unbox(__result__); } mscorlib::System::String ValueType::ToString() { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "ValueType", 0, NULL, "ToString", __native_object__, 0, NULL, NULL, NULL); return mscorlib::System::String(__result__); } } }
GyBraLAN/byceps
tests/integration/blueprints/site/user/test_views_create.py
""" :Copyright: 2006-2021 <NAME> :License: Revised BSD (see `LICENSE` file for details) """ from unittest.mock import patch import pytest from byceps.database import db from byceps.services.authentication.password.dbmodels import ( Credential as DbCredential, ) from byceps.services.authentication.session import service as session_service from byceps.services.authorization import service as authorization_service from byceps.services.brand import settings_service as brand_settings_service from byceps.services.consent import ( consent_service, subject_service as consent_subject_service, ) from byceps.services.newsletter import ( command_service as newsletter_command_service, service as newsletter_service, ) from byceps.services.user.dbmodels.user import User as DbUser from byceps.services.user import log_service, service as user_service from byceps.services.verification_token.dbmodels import Token as DbToken from byceps.services.verification_token.transfer.models import ( Purpose as TokenPurpose, ) from tests.helpers import http_client @pytest.fixture(scope='module') def terms_consent_subject_id(brand): consent_subject = consent_subject_service.create_subject( f'{brand.id}_terms-of-service_v1', f'Terms of service for {brand.title} / v1', 'Ich akzeptiere die <a href="{url}" target="_blank">Allgemeinen Geschäftsbedingungen</a>.', '/terms/', ) consent_subject_service.create_brand_requirement( brand.id, consent_subject.id ) yield consent_subject.id consent_subject_service.delete_brand_requirement( brand.id, consent_subject.id ) @pytest.fixture(scope='module') def privacy_policy_consent_subject_id(brand): consent_subject = consent_subject_service.create_subject( f'{brand.id}_privacy_policy_v1', f'Privacy policy for {brand.title} / v1', 'Ich akzeptiere die <a href="{url}" target="_blank">Datenschutzbestimmungen</a>.', '/privacy', ) consent_subject_service.create_brand_requirement( brand.id, consent_subject.id ) yield consent_subject.id consent_subject_service.delete_brand_requirement( brand.id, consent_subject.id ) @pytest.fixture(scope='module') def newsletter_list(brand): list_ = newsletter_command_service.create_list(brand.id, brand.title) name = 'newsletter_list_id' value = str(list_.id) brand_settings_service.create_setting(brand.id, name, value) yield brand_settings_service.remove_setting(brand.id, name) @patch('byceps.email.send') def test_create( send_email_mock, site_app, brand, site, terms_consent_subject_id, privacy_policy_consent_subject_id, newsletter_list, ): screen_name = 'Hiro' user_count_before = get_user_count() assert find_user(screen_name) is None form_data = { 'screen_name': screen_name, 'first_names': 'Hiroaki', 'last_name': 'Protagonist', 'email_address': '<EMAIL>', 'password': '<PASSWORD>', f'consent_to_subject_{terms_consent_subject_id.hex}': 'y', f'consent_to_subject_{privacy_policy_consent_subject_id.hex}': 'y', 'subscribe_to_newsletter': 'y', } response = send_request(site_app, form_data) assert response.status_code == 302 user_count_afterwards = get_user_count() assert user_count_afterwards == user_count_before + 1 user = find_user(screen_name) assert user is not None assert user.created_at is not None assert user.screen_name == 'Hiro' assert user.email_address == '<EMAIL>' assert not user.initialized assert not user.deleted # log entries assert_creation_log_entry_created(user.id, site.id) # password assert_password_credentials_created(user.id) # Session token should not have been created at this point. session_token = session_service.find_session_token_for_user(user.id) assert session_token is None # avatar assert user.avatar is None # details assert user.detail.first_names == 'Hiroaki' assert user.detail.last_name == 'Protagonist' # authorization role_ids = authorization_service.find_role_ids_for_user(user.id) assert role_ids == set() # consents assert_consent(user.id, terms_consent_subject_id) assert_consent(user.id, privacy_policy_consent_subject_id) # newsletter subscription assert is_subscribed_to_newsletter(user.id, brand.id) # confirmation e-mail verification_token = find_verification_token(user.id) assert verification_token is not None expected_sender = 'ACME Entertainment Convention <<EMAIL>>' expected_recipients = ['<EMAIL>'] expected_subject = 'Hiro, bitte bestätige deine E-Mail-Adresse' expected_body = f''' Hallo Hiro, bitte bestätige deine E-Mail-Adresse indem du diese URL aufrufst: https://www.acmecon.test/users/email_address/confirmation/{verification_token.token} '''.strip() assert_email( send_email_mock, expected_sender, expected_recipients, expected_subject, expected_body, ) @patch('byceps.email.send') def test_create_without_newsletter_subscription( send_email_mock, site_app, brand, site, terms_consent_subject_id, privacy_policy_consent_subject_id, newsletter_list, ): screen_name = 'Hiro2' form_data = { 'screen_name': screen_name, 'first_names': 'Hiroaki', 'last_name': 'Protagonist', 'email_address': '<EMAIL>', 'password': '<PASSWORD>', f'consent_to_subject_{terms_consent_subject_id.hex}': 'y', f'consent_to_subject_{privacy_policy_consent_subject_id.hex}': 'y', 'subscribe_to_newsletter': '', } response = send_request(site_app, form_data) assert response.status_code == 302 user = find_user(screen_name) assert user is not None # newsletter subscription assert not is_subscribed_to_newsletter(user.id, brand.id) # helpers def send_request(app, form_data): url = '/users/' with http_client(app) as client: return client.post(url, data=form_data) def find_user(screen_name): return user_service.find_db_user_by_screen_name(screen_name) def get_user_count(): return db.session.query(DbUser).count() def find_verification_token(user_id): return db.session \ .query(DbToken) \ .filter_by(user_id=user_id) \ .filter_by(_purpose=TokenPurpose.email_address_confirmation.name) \ .first() def is_subscribed_to_newsletter(user_id, brand_id): return newsletter_service.is_subscribed(user_id, brand_id) def assert_creation_log_entry_created(user_id, site_id): log_entries = log_service.get_log_entries_of_type_for_user( user_id, 'user-created' ) assert len(log_entries) == 1 first_log_entry = log_entries[0] assert first_log_entry.event_type == 'user-created' assert first_log_entry.data == {'site_id': site_id} def assert_password_credentials_created(user_id): credential = db.session.query(DbCredential).get(user_id) assert credential is not None assert credential.password_hash.startswith('<PASSWORD>:<PASSWORD>$') assert credential.updated_at is not None def assert_consent(user_id, subject_id): assert consent_service.has_user_consented_to_subject(user_id, subject_id) def assert_email( mock, expected_sender, expected_recipients, expected_subject, expected_body ): calls = mock.call_args_list assert len(calls) == 1 pos_args, _ = calls[0] actual_sender, actual_recipients, actual_subject, actual_body = pos_args assert actual_sender == expected_sender assert actual_recipients == expected_recipients assert actual_subject == expected_subject assert actual_body == expected_body
tk1012/ion-kit
include/ion-bb-image-processing/rt.h
// Don't use this file. // You can add only BB written by pure Halide function to ion-bb-image-processing.
iVS3D/iVS3D
iVS3D/src/iVS3D-core/controller/imageiterator.h
#ifndef IMAGEITERATOR_H #define IMAGEITERATOR_H #include "ModelInputIterator.h" /** * @class ImageIterator * * @ingroup Controller * * @brief The ImageIterator class is used to iterate given ModelInputPictures instance mip. Handles boundaries and * and allows for easy boundary checks. Every image is iterated. * * @author <NAME> * * @date 2021/02/11 */ class ImageIterator : public ModelInputIterator { public: /** * @brief steps for stepsize images forward from given currentIdx without leaving the boundaries of ModelInputPictures mip. * @param mip the ModelInputPictures instance to iterate * @param currentIdx the index to start from * @param stepsize the number of images to step from currentIdx * @return the new index which is min(currentIdx+stepsize, mip.getPicCount()-1) * * @see ModelInputPictures::getPicCount */ unsigned int getNext(ModelInputPictures *mip, unsigned int currentIdx, unsigned int stepsize = 1) override; /** * @brief steps for stepsize images backward from given currentIdx without leaving the boundaries of ModelInputPictures mip. * @param mip the ModelInputPictures instance to iterate * @param currentIdx the index to start from * @param stepsize the number of images to step from currentIdx * @return the new index which is max(currentIdx-stepsize, 0) */ unsigned int getPrevious(ModelInputPictures *mip, unsigned int currentIdx, unsigned int stepsize = 1) override; /** * @brief get index of first image in ModelInputPictures instance mip. First is 0. * @param mip the ModelInputPictures to iterate * @return 0 */ unsigned int getFirst(ModelInputPictures *mip) override; /** * @brief get index of last image in ModelINputPictures instance mip. Last is mip.getPicCount()-1. * @param mip the modelInputPictures to iterate * @return mip.getPicCount()-1 * * @see ModelInputPictures::getPicCount */ unsigned int getLast(ModelInputPictures *mip) override; /** * @brief check if currentIdx is first index in ModelInputPictures mip. * @param mip the ModelInputPictures to iterate * @param currentIdx index to check * @return @a true if currentIdx is first index, @a false otherwise */ bool isFirst(ModelInputPictures *mip, unsigned int currentIdx) override; /** * @brief check if currentIdx is last index in ModelInputPictures mip. * @param mip the ModelInputPictures to iterate * @param currentIdx index to check * @return @a true if currentIdx is first index, @a false otherwise */ bool isLast(ModelInputPictures *mip, unsigned int currentIdx) override; }; #endif // IMAGEITERATOR_H
Vankka/Platform-abstraction-layer
velocity/src/main/java/net/playeranalytics/plugin/scheduling/UnscheduledVelocityTask.java
package net.playeranalytics.plugin.scheduling; import com.velocitypowered.api.scheduler.Scheduler; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; public class UnscheduledVelocityTask implements UnscheduledTask { private final Object plugin; private final Scheduler scheduler; private final Runnable runnable; private final Consumer<Task> cancellableConsumer; public UnscheduledVelocityTask(Object plugin, Scheduler scheduler, Runnable runnable, Consumer<Task> cancellableConsumer) { this.plugin = plugin; this.scheduler = scheduler; this.runnable = runnable; this.cancellableConsumer = cancellableConsumer; } @Override public Task runTaskAsynchronously() { VelocityTask task = new VelocityTask(scheduler.buildTask(plugin, runnable).schedule()); cancellableConsumer.accept(task); return task; } @Override public Task runTaskLaterAsynchronously(long delayTicks) { VelocityTask task = new VelocityTask(scheduler.buildTask(plugin, runnable) .delay(TimeAmount.ticksToMillis(delayTicks), TimeUnit.MILLISECONDS) .schedule()); cancellableConsumer.accept(task); return task; } @Override public Task runTaskTimerAsynchronously(long delayTicks, long periodTicks) { VelocityTask task = new VelocityTask(scheduler.buildTask(plugin, runnable) .delay(TimeAmount.ticksToMillis(delayTicks), TimeUnit.MILLISECONDS) .repeat(TimeAmount.ticksToMillis(periodTicks), TimeUnit.MILLISECONDS) .schedule()); cancellableConsumer.accept(task); return task; } @Override public Task runTask() { return runTaskAsynchronously(); } @Override public Task runTaskLater(long delayTicks) { return runTaskLaterAsynchronously(delayTicks); } @Override public Task runTaskTimer(long delayTicks, long periodTicks) { return runTaskTimerAsynchronously(delayTicks, periodTicks); } }
nebula-genomics/iobio-services
gene/client/app/routes.js
import jQuery from 'jquery' global.jQuery = jQuery global.$ = jQuery import globalEduTour from './partials/GlobalEduTour.js' import d3 from 'd3' import _ from 'lodash' import Vue from 'vue' import VueRouter from 'vue-router' import App from './App.vue' import GeneHome from './components/pages/GeneHome.vue' import Tutorial from './components/pages/Tutorial.vue' import UseCases from './components/pages/UseCases.vue' import Exhibit from './components/pages/Exhibit.vue' import ExhibitCases from './components/pages/ExhibitCases.vue' import ExhibitCaseComplete from './components/pages/ExhibitCaseComplete.vue' import ExhibitCasesComplete from './components/pages/ExhibitCaseComplete.vue' import VueAnalytics from 'vue-analytics' import vue2animate from 'vue2-animate/dist/vue2-animate.min.css' import bootstrap from 'bootstrap/dist/css/bootstrap.css' import { Typeahead } from 'uiv' Vue.use(Typeahead) import Vuetify from 'vuetify' import 'vuetify/dist/vuetify.css' import '../assets/css/siteVuetify.css' Vue.use(Vuetify) import VTooltip from 'v-tooltip' import '../assets/css/v-tooltip.css' Vue.use(VTooltip) import vmodal from 'vue-js-modal' Vue.use(vmodal) import Util from './globals/Util.js' import GlobalApp from './globals/GlobalApp.js' Vue.use(VueRouter); const routes = [ { name: 'home', path: '/', component: GeneHome, beforeEnter: (to, from, next) => { console.log(to); var idx = to.hash.indexOf("#access_token"); if (idx == 0) { let queryParams = Qs.parse(to.hash.substring(1)); let { access_token, expires_in, token_type, ...otherQueryParams } = queryParams; localStorage.setItem('hub-iobio-tkn', token_type + ' ' + access_token); next('/' + Qs.stringify(otherQueryParams, { addQueryPrefix: true, arrayFormat: 'brackets' })); } else { var start = 0; if (idx == 0) { start = 3; } else { var idx = to.hash.indexOf("#\/"); var start = 0; if (idx == 0) { start = 3; } else { idx = to.hash.indexOf("#"); if (idx == 0) { start = 2; } } } if (idx == 0) { let queryParams = Qs.parse(to.hash.substring(start)); next('/' + Qs.stringify(queryParams, { addQueryPrefix: true, arrayFormat: 'brackets' })); } else { next(); } } }, props: (route) => ({ paramGene: route.query.gene, paramGenes: route.query.genes, paramSpecies: route.query.species, paramBuild: route.query.build, paramBatchSize: route.query.batchSize, paramGeneSource: route.query.geneSource, paramMyGene2: route.query.mygene2, paramLaunchedFromClin: route.query.launchedFromClin, paramMode: route.query.mode, paramTour: route.query.tour, paramFileId: route.query.fileId, paramAffectedSibs: route.query.affectedSibs, paramUnaffectedSibs: route.query.unaffectedSibs, paramRelationships: [route.query.rel0, route.query.rel1, route.query.rel2], paramSamples: [route.query.sample0, route.query.sample1, route.query.sample2], paramNames: [route.query.name0, route.query.name1, route.query.name2], paramBams: [route.query.bam0, route.query.bam1, route.query.bam2], paramBais: [route.query.bai0, route.query.bai1, route.query.bai2], paramVcfs: [route.query.vcf0, route.query.vcf1, route.query.vcf2], paramTbis: [route.query.tbi0, route.query.tbi1, route.query.tbi2], paramAffectedStatuses: [route.query.affectedStatus0, route.query.affectedStatus1, route.query.affectedStatus2], paramGeneName: route.query.geneName, paramGeneNames: route.query.geneNames, paramProjectId: route.query.project_id, paramSampleId: route.query.sample_id, paramSampleUuid: route.query.sample_uuid, paramIsPedigree: route.query.is_pedigree, paramSource: route.query.source, paramIobioSource: route.query.iobio_source, paramAnalysisId: route.query.analysis_id, paramFrameSource: route.query.frame_source, paramGeneSetId: route.query.gene_set_id, paramClientApplicationId : route.query.client_application_id, paramVariantSetId: route.query.variant_set_id, paramExperimentId: route.query.experiment_id }) }, { name: 'home-backward-compat1', path: '/#', redirect: '/' }, { name: 'home-backward-compat2', path: '/#/', redirect: '/' }, { name: 'home-hub', path: '/access_token*', redirect: '/' }, { name: 'tutorial', path: '/tutorial', component: Tutorial }, { name: 'use-cases', path: '/use-cases', component: UseCases, props: (route) => ({ paramTopic: route.query.topic }) }, { name: 'exhibit', path: '/exhibit', component: Exhibit }, { name: 'exhibit-cases', path: '/exhibit-cases', component: ExhibitCases }, { name: 'exhibit-case-complete', path: '/exhibit-case-complete', component: ExhibitCaseComplete }, { name: 'exhibit-cases-complete', path: '/exhibit-cases-complete', component: ExhibitCasesComplete } ] const router = new VueRouter({ 'mode': 'history', 'hashbang': false, 'base': '/', 'routes': routes }) // Google analytics Vue.use(VueAnalytics, { id: 'UA-47481907-5', router }) // define a globals mixin object Vue.mixin({ data: function() { return { utility: new Util(), globalApp: new GlobalApp() }; }, created: function(){ this.utility.globalApp = this.globalApp; this.globalApp.utility = this.utility; } }) //define a global filters Vue.filter('to-firstCharacterUppercase', function(value){ if (!value) return ''; value = value.toString(); return value.charAt(0).toUpperCase() + value.slice(1); }); window.vm = new Vue({ el: '#app', created: function() { }, render: h => h(App), router })
npocmaka/Windows-Server-2003
admin/wmi/wbem/providers/dsprovider/ldapcach.h
<reponame>npocmaka/Windows-Server-2003 // // Copyright (c) 1997-2001 Microsoft Corporation, All Rights Reserved // // *************************************************************************** // // Original Author: <NAME> // // $Author: rajeshr $ // $Date: 6/11/98 4:43p $ // $Workfile:ldapcach.h $ // // $Modtime: 6/11/98 11:21a $ // $Revision: 1 $ // $Nokeywords: $ // // // Description: Cache for LDAP Schema objects (Properties and Classes) // //*************************************************************************** #ifndef LDAP_CACHE_H #define LDAP_CACHE_H class CLDAPCache { public: static DWORD dwLDAPCacheCount; //*************************************************************************** // // CLDAPCache::CLDAPCache // // Purpose : Constructor. Fills in the cache with all the properties in LDAP. // // Parameters: // plogObject : Pointer to the ProvDebugLog object onto which logging will be done. //*************************************************************************** CLDAPCache(); //*************************************************************************** // // CLDAPCache::~CLDAPCache // // Purpose : Destructor // //*************************************************************************** ~CLDAPCache(); //*************************************************************************** // // CLDAPCache::IsInitialized // // Purpose : Indicates whether the cache was created and initialized succeddfully // // Parameters: // None // // Return value: // A boolean value indicating the status // //*************************************************************************** BOOLEAN IsInitialized(); //*************************************************************************** // // CLDAPCache::GetProperty // // Purpose : Retreives the IDirectory interface of an LDAP property. // // Parameters: // lpszPropertyName : The name of the LDAP Property to be retreived // ppADSIProperty : The address of the pointer where the CADSIProperty object will be placed // bWBEMName : True if the lpszPropertyName is the WBEM name. False, if it is the LDAP name // // Return value: // The COM value representing the return status. The user should delete the returned object when done. // //*************************************************************************** HRESULT GetProperty(LPCWSTR lpszPropertyName, CADSIProperty **ppADSIProperty, BOOLEAN bWBEMName); //*************************************************************************** // // CLDAPCache::GetClass // // Purpose : Retreives the IDirectory interface of an LDAP Class // // Parameters: // lpszClassName : The name of the Class to be retreived. // ppADSIClass : The address of the pointer where the CADSIClass object will be placed // // Return value: // The COM value representing the return status. The user should delete the returned object when done. // //*************************************************************************** HRESULT GetClass(LPCWSTR lpszWBEMClassName, LPCWSTR lpszClassName, CADSIClass **ppADSIClass); //*************************************************************************** // // CLDAPCache::EnumerateClasses // // Purpose : Retreives the IDirectory interface of an LDAP Class // // Parameters: // lppszWBEMSuperClass : The WBEM name of the immediate superclass of the classes to be retreived. This is optional // and is ignored if NULL // bDeep : Indicates whether a deep enumeration is required. Otherwise a shallow enumeration is done // pppszClassNames : The address of the array of LPWSTR pointers where the resulting objects will be // placed. The user should deallocate this array as well as its contents when done with them. // pdwNumRows : The number of elements in the above array returned // // Return value: // The COM value representing the return status. The user should delete the returned object when done. // //*************************************************************************** HRESULT EnumerateClasses(LPCWSTR lpszSuperclass, BOOLEAN bDeep, LPWSTR **pppADSIClasses, DWORD *pdwNumRows, BOOLEAN bArtificialClass ); //*************************************************************************** // // CLDAPCache::GetSchemaContainerSearch // // Purpose : To return the IDirectorySearch interface on the schema container // // Parameters: // ppDirectorySearch : The address where the pointer to the required interface will // be stored. // // // Return Value: The COM result representing the status. The user should release // the interface pointer when done with it. //*************************************************************************** HRESULT GetSchemaContainerSearch(IDirectorySearch ** ppDirectorySearch); //*************************************************************************** // // CLDAPCache::GetSchemaContainerObject // // Purpose : To return the IDirectoryObject interface on the schema container // // Parameters: // ppDirectoryObject : The address where the pointer to the required interface will // be stored. // // // Return Value: The COM result representing the status. The user should release // the interface pointer when done with it. //*************************************************************************** HRESULT GetSchemaContainerObject(IDirectoryObject ** ppDirectorySearch); //*************************************************************************** // // CLDAPCache :: CreateEmptyADSIClass // // Purpose: Creates a new ADSI class from a WBEM class // // Parameters: // lpszWBEMName : The WBEM Name of the class // // // Return Value: // //*************************************************************************** HRESULT CreateEmptyADSIClass( LPCWSTR lpszWBEMName, CADSIClass **ppADSIClass); HRESULT FillInAProperty(CADSIProperty *pNextProperty, ADS_SEARCH_HANDLE hADSSearchOuter); private: // The storage for cached properties CObjectTree m_objectTree; // Whether the cache was created successfully BOOLEAN m_isInitialized; // These are the search preferences often used ADS_SEARCHPREF_INFO m_pSearchInfo[3]; // The path to the schema container LPWSTR m_lpszSchemaContainerSuffix; LPWSTR m_lpszSchemaContainerPath; // The IDirectorySearch interface of the schema container IDirectorySearch *m_pDirectorySearchSchemaContainer; // Some other literals static LPCWSTR ROOT_DSE_PATH; static LPCWSTR SCHEMA_NAMING_CONTEXT; static LPCWSTR LDAP_PREFIX; static LPCWSTR LDAP_TOP_PREFIX; static LPCWSTR RIGHT_BRACKET; static LPCWSTR OBJECT_CATEGORY_EQUALS_ATTRIBUTE_SCHEMA; // A function to fill in the object tree // This can be called only after the m_pDirectorySearchSchemaContainer member // is initialized HRESULT InitializeObjectTree(); }; #endif /* LDAP_CACHE_H */
CloudSlang/cs-actions
cs-abbyy/src/main/java/io/cloudslang/content/abbyy/constants/InputNames.java
<reponame>CloudSlang/cs-actions /* * (c) Copyright 2020 EntIT Software LLC, a Micro Focus company, L.P. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License v2.0 which accompany this distribution. * * The Apache License is available at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.cloudslang.content.abbyy.constants; import io.cloudslang.content.httpclient.entities.HttpClientInputs; public final class InputNames { public static final String LOCATION_ID = "locationId"; public static final String APPLICATION_ID = "applicationId"; public static final String PASSWORD = "password"; public static final String LANGUAGE = "language"; public static final String PROFILE = "profile"; public static final String TEXT_TYPE = "textType"; public static final String IMAGE_SOURCE = "imageSource"; public static final String CORRECT_ORIENTATION = "correctOrientation"; public static final String CORRECT_SKEW = "correctSkew"; public static final String READ_BARCODES = "readBarcodes"; public static final String EXPORT_FORMAT = "exportFormat"; public static final String WRITE_FORMATTING = "writeFormatting"; public static final String WRITE_RECOGNITION_VARIANTS = "writeRecognitionVariants"; public static final String WRITE_TAGS = "writeTags"; public static final String DESCRIPTION = "description"; public static final String PDF_PASSWORD = "<PASSWORD>"; public static final String REGION = "region"; public static final String LETTER_SET = "letterSet"; public static final String REG_EXP = "regExp"; public static final String ONE_TEXT_LINE = "oneTextLine"; public static final String ONE_WORD_PER_TEXT_LINE = "oneWordPerTextLine"; public static final String MARKING_TYPE = "markingType"; public static final String PLACEHOLDERS_COUNT = "placeholdersCount"; public static final String WRITING_STYLE = "writingStyle"; public static final String DESTINATION_FOLDER = "destinationFolder"; public static final String DESTINATION_FILE = HttpClientInputs.DESTINATION_FILE; public static final String SOURCE_FILE = HttpClientInputs.SOURCE_FILE; public static final String PROXY_HOST = HttpClientInputs.PROXY_HOST; public static final String PROXY_PORT = HttpClientInputs.PROXY_PORT; public static final String PROXY_USERNAME = HttpClientInputs.PROXY_USERNAME; public static final String PROXY_PASSWORD = HttpClientInputs.PROXY_PASSWORD; public static final String TRUST_ALL_ROOTS = HttpClientInputs.TRUST_ALL_ROOTS; public static final String X509_HOSTNAME_VERIFIER = HttpClientInputs.X509_HOSTNAME_VERIFIER; public static final String TRUST_KEYSTORE = HttpClientInputs.TRUST_KEYSTORE; public static final String TRUST_PASSWORD = HttpClientInputs.TRUST_PASSWORD; public static final String CONNECT_TIMEOUT = HttpClientInputs.CONNECT_TIMEOUT; public static final String SOCKET_TIMEOUT = HttpClientInputs.SOCKET_TIMEOUT; public static final String KEEP_ALIVE = HttpClientInputs.KEEP_ALIVE; public static final String CONNECTIONS_MAX_PER_ROUTE = HttpClientInputs.CONNECTIONS_MAX_PER_ROUTE; public static final String CONNECTIONS_MAX_TOTAL = HttpClientInputs.CONNECTIONS_MAX_TOTAL; public static final String RESPONSE_CHARACTER_SET = HttpClientInputs.RESPONSE_CHARACTER_SET; public static final String DISABLE_SIZE_LIMIT = "disableSizeLimit"; private InputNames() { } }
thinkhy/x3c_extension
code/pkg_Core/Modules/PluginManager/Cx_ObjectFactory.cpp
<gh_stars>1-10 // Copyright 2008-2011 <NAME>, <EMAIL> // https://sourceforge.net/projects/x3c/ // // 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. // author: <NAME>, <NAME> // v2: 2011.1.5, change class-table to hash_map #include "StdAfx.h" #include "Cx_ObjectFactory.h" Cx_ObjectFactory::Cx_ObjectFactory() { } Cx_ObjectFactory::~Cx_ObjectFactory() { } bool Cx_ObjectFactory::IsCreatorRegister(const XCLSID& clsid) { _XCLASSMETA_ENTRY* pEntry = FindEntry(clsid); return pEntry && pEntry->pfnObjectCreator; } HRESULT Cx_ObjectFactory::CreateObject(const XCLSID& clsid, Ix_Object** ppv, HMODULE fromdll) { ASSERT(clsid.valid() && ppv != NULL); *ppv = NULL; _XCLASSMETA_ENTRY* pEntry = FindEntry(clsid); if (pEntry && pEntry->pfnObjectCreator) { *ppv = pEntry->pfnObjectCreator(fromdll); ASSERT(*ppv); return S_OK; } else { return E_NOTIMPL; } } long Cx_ObjectFactory::CreateSpecialInterfaceObjects(const char* iid) { ASSERT(iid && *iid); long count = 0; CLSMAP::const_iterator it = m_mapEntry.begin(); for (; it != m_mapEntry.end(); ++it) { const _XCLASSMETA_ENTRY& cls = it->second; if (lstrcmpiA(iid, cls.iidSpecial) == 0) { Ix_Object* pIF = NULL; pIF = (cls.pfnObjectCreator)(xGetModuleHandle()); ASSERT(pIF); pIF->Release(xGetModuleHandle()); count++; } } return count; } bool Cx_ObjectFactory::QuerySpecialInterfaceObject( long index, const char* iid, Ix_Object** ppv) { bool bRet = IsValidIndexOf(m_vecModule, index) && ppv != NULL; if (!bRet) { return false; } *ppv = NULL; const VCLSID& clsids = m_vecModule[index].clsids; VCLSID::const_iterator it = clsids.begin(); for (; it != clsids.end(); ++it) { CLSMAP::const_iterator mit = m_mapEntry.find(it->str()); if (mit != m_mapEntry.end() && lstrcmpiA(iid, mit->second.iidSpecial) == 0) { *ppv = (mit->second.pfnObjectCreator)(xGetModuleHandle()); return true; } } return false; } bool Cx_ObjectFactory::HasCreatorReplaced(const XCLSID& clsid) { clsid; return false; } _XCLASSMETA_ENTRY* Cx_ObjectFactory::FindEntry(const XCLSID& clsid) { CLSMAP::iterator it = m_mapEntry.find(clsid.str()); return (it == m_mapEntry.end()) ? NULL : &it->second; } int Cx_ObjectFactory::FindModule(HMODULE hModule) { int i = GetSize(m_vecModule); while (--i >= 0 && m_vecModule[i].hModule != hModule) ; return i; } Ix_Module* Cx_ObjectFactory::GetModule(HMODULE hModule) { int index = FindModule(hModule); if (index >= 0) { return m_vecModule[index].pModule; } typedef Ix_Module* (*FUNC_MODULE)(Ix_ObjectFactory*, HMODULE); FUNC_MODULE pfn = (FUNC_MODULE)GetProcAddress(hModule, "_xGetModuleInterface"); if (pfn != NULL) { Ix_Module* pModule = (*pfn)(this, hModule); return pModule; } else { return NULL; } } long Cx_ObjectFactory::RegisterClassEntryTable(HMODULE hModule) { int index = FindModule(hModule); ASSERT(index >= 0); // must call RegisterPlugin before Ix_Module* pModule = GetModule(hModule); ASSERT(pModule); // must call RegisterPlugin before if (!m_vecModule[index].clsids.empty()) { return GetSize(m_vecModule[index].clsids); } typedef DWORD (*FUNC_GET)(DWORD*, DWORD*, _XCLASSMETA_ENTRY*, DWORD); FUNC_GET pfn = (FUNC_GET)GetProcAddress(hModule, "_xGetClassEntryTable"); if (!pfn) // is not a plugin { return -1; } DWORD buildInfo = 0; int nClassCount = (*pfn)(&buildInfo, NULL, NULL, 0); if (nClassCount <= 0) { return 0; } std::vector<_XCLASSMETA_ENTRY> table(nClassCount); DWORD size = sizeof(_XCLASSMETA_ENTRY); nClassCount = (*pfn)(NULL, &size, &table[0], nClassCount); for (int i = 0; i < nClassCount; i++) { _XCLASSMETA_ENTRY& cls = table[i]; if (cls.clsid.valid()) { RegisterClass(index, cls); } if (cls.iidSpecial && *cls.iidSpecial) { char tmpclsid[40] = { 0 }; sprintf_s(tmpclsid, 40, "iid%lx:%d", hModule, i); cls.clsid = XCLSID(tmpclsid); RegisterClass(index, cls); } } return nClassCount; } bool Cx_ObjectFactory::RegisterClass(int moduleIndex, const _XCLASSMETA_ENTRY& cls) { ASSERT(moduleIndex >= 0 && cls.clsid.valid() && cls.pfnObjectCreator); _XCLASSMETA_ENTRY* pOldCls = FindEntry(cls.clsid); if (pOldCls) { char msg[256] = { 0, 0 }; sprintf_s(msg, 256, "The classid '%s' is already registered by '%s', then '%s' register fail.", cls.clsid.str(), pOldCls->className, cls.className); ASSERT_MESSAGE(false, msg); return false; } m_mapEntry[cls.clsid.str()] = cls; m_vecModule[moduleIndex].clsids.push_back(cls.clsid); return true; } void Cx_ObjectFactory::ReleaseModule(HMODULE hModule) { int index = FindModule(hModule); ASSERT(index >= 0); const VCLSID& clsids = m_vecModule[index].clsids; VCLSID::const_iterator it = clsids.begin(); for (; it != clsids.end(); ++it) { CLSMAP::iterator mit = m_mapEntry.find(it->str()); if (mit != m_mapEntry.end()) { m_mapEntry.erase(mit); } } if (m_vecModule[index].bOwner) { FreeLibrary(hModule); } m_vecModule.erase(m_vecModule.begin() + index); }
SFEley/ezmq
spec/spec_helper.rb
# This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # Require this file using `require "spec_helper"` to ensure that it is only # loaded once. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration require 'rspec/collection_matchers' require 'timeout' require 'ezmq' $:.unshift File.join(File.dirname(__FILE__), 'support') Process.setrlimit(:NOFILE, 8192) # Don't run out of file handles Thread.abort_on_exception = true # Log testing activity if there's a log directory logdir = File.join(File.dirname(__FILE__), '..', 'log') if Dir.exist?(logdir) require 'logger' EZMQ.logger = Logger.new File.join(logdir, 'spec.log'), 2, 2_000_000 EZMQ.logger.level = Logger::DEBUG end RSpec.configure do |config| config.run_all_when_everything_filtered = true config.filter_run :focus # Some specs are specific by 0mq version... case EZMQ.zmq_version when /^3\./ config.filter_run_excluding version: 4 when /^4\./ config.filter_run_excluding version: 3 end # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = 'random' config.raise_errors_for_deprecations! config.around(:each) do |example| begin Timeout::timeout(10) do example.run end ensure EZMQ.terminate! unless EZMQ.context.closed? end end end
alansuphd/sc-riscv
LinuxIO/final_demo/riscv/riscv64-unknown-elf/include/machine/syscfg.h
<gh_stars>1-10 #ifndef RISCV_SYSCFG_H #define RISCV_SYSCFG_H //------------------------------------------------------------------------ // RISC-V minimum and maximum vector length //------------------------------------------------------------------------ #define RISCV_SYSCFG_VLEN_MIN 4 #define RISCV_SYSCFG_VLEN_MAX 32 //------------------------------------------------------------------------ // Threads //------------------------------------------------------------------------ // Size of the various stacks #define RISCV_SYSCFG_USER_THREAD_STACK_SIZE 0x00010000 #define RISCV_SYSCFG_KERNEL_THREAD_STACK_SIZE 0x00010000 #define RISCV_SYSCFG_UT_THREAD_STACK_SIZE 0x00001000 #define RISCV_SYSCFG_MAX_PROCS 64 // maximum number of processors in the system #define RISCV_SYSCFG_MAX_KEYS 64 // maximum number of unique keys per thread #endif // RISCV_SYSCFG_H
shisheng-1/util
util-core/src/test/java/com/indeed/util/core/ReleaseVersionTest.java
package com.indeed.util.core; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; /** * @author <EMAIL> (<NAME>) */ public class ReleaseVersionTest { public static void assertVersionLessThan(final String lhs, final String rhs) { assertEquals(-1, ReleaseVersion.fromString(lhs).compareTo(ReleaseVersion.fromString(rhs))); } public static void assertVersionGreaterThan(final String lhs, final String rhs) { assertEquals(1, ReleaseVersion.fromString(lhs).compareTo(ReleaseVersion.fromString(rhs))); } public static void assertVersionEquals(final String lhs, final String rhs) { assertEquals(0, ReleaseVersion.fromString(lhs).compareTo(ReleaseVersion.fromString(rhs))); } @Test public void testVersionComparison() { assertVersionLessThan("3.1.1.0", "3.1.1.1"); assertVersionLessThan("3.1.1.0", "3.2.1.1"); assertVersionEquals("3.1.1.x", "3.1.1.1"); assertVersionEquals("3.1.x", "3.1.1.1"); assertVersionEquals("3.x", "3.1.1.1"); assertVersionEquals("4.0.x", "4.0.1.0"); assertVersionLessThan("4.0.0.0", "4.1.0.0"); assertVersionLessThan("4.0.0.0", "5.0.0.0"); assertVersionEquals("4.x", "4.0.0.1"); assertVersionGreaterThan("3.1.1.1", "3.1.1.0"); assertVersionGreaterThan("3.2.1.0", "3.1.1.1"); assertVersionGreaterThan("3.2.1.0", "3.1.x"); assertVersionGreaterThan("3.1.1.0", "3.1.0.x"); assertVersionEquals("3.1.1.1", "3.1.1.x"); assertVersionEquals("3.1.1.1", "3.1.x"); assertVersionEquals("3.1.1.1", "3.x"); assertVersionEquals("4.0.1.0", "4.0.x"); assertVersionGreaterThan("4.1.0.0", "4.0.0.0"); assertVersionGreaterThan("5.0.0.0", "4.0.0.0"); assertVersionEquals("4.0.0.1", "4.x"); assertVersionEquals("0.x", "0.0.0.0"); assertVersionEquals("1.524.x", "1.524.0.0"); assertVersionEquals("1.x", "1.0.0.0"); assertVersionEquals("1.0.0.x", "1.0.0.0"); assertVersionEquals("1.0.x", "1.0.0.0"); assertVersionEquals("1.x", "1.0.0.0"); assertVersionEquals("1.0.x", "1.0.0.0"); assertVersionEquals("1.0.0.x", "1.0.0.0"); assertVersionEquals("1.x", "1.0.0.0"); assertVersionEquals("1.0.x", "1.0.0.0"); assertVersionEquals("1.0.0.0", "1.x"); assertVersionEquals("32767.32767.32767.32767", "32767.32767.32767.32767"); // more than 4 parts discarded assertVersionEquals("1.1.1.1", "1.1.1.1.999"); assertVersionGreaterThan("32767.65535.65535.65535", "32767.65535.65535.65534"); assertVersionEquals("1.1.x", "1.1.1.x"); assertVersionGreaterThan("1.1.x", "1.0.0.x"); assertVersionGreaterThan("1.2.x", "1.1.x"); assertVersionLessThan("1.0.0.x", "1.1.x"); } public static void assertIllegalArgumentException(String version) { try { ReleaseVersion.fromString(version); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } } @Test public void testInvalidVersions() { assertIllegalArgumentException("1"); assertIllegalArgumentException("1.1"); assertIllegalArgumentException("1.1.1"); assertIllegalArgumentException("32768.0.0.0"); assertIllegalArgumentException("32767.65536.x"); assertIllegalArgumentException("32767.65535.65536.x"); assertIllegalArgumentException("32767.65535.65535.65536"); assertIllegalArgumentException("-1.x"); assertIllegalArgumentException("1.-206.x"); assertIllegalArgumentException("1.1.-29348.0"); assertIllegalArgumentException("1.1.1.-29348.0"); assertIllegalArgumentException("1..1.x"); assertIllegalArgumentException("x"); // TODO: should this be supported? ("match all versions") assertIllegalArgumentException(""); } @Test public void testFromStringSafely() { final ReleaseVersion expectedVersion = ReleaseVersion.fromString("1.0.0.0"); assertEquals(expectedVersion, ReleaseVersion.fromStringSafely("1.0.rc1", null)); assertEquals(expectedVersion, ReleaseVersion.fromStringSafely("1.-206.x", null)); assertEquals(expectedVersion, ReleaseVersion.fromStringSafely("1.0.0.65536", null)); final ReleaseVersion defaultVersion = ReleaseVersion.newBuilder().build(); assertEquals(defaultVersion, ReleaseVersion.fromStringSafely("32768.x", defaultVersion)); assertEquals(defaultVersion, ReleaseVersion.fromStringSafely("x", defaultVersion)); assertEquals(defaultVersion, ReleaseVersion.fromStringSafely("", defaultVersion)); } @Test public void testVersionToString() { assertEquals("1.x", ReleaseVersion.fromString("1.x").toString()); assertEquals("1.1.x", ReleaseVersion.fromString("1.1.x").toString()); assertEquals("1.1.1.x", ReleaseVersion.fromString("1.1.1.x").toString()); assertEquals("1.1.1.1", ReleaseVersion.fromString("1.1.1.1").toString()); assertEquals("1.1.1.1", ReleaseVersion.fromString("1.1.1.1.x").toString()); assertEquals("1.1.1.1", ReleaseVersion.fromString("1.1.1.1.x.x").toString()); assertEquals("1.1.1.1", ReleaseVersion.fromString("1.1.1.1.x.x.itsallgood").toString()); assertEquals("32767.65535.65535.65535", ReleaseVersion.fromString("32767.65535.65535.65535").toString()); } }
gentjankolicaj/EData
src/main/java/edata/converter/core/MyNasaPowerConverter.java
package edata.converter.core; import java.util.List; public interface MyNasaPowerConverter<S,D,C>{ D sourceToDto(S source); C sourceToCommand(S source); S dtoToSource(D dto); S commandToSource(C command); List<D> sourceToDto(List<S> source); List<C> sourceToCommand(List<S> source); List<D> sourceToDto(Iterable<S> source); List<C> sourceToCommand(Iterable<S> source); }
jhh67/chapel
third-party/llvm/llvm-src/include/llvm/CodeGen/MIRFormatter.h
<reponame>jhh67/chapel //===-- llvm/CodeGen/MIRFormatter.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 the declaration of the MIRFormatter class. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_MIRFORMATTER_H #define LLVM_CODEGEN_MIRFORMATTER_H #include "llvm/ADT/Optional.h" #include "llvm/CodeGen/PseudoSourceValue.h" #include "llvm/Support/raw_ostream.h" #include <cstdint> namespace llvm { class MachineFunction; class MachineInstr; struct PerFunctionMIParsingState; struct SlotMapping; /// MIRFormater - Interface to format MIR operand based on target class MIRFormatter { public: typedef function_ref<bool(StringRef::iterator Loc, const Twine &)> ErrorCallbackType; MIRFormatter() {} virtual ~MIRFormatter() = default; /// Implement target specific printing for machine operand immediate value, so /// that we can have more meaningful mnemonic than a 64-bit integer. Passing /// None to OpIdx means the index is unknown. virtual void printImm(raw_ostream &OS, const MachineInstr &MI, Optional<unsigned> OpIdx, int64_t Imm) const { OS << Imm; } /// Implement target specific parsing of immediate mnemonics. The mnemonic is /// dot seperated strings. virtual bool parseImmMnemonic(const unsigned OpCode, const unsigned OpIdx, StringRef Src, int64_t &Imm, ErrorCallbackType ErrorCallback) const { llvm_unreachable("target did not implement parsing MIR immediate mnemonic"); } /// Implement target specific printing of target custom pseudo source value. /// Default implementation is not necessarily the correct MIR serialization /// format. virtual void printCustomPseudoSourceValue(raw_ostream &OS, ModuleSlotTracker &MST, const PseudoSourceValue &PSV) const { PSV.printCustom(OS); } /// Implement target specific parsing of target custom pseudo source value. virtual bool parseCustomPseudoSourceValue( StringRef Src, MachineFunction &MF, PerFunctionMIParsingState &PFS, const PseudoSourceValue *&PSV, ErrorCallbackType ErrorCallback) const { llvm_unreachable( "target did not implement parsing MIR custom pseudo source value"); } /// Helper functions to print IR value as MIR serialization format which will /// be useful for target specific printer, e.g. for printing IR value in /// custom pseudo source value. static void printIRValue(raw_ostream &OS, const Value &V, ModuleSlotTracker &MST); /// Helper functions to parse IR value from MIR serialization format which /// will be useful for target specific parser, e.g. for parsing IR value for /// custom pseudo source value. static bool parseIRValue(StringRef Src, MachineFunction &MF, PerFunctionMIParsingState &PFS, const Value *&V, ErrorCallbackType ErrorCallback); }; } // end namespace llvm #endif
atharva8300/Engineering-Practical-Experiments
Semester 6/SPCC/Code optimization - Dead code elimination/main.py
# FINAL import os os.system("clear") with open("test.txt") as f: lines = [] lines = [i.replace("\n", "") for i in f.readlines()] def used(variable, code): counts = 0 for i in code: if variable in i: counts += 1 return False if counts > 0 else True def redefined_variables(): pass def dead_code_elimination(lines): variable = [] expressions = [] lines = [i.replace(" ", "") for i in lines] # print(lines) print("------------------------------") print("Original code...") for i in lines: print(i) for i in lines: left, right = i.split("=") variable.append(left) expressions.append(right) # print(variable) # print(expressions) # print(lines) # FIRST: REMOVING REDEFINED VARIABLES redefined_variables_line = [] for i in range(len(variable)): if variable[i] in variable[i+1:]: redefined_variables_line.append(i) # print(redefined_variables_line) variable = [j for i, j in enumerate(variable) if i not in redefined_variables_line] expressions = [j for i, j in enumerate(expressions) if i not in redefined_variables_line] lines = [j for i, j in enumerate(lines) if i not in redefined_variables_line] # print(variable) # print(expressions) # print(lines) # SECOND: REMOVING SIMPLE ASSIGNMENT STATEMENTS NOT USED like x = 3 dead_code = [] dead_code_line = [] for i in range(len(variable)): if len(expressions[i]) == 1: # print(variable[i], expressions[i+1:]) if used(variable[i], expressions[i+1:]): # print(variable[i]+"="+expressions[i]) dead_code.append((i, variable[i]+"="+expressions[i])) dead_code_line.append(i) # print("------------------------------") # print("Dead code lines...") # for i in dead_code: # print(f"Line: {i[0]+1}, code: {i[1]}") print("------------------------------") print("Removing dead code...") for i, j in enumerate(lines): if i in dead_code_line: continue else: print(j) lines = [j for i, j in enumerate(lines) if i not in dead_code_line] return lines # for i in range(2): # print(f"PASS - {i}") # lines = dead_code_elimination(lines) # print() dead_code_elimination(lines)
jpkulasingham/Eelbrain
examples/datasets/basic.py
""" .. _exa-dataset: Dataset basics ============== """ # Author: <NAME> <<EMAIL>> from eelbrain import * import numpy as np ############################################################################### # A dataset can be constructed column by column, by adding one variable after # another: # initialize an empty Dataset: ds = Dataset() # numeric values are added as Var object: ds['y'] = Var(np.random.normal(0, 1, 6)) # categorical data as represented in Factors: ds['a'] = Factor(['a', 'b', 'c'], repeat=2) # check the result: print(ds) ############################################################################### # For larger datasets it can be more convenient to print only the first few # cases... print(ds.head()) ############################################################################### # ... or a summary of variables: print(ds.summary()) ############################################################################### # An alternative way of constructing a dataset is case by case (i.e., row by # row): rows = [] for i in range(6): subject = f'S{i}' y = np.random.normal(0, 1) a = 'abc'[i % 3] rows.append([subject, y, a]) ds = Dataset.from_caselist(['subject', 'y', 'a'], rows, random='subject') print(ds)
avereon/cart2
source/test/java/com/avereon/cartesia/data/DesignEllipseTest.java
package com.avereon.cartesia.data; import com.avereon.cartesia.PointAssert; import com.avereon.curve.math.Constants; import javafx.geometry.Point3D; import org.assertj.core.data.Offset; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; import static com.avereon.cartesia.TestConstants.TOLERANCE; import static org.assertj.core.api.Assertions.assertThat; public class DesignEllipseTest { @Test void testModify() { DesignEllipse line = new DesignEllipse( new Point3D( 0, 0, 0 ), 1.0 ); assertThat( line.isModified() ).isTrue(); line.setModified( false ); assertThat( line.isModified() ).isFalse(); line.setOrigin( new Point3D( 0, 0, 0 ) ); line.setRadius( 1.0 ); assertThat( line.isModified() ).isFalse(); line.setOrigin( new Point3D( 1, 1, 0 ) ); assertThat( line.isModified() ).isTrue(); line.setModified( false ); assertThat( line.isModified() ).isFalse(); line.setRadius( 2.0 ); assertThat( line.isModified() ).isTrue(); line.setModified( false ); assertThat( line.isModified() ).isFalse(); } @Test void testOrigin() { DesignEllipse arc = new DesignEllipse( new Point3D( 0, 0, 0 ), 2.0 ); assertThat( arc.getOrigin() ).isEqualTo( new Point3D( 0, 0, 0 ) ); arc.setOrigin( new Point3D( 1, 2, 3 ) ); assertThat( arc.getOrigin() ).isEqualTo( new Point3D( 1, 2, 3 ) ); } @Test void testRadius() { DesignEllipse arc = new DesignEllipse( new Point3D( 0, 0, 0 ), 3.0 ); assertThat( arc.getRadius() ).isEqualTo( 3.0 ); arc.setRadius( 3.5 ); assertThat( arc.getRadius() ).isEqualTo( 3.5 ); } @Test void testToMapWithCircle() { DesignEllipse arc = new DesignEllipse( new Point3D( 1, 2, 3 ), 4.0 ); Map<String, Object> map = arc.asMap(); assertThat( map.get( DesignEllipse.SHAPE ) ).isEqualTo( DesignEllipse.CIRCLE ); assertThat( map.get( DesignEllipse.ORIGIN ) ).isEqualTo( new Point3D( 1, 2, 3 ) ); assertThat( map.get( DesignEllipse.RADIUS ) ).isEqualTo( 4.0 ); assertThat( map.get( DesignEllipse.X_RADIUS ) ).isNull(); assertThat( map.get( DesignEllipse.Y_RADIUS ) ).isNull(); assertThat( map.get( DesignEllipse.ROTATE ) ).isNull(); } @Test void testToMapWithEllipse() { DesignEllipse arc = new DesignEllipse( new Point3D( 1, 2, 3 ), 4.0, 5.0 ); Map<String, Object> map = arc.asMap(); assertThat( map.get( DesignEllipse.SHAPE ) ).isEqualTo( DesignEllipse.ELLIPSE ); assertThat( map.get( DesignEllipse.ORIGIN ) ).isEqualTo( new Point3D( 1, 2, 3 ) ); assertThat( map.get( DesignEllipse.X_RADIUS ) ).isEqualTo( 4.0 ); assertThat( map.get( DesignEllipse.Y_RADIUS ) ).isEqualTo( 5.0 ); assertThat( map.get( DesignEllipse.ROTATE ) ).isNull(); } @Test void testToMapWithRotatedEllipse() { DesignEllipse arc = new DesignEllipse( new Point3D( 1, 2, 3 ), 6.0, 7.0, 8.0 ); Map<String, Object> map = arc.asMap(); assertThat( map.get( DesignEllipse.SHAPE ) ).isEqualTo( DesignEllipse.ELLIPSE ); assertThat( map.get( DesignEllipse.ORIGIN ) ).isEqualTo( new Point3D( 1, 2, 3 ) ); assertThat( map.get( DesignEllipse.X_RADIUS ) ).isEqualTo( 6.0 ); assertThat( map.get( DesignEllipse.Y_RADIUS ) ).isEqualTo( 7.0 ); assertThat( map.get( DesignEllipse.ROTATE ) ).isEqualTo( 8.0 ); } @Test void testUpdateFromCircle() { Map<String, Object> map = new HashMap<>(); map.put( DesignEllipse.SHAPE, DesignEllipse.CIRCLE ); map.put( DesignEllipse.ORIGIN, "0,0,0" ); map.put( DesignEllipse.RADIUS, 4.0 ); DesignEllipse arc = new DesignEllipse(); arc.updateFrom( map ); assertThat( arc.getOrigin() ).isEqualTo( Point3D.ZERO ); assertThat( arc.getRadius() ).isEqualTo( 4.0 ); assertThat( arc.getXRadius() ).isEqualTo( 4.0 ); assertThat( arc.getYRadius() ).isEqualTo( 4.0 ); assertThat( arc.calcRotate() ).isEqualTo( 0.0 ); assertThat( arc.getRotate() ).isNull(); } @Test void testUpdateFromEllipse() { Map<String, Object> map = new HashMap<>(); map.put( DesignEllipse.SHAPE, DesignEllipse.ELLIPSE ); map.put( DesignEllipse.ORIGIN, "0,0,0" ); map.put( DesignEllipse.X_RADIUS, 4.0 ); map.put( DesignEllipse.Y_RADIUS, 5.0 ); DesignEllipse arc = new DesignEllipse(); arc.updateFrom( map ); assertThat( arc.getOrigin() ).isEqualTo( Point3D.ZERO ); assertThat( arc.getRadius() ).isEqualTo( 4.0 ); assertThat( arc.getXRadius() ).isEqualTo( 4.0 ); assertThat( arc.getYRadius() ).isEqualTo( 5.0 ); assertThat( arc.calcRotate() ).isEqualTo( 0.0 ); assertThat( arc.getRotate() ).isNull(); } @Test void testUpdateFromRotatedEllipse() { Map<String, Object> map = new HashMap<>(); map.put( DesignEllipse.SHAPE, DesignEllipse.ELLIPSE ); map.put( DesignEllipse.ORIGIN, "0,0,0" ); map.put( DesignEllipse.X_RADIUS, 6.0 ); map.put( DesignEllipse.Y_RADIUS, 7.0 ); map.put( DesignEllipse.ROTATE, 8.0 ); DesignEllipse arc = new DesignEllipse(); arc.updateFrom( map ); assertThat( arc.getOrigin() ).isEqualTo( Point3D.ZERO ); assertThat( arc.getRadius() ).isEqualTo( 6.0 ); assertThat( arc.getXRadius() ).isEqualTo( 6.0 ); assertThat( arc.getYRadius() ).isEqualTo( 7.0 ); assertThat( arc.calcRotate() ).isEqualTo( 8.0 ); assertThat( arc.getRotate() ).isEqualTo( 8.0 ); } @Test void testDistanceTo() { // Test circles DesignEllipse arc = new DesignEllipse( new Point3D( 5, 0, 0 ), 1.0 ); assertThat( arc.distanceTo( new Point3D( 0, 0, 0 ) ) ).isEqualTo( 4.0 ); assertThat( arc.distanceTo( new Point3D( 5, 0, 0 ) ) ).isEqualTo( 1.0 ); // TODO Test DesignEllipse.distanceTo() } @Test void testPathLength() { // Circle assertThat( new DesignEllipse( new Point3D( 5, 0, 0 ), 1.0 ).pathLength() ).isCloseTo( Constants.FULL_CIRCLE, TOLERANCE ); // Degenerate ellipses assertThat( new DesignEllipse( new Point3D( 5, 0, 0 ), 2.0, 0.0 ).pathLength() ).isCloseTo( 8.0, Offset.offset( Constants.RESOLUTION_LENGTH ) ); assertThat( new DesignEllipse( new Point3D( 5, 0, 0 ), 0.0, 1.0 ).pathLength() ).isCloseTo( 4.0, Offset.offset( Constants.RESOLUTION_LENGTH ) ); assertThat( new DesignEllipse( new Point3D( 5, 0, 0 ), 10.0, 5.0 ).pathLength() ).isCloseTo( 48.44224110273837, Offset.offset( Constants.RESOLUTION_LENGTH ) ); } @Test void testLocalTransform() { DesignEllipse ellipse = new DesignEllipse( new Point3D( 0, 0, 0 ), 2.0, 1.0 ); PointAssert.assertThat( ellipse.getLocalTransform().apply( new Point3D( 1, 1, 0 ) ) ).isCloseTo( new Point3D( 1, 2, 0 ) ); ellipse = new DesignEllipse( new Point3D( 0, 0, 0 ), 2.0, 4.0 ); PointAssert.assertThat( ellipse.getLocalTransform().apply( new Point3D( 1, 1, 0 ) ) ).isCloseTo( new Point3D( 1, 0.5, 0 ) ); } @Test void testLocalTransformWithRotationScaleAndTranslate() { double root2 = Math.sqrt( 2 ); DesignEllipse ellipse = new DesignEllipse( new Point3D( -3.0, 3.0, 0 ), 2.0, 1.0, 45.0 ); PointAssert.assertThat( ellipse.getLocalTransform().apply( ellipse.getOrigin() ) ).isCloseTo( new Point3D( 0, 0, 0 ) ); PointAssert.assertThat( ellipse.getLocalTransform().apply( new Point3D( -1, -1, 0 ) ) ).isCloseTo( new Point3D( -1 * root2, -6 * root2, 0 ) ); ellipse = new DesignEllipse( new Point3D( -3.0, -3.0, 0 ), 2.0, 4.0, 270.0 ); PointAssert.assertThat( ellipse.getLocalTransform().apply( ellipse.getOrigin() ) ).isCloseTo( new Point3D( 0, 0, 0 ) ); PointAssert.assertThat( ellipse.getLocalTransform().apply( new Point3D( -1, -1, 0 ) ) ).isCloseTo( new Point3D( -2, 1, 0 ) ); } }
doc22940/flawwwless-ui
src/components/Switch/index.js
<filename>src/components/Switch/index.js import React, { Component } from 'react'; import GetContext from "../GetContext"; import styles from "./Switch.scss"; class Switch extends Component { render(){ let { checked, name, onChange, disabled } = this.props; const { primaryColor } = this.props.context; const disabledClass = disabled ? styles.disabledClass : ""; return ( <label className={ styles.switch }> <input name={ name } checked={ checked } onChange={ onChange } disabled={ disabled } type="checkbox" /> <span onClick={ onChange } style={{ backgroundColor: checked ? primaryColor : "#d2d2d2" }} className={ `${ styles.slider } ${ disabledClass }` }></span> </label> ) } } Switch.defaultProps = { checked: undefined, name: undefined, onChange: undefined, disabled: false, } export default GetContext(Switch);
rogerhutchings/Panoptes
db/migrate/20150610200133_add_defaults_to_project_content.rb
class AddDefaultsToProjectContent < ActiveRecord::Migration def change %i(title description introduction science_case result faq education_content).each do |column| change_column_default :project_contents, column, "" end end end
elix22/AtomicGameEngine
Build/node_modules/filelist/node_modules/utilities/test/inflection.js
<filename>Build/node_modules/filelist/node_modules/utilities/test/inflection.js<gh_stars>1000+ /* * Utilities: A classic collection of JavaScript utilities * Copyright 2112 <NAME> (<EMAIL>) * * 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. * */ var inflection = require('../lib/inflection') , assert = require('assert') , esInflections , sInflections , iesInflections , vesInflections , icesInflections , renInflections , oesInflections , iInflections , genInflections , irregularInflections , noInflections , tests; /** * Most test inflections are from Ruby on Rails: * https://github.com/rails/rails/blob/master/activesupport/test/inflector_test_cases.rb * * Ruby on Rails is MIT licensed: http://www.opensource.org/licenses/MIT */ esInflections = [ ["search", "searches"] , ["switch", "switches"] , ["fix", "fixes"] , ["box", "boxes"] , ["process", "processes"] , ["address", "addresses"] , ["wish", "wishes"] , ["status", "statuses"] , ["alias", "aliases"] , ["basis", "bases"] , ["diagnosis", "diagnoses"] , ["bus", "buses"] ]; sInflections = [ ["stack", "stacks"] , ["shoe", "shoes"] , ["status_code", "status_codes"] , ["case", "cases"] , ["edge", "edges"] , ["archive", "archives"] , ["experience", "experiences"] , ["day", "days"] , ["comment", "comments"] , ["foobar", "foobars"] , ["newsletter", "newsletters"] , ["old_news", "old_news"] , ["perspective", "perspectives"] , ["diagnosis_a", "diagnosis_as"] , ["horse", "horses"] , ["prize", "prizes"] ]; iesInflections = [ ["category", "categories"] , ["query", "queries"] , ["ability", "abilities"] , ["agency", "agencies"] ]; vesInflections = [ ["wife", "wives"] , ["safe", "saves"] , ["half", "halves"] , ["elf", "elves"] , ["dwarf", "dwarves"] ]; icesInflections = [ ["index", "indices"] , ["vertex", "vertices"] , ["matrix", "matrices"] ]; renInflections = [ ["node_child", "node_children"] , ["child", "children"] ]; oesInflections = [ ["buffalo", "buffaloes"] , ["tomato", "tomatoes"] ]; iInflections = [ ["octopus", "octopi"] , ["virus", "viri"] ]; genInflections = [ ["salesperson", "salespeople"] , ["person", "people"] , ["spokesman", "spokesmen"] , ["man", "men"] , ["woman", "women"] ]; irregularInflections = [ ["datum", "data"] , ["medium", "media"] , ["ox", "oxen"] , ["cow", "kine"] , ["mouse", "mice"] , ["louse", "lice"] , ["axis", "axes"] , ["testis", "testes"] , ["crisis", "crises"] , ["analysis", "analyses"] , ["quiz", "quizzes"] ]; noInflections = [ ["fish", "fish"] , ["news", "news"] , ["series", "series"] , ["species", "species"] , ["rice", "rice"] , ["information", "information"] , ["equipment", "equipment"] ]; tests = { 'test es plural words for inflection': function () { var i = esInflections.length , value; while (--i >= 0) { value = esInflections[i]; assert.equal(value[1], inflection.pluralize(value[0])) } } , 'test es singular words for inflection': function () { var i = esInflections.length , value; while (--i >= 0) { value = esInflections[i]; assert.equal(value[0], inflection.singularize(value[1])) } } , 'test s plural words for inflection': function () { var i = sInflections.length , value; while (--i >= 0) { value = sInflections[i]; assert.equal(value[1], inflection.pluralize(value[0])) } } , 'test s singular words for inflection': function () { var i = sInflections.length , value; while (--i >= 0) { value = sInflections[i]; assert.equal(value[0], inflection.singularize(value[1])) } } , 'test ies plural words for inflection': function () { var i = iesInflections.length , value; while (--i >= 0) { value = iesInflections[i]; assert.equal(value[1], inflection.pluralize(value[0])) } } , 'test ies singular words for inflection': function () { var i = iesInflections.length , value; while (--i >= 0) { value = iesInflections[i]; assert.equal(value[0], inflection.singularize(value[1])) } } , 'test ves plural words for inflection': function () { var i = vesInflections.length , value; while (--i >= 0) { value = vesInflections[i]; assert.equal(value[1], inflection.pluralize(value[0])) } } , 'test ves singular words for inflection': function () { var i = vesInflections.length , value; while (--i >= 0) { value = vesInflections[i]; assert.equal(value[0], inflection.singularize(value[1])) } } , 'test ices plural words for inflection': function () { var i = icesInflections.length , value; while (--i >= 0) { value = icesInflections[i]; assert.equal(value[1], inflection.pluralize(value[0])) } } , 'test ices singular words for inflection': function () { var i = icesInflections.length , value; while (--i >= 0) { value = icesInflections[i]; assert.equal(value[0], inflection.singularize(value[1])) } } , 'test ren plural words for inflection': function () { var i = renInflections.length , value; while (--i >= 0) { value = renInflections[i]; assert.equal(value[1], inflection.pluralize(value[0])) } } , 'test ren singular words for inflection': function () { var i = renInflections.length , value; while (--i >= 0) { value = renInflections[i]; assert.equal(value[0], inflection.singularize(value[1])) } } , 'test oes plural words for inflection': function () { var i = oesInflections.length , value; while (--i >= 0) { value = oesInflections[i]; assert.equal(value[1], inflection.pluralize(value[0])) } } , 'test oes singular words for inflection': function () { var i = oesInflections.length , value; while (--i >= 0) { value = oesInflections[i]; assert.equal(value[0], inflection.singularize(value[1])) } } , 'test i plural words for inflection': function () { var i = iInflections.length , value; while (--i >= 0) { value = iInflections[i]; assert.equal(value[1], inflection.pluralize(value[0])) } } , 'test i singular words for inflection': function () { var i = iInflections.length , value; while (--i >= 0) { value = iInflections[i]; assert.equal(value[0], inflection.singularize(value[1])) } } , 'test gender and people plural words for inflection': function () { var i = genInflections.length , value; while (--i >= 0) { value = genInflections[i]; assert.equal(value[1], inflection.pluralize(value[0])) } } , 'test gender and people singular words for inflection': function () { var i = genInflections.length , value; while (--i >= 0) { value = genInflections[i]; assert.equal(value[0], inflection.singularize(value[1])) } } , 'test irregular plural words for inflection': function () { var i = irregularInflections.length , value; while (--i >= 0) { value = irregularInflections[i]; assert.equal(value[1], inflection.pluralize(value[0])) } } , 'test irregular singular words for inflection': function () { var i = irregularInflections.length , value; while (--i >= 0) { value = irregularInflections[i]; assert.equal(value[0], inflection.singularize(value[1])) } } , 'test no change plural words for inflection': function () { var i = noInflections.length , value; while (--i >= 0) { value = noInflections[i]; assert.equal(value[1], inflection.pluralize(value[0])) } } , 'test no change singular words for inflection': function () { var i = noInflections.length , value; while (--i >= 0) { value = noInflections[i]; assert.equal(value[0], inflection.singularize(value[1])) } } }; module.exports = tests;
olemeyer/eu.cloudwave.ude.fcore.plugin.bundled
src/eu/cloudwave/ude/fcore/plugin/model/Flavor.java
package eu.cloudwave.ude.fcore.plugin.model; public class Flavor { private int cpu; private int ram; public Flavor(int cpu, int ram) { super(); this.cpu = cpu; this.ram = ram; } public int getCpu() { return cpu; } public void setCpu(int cpu) { this.cpu = cpu; } public int getRam() { return ram; } public void setRam(int ram) { this.ram = ram; } }
usadson/WebEngine
ccompat.hpp
#pragma once /** * Copyright (C) 2020 Tristan. All Rights Reserved. * This file is licensed under the BSD 2-Clause license. * See the COPYING file for licensing information. * * CCompat is the Compatibility Layer for working with C, when it is needed. */ namespace CCompat { [[nodiscard]] const char * GetErrnoName(int error = 0); void CloseStandardIO(); } // namespace CCompat
rootsoluk/PulseTile-React
src/components/pages/Events/selectors.js
import { createSelector } from 'reselect'; import _ from 'lodash/fp'; import { operationsOnCollection } from '../../../utils/plugin-helpers.utils'; import { valuesNames } from './forms.config'; const eventsCreateFormSelector = _.getOr({}, 'form.eventsCreateFormSelector'); const eventsDetailFormSelector = _.getOr({}, 'form.eventsDetailFormSelector'); const userAccountSelector = ({ userAccount }) => userAccount; const patientEventsSelector = createSelector( ({ patientsEvents }) => patientsEvents, (state, props) => _.getOr(null, 'match.params.userId', props), (patientsEvents, userId) => { const allEvents = operationsOnCollection.modificate(patientsEvents[userId], [{ key: valuesNames.DATE_TIME, fn: item => new Date(item).getTime(), }]); return ({ allEvents, userId }); } ); const eventsDetailFormStateSelector = createSelector(eventsDetailFormSelector, eventsDetailFormState => ({ eventsDetailFormState })); const eventsCreateFormStateSelector = createSelector(eventsCreateFormSelector, eventsCreateFormState => ({ eventsCreateFormState })); const patientEventsDetailSelector = createSelector( ({ eventsDetail }) => eventsDetail, (state, props) => _.getOr(null, 'match.params.userId', props), (eventsDetail, userId) => { const eventDetail = eventsDetail[userId]; return ({ eventDetail, userId }); } ); const userSelector = createSelector( userAccountSelector, userAccount => ({ userAccount }) ); export { patientEventsSelector, eventsDetailFormStateSelector, eventsCreateFormStateSelector, patientEventsDetailSelector, userSelector }
Studyokee/studyokee-youtube
models/vocabulary.js
<reponame>Studyokee/studyokee-youtube 'use strict'; var mongoose = require('mongoose'); var q = require('q'); var Vocabulary; var vocabularySchema = mongoose.Schema({ userId: { type: String, required: true }, fromLanguage: { type: String, required: true }, toLanguage: { type: String, required: true }, words: [{ word: String, def: String, known: Boolean }] }); function findOne (query) { var findOneRequest = q.defer(); Vocabulary.findOne(query, findOneRequest.makeNodeResolver()); return findOneRequest.promise; } function save (saveObj) { var vocabulary = new Vocabulary(saveObj); var saveRequest = q.defer(); vocabulary.save(saveRequest.makeNodeResolver()); return saveRequest.promise.spread(function(res) { return res; }); } function getIndex (words, word) { for (var i = 0; i < words.length; i++) { if (words[i].word === word) { return i; } } return -1; } vocabularySchema.static('addWord', function(query, word, def) { var toReturn = null; return q.resolve().then(function () { return Vocabulary.findOrCreate(query); }).then(function (vocabulary) { toReturn = vocabulary; if (vocabulary.words.length < process.env.VOCABULARY_LIMIT && getIndex(vocabulary.words, word) === -1) { var toInsert = { word: word, def: def, known: false }; vocabulary.words.push(toInsert); var updates = { words: vocabulary.words }; var updateRequest = q.defer(); vocabulary.update(updates, updateRequest.makeNodeResolver()); return updateRequest.promise; } return q.resolve(); }).then(function () { return toReturn; }); }); vocabularySchema.static('removeWord', function(query, word) { var toReturn = null; var i; return q.resolve().then(function () { return Vocabulary.findOrCreate(query); }).then(function (vocabulary) { toReturn = vocabulary; i = getIndex(vocabulary.words, word); vocabulary.words[i].known = true; var updates = { words: vocabulary.words }; var updateRequest = q.defer(); vocabulary.update(updates, updateRequest.makeNodeResolver()); return updateRequest.promise; }).then(function () { return toReturn; }); }); vocabularySchema.static('updateWord', function(query, word) { var toReturn = null; var i; return q.resolve().then(function () { return Vocabulary.findOrCreate(query); }).then(function (vocabulary) { toReturn = vocabulary; i = getIndex(vocabulary.words, word.word); if (i < 0) { q.resolve(); } vocabulary.words[i].def = word.def; var updates = { words: vocabulary.words }; var updateRequest = q.defer(); vocabulary.update(updates, updateRequest.makeNodeResolver()); return updateRequest.promise; }).then(function () { return toReturn; }); }); vocabularySchema.static('findOrCreate', function (fields) { if (!fields.userId) { return q.reject('No user id provided'); } if (!fields.fromLanguage) { return q.reject('No from language provided'); } if (!fields.toLanguage) { return q.reject('No to language provided'); } return findOne({ userId: fields.userId, fromLanguage: fields.fromLanguage, toLanguage: fields.toLanguage }).then(function (vocabulary) { if (vocabulary) { return vocabulary; } console.log('failed to find vocabulary matching criteria, creating new one...'); return save({ userId: fields.userId, fromLanguage: fields.fromLanguage, toLanguage: fields.toLanguage }).fail(function() { // Save failed, try to get again in case concurrent request caused failure return findOne({ userId: fields.userId, fromLanguage: fields.fromLanguage, toLanguage: fields.toLanguage }); }); }); }); Vocabulary = mongoose.model('Vocabulary', vocabularySchema); module.exports = Vocabulary;
82ndAirborneDiv/esquire-frontend
src/components/Header/index.js
<filename>src/components/Header/index.js import React from 'react' import PropTypes from 'prop-types' import Grid from 'material-ui/Grid' import { withTheme } from 'material-ui/styles' import Logo from 'components/Logo' import Greeting from './components/Greeting' import Avatar from 'components/Avatar' import Admin from '../../scenes/Admin' import { Link } from 'react-router-dom' const Header = ({ theme, user }) => { const bgColor = theme.palette.primary['600'] const styles = { height: '100px', backgroundColor: bgColor, padding: '0 30px' } return ( <Grid container spacing={0} alignItems="center" style={styles}> <Grid item xs> <Link style={{ textDecoration: 'none' }} to="/"><Logo fontSize="30px" /></Link> </Grid> <Grid item> <Grid container spacing={8} alignItems="center"> <Grid item> <Greeting firstName={user.firstName} lastName={user.lastName} role={user.role} /> </Grid> <Grid item> <Link style={{ textDecoration: 'none' }} to="/admin"><Avatar big initials={user.firstName ? `${user.firstName[0]}${user.lastName[0]}` : ''} /></Link> </Grid> </Grid> </Grid> </Grid> ) } Header.propTypes = { theme: PropTypes.object.isRequired, user: PropTypes.object } export default withTheme()(Header)
openJT/auth-rest
apps/web/js/products.js
var products = (function (Global) { 'use strict'; var products, productDetail = {}; var dialog = document.querySelector('#productDialog'); var socket = io('/admin', { 'query': 'token=' + window.localStorage.getItem("token"), path: '/auth-rest/socket.io' }); var snackbarContainer = document.querySelector('#toast'); socket.on('addProduct', function (product) { products.push(product); Global.draw.productsTable(products); toast({ message: product.name + " added!" }); }); socket.on('deleteProduct', function (product) { products.forEach(function (t, i) { if (t._id === product._id) { products.splice(i, 1); if (product._id === productDetail._id) clearDetails(); Global.draw.productsTable(products); toast({ message: product.name + " deleted!" }); } }); }); socket.on('updateProduct', function (product) { products.forEach(function (t, i) { if (t._id === product._id) { products[i] = product; Global.draw.productsTable(products); toast({ message: product.name + " updated!" }); } }); }); socket.on('reset', function (product) { console.log('reset in products'); var http = new XMLHttpRequest(); var url = "/auth-rest/product"; http.open("GET", url, true); var token = 'Bearer ' + window.localStorage.getItem("token"); http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); if (window.localStorage.getItem("token")) http.setRequestHeader("Authorization", token) http.setRequestHeader("Accept", "application/json"); http.onreadystatechange = function () { if (http.readyState == 4 && http.status == 200) { products = JSON.parse(http.responseText); Global.draw.productsTable(products); toast({ message: "Data reset!" }); } else if (http.readyState == 4 && http.status == 401) { window.localStorage.removeItem("token"); window.location.assign('/auth-rest/web'); } } http.send(); }); return { getData: getData, addProductDialog: addProductDialog, saveProduct: saveProduct, getDetails: getDetails, setDetails: setDetails, cancelProduct: cancelProduct, deleteProduct: deleteProduct, reset: reset, resetForm: resetForm, logout: logout } function toast(msg) { snackbarContainer.MaterialSnackbar.showSnackbar(msg); } function getData() { var http = new XMLHttpRequest(); var url = "/auth-rest/product"; http.open("GET", url, true); var token = 'Bearer ' + window.localStorage.getItem("token"); http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); if (window.localStorage.getItem("token")) http.setRequestHeader("Authorization", token) http.setRequestHeader("Accept", "application/json"); http.onreadystatechange = function () { if (http.readyState == 4 && http.status == 200) { products = JSON.parse(http.responseText); Global.draw.productsTable(products); } else if (http.readyState == 4 && http.status == 401) { window.localStorage.removeItem("token"); window.location.assign('/auth-rest/web'); } } http.send(); } function getDetails(id) { productDetail = Global.draw.productDetails(id); } function setDetails(details) { productDetail = details; } function clearDetails() { var element = document.getElementById("productDetails"); element.innerHTML = ""; } function addProductDialog() { showDialog(); } function saveProduct() { if ( document.forms["productForm"].elements['name'].value === '' ) { var data = { message: 'Please fill all required fields' }; snackbarContainer.MaterialSnackbar.showSnackbar(data); } else { if (document.forms["productForm"].elements['returnable'].value === "on") { document.forms["productForm"].elements['returnable'].value = true; } else document.forms["productForm"].elements['returnable'].value = false; Global.rest.saveProduct(); } } function deleteProduct(i) { Global.rest.deleteProduct(products[i]._id); } function cancelProduct() { dialog.close(); resetForm(); } function resetForm() { console.log(document.forms["productForm"].elements['returnable'].value); document.forms["productForm"].reset(); document.forms["productForm"].elements['returnable'].value = 'off'; } function showDialog() { if (!dialog.showModal) dialogPolyfill.registerDialog(dialog); else dialog.showModal(); } function logout() { window.localStorage.removeItem("token"); window.location.assign('/'); } function reset() { rest.reset(); } })(this)
andyglick/openclover-git
clover-eclipse/com.atlassian.clover.eclipse.core/src/com/atlassian/clover/eclipse/core/views/actions/ToggleCloverCompilerActionDelegate.java
<reponame>andyglick/openclover-git package com.atlassian.clover.eclipse.core.views.actions; import org.eclipse.jface.action.IAction; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import com.atlassian.clover.eclipse.core.projects.CloverProject; import com.atlassian.clover.eclipse.core.CloverPlugin; public class ToggleCloverCompilerActionDelegate extends SingleCloverProjectActionDelegate { @Override protected void updateStateForSelection(IAction action) { super.updateStateForSelection(action); if (action.isEnabled()) { try { CloverProject project = CloverProject.getFor((IProject)projects.iterator().next()); action.setChecked(project.getSettings().isInstrumentationEnabled()); } catch (CoreException e) { CloverPlugin.logError("Unable to check/uncheck " + getClass().getName(), e); } } } @Override public void run(IAction action) { try { CloverProject project = CloverProject.getFor((IProject)projects.iterator().next()); if (project != null) { project.getSettings().setInstrumentationEnabled(action.isChecked()); CloverPlugin.getInstance().getCoverageMonitor().fireCoverageChange(project); if (project.okayToRebuild(getShell())) { project.getProject().build(IncrementalProjectBuilder.CLEAN_BUILD, null); } } } catch (CoreException e) { CloverPlugin.logError("Unable to toggle Clover compiler", e); } } }
Elizabeth-Warren/pollaris
backend/pollaris/app/tests/test_side_effects.py
import copy import json import pprint import urllib import pytest import responses from django.test import Client BSD_PROXY_URL = "https://bsd-signup-proxy" FORM_REQUEST_IA = { # This comes from inspecting the form submission in Chrome and # choosing "Copy as cURL". "form": "firstname=Jason&lastname=Katz-Brown&email=example%40example.com&phone=5105551234&addr1=1140%20Vividell%20Ln&city=West%20Des%20Moines&state_cd=IA&zip=50266&custom-16069=50266&custom-16063=947770&custom-16067=West%20Des%20Moines&custom-16065=Monday%2C%20February%203%2C%202020.%20The%20caucus%20starts%20at%207pm%2C%20but%20we%20recommend%20you%20arrive%20at%206%3A30pm.&custom-16068=IA&custom-16064=Valley%20High%20School%20-%20Cafeteria&custom-16066=3650%20Woodland%20Ave&custom-16616=en-US" } FORM_REQUEST_NH = { "form": "firstname=Jason&lastname=Katz-Brown&email=example%40example.com&phone=5105551234&addr1=6%20Sunrise%20Trail&city=Nashua&state_cd=NH&zip=03062&custom-16069=03062&custom-16063=972394&custom-16067=Nashua&custom-16065=6:00%20AM%20-%208:00%20PM&custom-16068=NH&custom-16064=MAIN%20DUNSTABLE%20ELEMENTARY%20SCHOOL&custom-16066=20%20Whitford%20Road&custom-16616=en-US" } FORM_REQUEST_NV_EARLY_VOTE = { "form": "firstname=Jason&lastname=Katz-Brown&email=example%40example.com&phone=5105551234&addr1=6%20California%20Way&city=Henderson&state_cd=NV&zip=89015&custom-16616=en-US&custom-16069=89015&custom-16063=9139047815396910000&custom-17132=https%3A%2F%2Fexample.com%2Fvote%3Fid%3DChIJaVLWwrvWyIARxS_ve7bmrgY&custom-17131=early_vote_locations&custom-16067=Henderson&custom-16065=Sa%202%2F15%2010AM%20-%206PM%2C%20Su%202%2F16%201PM%20-%205PM%2C%20Mo%202%2F17%2010AM%20-%206PM%2C%20Tu%202%2F18%208AM%20-%208PM&custom-16068=NV&custom-16064=Steelworkers%20Local%204856&custom-16066=47%20S%20Water%20Street&custom-17240=9139047815396910000" } FORM_REQUEST_NV_CAUCUS = { "form": "firstname=Jason&lastname=Katz-Brown&email=example%40example.com&phone=5105551234&addr1=6%20California%20Way&city=Henderson&state_cd=NV&zip=89015&custom-16616=en-US&custom-16069=89015&custom-16063=3937382232689271000&custom-17132=https%3A%2F%2Fexample.com%2Fvote%3Fid%3DChIJaVLWwrvWyIARxS_ve7bmrgY%26streetNumber%3D6&custom-17131=polling_locations&custom-16067=HENDERSON&custom-16065=Caucus%20Registration%20Opens%20at%2010AM%2C%20Registration%20Closes%20at%2012PM&custom-16068=NV&custom-16064=Caucus%20Day%20Location%20-%20LYAL%20BURKHOLDER%20MIDDLE%20SCHOOL&custom-16066=355%20W%20VAN%20WAGENEN%20ST&custom-17240=3937382232689271000" } FORM_REQUEST_CA_VOTE_BY_MAIL = { "form": "firstname=Jason&lastname=Katz-Brown&email=example%40example.com&phone=5105551234&addr1=20%20Belvedere%20Ave&city=Richmond&state_cd=CA&zip=94801&custom-16616=en-US&custom-17132=https%3A%2F%2Fwarrenreports-staging-pr-704.herokuapp.com%2Fvote%3Fid%3DChIJB9p2QsSChYARaTB0k8y-N8Y%26streetNumber%3D20&custom-17131=vote_by_mail&custom-18207=warrenreports-staging-pr-704.herokuapp.com%2Fvote%2Fcalifornia&custom-17816=14822091002910517536" } MOBILE_COMMONS_PROFILE_UPDATE_GOLDEN_IA = { "phone_number": "15105551234", "email": "<EMAIL>", "postal_code": "50266", "first_name": "Jason", "last_name": "Katz-Brown", "street1": "1140 Vividell Ln", "city": "West Des Moines", "state": "IA", "country": "US", "polling_location_name": "Valley High School - Cafeteria", "polling_address": "3650 Woodland Ave", "polling_city": "West Des Moines", "polling_state": "IA", "polling_zip": "50266", "polling_time": "Monday, February 3, 2020. The caucus starts at 7pm, but we recommend you arrive at 6:30pm.", "polling_precinct_id": "947770", "opt_in_path_id": 290677, } MOBILE_COMMONS_PROFILE_UPDATE_GOLDEN_NH = { "phone_number": "15105551234", "email": "<EMAIL>", "postal_code": "03062", "first_name": "Jason", "last_name": "Katz-Brown", "street1": "6 Sunrise Trail", "city": "Nashua", "state": "NH", "country": "US", "polling_location_name": "MAIN DUNSTABLE ELEMENTARY SCHOOL", "polling_address": "20 Whitford Road", "polling_city": "Nashua", "polling_state": "NH", "polling_zip": "03062", "polling_time": "6:00 AM - 8:00 PM", "polling_precinct_id": "972394", "opt_in_path_id": 291258, } MOBILE_COMMONS_PROFILE_UPDATE_GOLDEN_NV_EARLY_VOTE = { "city": "Henderson", "country": "US", "email": "<EMAIL>", "first_name": "Jason", "last_name": "Katz-Brown", "opt_in_path_id": 292302, "phone_number": "15105551234", "polling_address": "47 S Water Street", "polling_city": "Henderson", "polling_location_name": "Steelworkers Local 4856", "polling_precinct_id": "9139047815396910000", "polling_state": "NV", "polling_time": "Sa 2/15 10AM - 6PM, Su 2/16 1PM - 5PM, Mo 2/17 10AM - 6PM, " "Tu 2/18 8AM - 8PM", "polling_zip": "89015", "postal_code": "89015", "state": "NV", "street1": "6 California Way", } MOBILE_COMMONS_PROFILE_UPDATE_GOLDEN_NV_CAUCUS = { "city": "Henderson", "country": "US", "email": "<EMAIL>", "first_name": "Jason", "last_name": "Katz-Brown", "opt_in_path_id": 292305, "phone_number": "15105551234", "polling_address": "355 W VAN WAGENEN ST", "polling_city": "HENDERSON", "polling_location_name": "Caucus Day Location - LYAL BURKHOLDER MIDDLE SCHOOL", "polling_precinct_id": "3937382232689271000", "polling_state": "NV", "polling_time": "Caucus Registration Opens at 10AM, Registration Closes at 12PM", "polling_zip": "89015", "postal_code": "89015", "state": "NV", "street1": "6 California Way", } MOBILE_COMMONS_PROFILE_UPDATE_GOLDEN_CA_VOTE_BY_MAIL = { "city": "Richmond", "country": "US", "email": "<EMAIL>", "first_name": "Jason", "last_name": "Katz-Brown", "opt_in_path_id": 294243, "phone_number": "15105551234", "postal_code": "94801", "state": "CA", "street1": "20 Belvedere Ave", } MOBILE_COMMONS_SEND_MESSAGE_GOLDEN_IA = { "campaign_id": 189358, "phone_number": "15105551234", "body": "Your caucus location:\nValley High School - Cafeteria\n3650 Woodland Ave\nWest Des Moines, IA 50266\nMonday, February 3, 2020. The caucus starts at 7pm, but we recommend you arrive at 6:30pm.", } MOBILE_COMMONS_SEND_MESSAGE_GOLDEN_NH = { "campaign_id": 189358, "phone_number": "15105551234", "body": "Your polling location:\nMAIN DUNSTABLE ELEMENTARY SCHOOL\n20 Whitford Road\nNashua, NH 03062\n6:00 AM - 8:00 PM", } MOBILE_COMMONS_SEND_MESSAGE_GOLDEN_NV_EARLY_VOTE = { "body": "Your early vote location:\n" "Steelworkers Local 4856\n" "47 S Water Street\n" "Henderson, NV 89015\n" "Sa 2/15 10AM - 6PM, Su 2/16 1PM - 5PM, Mo 2/17 10AM - 6PM, Tu 2/18 " "8AM - 8PM", "campaign_id": 189358, "phone_number": "15105551234", } MOBILE_COMMONS_SEND_MESSAGE_GOLDEN_NV_EARLY_VOTE_ES = { "body": "Tu localizacion de votacion temprana:\n" "Steelworkers Local 4856\n" "47 S Water Street\n" "Henderson, NV 89015\n" "Sa 2/15 10AM - 6PM, Su 2/16 1PM - 5PM, Mo 2/17 10AM - 6PM, Tu 2/18 " "8AM - 8PM", "campaign_id": 189358, "phone_number": "15105551234", } MOBILE_COMMONS_SEND_MESSAGE_GOLDEN_NV_CAUCUS = { "body": "Your caucus location:\n" "Caucus Day Location - LYAL BURKHOLDER MIDDLE SCHOOL\n" "355 W VAN WAGENEN ST\n" "HENDERSON, NV 89015\n" "Caucus Registration Opens at 10AM, Registration Closes at 12PM", "campaign_id": 189358, "phone_number": "15105551234", } MOBILE_COMMONS_SEND_MESSAGE_GOLDEN_CA_VOTE_BY_MAIL = { "body": "Learn more about how to vote: " "warrenreports-staging-pr-704.herokuapp.com/vote/california", "campaign_id": 189358, "phone_number": "15105551234", } SES_SEND_EMAIL_ARGUMENTS_GOLDEN_IA = { "template_name": "voting_location_IA", "from_email": "I<NAME> <<EMAIL>>", "recipient": "<EMAIL>", "reply_to_email": "Iowa for Warren <<EMAIL>>", "configuration_set_name": "organizing_emails", "payload": { "addr1": "1140 Vividell Ln", "city": "West Des Moines", "dropbox_locations": False, "early_vote_locations": False, "email": "<EMAIL>", "firstname": "Jason", "language": "en-US", "lastname": "Katz-Brown", "vote_by_mail": False, "name_of_location": "Valley High School - Cafeteria", "phone": "5105551234", "polling_address": "3650 Woodland Ave", "polling_city": "West Des Moines", "polling_locations": True, "polling_state": "IA", "polling_zip": "50266", "preferred_voting_type": "polling_locations", "state_cd": "IA", "time_of_event": "Monday, February 3, 2020. The caucus starts at " "7pm, but we recommend you arrive at 6:30pm.", "transactional": True, "van_precinct_id": "947770", "zip": "50266", }, "application_name": "pollaris", } SES_SEND_EMAIL_ARGUMENTS_GOLDEN_NH = { "template_name": "voting_location_generic", "from_email": "New Hampshire for Warren <<EMAIL>>", "recipient": "<EMAIL>", "reply_to_email": "New Hampshire for Warren <<EMAIL>>", "configuration_set_name": "organizing_emails", "payload": { "addr1": "6 Sunrise Trail", "city": "Nashua", "dropbox_locations": False, "early_vote_locations": False, "email": "<EMAIL>", "firstname": "Jason", "language": "en-US", "lastname": "Katz-Brown", "vote_by_mail": False, "name_of_location": "MAIN DUNSTABLE ELEMENTARY SCHOOL", "phone": "5105551234", "polling_address": "20 Whitford Road", "polling_city": "Nashua", "polling_locations": True, "polling_state": "NH", "polling_zip": "03062", "preferred_voting_type": "polling_locations", "state_cd": "NH", "time_of_event": "6:00 AM - 8:00 PM", "transactional": True, "van_precinct_id": "972394", "zip": "03062", }, "application_name": "pollaris", } SES_SEND_EMAIL_ARGUMENTS_GOLDEN_NV_EARLY_VOTE = { "application_name": "pollaris", "configuration_set_name": "organizing_emails", "from_email": "<NAME> <<EMAIL>>", "payload": { "addr1": "6 California Way", "city": "Henderson", "dropbox_locations": False, "early_vote_locations": True, "email": "<EMAIL>", "firstname": "Jason", "language": "en-US", "lastname": "Katz-Brown", "vote_by_mail": False, "name_of_location": "Steelworkers Local 4856", "phone": "5105551234", "pollaris_search_id": "9139047815396910000", "polling_address": "47 S Water Street", "polling_city": "Henderson", "polling_locations": False, "polling_state": "NV", "polling_zip": "89015", "preferred_voting_type": "early_vote_locations", "results_url": "https://example.com/vote?id=ChIJaVLWwrvWyIARxS_ve7bmrgY", "state_cd": "NV", "time_of_event": "Sa 2/15 10AM - 6PM, Su 2/16 1PM - 5PM, Mo 2/17 " "10AM - 6PM, Tu 2/18 8AM - 8PM", "transactional": True, "van_precinct_id": "9139047815396910000", "zip": "89015", }, "recipient": "<EMAIL>", "reply_to_email": "<NAME> <<EMAIL>>", "template_name": "voting_location_NV", } SES_SEND_EMAIL_ARGUMENTS_GOLDEN_NV_CAUCUS = { "application_name": "pollaris", "configuration_set_name": "organizing_emails", "from_email": "<NAME> <<EMAIL>>", "payload": { "addr1": "6 California Way", "city": "Henderson", "dropbox_locations": False, "early_vote_locations": False, "email": "<EMAIL>", "firstname": "Jason", "language": "en-US", "lastname": "Katz-Brown", "vote_by_mail": False, "name_of_location": "Caucus Day Location - LYAL BURKHOLDER MIDDLE SCHOOL", "phone": "5105551234", "pollaris_search_id": "3937382232689271000", "polling_address": "355 W VAN WAGENEN ST", "polling_city": "HENDERSON", "polling_locations": True, "polling_state": "NV", "polling_zip": "89015", "preferred_voting_type": "polling_locations", "results_url": "https://example.com/vote?id=ChIJaVLWwrvWyIARxS_ve7bmrgY&streetNumber=6", "state_cd": "NV", "time_of_event": "Caucus Registration Opens at 10AM, Registration " "Closes at 12PM", "transactional": True, "van_precinct_id": "3937382232689271000", "zip": "89015", }, "recipient": "<EMAIL>", "reply_to_email": "<NAME> <<EMAIL>>", "template_name": "voting_location_NV", } SES_SEND_EMAIL_ARGUMENTS_GOLDEN_CA_VOTE_BY_MAIL = { "application_name": "pollaris", "configuration_set_name": "organizing_emails", "from_email": "ElizabethWarren.com <<EMAIL>>", "payload": { "addr1": "20 Belvedere Ave", "city": "Richmond", "custom-17816": "14822091002910517536", "dropbox_locations": False, "early_vote_locations": False, "email": "<EMAIL>", "firstname": "Jason", "language": "en-US", "lastname": "Katz-Brown", "phone": "5105551234", "polling_locations": False, "preferred_voting_type": "vote_by_mail", "results_url": "https://warrenreports-staging-pr-704.herokuapp.com/vote?id=ChIJB9p2QsSChYARaTB0k8y-N8Y&streetNumber=20", "state_cd": "CA", "transactional": True, "vote_by_mail": True, "voter_education_url": "warrenreports-staging-pr-704.herokuapp.com/vote/california", "zip": "94801", }, "recipient": "<EMAIL>", "reply_to_email": "ElizabethWarren.com <<EMAIL>>", "template_name": "voting_location_generic", } BSD_PROXY_SUBMIT_RESPONSE = { "statusCode": 202, "body": '{"api_version":1,"status":"success","thanks_url":"https:\\/\\/my.elizabethwarren.com\\/page\\/st\\/web-poll-tool?action_code=FgxRWxYUOVIKQV0YAFUHUU4J&td=VZHLTsMwEEV_JcqWprKTtCVZUakIsUBC4rVAyHLsSWvJsSM_ilrEvzMmhUJWnnNHc-9kPnJhownukLf500M-y2HgSmOxl8rzd-4uAvhwBVodeQdhh8SBmQs7YG-vnA-GD4D9z8rvuEao-S_bTCMQcikdRVLSJrvObhw3MlvvARWhQvLegM_urDLgkfnA...', } MOBILE_COMMONS_PROFILE_UPDATE_RESPONSE = """ <response success="true"> <profile id="345304097"> <first_name>Jason</first_name> <last_name>Katz-Brown</last_name> <phone_number>15105551234</phone_number> </profile> </response> """ MOBILE_COMMONS_SEND_MESSAGE_RESPONSE = """ <response success="true"> <message id="6755704007" type="generic" status="queued"> <phone_number>15105551234</phone_number> <profile>338948442</profile> <body>Your location...</body> <sent_at>2019-05-31 05:04:17 UTC</sent_at> <message_template_id/> <campaign id="189358" active="true"> <name>National</name> </campaign> </message> </response> """ @responses.activate def test_after_search_bad_request(mocker): responses.add( responses.POST, BSD_PROXY_URL, json=BSD_PROXY_SUBMIT_RESPONSE, ) invalid_request = { "form": "firstname=Jason&lastname=Katz-Brown&email=example%40example.com" } email_service_mock = mocker.patch("pollaris.app.views.side_effects.EmailService") resp = Client().post( "/api/v1/forms/after_search", invalid_request, content_type="application/json" ) assert resp.status_code == 400 assert resp.json()["error_message"].startswith("Form data doesn't include state_cd") @responses.activate def test_after_search_mobile_commons_failure(mocker): responses.add( responses.POST, BSD_PROXY_URL, json=BSD_PROXY_SUBMIT_RESPONSE, ) email_service_mock = mocker.patch("pollaris.app.views.side_effects.EmailService") resp = Client().post( "/api/v1/forms/after_search", FORM_REQUEST_IA, content_type="application/json" ) # We won't mock Mobile Commons, so it'll raise an exception. assert resp.status_code == 400 assert resp.json()["error_message"] == "Failure in sending voting location SMS" @responses.activate def test_after_search_ia(mocker): run_generic_test( mocker, FORM_REQUEST_IA, MOBILE_COMMONS_PROFILE_UPDATE_GOLDEN_IA, MOBILE_COMMONS_SEND_MESSAGE_GOLDEN_IA, SES_SEND_EMAIL_ARGUMENTS_GOLDEN_IA, ) @responses.activate def test_after_search_nh(mocker): run_generic_test( mocker, FORM_REQUEST_NH, MOBILE_COMMONS_PROFILE_UPDATE_GOLDEN_NH, MOBILE_COMMONS_SEND_MESSAGE_GOLDEN_NH, SES_SEND_EMAIL_ARGUMENTS_GOLDEN_NH, ) @responses.activate def test_after_search_nv_early_vote(mocker): run_generic_test( mocker, FORM_REQUEST_NV_EARLY_VOTE, MOBILE_COMMONS_PROFILE_UPDATE_GOLDEN_NV_EARLY_VOTE, MOBILE_COMMONS_SEND_MESSAGE_GOLDEN_NV_EARLY_VOTE, SES_SEND_EMAIL_ARGUMENTS_GOLDEN_NV_EARLY_VOTE, ) @responses.activate def test_after_search_nv_caucus(mocker): run_generic_test( mocker, FORM_REQUEST_NV_CAUCUS, MOBILE_COMMONS_PROFILE_UPDATE_GOLDEN_NV_CAUCUS, MOBILE_COMMONS_SEND_MESSAGE_GOLDEN_NV_CAUCUS, SES_SEND_EMAIL_ARGUMENTS_GOLDEN_NV_CAUCUS, ) @responses.activate def test_after_search_ca_vote_by_mail(mocker): run_generic_test( mocker, FORM_REQUEST_CA_VOTE_BY_MAIL, MOBILE_COMMONS_PROFILE_UPDATE_GOLDEN_CA_VOTE_BY_MAIL, MOBILE_COMMONS_SEND_MESSAGE_GOLDEN_CA_VOTE_BY_MAIL, SES_SEND_EMAIL_ARGUMENTS_GOLDEN_CA_VOTE_BY_MAIL, ) @responses.activate def test_after_search_nv_early_vote_es(mocker): form_request_es = FORM_REQUEST_NV_EARLY_VOTE.copy() form_request_es["form"] = urllib.parse.urlencode( [ x for x in urllib.parse.parse_qsl(form_request_es["form"]) if x[0] != "custom-16616" ] + [("custom-16616", "es-MX")] ) ses_send_email_arguments_es = copy.deepcopy( SES_SEND_EMAIL_ARGUMENTS_GOLDEN_NV_EARLY_VOTE ) ses_send_email_arguments_es["payload"]["language"] = "es-MX" ses_send_email_arguments_es["template_name"] = "voting_location_NV_es" ses_send_email_arguments_es[ "from_email" ] = "<NAME> <<EMAIL>>" ses_send_email_arguments_es[ "from_email" ] = "<NAME> <<EMAIL>>" ses_send_email_arguments_es[ "reply_to_email" ] = "<NAME> <<EMAIL>>" run_generic_test( mocker, form_request_es, MOBILE_COMMONS_PROFILE_UPDATE_GOLDEN_NV_EARLY_VOTE, MOBILE_COMMONS_SEND_MESSAGE_GOLDEN_NV_EARLY_VOTE_ES, ses_send_email_arguments_es, ) @responses.activate def test_after_search_no_phone(mocker): form_request_no_phone = FORM_REQUEST_IA.copy() form_request_no_phone["form"] = urllib.parse.urlencode( [ x for x in urllib.parse.parse_qsl(form_request_no_phone["form"]) if x[0] != "phone" ] ) ses_send_email_arguments_no_phone = copy.deepcopy( SES_SEND_EMAIL_ARGUMENTS_GOLDEN_IA ) del ses_send_email_arguments_no_phone["payload"]["phone"] run_generic_test( mocker, form_request_no_phone, None, None, ses_send_email_arguments_no_phone ) @responses.activate def test_after_search_draft_email(mocker): """Same as IA caucus location lookup, but with email address with +draftdraftdraft. This triggers mail using template with '_draft' suffix, i.e. 'voting_location_IA_draft' mailing template. """ draft_email = "<EMAIL>" form_request_draft_email = FORM_REQUEST_IA.copy() form_request_draft_email["form"] = urllib.parse.urlencode( [ x for x in urllib.parse.parse_qsl(form_request_draft_email["form"]) if x[0] != "email" ] + [("email", draft_email)] ) mobile_commons_profile_update_draft_email = ( MOBILE_COMMONS_PROFILE_UPDATE_GOLDEN_IA.copy() ) mobile_commons_profile_update_draft_email[ "email" ] = "<EMAIL>" ses_send_email_arguments_draft_email = copy.deepcopy( SES_SEND_EMAIL_ARGUMENTS_GOLDEN_IA ) ses_send_email_arguments_draft_email["recipient"] = draft_email ses_send_email_arguments_draft_email["payload"]["email"] = draft_email ses_send_email_arguments_draft_email["template_name"] = "voting_location_IA_draft" run_generic_test( mocker, form_request_draft_email, mobile_commons_profile_update_draft_email, MOBILE_COMMONS_SEND_MESSAGE_GOLDEN_IA, ses_send_email_arguments_draft_email, ) def run_generic_test( mocker, form_request_base, mobile_commons_profile_update_golden, mobile_commons_send_message_golden, ses_send_email_arguments_golden, ): form_request = form_request_base.copy() def check_bsd_submission_request_body(request): body = json.loads(request.body) print("Got BSD request body:") pprint.pprint(body) assert body == form_request return (200, {}, json.dumps(BSD_PROXY_SUBMIT_RESPONSE)) responses.add_callback( responses.POST, BSD_PROXY_URL, callback=check_bsd_submission_request_body, match_querystring=True, ) if mobile_commons_profile_update_golden: def check_mobile_commons_update_profile_request_body(request): body = json.loads(request.body) print("Got Mobile Commons update profile request:") pprint.pprint(body) expected = mobile_commons_profile_update_golden for k, v in expected.items(): assert body[k] == v return (200, {}, MOBILE_COMMONS_PROFILE_UPDATE_RESPONSE) responses.add_callback( responses.POST, "https://secure.mcommons.com/api/profile_update", callback=check_mobile_commons_update_profile_request_body, match_querystring=True, ) if mobile_commons_send_message_golden: def check_mobile_commons_send_message_request_body(request): body = json.loads(request.body) print("Got Mobile Commons send message request:") pprint.pprint(body) expected = mobile_commons_send_message_golden for k, v in expected.items(): assert body[k] == v return (200, {}, MOBILE_COMMONS_SEND_MESSAGE_RESPONSE) responses.add_callback( responses.POST, "https://secure.mcommons.com/api/send_message", callback=check_mobile_commons_send_message_request_body, match_querystring=True, ) email_service_mock = mocker.patch("pollaris.app.views.side_effects.EmailService") resp = Client().post( "/api/v1/forms/after_search", form_request, content_type="application/json" ) assert resp.status_code == 200 assert resp.json()["status"] == "success" email_service_mock.return_value.send_email.assert_called_once_with( **ses_send_email_arguments_golden ) # Try again in an unknown language; make sure English still sends form_request["custom-16616"] = "ja-JP" resp = Client().post( "/api/v1/forms/after_search", form_request, content_type="application/json" ) assert resp.status_code == 200 assert resp.json()["status"] == "success" # TODO(<NAME>): Spanish-language test when that is done
AppGalleryConnect/agc-android-demos
publishapi/src/test/java/com/huawei/demo/api/UpdateAppLang.java
/* * Copyright (c) Huawei Technologies Co., Ltd. 2019-2019. All rights reserved. */ package com.huawei.demo.api; import com.huawei.demo.common.KeyConstants; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.http.Consts; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; /** * 功能描述 * * @since 2021-01-13 */ public class UpdateAppLang { private static String LANG = "ar"; // Type of language you need to update private static String APP_NAME = "PublishAPI_Demo"; // App name update private static String APP_DESC = "This is a demo"; // Application-related description information public static void updateAppLang(String domain, String clientId, String token, String appId) throws IOException { HttpPut put = new HttpPut(domain + "/publish/v2/app-language-info?appId" + appId); put.setHeader("Authorization", "Bearer " + token); put.setHeader("client_id", clientId); JSONObject keyString = new JSONObject(); keyString.put("lang", LANG); keyString.put("appName", APP_NAME); keyString.put("appDesc", APP_DESC); StringEntity entity = new StringEntity(keyString.toString(), Charset.forName("UTF-8")); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); put.setEntity(entity); try { CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = httpClient.execute(put); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), Consts.UTF_8)); String result = br.readLine(); JSONObject object = JSON.parseObject(result); JSONObject ret = (JSONObject) object.get("ret"); if (ret.get("code").equals(KeyConstants.SUCCESS)) { // The application language information was updated successfully } else { // Application language information update failed, please refer to the error code statement in the // materials for specific reasons } br.close(); httpClient.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
ppi-ag/deep-sampler
deepsampler-core/src/main/java/de/ppi/deepsampler/core/model/OriginalMethodInvocation.java
package de.ppi.deepsampler.core.model; /** * A {@link FunctionalInterface} that is used to pass a means of calling the original method, to an {@link Answer}. */ @FunctionalInterface public interface OriginalMethodInvocation { /** * Calls the original method using the particular means of the particular AOP-framework that is used for stubbing. * @return If the original method is a void method, null is returned. Otherwise the return value from the original method * is returned. * * @throws Throwable The underlying AOP-Libraries will most likely declare {@link Throwable} on the method that calls the original method. At least * this is the case with spring and guice-aop. This is why we have to relay {@link Throwable} here, even though this might appear most unusual. */ @SuppressWarnings("java:S112") // Ignore complaints about throws Throwable since this is the result of the AOP APIs which are called by this Method Object call() throws Throwable; }
cinder-config/extractor
src/main/java/ch/uzh/ciclassifier/features/configuration/UseBranches.java
package ch.uzh.ciclassifier.features.configuration; import ch.uzh.ciclassifier.evaluation.Evaluation; import ch.uzh.ciclassifier.features.Feature; import ch.uzh.ciclassifier.features.FeatureType; import org.json.simple.JSONObject; import java.io.IOException; public class UseBranches implements Feature { private boolean use; @Override public void extract(Evaluation evaluation) throws IOException { JSONObject parsed = evaluation.getConfiguration().getParsed(); JSONObject config = (JSONObject) parsed.get("config"); this.use = config.containsKey("branches"); } @Override public String getData() { return this.use ? "1" : "0"; } @Override public FeatureType supportedFeatureType() { return FeatureType.CONFIGURATION; } public boolean isUse() { return use; } }
roj234/rojlib
roj/math/MathUtils.java
<gh_stars>1-10 /* * This file is a part of MI * * The MIT License (MIT) * * Copyright (c) 2021 Roj234 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package roj.math; import roj.collect.SimpleList; import roj.text.TextUtil; import java.util.*; import java.util.function.Consumer; /** * Math utilities. */ public abstract class MathUtils { public static final double HALF_PI = Math.PI / 2; public static final double TWO_PI = 6.283185307179586476925286766559; // 2 * Pi // public static final double E = Math.E; // public static final double LN_10 = 2.30258509299404568401799145468; public static final double EPS_2 = 0.00000000000001; // 1e-14 // public static final double EPS_1 = EPS_2 * EPS_2; public static final double P5_DEG_MUL = 1.0 / (180.0 * Math.PI); // 1e-28 public static final byte[] HEX_MAXS = new byte[8], OCT_MAXS = new byte[16], BIN_MAXS = new byte[32]; static { Arrays.fill(MathUtils.HEX_MAXS, (byte) 'f'); MathUtils.HEX_MAXS[7]++; Arrays.fill(MathUtils.OCT_MAXS, (byte) '7'); MathUtils.OCT_MAXS[15]++; Arrays.fill(MathUtils.BIN_MAXS, (byte) '1'); MathUtils.BIN_MAXS[31]++; } public static int sig(int num) { return num == 0 ? 0 : num < 0 ? -1 : 1; } //public static final BigDecimal BIG_PI = new BigDecimal("3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038964"); //public static final BigDecimal BIG_E = new BigDecimal("2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274"); /** * @see MathUtils#clamp(double, double, double) */ public static long clamp(long val, long min, long max) { return val < min ? min : val > max ? max : val; } /** * Clamps the given value using the specified maximum and minimum. * * @param val the value to be clamped. * @param min the minimum to which the given value should be clamped. * @param max the maximum to which the given value should be clamped * @return the clamped value, i.e. {@code val} if {@code val} is between {@code minBlock} and {@code maxBlock}, {@code maxBlock } * if {@code val} is greater than {@code maxBlock} or {@code minBlock} if {@code val} is smaller than {@code minBlock}. */ public static double clamp(double val, double min, double max) { return val < min ? min : val > max ? max : val; } /** * @see MathUtils#clamp(double, double, double) */ public static int clamp(int val, int min, int max) { return val < min ? min : val > max ? max : val; } public static int max(int... ints) { int i = 0, v = Integer.MIN_VALUE, cur; while (i < ints.length) if((cur = ints[i++]) > v) v = cur; return v; } public static int min(int... ints) { int i = 0, v = Integer.MAX_VALUE, cur; while (i < ints.length) if((cur = ints[i++]) < v) v = cur; return v; } /** * 投影点 * @param v 还是容器 */ public static Vec3d project(Vec3d point, Vec3d line, Vec3d v) { /*Mat3d A = new Mat3d(point.x, point.y, point.z, line.x, line.y, line.z, 0, 0, 1); Mat3d tmp = new Mat3d(); A.mul(tmp.set(A).invert()).mul(tmp.set(A).transpose()).mul(tmp.invert());*/ v.set(point) // 1. Point和Line所在的平面的法线 .cross(line) // 2. 与Line垂直和(法线垂直 => 平面内)的向量 .cross(line); // A * line (4,5,6 * A) = B * v (1,2,3 + B * v) // A = (point.x + B * v.x) / line.x = (point.y + B * v.y) / line.y; double B = (line.x * point.y / line.y - point.x) / (v.x - line.x * v.y / line.y); //double A = (point.y + B * v.y) / line.y; return v.mul(B).add(point); } /** * @see #legalLine(Vec3d, Vec3d, Vec3d) */ private static Vec3d legalLine(Vec3d a, Vec3d b) { return legalLine(a, b, new Vec3d()); } /** * 法线(与a,b都垂直的向量) <BR> * 自己推的公式, 感觉没有人家{@link Vec3d#cross(Vec3d)}简洁呢 * @param holder 存储返回值的容器 */ private static Vec3d legalLine(Vec3d a, Vec3d b, Vec3d holder) { // ux + vy + wz = 0 // ax + by + cz = 0 // define x = 1 // vy + wz = -u // by + cz = -a // y = -(u + wz) / v // b( (-u - wz) / v ) + cz = -a // (-ub / v + a) / (-c + wb / v) = z // u b v a c w b v double z = (-a.x * b.y / a.y + b.x) / (-b.z + a.z * b.y / a.y); // u w z v double y = -(a.x + a.z * z) / a.y; return holder.set(1, y, z); } /** * 多边形面积 */ public static double polygon_Area(IPolygon polygon) { List<Vec2d> vertices = polygon.getPoints(); int N = vertices.size(); if(N < 3) return 0; double area = vertices.get(0).y * (vertices.get(N - 1).x - vertices.get(1).x); for(int i = 1; i < N; ++i) area += vertices.get(i).y * (vertices.get(i - 1).x - vertices.get((i + 1) % N).x); return Math.abs(area / 2); } /** * "双倍多边形面积" <br> * 实际用途:通过符号可以判断多边形的顶点排列顺序 */ public static double signedDoubleArea(IPolygon polygon) { List<Vec2d> vertices = polygon.getPoints(); double signedDoubleArea = 0; for (int index = 0; index < vertices.size(); ++index) { int nextIndex = (index + 1) % vertices.size(); Vec2d point = vertices.get(index); Vec2d next = vertices.get(nextIndex); signedDoubleArea += point.x * next.y - next.x * point.y; } return signedDoubleArea; } /** * 判断多边形的顶点排列顺序 * <br> -1: 逆时针, 1: 顺时针, 0: 未知 */ public static int polygon_Winding(IPolygon polygon) { double d = signedDoubleArea(polygon); if(d < 0) return -1; else if (d > 0) return 1; return 0; } /** * 判断点是否在折线上 */ public static boolean isOn_PolyLine(Vec2d point, IPolygon polyline) { Rect2d bounds = polyline.getBounds(); if(bounds.contains(point)) { return false; } //判断点是否在线段上,设点为Q,线段为P1P2 , //判断点Q在该线段上的依据是:( Q - P1 ) × ( P2 - P1 ) = 0,且 Q 在以 P1,P2为对角顶点的矩形内 List<Vec2d> pts = polyline.getPoints();//获取多边形点 int N = pts.size() - 1; for(int i = 0; i < N; i++){ Vec2d curPt = pts.get(i); Vec2d nextPt = pts.get(i + 1); //首先判断point是否在curPt和nextPt之间,即:此判断该点是否在该线段的外包矩形内 if (point.y >= Math.min(curPt.y, nextPt.y) && point.y <= Math.max(curPt.y, nextPt.y) && point.x >= Math.min(curPt.x, nextPt.x) && point.x <= Math.max(curPt.x, nextPt.x)){ //判断点是否在直线上公式 double precision = (curPt.y - point.y) * (nextPt.x - point.x) - (nextPt.y - point.y) * (curPt.x - point.x); if(Math.abs(precision) < EPS_2) { return true; } } } return false; } /** * 判断点是否多边形内 * @param canOn 点位于多边形的顶点或边上,也算做点在多边形内吗 */ public static boolean isIn_Polygon(Vec2d point, IPolygon polygon, boolean canOn) { Rect2d bounds = polygon.getBounds(); if(bounds.contains(point)) { return false; } List<Vec2d> pts = polygon.getPoints(); //下述代码来源:http://paulbourke.net/geometry/insidepoly/,进行了部分修改 //基本思想是利用射线法,计算射线与多边形各边的交点,如果是偶数,则点在多边形外,否则 //在多边形内。还会考虑一些特殊情况,如点在多边形顶点上,点在多边形边上等特殊情况。 int N = pts.size(); int intersects = 0;//cross points count of x Vec2d p1, p2;//neighbour bound vertices p1 = pts.get(0);//left vertex for(int i = 1; i <= N; ++i){//check all rays if(point.equals(p1)){ return canOn;//p is an vertex } p2 = pts.get(i % N);//right vertex if(point.x < Math.min(p1.x, p2.x) || point.x > Math.max(p1.x, p2.x)){//ray is outside of our interests p1 = p2; continue;//next ray left point } if(point.x > Math.min(p1.x, p2.x) && point.x < Math.max(p1.x, p2.x)){//ray is crossing over by the algorithm (common part of) if(point.y <= Math.max(p1.y, p2.y)){//x is before of ray if(p1.x == p2.x && point.y >= Math.min(p1.y, p2.y)){//overlies on a horizontal ray return canOn; } if(p1.y == p2.y){//ray is vertical if(p1.y == point.y){//overlies on a vertical ray return canOn; }else{//before ray ++intersects; } }else{//cross point on the left side double xinters = (point.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;//cross point of y if(Math.abs(point.y - xinters) < EPS_2) {//overlies on a ray return canOn; } if(point.y < xinters){//before ray ++intersects; } } } } else {//special case when ray is crossing through the vertex if(point.x == p2.x && point.y <= p2.y){//p crossing over p2 Vec2d p3 = pts.get((i + 1) % N); //next vertex if(point.x >= Math.min(p1.x, p3.x) && point.x <= Math.max(p1.x, p3.x)){//p.x lies between p1.x & p3.x ++intersects; }else{ intersects += 2; } } } p1 = p2;//next ray left point } //偶数在多边形外, 奇数在多边形内 return (intersects & 1) != 0; } /** * 计算折线或者点数组的长度 */ public static double polyLineLength(IPolygon polyline) { List<Vec2d> pts = polyline.getPoints();//获取多边形点 int N = pts.size() - 1; if(N < 1) {//小于2个点,返回0 return 0; } //遍历所有线段将其相加,计算整条线段的长度 double totalDis = 0; for(int i = 0; i < N; i++){ Vec2d curPt = pts.get(i); Vec2d nextPt = pts.get(i + 1); totalDis += curPt.sub(nextPt).len(); curPt.add(nextPt); } return totalDis; } /** * @see #interpolate(double, double, double, double, double) */ public static float interpolate(float in, float inMin, float inMax, float outMin, float outMax) { if (inMin > inMax) { // reverse float t = inMin; inMin = inMax; inMax = t; t = outMin; outMin = outMax; outMax = t; } if (in <= inMin) return outMin; if (in >= inMax) return outMax; float xFrac = (in - inMin) / (inMax - inMin); return outMin + xFrac * (outMax - outMin); } /** * <p> * linearly interpolate for y between [inMin, outMin] to [inMax, outMax] using in * </p> * y = outMin + (outMax - outMin) * (in - inMin) / (inMax - inMin) <br> * For example: <br> * if [inMin, outMin] is [0, 100], and [inMax,outMax] is [1, 200], <br> * then as in increases from 0 to 1, this function will increase from 100 to 200 <br> * * @return linearly interpolated value. If in is outside the range, clip it to the nearest end */ public static double interpolate(double in, double inMin, double inMax, double outMin, double outMax) { if (inMin > inMax) { // reverse double t = inMin; inMin = inMax; inMax = t; t = outMin; outMin = outMax; outMax = t; } if (in <= inMin) return outMin; if (in >= inMax) return outMax; double xFrac = (in - inMin) / (inMax - inMin); return outMin + xFrac * (outMax - outMin); } /** * @see #interpolate(double, double, double, double, double) */ public static double interpolateMy(double in, int inMin, int inMax, double outMin, double outMax) { if (in <= inMin) return outMin; if (in >= inMax) return outMax; double xFrac = (in - inMin) / (inMax - inMin); return outMin + xFrac * (outMax - outMin); } /** * As same as interpolate(delta, 0, 1, old, now) * @see #interpolate(double, double, double, double, double) */ public static double interpolate(double old, double now, double delta) { return old + delta * (now - old); } /** * As same as interpolate(delta, 0, 1, old, now) * @see #interpolate(double, double, double, double, double) */ public static float interpolate(float old, float now, float delta) { return old + delta * (now - old); } /** * Implementation detail: The runtime complexity is in O(log2(n)). <br> * Negative numbers has the same number of digits as the corresponding positive ones. * * @param n The given integer * @return The number of digits of the given integer n in O(log2(n)) */ public static int digitCount(int n) { /* overflow if n is negative */ if (n == Integer.MIN_VALUE) return 10; /* make positive */ if (n < 0) n = -n; if (n < 100000) /* 1 <= digit count <= 5 */ if (n < 100) /* 1 <= digit count <= 2 */ return (n < 10) ? 1 : 2; else /* 3 <= digit count <= 5 */ if (n < 1000) return 3; else /* 4 <= digit count <= 5 */ return (n < 10000) ? 4 : 5; else /* 6 <= digit count <= 10 */ if (n < 10000000) /* 6 <= digit count <= 7 */ return (n < 1000000) ? 6 : 7; else /* 8 <= digit count <= 10 */ if (n < 100000000) return 8; else /* 9 <= digit count <= 10 */ return (n < 1000000000) ? 9 : 10; } public static final char[] CHINA_NUMERIC = new char[]{ '零', '一', '二', '三', '四', '五', '六', '七', '八', '九' }; static final char[] CHINA_NUMERIC_POSITION = new char[]{ '十', '百', '千' }; static final char[] CHINA_NUMERIC_LEV = new char[]{ '万', '亿' }; public static StringBuilder toChinaString(StringBuilder list, long number) { StringBuilder sb = new StringBuilder(); if (number < 0) { sb.append('负'); number = -number; } while (number > 0) { int curs = (int) (number % 10); number = (number - curs) / 10; sb.append(CHINA_NUMERIC[curs]); } // Step 1 一二三四五六七八九 sb.reverse(); final int firstLength = 3; // 万 final char C_ZERO = CHINA_NUMERIC[0]; int j = 0; boolean k = false; for (int i = sb.length() - 1; i >= 1; i--) { char c = sb.charAt(i - 1); if (c != C_ZERO) { char t = j == firstLength ? CHINA_NUMERIC_LEV[k ? 1 : 0] : CHINA_NUMERIC_POSITION[j]; sb.insert(i, t); } else if (j == firstLength) { sb.setCharAt(i, CHINA_NUMERIC_LEV[k ? 1 : 0]); } if ((j++) == CHINA_NUMERIC_POSITION.length) { j = 0; k = !k; } } // Step 2 六万七千八百九十一亿二千三百四十五万六千七百八十九 int zero = -1; int van = 0; for (int i = sb.length() - 1; i > 0; i--) { char c = sb.charAt(i); switch (c) { case '零': { if (zero == -1 || zero++ > 0) sb.deleteCharAt(i); } break; // rem 亿万 因为是反过来的 case '万': { van = 1; if (zero != -1) zero++; } break; case '亿': { if (zero != -1) zero++; if (van == 1) { sb.deleteCharAt(i + 1); van = 0; } } break; default: zero = 0; van = 0; } } if (sb.charAt(0) == CHINA_NUMERIC[1] && sb.charAt(1) == CHINA_NUMERIC_POSITION[0]) sb.deleteCharAt(0); return list.append(sb); } /** * Returns an iterator providing a number sequence. This sequence starts with <i>{@code from}</i> (given as * parameter) and ends with <i>{@code to}</i> (given as parameter). In between, new values are calculated as * sigmoid function e^t(x) / (1 + e^t(x)). * * @param from First number in the sequence * @param to Last number in the sequence * @param steps The length of the sequence (exclusive <i>{@code from}</i> and <i>{@code to}</i>) * @return an iterator providing a number sequence calculated as sigmoid function. * {@link Iterator#hasNext() hasNext()} returns false, if the sequence has finished, but * {@link Iterator#next() next()} will return <i>{@code to}</i> * @throws IllegalArgumentException if <i>{@code from}</i> {@code >=} <i>{@code to}</i> * @throws IllegalArgumentException if <i>{@code from}</i> {@code <} <i>{@code 0}</i> * @throws IllegalArgumentException if <i>{@code steps}</i> {@code <} <i>{@code 0}</i> */ public static PrimitiveIterator.OfInt createSigmoidSequence(int from, int to, int steps) { if (from >= to) throw new IllegalArgumentException("from >= to"); if (from < 0) throw new IllegalArgumentException("from < 0"); if (steps < 0) throw new IllegalArgumentException("steps < 0"); return new PrimitiveIterator.OfInt() { // e^t(x) / (1 + e^t(x)) in [0, xmax] for t(x) = 8 * x / xmax - 4 private int step = 0; private final int delta = to - from; private final int maxStep = steps + 1; @Override public boolean hasNext() { return step <= maxStep; } @Override public int nextInt() { if (step > maxStep) throw new NoSuchElementException(); int s = step++; if (s == maxStep) return to; else if (s == 0) return from; else { double x = s / (double) maxStep; double tmp = Math.exp(8 * x - 4); return (int) (delta * (tmp / (1 + tmp)) + from); } } // result for (from, to, steps) = (0, 20, 18) // |20| | | | | | | | | | | | | | | | | | | | x| // |19| | | | | | | | | | | | | | | | | | x| x| | // |18| | | | | | | | | | | | | | | | x| x| | | | // |17| | | | | | | | | | | | | | | x| | | | | | // |16| | | | | | | | | | | | | | x| | | | | | | // |15| | | | | | | | | | | | | | | | | | | | | // |14| | | | | | | | | | | | | x| | | | | | | | // |13| | | | | | | | | | | | x| | | | | | | | | // |12| | | | | | | | | | | | | | | | | | | | | // |11| | | | | | | | | | | x| | | | | | | | | | // |10| | | | | | | | | | | | | | | | | | | | | // | 9| | | | | | | | | | | | | | | | | | | | | // | 8| | | | | | | | | | x| | | | | | | | | | | // | 7| | | | | | | | | | | | | | | | | | | | | // | 6| | | | | | | | | x| | | | | | | | | | | | // | 5| | | | | | | | x| | | | | | | | | | | | | // | 4| | | | | | | | | | | | | | | | | | | | | // | 3| | | | | | | x| | | | | | | | | | | | | | // | 2| | | | | | x| | | | | | | | | | | | | | | // | 1| | | | x| x| | | | | | | | | | | | | | | | // | 0| x| x| x| | | | | | | | | | | | | | | | | | // | 0| 1| 2| 3| 4| 5| 6| 7| 8| 9|10|11|12|13|14|15|16|17|18|19| }; } public static int getMin2PowerOf(int x) { if(x >= 1073741824) return 1073741824; x--; x |= x >>> 1; x |= x >>> 2; x |= x >>> 4; x |= x >>> 8; x |= x >>> 16; return (x < 0) ? 1 : x + 1; } public static double cos(double value) { return sin(HALF_PI + value); } public static float cos(float value) { return (float) sin(HALF_PI + value); } public static float sin(float value) { return (float) sin((double) value); } /** * 使用切比雪夫多项式快速计算sin * <br> * 精度1e-6 * * @param value radian * @return sin value */ public static double sin(double value) { if (value >= 0) { if(value <= HALF_PI) { return ((((((-0.000960664 * value + 0.0102697866) * value - 0.00198601997) * value - 0.1656067221) * value - 0.0002715666) * value + 1.000026227) * value); } else { if (value >= TWO_PI) { value %= TWO_PI; } if (value >= Math.PI) { return -sin(value - Math.PI); } if (value > HALF_PI) { value = sin(value - HALF_PI); value *= value; return value > 1 ? 0 : sqrt(1 - value); } return sin(value); } } else { return -sin(-value); } } public static int floor(float value) { int i = (int) value; return value < i ? i - 1 : i; } public static int ceil(float value) { int i = (int) value; return value > i ? i + 1 : i; } public static int floor(double value) { int i = (int) value; return value < i ? i - 1 : i; } /*public static float invSqrt(float x) { float halfX = 0.5f * x; int i = Float.floatToRawIntBits(x); // get bits for floating VALUE i = 0x5f375a86 - (i >> 1); // gives initial guess y0 x = Float.intBitsToFloat(i); // convert bits BACK to float x = x * (1.5f - halfX * x * x); // Newton step, repeating increases accuracy x = x * (1.5f - halfX * x * x); x = x * (1.5f - halfX * x * x); return x; } public static double invSqrtd(double x) { double halfX = 0.5f * x; long i = Double.doubleToRawLongBits(x); i = 6910469410427058090L - (i >> 1); x = Double.longBitsToDouble(i); x = x * (1.5f - halfX * x * x); x = x * (1.5f - halfX * x * x); x = x * (1.5f - halfX * x * x); x = x * (1.5f - halfX * x * x); return x; }*/ public static double sqrt(double x) { return Math.sqrt(x); //if (x < 0) throw new IllegalArgumentException("Must be non-negative"); //if (x == 0) return 0; //return 1 / invSqrtd(x);//(y + x / y) / 2; } public static float sqrt(float x) { return (float) Math.sqrt(x); //if (x < 0) throw new IllegalArgumentException("Must be non-negative"); //if (x == 0) return 0; //return 1 / invSqrt(x);//(y + x / y) / 2; } public static double log10(double x) { return Math.log10(x); //return logE(x) / LN_10; } public static double logE(double x) { return Math.log(x); //if (x <= 0) throw new IllegalArgumentException("Must be positive"); //if (x == 1) return 0; //int k = 0; //for (; x > 0.1; k++) x /= 10; //for (; x <= 0.01; k--) x *= 10; //return k * LN_10 - logNeg(x); } /*private static double logNeg(double q) { // q in ( 0.01, 0.1 ] double r = q, s = q, n = q, q2 = q * q, q1 = q2 * q; for (boolean p = true; (n *= q1) > EPS_1; s += n, q1 *= q2) r += (p = !p) ? n : -n; double u = 1 - 2 * r, v = 1 + 2 * s, t = u / v; double a = 1, b = sqrt(1 - t * t * t * t); for (; a - b > EPS_2; b = sqrt(a * b), a = t) t = (a + b) / 2; return TWO_PI / (a + b) / v / v; }*/ public static int average(int[] values) { if (values == null || values.length == 0) return 0; int sum = 0; for (int v : values) sum += v; return sum / values.length; } public static long average(long[] values) { if (values == null || values.length == 0) return 0L; long sum = 0L; for (long v : values) sum += v; return sum / values.length; } /** * 笛卡儿积 (values所有可能的排列 = values[0].length * values[1].length * ...) */ public static <T> void dikaerProduct(List<T[]> values, Consumer<List<T>> consumer) { SimpleList<T> cache = new SimpleList<>(values.size()); cache.i_setSize(values.size()); dikaerProduct(values, 0, consumer, cache); } static <T> void dikaerProduct(List<T[]> values, int layer, Consumer<List<T>> consumer, SimpleList<T> cache) { T[] v = values.get(layer); boolean last = layer == values.size() - 1; for (T t : v) { cache.set(layer, t); if (last) { consumer.accept(cache); } else { dikaerProduct(values, layer + 1, consumer, cache); } } } public static <T> int dikaerLength(List<T[]> stacks) { int len = 1; for (int i = 0; i < stacks.size(); i++) { len *= stacks.get(i).length; } return len; } /** * @param pitch 仰角 * @param yaw 旋转角 */ public static Vec3f rotationVector(float pitch, float yaw) { float f = cos(-yaw * 0.017453292F - 3.1415927F); float f1 = sin(-yaw * 0.017453292F - 3.1415927F); float f2 = -cos(-pitch * 0.017453292F); float f3 = sin(-pitch * 0.017453292F); return new Vec3f((f1 * f2), f3, (f * f2)); } /** * @param pitch 仰角 * @param yaw 旋转角 */ public static Vec3d rotationVectord(double pitch, double yaw) { double f = cos(-yaw * P5_DEG_MUL - Math.PI); double f1 = sin(-yaw * P5_DEG_MUL - Math.PI); double f2 = -cos(-pitch * P5_DEG_MUL); double f3 = sin(-pitch * P5_DEG_MUL); return new Vec3d((f1 * f2), f3, (f * f2)); } /** * 开方算法测试版 */ @Deprecated public static double slowSqrt(double x) { double a = x / 2, da; do { double b = x / a; da = a; a = (a + b) / 2; } while (Math.abs(a - da) > 10E-6); return a; } public static double[] pdf2cdf(double[] pdf) { double[] cdf = Arrays.copyOf(pdf, pdf.length); for (int i = 1; i < cdf.length - 1; i++) cdf[i] += cdf[i - 1]; // Force set last cdf to 1, preventing floating-point summing error in the loop. cdf[cdf.length - 1] = 1; return cdf; } public static int cdfRandom(Random rand, double[] targetCdf) { double x = rand.nextDouble(); for (int i = 0; i < targetCdf.length; i++) { if (x < targetCdf[i]) return i; } throw new IllegalArgumentException("targetCdf"); } public static float rad(float angle) { return angle * (float) Math.PI / 180; } public static int randomRange(Random rand, int min, int max) { return min + rand.nextInt(max - min + 1); } public static int parseInt(CharSequence s) throws NumberFormatException { return parseInt(s, 10); } public static int parseInt(CharSequence s, int radix) throws NumberFormatException { boolean n = s.charAt(0) == '-'; int i = parseInt(s, n ? 1 : 0, s.length(), radix); return n ? -i : i; } public static int parseInt(CharSequence s, int i, int end, int radix) throws NumberFormatException { long result = 0; if (end - i > 0) { int digit; while (i < end) { if ((digit = Character.digit(s.charAt(i++), radix)) < 0) throw new NumberFormatException("Not a number at offset " + (i - 1) + "(" + s.charAt(i - 1) + "): " + s); result *= radix; result += digit; } } else { throw new NumberFormatException("Len=0: " + s); } if (result > 4294967295L || result < Integer.MIN_VALUE) throw new NumberFormatException("Value overflow " + result + " : " + s); return (int) result; } public static boolean parseIntErrorable(CharSequence s, int[] radixAndReturn) { long result = 0; int radix = radixAndReturn[0]; if (s.length() > 0) { int i = 0, len = s.length(); int digit; while (i < len) { if ((digit = Character.digit(s.charAt(i++), radix)) < 0) return false; result *= radix; result += digit; } } else { return false; } if (result > 4294967295L || result < Integer.MIN_VALUE) return false; radixAndReturn[0] = (int) result; return true; } public static int parseIntChecked(CharSequence s, int radix, boolean negative) throws NumberFormatException { long result = 0; if (s.length() > 0) { int i = 0, len = s.length(); byte[] c; switch (radix) { case 16: c = HEX_MAXS; break; case 8: c = OCT_MAXS; break; case 10: c = TextUtil.INT_MAXS; break; case 2: c = BIN_MAXS; break; default: throw new NumberFormatException("Unsupported radix " + radix); } if (!TextUtil.checkInt(c, s, 0, negative)) { throw new NumberFormatException("checkInt() failed : " + s); } int digit; while (i < len) { if ((digit = Character.digit(s.charAt(i++), radix)) < 0) throw new NumberFormatException("Not a number at offset " + (i - 1) + " : " + s); result *= radix; result += digit; } } else { throw new NumberFormatException(s.toString()); } if (result > 4294967295L || result < Integer.MIN_VALUE) throw new NumberFormatException("Value overflow " + result + " : " + s); return (int) (negative ? -result : result); } }
amylittleyang/OtraCAD
cadnano25/cadnano/part/removeallstrandscmd.py
<reponame>amylittleyang/OtraCAD from cadnano.cnproxy import UndoCommand class RemoveAllStrandsCommand(UndoCommand): """ 1. Remove all strands. Emits strandRemovedSignal for each. 2. Remove all oligos. """ def __init__(self, part): super(RemoveAllStrandsCommand, self).__init__("remove all strands") self._part = part self._vhs = vhs = part.getVirtualHelices() self._strand_sets = [] for vh in self._vhs: x = vh.getStrandSets() self._strand_sets.append(x[0]) self._strand_sets.append(x[1]) self._strandSetListCopies = \ [[y for y in x._strand_list] for x in self._strand_sets] self._oligos = set(part.oligos()) # end def def redo(self): part = self._part # Remove the strand for s_set in self.__strand_set: s_list = s_set._strand_list for strand in s_list: s_set.removeStrand(strand) # end for s_set._strand_list = [] #end for #for vh in self._vhs: # for updating the Slice View displayed helices #part.partStrandChangedSignal.emit(part, vh) # end for self._oligos.clear() # end def def undo(self): part = self._part # Remove the strand sListCopyIterator = iter(self._strandSetListCopies) for s_set in self._strand_sets: s_list = next(sListCopyIterator) for strand in s_list: s_set.strandsetStrandAddedSignal.emit(s_set, strand) # end for s_set._strand_list = s_list #end for for vh in self._vhs: # for updating the Slice View displayed helices part.partStrandChangedSignal.emit(part, vh) # end for for olg in self._oligos: part.addOligo(olg) # end def # end class
Matematica-Divertida/mobile
app/screens/Question/Components/Footer.js
<reponame>Matematica-Divertida/mobile import React, { useRef } from 'react'; import { View, Text, Platform, StyleSheet, TouchableOpacity } from 'react-native'; import Popover from 'react-native-popover-view'; const styles = StyleSheet.create({ submit: { height: 64, backgroundColor: Platform.OS === 'ios' ? 'white' : '#e6e6e6', justifyContent: 'center', shadowOffset: { width: 0, height: -1, }, shadowColor: 'gray', shadowOpacity: 0.5, elevation: 1 }, button: { backgroundColor: '#122b61', padding: 8, paddingHorizontal: 32, position: 'absolute', right: 16, borderRadius: 4 }, text: { fontWeight: 'bold', fontSize: 16, color: 'white' }, arrow: { backgroundColor: '#e6e6e6' }, popover: { padding: 16, backgroundColor: '#e6e6e6', shadowOffset: { width: 0, height: -1, }, shadowColor: 'gray', shadowOpacity: 0.5, elevation: 1 }, background: { backgroundColor: 'transparent' }, disabled: { backgroundColor: Platform.OS === 'ios' ? '#E6E6E6' : '#D4D4D4' } }); const Footer = ({ text, onSubmit, showPopover, disabled }) => { const touchable = useRef(); return ( <> <View style={styles.submit}> <TouchableOpacity ref={touchable} style={[styles.button, disabled && styles.disabled]} onPress={onSubmit} disabled={disabled} > <Text style={styles.text}>{text}</Text> </TouchableOpacity> </View> <Popover from={touchable} isVisible={showPopover} onRequestClose={onSubmit} backgroundStyle={styles.background} arrowStyle={styles.arrow} > <View style={styles.popover}> <Text>Clique aqui para prosseguir.</Text> </View> </Popover> </> ); } export default Footer;
seandong23x3m/tobantalx
chapter-06/security-samples/src/main/java/org/rpis5/chapters/chapter_06/security/ProfileService.java
package org.rpis5.chapters.chapter_06.security; import reactor.core.publisher.Mono; public interface ProfileService { Mono<Profile> getByUser(String name); }
shenyiliu/mgcfx
src/main/java/com/pearadmin/modules/sys/domain/NewE.java
<filename>src/main/java/com/pearadmin/modules/sys/domain/NewE.java package com.pearadmin.modules.sys.domain; import java.util.ArrayList; import java.util.Date; import lombok.Data; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.pearadmin.common.web.base.BaseDomain; /** * 获取文章对象 new_e * * @author jmys * @date 2021-10-28 */ @Data public class NewE extends BaseDomain { private static final long serialVersionUID = 1L; /** 文章ID */ private Long newid; /** 文章内容 */ private String newcontent; /** 路径 */ private String newurl; /** 标题 */ private String newtitle; /** 文章创作时间 */ private Date newcreatetime; /** 文章来源 */ private String newsource; /** 文章作者 */ private String newauthor; /** 收集时间 */ private Date collecttime; /** 其他 */ private String newother; }
amadavan/Stuka
include/stuka/LP/preconditioner/bounds_zero.h
<reponame>amadavan/Stuka<filename>include/stuka/LP/preconditioner/bounds_zero.h // // Created by <NAME> on 2019-07-06. // #ifndef STUKA_LP_BOUNDS_ZERO_H #define STUKA_LP_BOUNDS_ZERO_H #include "base_preconditioner.h" namespace stuka { namespace LP { class BoundsZero : public BasePreconditioner { public: BoundsZero(const std::shared_ptr<BaseLinearProgram> &next); void initialize(const LinearProgram &prog) override; void setObjective(const std::shared_ptr<Eigen::VectorXd> &c) override; void setRHS(const std::shared_ptr<Eigen::VectorXd> &b_ub, const std::shared_ptr<Eigen::VectorXd> &b_eq) override; void setBounds(const std::shared_ptr<Eigen::VectorXd> &lb, const std::shared_ptr<Eigen::VectorXd> &ub) override; void addVar(double c, std::shared_ptr<Eigen::VectorXd> a_ub, std::shared_ptr<Eigen::VectorXd> a_eq, double lb, double ub) override; void addVars(std::shared_ptr<Eigen::VectorXd> c, std::shared_ptr<Eigen::SparseMatrix<double>> A_ub, std::shared_ptr<Eigen::SparseMatrix<double>> A_eq, std::shared_ptr<Eigen::VectorXd> lb, std::shared_ptr<Eigen::VectorXd> ub) override; void removeVar(size_t var) override; void removeVars(size_t index, size_t n_remove) override; void removeBackVars(size_t n_remove) override; void addConstr_ub(const std::shared_ptr<Eigen::VectorXd> &a, const double &b) override; void addConstrs_ub(const std::shared_ptr<Eigen::SparseMatrix<double>> &A, const std::shared_ptr<Eigen::VectorXd> &b) override; void removeConstr_ub(size_t index) override; void removeConstrs_ub(size_t index, size_t n_remove) override; void addConstr_eq(const std::shared_ptr<Eigen::VectorXd> &a, const double &b) override; void addConstrs_eq(const std::shared_ptr<Eigen::SparseMatrix<double>> &A, const std::shared_ptr<Eigen::VectorXd> &b) override; void removeConstr_eq(size_t index) override; void removeConstrs_eq(size_t index, size_t n_remove) override; Eigen::VectorXd convertState(const Eigen::VectorXd &x) override; Eigen::VectorXd revertState(const Eigen::VectorXd &x) override; private: size_t n_dim_; size_t n_ub_; size_t n_split_; size_t n_bounds_; size_t n_slack_; enum StateType { NORMAL, NEGATIVE, UNBOUNDED, COMPACT }; Eigen::VectorXd x_shift_; std::vector<StateType> x_type_; }; }} #endif //STUKA_LP_BOUNDS_ZERO_H
codhab/support2
app/models/support/document/allotment_authenticate.rb
<reponame>codhab/support2 require_dependency 'application_record' module Support module Document class AllotmentAuthenticate < ApplicationRecord self.table_name = 'sihab.document_allotment_authenticates' audited end end end
waldosax/PlexSports
Plug-ins/PlexSportsAgent.bundle/Contents/Code/Data/SportsDataIODownloader.py
import threading from Constants import * from UserAgent import * from Data.GetResultFromNetwork import * SPORTS_DATA_IO_MLB_API_KEY = "<KEY>" # TODO: Read from settings file? SPORTS_DATA_IO_NBA_API_KEY = "<KEY>" # TODO: Read from settings file? SPORTS_DATA_IO_NFL_API_KEY = "<KEY>" # TODO: Read from settings file? SPORTS_DATA_IO_NHL_API_KEY = "<KEY>" # TODO: Read from settings file? SPORTS_DATA_IO_BASE_URL = "https://fly.sportsdata.io/v3/%s/" # (League) SPORTS_DATA_IO_GET_ACTIVE_TEAMS_FOR_LEAGUE = SPORTS_DATA_IO_BASE_URL + "scores/json/Teams?key=%s" # (League, ApiKey) SPORTS_DATA_IO_GET_ALL_TEAMS_FOR_LEAGUE = SPORTS_DATA_IO_BASE_URL + "scores/json/AllTeams?key=%s" # (League, ApiKey) SPORTS_DATA_IO_GET_MLB_GAMES_FOR_SEASON = SPORTS_DATA_IO_BASE_URL + "scores/json/Games/%s?key=%s" # (Season, ApiKey) SPORTS_DATA_IO_GET_NBA_GAMES_FOR_SEASON = SPORTS_DATA_IO_BASE_URL + "scores/json/Games/%s?key=%s" # (Season, ApiKey) SPORTS_DATA_IO_GET_NFL_SCHEDULE_FOR_SEASON = SPORTS_DATA_IO_BASE_URL + "scores/json/Schedules/%s?key=%s" # (Season, ApiKey) SPORTS_DATA_IO_GET_NHL_GAMES_FOR_SEASON = SPORTS_DATA_IO_BASE_URL + "scores/json/Games/%s?key=%s" # (Season, ApiKey) SPORTS_DATA_IO_SUBSCRIPTION_KEY_NAME = "Ocp-Apim-Subscription-Key" sports_data_io_headers = { "User-Agent": USER_AGENT, SPORTS_DATA_IO_SUBSCRIPTION_KEY_NAME: "", } sports_data_io_api_keys = { LEAGUE_MLB: SPORTS_DATA_IO_MLB_API_KEY, LEAGUE_NBA: SPORTS_DATA_IO_NBA_API_KEY, LEAGUE_NFL: SPORTS_DATA_IO_NFL_API_KEY, LEAGUE_NHL: SPORTS_DATA_IO_NHL_API_KEY } sports_data_io_schedule_url_fragments = { LEAGUE_MLB: SPORTS_DATA_IO_GET_MLB_GAMES_FOR_SEASON, LEAGUE_NBA: SPORTS_DATA_IO_GET_NBA_GAMES_FOR_SEASON, LEAGUE_NFL: SPORTS_DATA_IO_GET_NFL_SCHEDULE_FOR_SEASON, LEAGUE_NHL: SPORTS_DATA_IO_GET_NHL_GAMES_FOR_SEASON } SPORTS_DATA_IO_SUBSEASON_PRESEASON = "PRE" SPORTS_DATA_IO_SUBSEASON_REGULARSEASON = "" SPORTS_DATA_IO_SUBSEASON_POSTSEASON = "POST" SPORTS_DATA_IO_SUBSEASON_ALLSTAR = "STAR" def DownloadActiveTeamsForLeague(league): if (league in known_leagues.keys() == False): return None # TODO: Throw key = sports_data_io_api_keys[league] headers = sports_data_io_headers.copy() headers[SPORTS_DATA_IO_SUBSCRIPTION_KEY_NAME] = key print("Getting active %s teams data from SportsData.io ..." % league) return GetResultFromNetwork(SPORTS_DATA_IO_GET_ACTIVE_TEAMS_FOR_LEAGUE % (league, sports_data_io_api_keys[league]), headers, True, cacheExtension=EXTENSION_JSON) def DownloadAllTeamsForLeague(league): if (league in known_leagues.keys() == False): return None # TODO: Throw key = sports_data_io_api_keys[league] headers = sports_data_io_headers.copy() headers[SPORTS_DATA_IO_SUBSCRIPTION_KEY_NAME] = key print("Getting all %s teams data from SportsData.io ..." % league) return GetResultFromNetwork(SPORTS_DATA_IO_GET_ALL_TEAMS_FOR_LEAGUE % (league, sports_data_io_api_keys[league]), headers, True, cacheExtension=EXTENSION_JSON) def DownloadScheduleForLeagueAndSeason(league, season, subseason=None): if (league in known_leagues.keys() == False): return None # TODO: Throw key = sports_data_io_api_keys[league] headers = sports_data_io_headers.copy() headers[SPORTS_DATA_IO_SUBSCRIPTION_KEY_NAME] = key allSubseasons = [SPORTS_DATA_IO_SUBSEASON_PRESEASON, SPORTS_DATA_IO_SUBSEASON_REGULARSEASON, SPORTS_DATA_IO_SUBSEASON_POSTSEASON, SPORTS_DATA_IO_SUBSEASON_ALLSTAR] subseasons = [] if not subseason: subseasons = allSubseasons[0:] elif isinstance(list, subseason): for suffix in subseason: if suffix in allSubseasons: subseasons.append(suffix) elif isinstance(subseason, basestring): if subseason in allSubseasons: subseasons.append(subseason) if len(subseasons) == 0: subseasons.append(SPORTS_DATA_IO_SUBSEASON_REGULARSEASON) def get_and_append_data(season, suffix, results): print("Getting %s %s%s schedule data from SportsData.io ..." % (league, season, suffix)) json = GetResultFromNetwork(sports_data_io_schedule_url_fragments[league] % (league, str(season) + suffix, sports_data_io_api_keys[league]), headers, True, cacheExtension=EXTENSION_JSON) results.append (json) pass results = [] threads = [] for suffix in subseasons: s = season if league == LEAGUE_NBA: s = int(season)+1 t = threading.Thread(target=get_and_append_data, kwargs={"suffix": suffix, "season": s, "results": results}) threads.append(t) t.start() for t in threads: t.join() return results
shriramrseee/stock-market-chart
chart/src/main/java/com/stock/chart/core/controllers/BoardOfDirectorsController.java
<filename>chart/src/main/java/com/stock/chart/core/controllers/BoardOfDirectorsController.java package com.stock.chart.core.controllers; import com.stock.chart.core.entities.BoardOfDirectors; import com.stock.chart.core.services.BoardOfDirectorsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(path="/board_of_directors") public class BoardOfDirectorsController { @Autowired private BoardOfDirectorsService boardOfDirectorsService; @PostMapping("/add") public void addBoard_of_Directors(@RequestBody BoardOfDirectors board_of_directors) { boardOfDirectorsService.addBoard_of_Directors(board_of_directors); } @GetMapping("/all") public List<BoardOfDirectors> getAllBoard_of_Directors() { return boardOfDirectorsService.getAllBoard_of_Directors(); } @PutMapping("/update") public void updateBoard_of_Directors(@RequestBody BoardOfDirectors board_of_directors) { boardOfDirectorsService.updateBoard_of_Directors(board_of_directors); } @DeleteMapping("/delete/{id}") public void deleteBoard_of_Directors(@PathVariable Integer id){ boardOfDirectorsService.deleteBoard_of_Directors(id); } }
Phindani/collect
collect_app/src/main/java/org/odk/collect/android/backgroundwork/AutoUpdateTaskSpec.java
<reponame>Phindani/collect<gh_stars>1-10 /* * Copyright 2018 Nafundi * * 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.odk.collect.android.backgroundwork; import android.content.Context; import androidx.work.WorkerParameters; import org.jetbrains.annotations.NotNull; import org.odk.collect.android.R; import org.odk.collect.android.formmanagement.FormDownloadException; import org.odk.collect.android.formmanagement.FormDownloader; import org.odk.collect.android.formmanagement.ServerFormDetails; import org.odk.collect.android.formmanagement.ServerFormsDetailsFetcher; import org.odk.collect.android.injection.DaggerUtils; import org.odk.collect.android.notifications.Notifier; import org.odk.collect.android.preferences.PreferencesProvider; import org.odk.collect.android.storage.migration.StorageMigrationRepository; import org.odk.collect.android.utilities.TranslationHandler; import org.odk.collect.async.TaskSpec; import org.odk.collect.async.WorkerAdapter; import org.odk.collect.android.forms.FormSourceException; import java.util.HashMap; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Named; import static org.odk.collect.android.preferences.GeneralKeys.KEY_AUTOMATIC_UPDATE; public class AutoUpdateTaskSpec implements TaskSpec { @Inject ServerFormsDetailsFetcher serverFormsDetailsFetcher; @Inject StorageMigrationRepository storageMigrationRepository; @Inject FormDownloader formDownloader; @Inject Notifier notifier; @Inject PreferencesProvider preferencesProvider; @Inject @Named("FORMS") ChangeLock changeLock; @NotNull @Override public Supplier<Boolean> getTask(@NotNull Context context) { DaggerUtils.getComponent(context).inject(this); return () -> { try { List<ServerFormDetails> serverForms = serverFormsDetailsFetcher.fetchFormDetails(); List<ServerFormDetails> updatedForms = serverForms.stream().filter(ServerFormDetails::isUpdated).collect(Collectors.toList()); if (!updatedForms.isEmpty()) { if (preferencesProvider.getGeneralSharedPreferences().getBoolean(KEY_AUTOMATIC_UPDATE, false)) { changeLock.withLock(acquiredLock -> { if (acquiredLock) { HashMap<ServerFormDetails, String> results = new HashMap<>(); for (ServerFormDetails serverFormDetails : updatedForms) { try { formDownloader.downloadForm(serverFormDetails, null, null); results.put(serverFormDetails, TranslationHandler.getString(context, R.string.success)); } catch (FormDownloadException e) { results.put(serverFormDetails, TranslationHandler.getString(context, R.string.failure)); } catch (InterruptedException e) { break; } } notifier.onUpdatesDownloaded(results); } return null; }); } else { notifier.onUpdatesAvailable(updatedForms); } } return true; } catch (FormSourceException e) { return true; } }; } @NotNull @Override public Class<? extends WorkerAdapter> getWorkManagerAdapter() { return Adapter.class; } public static class Adapter extends WorkerAdapter { public Adapter(@NotNull Context context, @NotNull WorkerParameters workerParams) { super(new AutoUpdateTaskSpec(), context, workerParams); } } }
Passw/pmwkaa-sophia
sophia/database/sd_scheme.c
<reponame>Passw/pmwkaa-sophia /* * sophia database * sphia.org * * Copyright (c) <NAME> * BSD License */ #include <libss.h> #include <libsf.h> #include <libsr.h> #include <libsv.h> #include <libsd.h> int sd_schemebegin(sdscheme *c, sr *r) { int rc = ss_bufensure(&c->buf, r->a, sizeof(sdschemeheader)); if (ssunlikely(rc == -1)) return sr_oom(r->e); sdschemeheader *h = (sdschemeheader*)c->buf.s; memset(h, 0, sizeof(sdschemeheader)); ss_bufadvance(&c->buf, sizeof(sdschemeheader)); return 0; } int sd_schemeadd(sdscheme *c, sr *r, uint8_t id, sstype type, void *value, uint32_t size) { sdschemeopt opt = { .type = type, .id = id, .size = size }; int rc = ss_bufadd(&c->buf, r->a, &opt, sizeof(opt)); if (ssunlikely(rc == -1)) goto error; rc = ss_bufadd(&c->buf, r->a, value, size); if (ssunlikely(rc == -1)) goto error; sdschemeheader *h = (sdschemeheader*)c->buf.s; h->count++; return 0; error: return sr_oom(r->e); } int sd_schemecommit(sdscheme *c, sr *r) { if (ssunlikely(ss_bufused(&c->buf) == 0)) return 0; sdschemeheader *h = (sdschemeheader*)c->buf.s; h->size = ss_bufused(&c->buf) - sizeof(sdschemeheader); h->crc = ss_crcs(r->crc, (char*)h, ss_bufused(&c->buf), 0); return 0; } int sd_schemewrite(sdscheme *c, sr *r, char *path, int sync) { ssfile meta; ss_fileinit(&meta, r->vfs); int rc = ss_filenew(&meta, path, 0); if (ssunlikely(rc == -1)) goto error; rc = ss_filewrite(&meta, c->buf.s, ss_bufused(&c->buf)); if (ssunlikely(rc == -1)) goto error; if (sync) { rc = ss_filesync(&meta); if (ssunlikely(rc == -1)) goto error; } ss_fileadvise(&meta, 0, 0, meta.size); rc = ss_fileclose(&meta); if (ssunlikely(rc == -1)) goto error; return 0; error: sr_error(r->e, "scheme file '%s' error: %s", path, strerror(errno)); ss_fileclose(&meta); return -1; } int sd_schemerecover(sdscheme *c, sr *r, char *path) { ssize_t size = ss_vfssize(r->vfs, path); if (ssunlikely(size == -1)) goto error; if (ssunlikely((unsigned int)size < sizeof(sdschemeheader))) { sr_error(r->e, "scheme file '%s' is corrupted", path); return -1; } int rc = ss_bufensure(&c->buf, r->a, size); if (ssunlikely(rc == -1)) return sr_oom(r->e); ssfile meta; ss_fileinit(&meta, r->vfs); rc = ss_fileopen(&meta, path, 0); if (ssunlikely(rc == -1)) goto error; rc = ss_filepread(&meta, 0, c->buf.s, size); if (ssunlikely(rc == -1)) goto error; rc = ss_fileclose(&meta); if (ssunlikely(rc == -1)) goto error; ss_bufadvance(&c->buf, size); return 0; error: sr_error(r->e, "scheme file '%s' error: %s", path, strerror(errno)); return -1; }
osorubeki-fujita/odpt_tokyo_metro
lib/tokyo_metro/refinement/api/station_timetable.rb
<filename>lib/tokyo_metro/refinement/api/station_timetable.rb module TokyoMetro::Refinement::Api::StationTimetable end
joshwalawender/PypeIt
pypeit/tests/test_flux.py
""" Module to run tests on simple fitting routines for arrays """ import os import sys import numpy as np import pytest #try: # tsterror = FileExistsError #except NameError: # FileExistsError = OSError from astropy import units from pypeit.core import flux_calib from pypeit.core import load from pypeit.spectrographs.util import load_spectrograph from pypeit import specobjs from pypeit.tests.tstutils import dummy_fitstbl #from xastropy.xutils import afits as xafits #from xastropy.xutils import xdebug as xdb def data_path(filename): data_dir = os.path.join(os.path.dirname(__file__), 'files') return os.path.join(data_dir, filename) # JFH This test is defunct #def test_bspline_fit(): # # Testing the bspline works ok (really testing bkspace) # fit_dict = linetools.utils.loadjson(data_path('flux_data.json')) # wave = np.array(fit_dict['wave']) # magfunc = np.array(fit_dict['magf']) # logivar = np.array(fit_dict['logiv']) # bspline_par = dict(bkspace=fit_dict['bkspec']) # mask, tck = utils.robust_polyfit(wave, magfunc, 3, function='bspline', # weights=np.sqrt(logivar), bspline_par=bspline_par) def test_gen_sensfunc(): kastr = load_spectrograph('shane_kast_red') # Load a random spectrum for the sensitivity function sfile = data_path('spec1d_r153-J0025-0312_KASTr_2015Jan23T025323.850.fits') sobjs = specobjs.SpecObjs.from_fitsfile(sfile) # telescope = telescopes.ShaneTelescopePar() fitstbl = dummy_fitstbl() RA = '05:06:36.6' DEC = '52:52:01.0' # Get the sensitivity function sens_dict = flux_calib.generate_sensfunc(sobjs[0].BOX_WAVE, sobjs[0].BOX_COUNTS, sobjs[0].BOX_COUNTS_IVAR, fitstbl['airmass'][4], fitstbl['exptime'][4], kastr.telescope['longitude'], kastr.telescope['latitude'], ra=RA, dec=DEC) # Test assert isinstance(sens_dict, dict) assert isinstance(sens_dict['wave_min'], units.Quantity) def test_find_standard(): # G191b2b std_ra = '05:06:30.6' std_dec = '52:49:51.0' # Grab std_dict = flux_calib.find_standard_file(std_ra, std_dec) # Test assert std_dict['name'] == 'G191B2B' # assert std_dict['cal_file'] == 'data/standards/calspec/g191b2b_mod_005.fits' assert std_dict['cal_file'] == 'data/standards/calspec/g191b2b_stisnic_002.fits' assert std_dict['std_source'] == 'calspec' # Fail to find # near G191b2b std_ra = '05:06:36.6' std_dec = '52:22:01.0' std_dict = flux_calib.find_standard_file(std_ra, std_dec) assert std_dict is None def test_load_extinction(): # Load extinct = flux_calib.load_extinction_data(121.6428, 37.3413889) np.testing.assert_allclose(extinct['wave'][0], 3200.) assert extinct['wave'].unit == units.AA np.testing.assert_allclose(extinct['mag_ext'][0], 1.084) # Fail extinct = flux_calib.load_extinction_data(0., 37.3413889) assert extinct is None def test_extinction_correction(): # Load extinct = flux_calib.load_extinction_data(121.6428, 37.3413889) # Correction wave = np.arange(3000.,10000.)*units.AA AM=1.5 flux_corr = flux_calib.extinction_correction(wave, AM, extinct) # Test np.testing.assert_allclose(flux_corr[0], 4.47095192)
lazergenixdev/Fission
include/Fission/config.h
<gh_stars>1-10 /** * * @file: config.h * @author: <EMAIL> * * * This file is provided under the MIT License: * * Copyright (c) 2021 Lazergenix Software * * 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 <Fission/Platform/Platform.h> /*!< Determine Target Platform */ //\\//\\||//\\//\\||//\\//\\||//\\//\\||//\\//\\||//\\//\\||//\\//\\||//\\//\\ // Configuration stuff /* FISSION_API */ #ifdef FISSION_PLATFORM_WINDOWS #ifdef FISSION_BUILD_DLL #define FISSION_API __declspec(dllexport) #else #define FISSION_API __declspec(dllimport) #endif // FISSION_BUILD_DLL #else #define FISSION_API extern #endif // FISSION_PLATFORM_WINDOWS /*! @brief Engine Name */ #define FISSION_ENGINE "Fission Engine" /*! @brief Fission Engine Build String, identifying the config we built. */ #ifdef FISSION_DEBUG #define FISSION_BUILD_STRING "(Debug)" /* Debug build of the engine. */ #elif defined(FISSION_RELEASE) #define FISSION_BUILD_STRING "(Release)" /* Release build of the engine. */ #else #define FISSION_BUILD_STRING "" /* Distribution build of the engine. */ #endif /*! @brief Functions that should be thread safe */ #define FISSION_THREAD_SAFE /* FISSION_FORCE_INLINE */ #if _MSC_VER #define FISSION_FORCE_INLINE __forceinline #else #define FISSION_FORCE_INLINE #endif //\\//\\||//\\//\\||//\\//\\||//\\//\\||//\\//\\||//\\//\\||//\\//\\||//\\//\\ /** * standard library includes */ #include <memory> #include <utility> #include <algorithm> /* Literally one of the most useful headers in the C++ standard lib. */ #include <functional> #include <optional> /* I am only optionally including this header. */ #include <string> #include <sstream> #include <array> #include <vector> #include <chrono> /* "I told you not to fuck with time Morty!" */ #include <mutex> #include <condition_variable> #include <unordered_map> #include <map> #include <filesystem> #include <thread> //\\//\\||//\\//\\||//\\//\\||//\\//\\||//\\//\\||//\\//\\||//\\//\\||//\\//\\ /** * Assertions */ #include <cassert> #if FISSION_DEBUG && 1 #define FISSION_ASSERT( expression, ... ) assert( expression && "" __VA_ARGS__ ) #else #define FISSION_ASSERT( expression, ... ) ((void)0) #endif // FISSION_DEBUG /** * Macro Helpers */ #define FISSION_MK_STR(X) #X /** * Important Web Address */ #define FISSION_Rx2 "https://youtu.be/dQw4w9WgXcQ" //\\//\\||//\\//\\||//\\//\\||//\\//\\||//\\//\\||//\\//\\||//\\//\\||//\\//\\ /** * TODO: Find a place for this in Base/ */ namespace Fission { template <typename T> class list_view { public: using iterator = T *; using const_iterator = const T *; list_view( iterator begin, iterator end ) : m_pBegin( begin ), m_pEnd( end ), m_Size( end - begin ) {} const T & operator[]( int index ) const { return m_pBegin[index]; } T & operator[]( int index ) { return m_pBegin[index]; } iterator begin() { return m_pBegin; } iterator end() { return m_pEnd; } const_iterator begin() const { return m_pBegin; } const_iterator end() const { return m_pEnd; } size_t size() const { return m_Size; } private: iterator m_pBegin; iterator m_pEnd; size_t m_Size; }; }
jhauberg/SHIZEN
src/zrand.c
<reponame>jhauberg/SHIZEN //// // __| | | _ _| __ / __| \ | // \__ \ __ | | / _| . | // ____/ _| _| ___| ____| ___| _|\_| // // Copyright (c) 2017 <NAME> // // This library is free software; you can redistribute and modify it // under the terms of the MIT license. See LICENSE for details. // #include <SHIZEN/zrand.h> #include <SHIZEN/zmath.h> #include <SHIZEN/ztype.h> // #include <stdlib.h> // NULL #include <math.h> // ldexpf, M_PI #include <time.h> // time() #ifdef SHIZ_DEBUG #include "io.h" #endif #include <pcg/pcg_basic.h> static uint32_t current_seed; void z_rand_seed(uint32_t seed) { pcg32_srandom(seed, 0xda3e39cb94b95bdbULL); current_seed = seed; #ifdef SHIZ_DEBUG z_io__debug("Seeding: %d", current_seed); #endif } void z_rand_seed_now() { z_rand_seed((uint32_t)time(NULL)); } uint32_t z_rand_get_seed() { return current_seed; } uint32_t z_rand() { return pcg32_random(); } int32_t z_rand_range(int32_t const min, int32_t const max) { uint32_t const range = (uint32_t)abs(max - min); uint32_t const r = pcg32_boundedrand(range + 1); // both min and max inclusive int32_t const result = min + (int32_t)r; return result; } float z_randf() { return ldexpf(z_rand(), -32); } float z_randf_range(float const min, float const max) { return z_lerp(min, max, z_randf()); } float z_randf_angle() { return z_randf_range((float)-M_PI, (float)M_PI); } SHIZColor z_rand_color() { return SHIZColorMake(z_randf(), z_randf(), z_randf(), 1); } bool z_rand_choice() { return z_rand_range(0, 1) > 0; } bool z_rand_chance(float const percentage) { return z_randf() < percentage; }
ReadyTalk/cultivar
cultivar-core/src/main/java/com/readytalk/cultivar/CuratorFrameworkProvider.java
package com.readytalk.cultivar; import java.util.concurrent.ThreadFactory; import javax.annotation.Nonnegative; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; import org.apache.curator.RetryPolicy; import org.apache.curator.drivers.TracerDriver; import org.apache.curator.ensemble.EnsembleProvider; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.ACLProvider; import org.apache.curator.framework.api.CompressionProvider; import org.apache.curator.utils.ZookeeperFactory; import com.google.common.annotations.Beta; import com.google.common.base.Optional; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.name.Named; /** * Wraps a CuratorFrameworkFactory.Builder instance and uses setter injection to construct the instance. */ @Beta @ThreadSafe class CuratorFrameworkProvider implements Provider<CuratorFramework> { private final CuratorFrameworkFactory.Builder builder; private Optional<TracerDriver> tracerDriver = Optional.absent(); @Inject public CuratorFrameworkProvider(final CuratorFrameworkFactory.Builder builder) { this.builder = builder; } @Inject public void setEnsembleProvider(@Curator final EnsembleProvider ensembleProvider) { this.builder.ensembleProvider(ensembleProvider); } @Inject public void setRetryPolicy(@Curator final RetryPolicy retryPolicy) { this.builder.retryPolicy(retryPolicy); } @Inject(optional = true) public void setConnectionTimeoutMs( @Named("Cultivar.Curator.connectionTimeoutMs") @Nonnegative final int connectionTimeoutMs) { this.builder.connectionTimeoutMs(connectionTimeoutMs); } @Inject(optional = true) public void setACLProvider(@Curator final ACLProvider aclProvider) { this.builder.aclProvider(aclProvider); } @Inject(optional = true) public void setAuthorization(@Named("Cultivar.Curator.auth.scheme") @Nullable final String scheme, @Named("Cultivar.Curator.auth.auth") @Nullable final byte[] auth) { this.builder.authorization(scheme, auth); } @Inject(optional = true) public void setCompressionProvider(@Curator final CompressionProvider compressionProvider) { this.builder.compressionProvider(compressionProvider); } @Inject(optional = true) public void setDefaultData(@Named("Cultivar.Curator.defaultData") final byte[] defaultData) { this.builder.defaultData(defaultData); } @Inject(optional = true) public void setNamespace(@Named("Cultivar.Curator.baseNamespace") @Nullable final String namespace) { this.builder.namespace(namespace); } @Inject(optional = true) public void setSessionTimeoutMs(@Named("Cultivar.Curator.sessionTimeoutMs") @Nonnegative final int sessionTimeoutMs) { this.builder.sessionTimeoutMs(sessionTimeoutMs); } @Inject(optional = true) public void setCanBeReadOnly(@Named("Cultivar.Curator.canBeReadOnly") final boolean canBeReadOnly) { this.builder.canBeReadOnly(canBeReadOnly); } @Inject(optional = true) public void setThreadFactory(@Curator final ThreadFactory threadFactory) { this.builder.threadFactory(threadFactory); } @Inject(optional = true) public void setZookeeperFactory(@Curator final ZookeeperFactory zookeeperFactory) { this.builder.zookeeperFactory(zookeeperFactory); } @Inject(optional = true) public void setTracerDriver(@Curator final TracerDriver tracerDriver) { this.tracerDriver = Optional.of(tracerDriver); } @Override public CuratorFramework get() { CuratorFramework retval; retval = builder.build(); if (tracerDriver.isPresent()) { retval.getZookeeperClient().setTracerDriver(tracerDriver.get()); } return retval; } }
gkontsevich/leapserial
src/LeapSerial/LeapSerial.h
// Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved. #pragma once #include "Allocation.h" #include "Archive.h" #include "Descriptor.h" #include "field_serializer.h" #include "ArchiveLeapSerial.h" #include "IArchiveProtobuf.h" #include "OArchiveProtobuf.h" #include "SchemaWriterProtobuf.h" #include <memory> #include <istream> namespace leap { struct descriptor; template<typename T, typename> struct field_serializer_t; struct leapserial { typedef IArchiveLeapSerial iarchive; typedef OArchiveLeapSerial oarchive; }; struct protobuf_v1 { typedef IArchiveProtobuf iarchive; typedef OArchiveProtobuf oarchive; typedef SchemaWriterProtobuf schema; }; struct protobuf_v2 { typedef IArchiveProtobuf iarchive; typedef OArchiveProtobuf oarchive; typedef SchemaWriterProtobuf2 schema; }; template<typename archive_t, typename T> void SerializeWithArchive(archive_t& ar, const T& obj) { static_assert(!std::is_pointer<T>::value, "Do not serialize a pointer to an object, serialize a reference"); static_assert( !std::is_base_of<std::false_type, field_serializer_t<T, void>>::value, "serial_traits is not specialized on the specified type, and this type also doesn't provide a GetDescriptor routine" ); ar.WriteObject( field_serializer_t<T, void>::GetDescriptor(), &obj ); } template<typename archive_t, typename stream_t> void Serialize(stream_t& os, const leap::descriptor& desc) { typename archive_t::schema s{ desc }; s.Write(os); } template<typename archive_t, typename T> void Serialize(std::ostream& os, const T& obj) { leap::OutputStreamAdapter osa{ os }; archive_t ar(osa); SerializeWithArchive<archive_t, T>(ar, obj); } template<typename archive_t, typename T> void Serialize(IOutputStream& os, const T& obj) { archive_t ar(os); SerializeWithArchive(ar, obj); } template<typename T> void Serialize(std::ostream& os, const T& obj) { leap::OutputStreamAdapter osa{ os }; leap::OArchiveLeapSerial ar(osa); SerializeWithArchive(ar, obj); } template<typename T> void Serialize(IOutputStream& os, const T& obj) { leap::OArchiveLeapSerial ar(os); SerializeWithArchive(ar, obj); } ///I/OArchiveLeapSerial defaulted versions: template<typename archive_t, typename stream_t, typename T> void Serialize(stream_t&& os, const T& obj) { Serialize<archive_t, T>(os, obj); } template<typename stream_t, typename T> void Serialize(stream_t&& os, const T& obj) { Serialize<leap::OArchiveLeapSerial, T>(os, obj); } /// <summary> /// Deserialization routine that returns an std::shared_ptr for memory allocation maintenance /// </summary> template<class T = void, class archive_t = IArchiveLeapSerial, class stream_t = std::istream> std::shared_ptr<T> Deserialize(stream_t&& is) { auto retVal = std::make_shared<leap::internal::Allocation<T>>(); T* pObj = &retVal->val; // Initialize the archive with work to be done: archive_t ar(is); ar.ReadObject(field_serializer_t<T, void>::GetDescriptor(), pObj, retVal.get() ); // Aliasing ctor, because T is a member of Allocation<T> and not a base return { retVal, pObj }; } /// <summary> /// Deserialization routine that modifies object in place /// </summary> template<class archive_t = IArchiveLeapSerial, class T = void, class stream_t = std::istream> void Deserialize(stream_t&& is, T& obj) { // Initialize the archive with work to be done: archive_t ar(is); ar.ReadObject(field_serializer_t<T, void>::GetDescriptor(), &obj, nullptr); } // Fill a collection with objects serialized to 'is' // Returns one past the end of the container template<class T, class archive_t = IArchiveLeapSerial, class stream_t = std::istream> std::vector<T> DeserializeToVector(stream_t&& is) { std::vector<T> collection; while (is.peek() != std::char_traits<char>::eof()) { collection.emplace_back(); Deserialize<archive_t, T>(is, collection.back()); } return collection; } // Utility method until everyone moves to C++14 template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) { return std::unique_ptr<T>{new T{ std::forward<Args&&>(args)... }}; } }
quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
Source/devtools/front_end/sources/CallStackSidebarPane.js
/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor * @extends {WebInspector.SidebarPane} */ WebInspector.CallStackSidebarPane = function() { WebInspector.SidebarPane.call(this, WebInspector.UIString("Call Stack")); this.bodyElement.addEventListener("keydown", this._keyDown.bind(this), true); this.bodyElement.tabIndex = 0; var asyncCheckbox = this.titleElement.appendChild(WebInspector.SettingsUI.createSettingCheckbox(WebInspector.UIString("Async"), WebInspector.settings.enableAsyncStackTraces, true, undefined, WebInspector.UIString("Capture async stack traces"))); asyncCheckbox.classList.add("scripts-callstack-async"); asyncCheckbox.addEventListener("click", consumeEvent, false); WebInspector.settings.enableAsyncStackTraces.addChangeListener(this._asyncStackTracesStateChanged, this); } WebInspector.CallStackSidebarPane.Events = { CallFrameRestarted: "CallFrameRestarted", CallFrameSelected: "CallFrameSelected" } WebInspector.CallStackSidebarPane.prototype = { /** * @param {?WebInspector.DebuggerPausedDetails} details */ update: function(details) { this.bodyElement.removeChildren(); if (!details) { var infoElement = this.bodyElement.createChild("div", "info"); infoElement.textContent = WebInspector.UIString("Not Paused"); return; } this._target = details.target(); var callFrames = details.callFrames; var asyncStackTrace = details.asyncStackTrace; delete this._statusMessageElement; delete this._hiddenPlacardsMessageElement; /** @type {!Array.<!WebInspector.CallStackSidebarPane.Placard>} */ this.placards = []; this._hiddenPlacards = 0; this._appendSidebarPlacards(callFrames); var topStackHidden = (this._hiddenPlacards === this.placards.length); while (asyncStackTrace) { var title = asyncStackTrace.description; if (title) title += " " + WebInspector.UIString("(async)"); else title = WebInspector.UIString("Async Call"); var asyncPlacard = new WebInspector.Placard(title, ""); asyncPlacard.element.addEventListener("click", this._selectNextVisiblePlacard.bind(this, this.placards.length, false), false); asyncPlacard.element.addEventListener("contextmenu", this._asyncPlacardContextMenu.bind(this, this.placards.length), true); asyncPlacard.element.classList.add("placard-label"); this.bodyElement.appendChild(asyncPlacard.element); this._appendSidebarPlacards(asyncStackTrace.callFrames, asyncPlacard); asyncStackTrace = asyncStackTrace.asyncStackTrace; } if (topStackHidden) this._revealHiddenPlacards(); if (this._hiddenPlacards) { var element = document.createElementWithClass("div", "hidden-placards-message"); if (this._hiddenPlacards === 1) element.textContent = WebInspector.UIString("1 stack frame is hidden (black-boxed)."); else element.textContent = WebInspector.UIString("%d stack frames are hidden (black-boxed).", this._hiddenPlacards); element.createTextChild(" "); var showAllLink = element.createChild("span", "node-link"); showAllLink.textContent = WebInspector.UIString("Show"); showAllLink.addEventListener("click", this._revealHiddenPlacards.bind(this), false); this.bodyElement.insertBefore(element, this.bodyElement.firstChild); this._hiddenPlacardsMessageElement = element; } }, /** * @param {!Array.<!WebInspector.DebuggerModel.CallFrame>} callFrames * @param {!WebInspector.Placard=} asyncPlacard */ _appendSidebarPlacards: function(callFrames, asyncPlacard) { var allPlacardsHidden = true; for (var i = 0, n = callFrames.length; i < n; ++i) { var callFrame = callFrames[i]; var placard = new WebInspector.CallStackSidebarPane.Placard(callFrame, asyncPlacard); placard.element.addEventListener("click", this._placardSelected.bind(this, placard), false); placard.element.addEventListener("contextmenu", this._placardContextMenu.bind(this, placard), true); this.placards.push(placard); this.bodyElement.appendChild(placard.element); if (callFrame.script.isFramework()) { placard.setHidden(true); placard.element.classList.add("dimmed"); ++this._hiddenPlacards; } else { allPlacardsHidden = false; } } if (allPlacardsHidden && asyncPlacard) asyncPlacard.setHidden(true); }, _revealHiddenPlacards: function() { if (!this._hiddenPlacards) return; this._hiddenPlacards = 0; for (var i = 0; i < this.placards.length; ++i) { var placard = this.placards[i]; placard.setHidden(false); if (placard._asyncPlacard) placard._asyncPlacard.setHidden(false); } if (this._hiddenPlacardsMessageElement) { this._hiddenPlacardsMessageElement.remove(); delete this._hiddenPlacardsMessageElement; } }, /** * @param {!WebInspector.CallStackSidebarPane.Placard} placard * @param {?Event} event */ _placardContextMenu: function(placard, event) { var contextMenu = new WebInspector.ContextMenu(event); if (!placard._callFrame.isAsync()) contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Restart frame" : "Restart Frame"), this._restartFrame.bind(this, placard)); contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Copy stack trace" : "Copy Stack Trace"), this._copyStackTrace.bind(this)); contextMenu.show(); }, /** * @param {number} index * @param {?Event} event */ _asyncPlacardContextMenu: function(index, event) { for (; index < this.placards.length; ++index) { var placard = this.placards[index]; if (!placard.isHidden()) { this._placardContextMenu(placard, event); break; } } }, /** * @param {!WebInspector.CallStackSidebarPane.Placard} placard */ _restartFrame: function(placard) { placard._callFrame.restart(); this.dispatchEventToListeners(WebInspector.CallStackSidebarPane.Events.CallFrameRestarted, placard._callFrame); }, _asyncStackTracesStateChanged: function() { var enabled = WebInspector.settings.enableAsyncStackTraces.get(); if (!enabled && this.placards) this._removeAsyncPlacards(); }, _removeAsyncPlacards: function() { var shouldSelectTopFrame = false; var lastSyncPlacardIndex = -1; for (var i = 0; i < this.placards.length; ++i) { var placard = this.placards[i]; if (placard._asyncPlacard) { if (placard.selected) shouldSelectTopFrame = true; placard._asyncPlacard.element.remove(); placard.element.remove(); } else { lastSyncPlacardIndex = i; } } this.placards.length = lastSyncPlacardIndex + 1; if (shouldSelectTopFrame) this._selectNextVisiblePlacard(0); }, /** * @param {!WebInspector.DebuggerModel.CallFrame} x */ setSelectedCallFrame: function(x) { for (var i = 0; i < this.placards.length; ++i) { var placard = this.placards[i]; placard.selected = (placard._callFrame === x); if (placard.selected && placard.isHidden()) this._revealHiddenPlacards(); } }, /** * @return {boolean} */ _selectNextCallFrameOnStack: function() { var index = this._selectedCallFrameIndex(); if (index === -1) return false; return this._selectNextVisiblePlacard(index + 1); }, /** * @return {boolean} */ _selectPreviousCallFrameOnStack: function() { var index = this._selectedCallFrameIndex(); if (index === -1) return false; return this._selectNextVisiblePlacard(index - 1, true); }, /** * @param {number} index * @param {boolean=} backward * @return {boolean} */ _selectNextVisiblePlacard: function(index, backward) { while (0 <= index && index < this.placards.length) { var placard = this.placards[index]; if (!placard.isHidden()) { this._placardSelected(placard); return true; } index += backward ? -1 : 1; } return false; }, /** * @return {number} */ _selectedCallFrameIndex: function() { var selectedCallFrame = this._target.debuggerModel.selectedCallFrame(); if (!selectedCallFrame) return -1; for (var i = 0; i < this.placards.length; ++i) { var placard = this.placards[i]; if (placard._callFrame === selectedCallFrame) return i; } return -1; }, /** * @param {!WebInspector.CallStackSidebarPane.Placard} placard */ _placardSelected: function(placard) { placard.element.scrollIntoViewIfNeeded(); this.dispatchEventToListeners(WebInspector.CallStackSidebarPane.Events.CallFrameSelected, placard._callFrame); }, _copyStackTrace: function() { var text = ""; var lastPlacard = null; for (var i = 0; i < this.placards.length; ++i) { var placard = this.placards[i]; if (placard.isHidden()) continue; if (lastPlacard && placard._asyncPlacard !== lastPlacard._asyncPlacard) text += placard._asyncPlacard.title + "\n"; text += placard.title + " (" + placard.subtitle + ")\n"; lastPlacard = placard; } InspectorFrontendHost.copyText(text); }, /** * @param {function(!Array.<!WebInspector.KeyboardShortcut.Descriptor>, function(?Event=):boolean)} registerShortcutDelegate */ registerShortcuts: function(registerShortcutDelegate) { registerShortcutDelegate(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.NextCallFrame, this._selectNextCallFrameOnStack.bind(this)); registerShortcutDelegate(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.PrevCallFrame, this._selectPreviousCallFrameOnStack.bind(this)); }, /** * @param {!Element|string} status */ setStatus: function(status) { if (!this._statusMessageElement) this._statusMessageElement = this.bodyElement.createChild("div", "info"); if (typeof status === "string") { this._statusMessageElement.textContent = status; } else { this._statusMessageElement.removeChildren(); this._statusMessageElement.appendChild(status); } }, _keyDown: function(event) { if (event.altKey || event.shiftKey || event.metaKey || event.ctrlKey) return; if (event.keyIdentifier === "Up" && this._selectPreviousCallFrameOnStack() || event.keyIdentifier === "Down" && this._selectNextCallFrameOnStack()) event.consume(true); }, __proto__: WebInspector.SidebarPane.prototype } /** * @constructor * @extends {WebInspector.Placard} * @param {!WebInspector.DebuggerModel.CallFrame} callFrame * @param {!WebInspector.Placard=} asyncPlacard */ WebInspector.CallStackSidebarPane.Placard = function(callFrame, asyncPlacard) { WebInspector.Placard.call(this, callFrame.functionName || WebInspector.UIString("(anonymous function)"), ""); callFrame.createLiveLocation(this._update.bind(this)); this._callFrame = callFrame; this._asyncPlacard = asyncPlacard; } WebInspector.CallStackSidebarPane.Placard.prototype = { /** * @param {!WebInspector.UILocation} uiLocation */ _update: function(uiLocation) { this.subtitle = uiLocation.linkText().trimMiddle(100); }, __proto__: WebInspector.Placard.prototype }