repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
mars-lan/WhereHows | datahub-web/@datahub/utils/addon/test-helpers/stub-service.ts | 650 | import Service from '@ember/service';
import { TestContext } from 'ember-test-helpers';
import { getContext } from '@ember/test-helpers';
/**
* Registers a stub service for component integration testing
* @param {string} name the name of the service without the service: prefix e.g. 'location-data'
* @param {*} [props={}] properties to be stubbed on the service interface
*/
export const stubService = (name: string, props = {}): void => {
const serviceStub = Service.extend(props);
const { owner } = getContext() as TestContext; // getContext return type is object, assert TestContext
owner.register(`service:${name}`, serviceStub);
};
| apache-2.0 |
toddmeinershagen/Demo.ADTProcessing | src/Demo.ADTProcessing.Router/Program.cs | 358 | using System.Collections.Concurrent;
namespace Demo.ADTProcessing.Router
{
class Program
{
public static readonly ConcurrentDictionary<string, string> Queues = new ConcurrentDictionary<string, string>();
static void Main(string[] args)
{
var router = new Router();
router.Run();
}
}
}
| apache-2.0 |
heriram/incubator-asterixdb | hyracks-fullstack/hyracks/hyracks-control/hyracks-control-cc/src/main/java/org/apache/hyracks/control/cc/ClusterControllerService.java | 18348 | /*
* 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.hyracks.control.cc;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hyracks.api.application.ICCApplication;
import org.apache.hyracks.api.application.IClusterLifecycleListener;
import org.apache.hyracks.api.client.ClusterControllerInfo;
import org.apache.hyracks.api.comm.NetworkAddress;
import org.apache.hyracks.api.config.IApplicationConfig;
import org.apache.hyracks.api.config.IOption;
import org.apache.hyracks.api.context.ICCContext;
import org.apache.hyracks.api.deployment.DeploymentId;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.exceptions.HyracksException;
import org.apache.hyracks.api.job.JobIdFactory;
import org.apache.hyracks.api.job.resource.IJobCapacityController;
import org.apache.hyracks.api.service.IControllerService;
import org.apache.hyracks.api.topology.ClusterTopology;
import org.apache.hyracks.api.topology.TopologyDefinitionParser;
import org.apache.hyracks.control.cc.application.CCServiceContext;
import org.apache.hyracks.control.cc.cluster.INodeManager;
import org.apache.hyracks.control.cc.cluster.NodeManager;
import org.apache.hyracks.control.cc.dataset.DatasetDirectoryService;
import org.apache.hyracks.control.cc.dataset.IDatasetDirectoryService;
import org.apache.hyracks.control.cc.job.IJobManager;
import org.apache.hyracks.control.cc.job.JobManager;
import org.apache.hyracks.control.cc.scheduler.IResourceManager;
import org.apache.hyracks.control.cc.scheduler.ResourceManager;
import org.apache.hyracks.control.cc.web.WebServer;
import org.apache.hyracks.control.cc.work.GatherStateDumpsWork.StateDumpRun;
import org.apache.hyracks.control.cc.work.GetIpAddressNodeNameMapWork;
import org.apache.hyracks.control.cc.work.GetThreadDumpWork.ThreadDumpRun;
import org.apache.hyracks.control.cc.work.RemoveDeadNodesWork;
import org.apache.hyracks.control.cc.work.ShutdownNCServiceWork;
import org.apache.hyracks.control.cc.work.TriggerNCWork;
import org.apache.hyracks.control.common.config.ConfigManager;
import org.apache.hyracks.control.common.context.ServerContext;
import org.apache.hyracks.control.common.controllers.CCConfig;
import org.apache.hyracks.control.common.controllers.NCConfig;
import org.apache.hyracks.control.common.deployment.DeploymentRun;
import org.apache.hyracks.control.common.ipc.CCNCFunctions;
import org.apache.hyracks.control.common.logs.LogFile;
import org.apache.hyracks.control.common.shutdown.ShutdownRun;
import org.apache.hyracks.control.common.work.WorkQueue;
import org.apache.hyracks.ipc.api.IIPCI;
import org.apache.hyracks.ipc.impl.IPCSystem;
import org.apache.hyracks.ipc.impl.JavaSerializationBasedPayloadSerializerDeserializer;
import org.xml.sax.InputSource;
public class ClusterControllerService implements IControllerService {
private static final Logger LOGGER = Logger.getLogger(ClusterControllerService.class.getName());
private final CCConfig ccConfig;
private final ConfigManager configManager;
private IPCSystem clusterIPC;
private IPCSystem clientIPC;
private final LogFile jobLog;
private ServerContext serverCtx;
private WebServer webServer;
private ClusterControllerInfo info;
private CCServiceContext serviceCtx;
private final PreDistributedJobStore preDistributedJobStore = new PreDistributedJobStore();
private final WorkQueue workQueue;
private ExecutorService executor;
private final Timer timer;
private final ICCContext ccContext;
private final DeadNodeSweeper sweeper;
private final IDatasetDirectoryService datasetDirectoryService;
private final Map<DeploymentId, DeploymentRun> deploymentRunMap;
private final Map<String, StateDumpRun> stateDumpRunMap;
private final Map<String, ThreadDumpRun> threadDumpRunMap;
private final INodeManager nodeManager;
private final IResourceManager resourceManager = new ResourceManager();
private final ICCApplication application;
private final JobIdFactory jobIdFactory;
private IJobManager jobManager;
private ShutdownRun shutdownCallback;
public ClusterControllerService(final CCConfig config) throws Exception {
this(config, getApplication(config));
}
public ClusterControllerService(final CCConfig config, final ICCApplication application) throws Exception {
this.ccConfig = config;
this.configManager = ccConfig.getConfigManager();
if (application == null) {
throw new IllegalArgumentException("ICCApplication cannot be null");
}
this.application = application;
configManager.processConfig();
File jobLogFolder = new File(ccConfig.getRootDir(), "logs/jobs");
jobLog = new LogFile(jobLogFolder);
// WorkQueue is in charge of heartbeat as well as other events.
workQueue = new WorkQueue("ClusterController", Thread.MAX_PRIORITY);
this.timer = new Timer(true);
final ClusterTopology topology = computeClusterTopology(ccConfig);
ccContext = new ClusterControllerContext(topology);
sweeper = new DeadNodeSweeper();
datasetDirectoryService = new DatasetDirectoryService(ccConfig.getResultTTL(),
ccConfig.getResultSweepThreshold(), preDistributedJobStore);
deploymentRunMap = new HashMap<>();
stateDumpRunMap = new HashMap<>();
threadDumpRunMap = Collections.synchronizedMap(new HashMap<>());
// Node manager is in charge of cluster membership management.
nodeManager = new NodeManager(ccConfig, resourceManager);
jobIdFactory = new JobIdFactory();
}
private static ClusterTopology computeClusterTopology(CCConfig ccConfig) throws Exception {
if (ccConfig.getClusterTopology() == null) {
return null;
}
FileReader fr = new FileReader(ccConfig.getClusterTopology());
InputSource in = new InputSource(fr);
try {
return TopologyDefinitionParser.parse(in);
} finally {
fr.close();
}
}
@Override
public void start() throws Exception {
LOGGER.log(Level.INFO, "Starting ClusterControllerService: " + this);
serverCtx = new ServerContext(ServerContext.ServerType.CLUSTER_CONTROLLER, new File(ccConfig.getRootDir()));
IIPCI ccIPCI = new ClusterControllerIPCI(this);
clusterIPC = new IPCSystem(new InetSocketAddress(ccConfig.getClusterListenPort()), ccIPCI,
new CCNCFunctions.SerializerDeserializer());
IIPCI ciIPCI = new ClientInterfaceIPCI(this, jobIdFactory);
clientIPC = new IPCSystem(
new InetSocketAddress(ccConfig.getClientListenAddress(), ccConfig.getClientListenPort()),
ciIPCI, new JavaSerializationBasedPayloadSerializerDeserializer());
webServer = new WebServer(this, ccConfig.getConsoleListenPort());
clusterIPC.start();
clientIPC.start();
webServer.start();
info = new ClusterControllerInfo(ccConfig.getClientListenAddress(), ccConfig.getClientListenPort(),
webServer.getListeningPort());
timer.schedule(sweeper, 0, ccConfig.getHeartbeatPeriod());
jobLog.open();
startApplication();
datasetDirectoryService.init(executor);
workQueue.start();
connectNCs();
LOGGER.log(Level.INFO, "Started ClusterControllerService");
notifyApplication();
}
private void startApplication() throws Exception {
serviceCtx = new CCServiceContext(this, serverCtx, ccContext, ccConfig.getAppConfig());
serviceCtx.addJobLifecycleListener(datasetDirectoryService);
executor = Executors.newCachedThreadPool(serviceCtx.getThreadFactory());
application.start(serviceCtx, ccConfig.getAppArgsArray());
IJobCapacityController jobCapacityController = application.getJobCapacityController();
// Job manager is in charge of job lifecycle management.
try {
Constructor<?> jobManagerConstructor = this.getClass().getClassLoader()
.loadClass(ccConfig.getJobManagerClass())
.getConstructor(CCConfig.class, ClusterControllerService.class, IJobCapacityController.class);
jobManager = (IJobManager) jobManagerConstructor.newInstance(ccConfig, this, jobCapacityController);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException
| InvocationTargetException e) {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.log(Level.WARNING, "class " + ccConfig.getJobManagerClass() + " could not be used: ", e);
}
// Falls back to the default implementation if the user-provided class name is not valid.
jobManager = new JobManager(ccConfig, this, jobCapacityController);
}
}
private Pair<String, Integer> getNCService(String nodeId) {
IApplicationConfig ncConfig = configManager.getNodeEffectiveConfig(nodeId);
return Pair.of(ncConfig.getString(NCConfig.Option.NCSERVICE_ADDRESS),
ncConfig.getInt(NCConfig.Option.NCSERVICE_PORT));
}
private Map<String, Pair<String, Integer>> getNCServices() {
Map<String, Pair<String, Integer>> ncMap = new TreeMap<>();
for (String ncId : configManager.getNodeNames()) {
Pair<String, Integer> ncService = getNCService(ncId);
if (ncService.getRight() != NCConfig.NCSERVICE_PORT_DISABLED) {
ncMap.put(ncId, ncService);
}
}
return ncMap;
}
private void connectNCs() {
getNCServices().entrySet().forEach(ncService -> {
final TriggerNCWork triggerWork = new TriggerNCWork(ClusterControllerService.this,
ncService.getValue().getLeft(), ncService.getValue().getRight(), ncService.getKey());
workQueue.schedule(triggerWork);
});
serviceCtx.addClusterLifecycleListener(new IClusterLifecycleListener() {
@Override
public void notifyNodeJoin(String nodeId, Map<IOption, Object> ncConfiguration) throws HyracksException {
// no-op, we don't care
}
@Override
public void notifyNodeFailure(Collection<String> deadNodeIds) throws HyracksException {
for (String nodeId : deadNodeIds) {
Pair<String, Integer> ncService = getNCService(nodeId);
final TriggerNCWork triggerWork = new TriggerNCWork(ClusterControllerService.this,
ncService.getLeft(), ncService.getRight(), nodeId);
workQueue.schedule(triggerWork);
}
}
});
}
private void terminateNCServices() throws Exception {
List<ShutdownNCServiceWork> shutdownNCServiceWorks = new ArrayList<>();
getNCServices().entrySet().forEach(ncService -> {
ShutdownNCServiceWork shutdownWork = new ShutdownNCServiceWork(ncService.getValue().getLeft(),
ncService.getValue().getRight(), ncService.getKey());
workQueue.schedule(shutdownWork);
shutdownNCServiceWorks.add(shutdownWork);
});
for (ShutdownNCServiceWork shutdownWork : shutdownNCServiceWorks) {
shutdownWork.sync();
}
}
private void notifyApplication() throws Exception {
application.startupCompleted();
}
public void stop(boolean terminateNCService) throws Exception {
if (terminateNCService) {
terminateNCServices();
}
stop();
}
@Override
public void stop() throws Exception {
LOGGER.log(Level.INFO, "Stopping ClusterControllerService");
stopApplication();
webServer.stop();
sweeper.cancel();
workQueue.stop();
executor.shutdownNow();
clusterIPC.stop();
jobLog.close();
clientIPC.stop();
LOGGER.log(Level.INFO, "Stopped ClusterControllerService");
}
private void stopApplication() throws Exception {
application.stop();
}
public ServerContext getServerContext() {
return serverCtx;
}
public ICCContext getCCContext() {
return ccContext;
}
public IJobManager getJobManager() {
return jobManager;
}
public INodeManager getNodeManager() {
return nodeManager;
}
public PreDistributedJobStore getPreDistributedJobStore() throws HyracksException {
return preDistributedJobStore;
}
public IResourceManager getResourceManager() {
return resourceManager;
}
public LogFile getJobLogFile() {
return jobLog;
}
public WorkQueue getWorkQueue() {
return workQueue;
}
@Override
public ExecutorService getExecutor() {
return executor;
}
public CCConfig getConfig() {
return ccConfig;
}
@Override
public CCServiceContext getContext() {
return serviceCtx;
}
public ClusterControllerInfo getClusterControllerInfo() {
return info;
}
public CCConfig getCCConfig() {
return ccConfig;
}
public IPCSystem getClusterIPC() {
return clusterIPC;
}
public NetworkAddress getDatasetDirectoryServiceInfo() {
return new NetworkAddress(ccConfig.getClientListenAddress(), ccConfig.getClientListenPort());
}
public JobIdFactory getJobIdFactory() {
return jobIdFactory;
}
private final class ClusterControllerContext implements ICCContext {
private final ClusterTopology topology;
private ClusterControllerContext(ClusterTopology topology) {
this.topology = topology;
}
@Override
public void getIPAddressNodeMap(Map<InetAddress, Set<String>> map) throws HyracksDataException {
GetIpAddressNodeNameMapWork ginmw = new GetIpAddressNodeNameMapWork(
ClusterControllerService.this.getNodeManager(), map);
try {
workQueue.scheduleAndSync(ginmw);
} catch (Exception e) {
throw new HyracksDataException(e);
}
}
@Override
public ClusterControllerInfo getClusterControllerInfo() {
return info;
}
@Override
public ClusterTopology getClusterTopology() {
return topology;
}
}
private class DeadNodeSweeper extends TimerTask {
@Override
public void run() {
workQueue.schedule(new RemoveDeadNodesWork(ClusterControllerService.this));
}
}
public IDatasetDirectoryService getDatasetDirectoryService() {
return datasetDirectoryService;
}
public synchronized void addStateDumpRun(String id, StateDumpRun sdr) {
stateDumpRunMap.put(id, sdr);
}
public synchronized StateDumpRun getStateDumpRun(String id) {
return stateDumpRunMap.get(id);
}
public synchronized void removeStateDumpRun(String id) {
stateDumpRunMap.remove(id);
}
/**
* Add a deployment run
*
* @param deploymentKey
* @param dRun
*/
public synchronized void addDeploymentRun(DeploymentId deploymentKey, DeploymentRun dRun) {
deploymentRunMap.put(deploymentKey, dRun);
}
/**
* Get a deployment run
*
* @param deploymentKey
*/
public synchronized DeploymentRun getDeploymentRun(DeploymentId deploymentKey) {
return deploymentRunMap.get(deploymentKey);
}
/**
* Remove a deployment run
*
* @param deploymentKey
*/
public synchronized void removeDeploymentRun(DeploymentId deploymentKey) {
deploymentRunMap.remove(deploymentKey);
}
public synchronized void setShutdownRun(ShutdownRun sRun) {
shutdownCallback = sRun;
}
public synchronized ShutdownRun getShutdownRun() {
return shutdownCallback;
}
public void addThreadDumpRun(String requestKey, ThreadDumpRun tdr) {
threadDumpRunMap.put(requestKey, tdr);
}
public ThreadDumpRun removeThreadDumpRun(String requestKey) {
return threadDumpRunMap.remove(requestKey);
}
private static ICCApplication getApplication(CCConfig ccConfig)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
if (ccConfig.getAppClass() != null) {
Class<?> c = Class.forName(ccConfig.getAppClass());
return (ICCApplication) c.newInstance();
} else {
return BaseCCApplication.INSTANCE;
}
}
public ICCApplication getApplication() {
return application;
}
@Override
public Object getApplicationContext() {
return application.getApplicationContext();
}
}
| apache-2.0 |
txs72/BUPTJava | additional/junit5example/src/test/java/MyIntegerTest.java | 3690 | import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@DisplayName("MyInteger类相关测试")
public class MyIntegerTest {
int even[] = {
2, 4, 6, 8, 20, 32, 46, 108, 200, 1004
};
int odd[] = {
1, 3, 5, 7, 31, 47, 69, 77, 107, 309
};
int prime[] = {
2, 3, 5, 7, 11, 373, 1103, 1721, 3491, 9619
};
MyInteger miEven[];
MyInteger miOdd[];
MyInteger miPrime[];
char[] c;
@BeforeEach
void initAll() {
miEven = new MyInteger[even.length];
for (int i = 0; i < miEven.length; i++) {
miEven[i] = new MyInteger(even[i]);
}
miOdd = new MyInteger[odd.length];
for (int i = 0; i < miOdd.length; i++) {
miOdd[i] = new MyInteger(odd[i]);
}
miPrime = new MyInteger[prime.length];
for (int i = 0; i < miPrime.length; i++) {
miPrime[i] = new MyInteger(prime[i]);
}
}
@Test
@DisplayName("测试isEven()普通成员函数")
void testIsEvenVoid() {
for (MyInteger mi : miEven) {
assertTrue(mi.isEven());
}
}
@Test
@DisplayName("测试isOdd()普通成员函数")
void testIsOddVoid() {
for (MyInteger mi : miOdd) {
assertTrue(mi.isOdd());
}
}
@Test
@DisplayName("测试isPrime()普通成员函数")
void testIsPrimeVoid() {
for (MyInteger mi : miPrime) {
assertTrue(mi.isPrime());
}
}
// 测试静态方法isEven(int), isOdd(int), isPrime(int)
@Test
@DisplayName("测试isEven(int)静态成员函数")
void testIsEvenInt() {
for (int e : even) {
assertTrue(MyInteger.isEven(e));
}
}
@Test
@DisplayName("测试isOdd(int)静态成员函数")
void testIsOddInt() {
for (int o : odd) {
assertTrue(MyInteger.isOdd(o));
}
}
@Test
@DisplayName("测试isPrime(int)静态成员函数")
void testIsPrimeInt() {
for (int p : prime) {
assertTrue(MyInteger.isPrime(p));
}
}
// 测试静态方法IsEven(MyInteger), isOdd(MyInteger), isPrime(MyInteger)
@Test
@DisplayName("测试isEven(MyInteger)静态成员函数")
void testIsEvenMI(){
for(MyInteger mi: miEven){
assertTrue(MyInteger.isEven(mi));
}
}
@Test
@DisplayName("测试isOdd(MyInteger)静态成员函数")
void testIsOddMI(){
for(MyInteger mi: miOdd){
assertTrue(MyInteger.isOdd(mi));
}
}
@Test
@DisplayName("测试isPrime(MyInteger)静态成员函数")
void testIsPrimeMI(){
for(MyInteger mi: miPrime){
assertTrue(MyInteger.isPrime(mi));
}
}
// 测试equals函数的各个版本
@Test
@DisplayName("测试equals函数的各个版本")
void testEquals(){
assertTrue(new MyInteger(10).equals(10));
assertTrue(new MyInteger(20).equals(new MyInteger(20)));
}
// 测试parseInt函数的各个版本
@Test
@DisplayName("测试parseInt静态成员函数的各个版本")
void testParseInt(){
assertEquals(23464, MyInteger.parseInt("23464"));
assertEquals(2732923, MyInteger.parseInt(new String("2732923")));
c = new char[8];
for(int i=0; i<c.length; i++){
c[i] = (char)(i + '1');
}
// c = "12345"
assertEquals(12345678, MyInteger.parseInt(c));
}
}
| apache-2.0 |
stdlib-js/stdlib | lib/node_modules/@stdlib/net/http-server/test/test.js | 7909 | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var http = require( 'http' );
var tape = require( 'tape' );
var objectKeys = require( '@stdlib/utils/keys' );
var noop = require( '@stdlib/utils/noop' );
var createServer = require( './fixtures/server.js' );
var httpServer = require( './../lib' );
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.equal( typeof httpServer, 'function', 'main export is a function' );
t.end();
});
tape( 'the function will throw an error if provided an invalid option', function test( t ) {
t.throws( foo, Error, 'throws error' );
t.throws( bar, Error, 'throws error' );
t.end();
function foo() {
httpServer({
'port': 3.14
});
}
function bar() {
httpServer({
'maxport': 3.14
}, noop );
}
});
tape( 'the function will throw an error if provided a request listener which is not a function', function test( t ) {
var values;
var i;
values = [
'5',
5,
NaN,
true,
null,
void 0,
[],
{}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[ i ] ), TypeError, 'throws an error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
httpServer( {}, value );
};
}
});
tape( 'the function returns a function', function test( t ) {
t.equal( typeof httpServer(), 'function', 'returns a function' );
t.end();
});
tape( 'the returned function will throw an error if provided a callback argument which is not a function', function test( t ) {
var values;
var create;
var i;
values = [
'5',
5,
NaN,
true,
null,
void 0,
[],
{}
];
create = httpServer( {} );
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[ i ] ), TypeError, 'throws an error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
create( value );
};
}
});
tape( 'the created server listens on a specified port', function test( t ) {
var create;
var opts;
opts = {};
opts.port = 7331;
create = httpServer( opts );
create( onServer );
function onServer( error, server ) {
if ( error ) {
t.ok( false, error.message );
} else {
t.equal( server.address().port, opts.port, 'listens on port '+opts.port );
}
server.close();
t.end();
}
});
tape( 'the returned function will throw if the server encounters an error', function test( t ) {
var create;
var server;
var opts;
opts = {};
opts.port = 1337;
create = httpServer( opts );
create( next );
function next( error, s ) {
if ( error ) {
t.ok( false, error.message );
}
server = s;
t.throws( foo, Error, 'throws error' );
server.close();
t.end();
}
function foo() {
var err = new Error( 'Server error.' );
server.emit( 'error', err );
}
});
tape( 'the returned function will throw if unable to listen on a specified port (default behavior)', function test( t ) {
var create;
var server;
var opts;
opts = {};
opts.port = 10000;
create = httpServer( opts );
create( next );
function next( error, s ) {
if ( error ) {
t.ok( false, error.message );
}
server = s;
t.throws( foo, Error, 'throws an error' );
server.close();
t.end();
}
function foo() {
var err = new Error( 'Server address already in use.' );
err.code = 'EADDRINUSE';
server.emit( 'error', err );
}
});
tape( 'the returned function will port hunt', function test( t ) {
var eServer;
var server;
var create;
var opts;
opts = {};
opts.port = 8080;
opts.maxport = 9999;
create = httpServer( opts );
eServer = createServer( opts.port, next );
function next() {
var addr = eServer.address();
t.equal( addr.port, opts.port, 'fixture server bound to port '+opts.port+' and with address '+addr.address );
create( onServer );
}
function onServer( error, s ) {
var port;
server = s;
if ( error ) {
t.ok( false, error.message );
} else {
port = server.address().port;
t.equal( port > opts.port, true, 'returns a server with a port ('+port+') higher than '+opts.port );
}
setTimeout( onTimeout, 0 );
}
function onTimeout() {
server.close();
eServer.close();
t.end();
}
});
tape( 'the server will listen on a specified hostname', function test( t ) {
var create;
var opts;
opts = {};
opts.hostname = 'localhost';
create = httpServer( opts );
create( onServer );
function onServer( error, server ) {
if ( error ) {
t.ok( false, error.message );
} else {
t.equal( server.address().address, '127.0.0.1', 'listens on address 127.0.0.1 (localhost)' );
}
server.close();
t.end();
}
});
tape( 'the server will listen on a specified address', function test( t ) {
var create;
var opts;
opts = {};
opts.address = '127.0.0.1';
create = httpServer( opts );
create( onServer );
function onServer( error, server ) {
if ( error ) {
t.ok( false, error.message );
} else {
t.equal( server.address().address, opts.address, 'listens at address '+opts.address );
}
server.close();
t.end();
}
});
tape( 'the server will use a provided request listener (no options)', function test( t ) {
var connections;
var create;
var server;
connections = {};
create = httpServer( onRequest );
create( onServer );
function onRequest( request, response ) {
t.ok( true, 'uses request listener' );
response.end( 'OK' );
server.close();
setTimeout( destroyConnections, 10 );
}
function onServer( error, s ) {
var addr;
if ( error ) {
t.ok( false, error.message );
}
server = s;
server.on( 'connection', onConnection );
server.once( 'close', onClose );
addr = s.address();
http.get( 'http://'+addr.address+':'+addr.port, noop );
}
function onClose() {
t.end();
}
function onConnection( socket ) {
var key;
key = socket.remoteAddress+':'+socket.remotePort;
connections[ key ] = socket;
socket.once( 'close', onSocketClose );
function onSocketClose() {
delete connections[ key ];
}
}
function destroyConnections() {
var keys;
var i;
keys = objectKeys( connections );
for ( i = 0; i < keys.length; i++ ) {
connections[ keys[i] ].destroy();
}
}
});
tape( 'the server will use a provided request listener (options)', function test( t ) {
var connections;
var create;
var server;
var opts;
opts = {};
opts.port = 7331;
connections = {};
create = httpServer( opts, onRequest );
create( onServer );
function onRequest( request, response ) {
t.ok( true, 'uses request listener' );
response.end( 'OK' );
server.close();
setTimeout( destroyConnections, 10 );
}
function onServer( error, s ) {
var addr;
if ( error ) {
t.ok( false, error.message );
}
server = s;
server.on( 'connection', onConnection );
server.once( 'close', onClose );
addr = s.address();
http.get( 'http://'+addr.address+':'+addr.port, noop );
}
function onClose() {
t.end();
}
function onConnection( socket ) {
var key;
key = socket.remoteAddress+':'+socket.remotePort;
connections[ key ] = socket;
socket.once( 'close', onSocketClose );
function onSocketClose() {
delete connections[ key ];
}
}
function destroyConnections() {
var keys;
var i;
keys = objectKeys( connections );
for ( i = 0; i < keys.length; i++ ) {
connections[ keys[i] ].destroy();
}
}
});
| apache-2.0 |
datastax/java-driver | core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestSyncProcessor.java | 2606 | /*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.dse.driver.internal.core.cql.continuous;
import com.datastax.dse.driver.api.core.cql.continuous.ContinuousAsyncResultSet;
import com.datastax.dse.driver.api.core.cql.continuous.ContinuousResultSet;
import com.datastax.oss.driver.api.core.cql.Statement;
import com.datastax.oss.driver.api.core.session.Request;
import com.datastax.oss.driver.api.core.type.reflect.GenericType;
import com.datastax.oss.driver.internal.core.context.InternalDriverContext;
import com.datastax.oss.driver.internal.core.session.DefaultSession;
import com.datastax.oss.driver.internal.core.session.RequestProcessor;
import com.datastax.oss.driver.internal.core.util.concurrent.BlockingOperation;
import com.datastax.oss.driver.internal.core.util.concurrent.CompletableFutures;
import net.jcip.annotations.ThreadSafe;
@ThreadSafe
public class ContinuousCqlRequestSyncProcessor
implements RequestProcessor<Statement<?>, ContinuousResultSet> {
public static final GenericType<ContinuousResultSet> CONTINUOUS_RESULT_SYNC =
GenericType.of(ContinuousResultSet.class);
private final ContinuousCqlRequestAsyncProcessor asyncProcessor;
public ContinuousCqlRequestSyncProcessor(ContinuousCqlRequestAsyncProcessor asyncProcessor) {
this.asyncProcessor = asyncProcessor;
}
@Override
public boolean canProcess(Request request, GenericType<?> resultType) {
return request instanceof Statement && resultType.equals(CONTINUOUS_RESULT_SYNC);
}
@Override
public ContinuousResultSet process(
Statement<?> request,
DefaultSession session,
InternalDriverContext context,
String sessionLogPrefix) {
BlockingOperation.checkNotDriverThread();
ContinuousAsyncResultSet firstPage =
CompletableFutures.getUninterruptibly(
asyncProcessor.process(request, session, context, sessionLogPrefix));
return new DefaultContinuousResultSet(firstPage);
}
@Override
public ContinuousResultSet newFailure(RuntimeException error) {
throw error;
}
}
| apache-2.0 |
aosp-mirror/platform_frameworks_support | app-toolkit/common/src/main/java/androidx/arch/core/internal/SafeIterableMap.java | 11134 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.arch.core.internal;
import androidx.annotation.NonNull;
import androidx.annotation.RestrictTo;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;
/**
* LinkedList, which pretends to be a map and supports modifications during iterations.
* It is NOT thread safe.
*
* @param <K> Key type
* @param <V> Value type
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class SafeIterableMap<K, V> implements Iterable<Map.Entry<K, V>> {
private Entry<K, V> mStart;
private Entry<K, V> mEnd;
// using WeakHashMap over List<WeakReference>, so we don't have to manually remove
// WeakReferences that have null in them.
private WeakHashMap<SupportRemove<K, V>, Boolean> mIterators = new WeakHashMap<>();
private int mSize = 0;
protected Entry<K, V> get(K k) {
Entry<K, V> currentNode = mStart;
while (currentNode != null) {
if (currentNode.mKey.equals(k)) {
break;
}
currentNode = currentNode.mNext;
}
return currentNode;
}
/**
* If the specified key is not already associated
* with a value, associates it with the given value.
*
* @param key key with which the specified value is to be associated
* @param v value to be associated with the specified key
* @return the previous value associated with the specified key,
* or {@code null} if there was no mapping for the key
*/
public V putIfAbsent(@NonNull K key, @NonNull V v) {
Entry<K, V> entry = get(key);
if (entry != null) {
return entry.mValue;
}
put(key, v);
return null;
}
protected Entry<K, V> put(@NonNull K key, @NonNull V v) {
Entry<K, V> newEntry = new Entry<>(key, v);
mSize++;
if (mEnd == null) {
mStart = newEntry;
mEnd = mStart;
return newEntry;
}
mEnd.mNext = newEntry;
newEntry.mPrevious = mEnd;
mEnd = newEntry;
return newEntry;
}
/**
* Removes the mapping for a key from this map if it is present.
*
* @param key key whose mapping is to be removed from the map
* @return the previous value associated with the specified key,
* or {@code null} if there was no mapping for the key
*/
public V remove(@NonNull K key) {
Entry<K, V> toRemove = get(key);
if (toRemove == null) {
return null;
}
mSize--;
if (!mIterators.isEmpty()) {
for (SupportRemove<K, V> iter : mIterators.keySet()) {
iter.supportRemove(toRemove);
}
}
if (toRemove.mPrevious != null) {
toRemove.mPrevious.mNext = toRemove.mNext;
} else {
mStart = toRemove.mNext;
}
if (toRemove.mNext != null) {
toRemove.mNext.mPrevious = toRemove.mPrevious;
} else {
mEnd = toRemove.mPrevious;
}
toRemove.mNext = null;
toRemove.mPrevious = null;
return toRemove.mValue;
}
/**
* @return the number of elements in this map
*/
public int size() {
return mSize;
}
/**
* @return an ascending iterator, which doesn't include new elements added during an
* iteration.
*/
@NonNull
@Override
public Iterator<Map.Entry<K, V>> iterator() {
ListIterator<K, V> iterator = new AscendingIterator<>(mStart, mEnd);
mIterators.put(iterator, false);
return iterator;
}
/**
* @return an descending iterator, which doesn't include new elements added during an
* iteration.
*/
public Iterator<Map.Entry<K, V>> descendingIterator() {
DescendingIterator<K, V> iterator = new DescendingIterator<>(mEnd, mStart);
mIterators.put(iterator, false);
return iterator;
}
/**
* return an iterator with additions.
*/
public IteratorWithAdditions iteratorWithAdditions() {
@SuppressWarnings("unchecked")
IteratorWithAdditions iterator = new IteratorWithAdditions();
mIterators.put(iterator, false);
return iterator;
}
/**
* @return eldest added entry or null
*/
public Map.Entry<K, V> eldest() {
return mStart;
}
/**
* @return newest added entry or null
*/
public Map.Entry<K, V> newest() {
return mEnd;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof SafeIterableMap)) {
return false;
}
SafeIterableMap map = (SafeIterableMap) obj;
if (this.size() != map.size()) {
return false;
}
Iterator<Map.Entry<K, V>> iterator1 = iterator();
Iterator iterator2 = map.iterator();
while (iterator1.hasNext() && iterator2.hasNext()) {
Map.Entry<K, V> next1 = iterator1.next();
Object next2 = iterator2.next();
if ((next1 == null && next2 != null)
|| (next1 != null && !next1.equals(next2))) {
return false;
}
}
return !iterator1.hasNext() && !iterator2.hasNext();
}
@Override
public int hashCode() {
int h = 0;
Iterator<Map.Entry<K, V>> i = iterator();
while (i.hasNext()) {
h += i.next().hashCode();
}
return h;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[");
Iterator<Map.Entry<K, V>> iterator = iterator();
while (iterator.hasNext()) {
builder.append(iterator.next().toString());
if (iterator.hasNext()) {
builder.append(", ");
}
}
builder.append("]");
return builder.toString();
}
private abstract static class ListIterator<K, V> implements Iterator<Map.Entry<K, V>>,
SupportRemove<K, V> {
Entry<K, V> mExpectedEnd;
Entry<K, V> mNext;
ListIterator(Entry<K, V> start, Entry<K, V> expectedEnd) {
this.mExpectedEnd = expectedEnd;
this.mNext = start;
}
@Override
public boolean hasNext() {
return mNext != null;
}
@Override
public void supportRemove(@NonNull Entry<K, V> entry) {
if (mExpectedEnd == entry && entry == mNext) {
mNext = null;
mExpectedEnd = null;
}
if (mExpectedEnd == entry) {
mExpectedEnd = backward(mExpectedEnd);
}
if (mNext == entry) {
mNext = nextNode();
}
}
private Entry<K, V> nextNode() {
if (mNext == mExpectedEnd || mExpectedEnd == null) {
return null;
}
return forward(mNext);
}
@Override
public Map.Entry<K, V> next() {
Map.Entry<K, V> result = mNext;
mNext = nextNode();
return result;
}
abstract Entry<K, V> forward(Entry<K, V> entry);
abstract Entry<K, V> backward(Entry<K, V> entry);
}
static class AscendingIterator<K, V> extends ListIterator<K, V> {
AscendingIterator(Entry<K, V> start, Entry<K, V> expectedEnd) {
super(start, expectedEnd);
}
@Override
Entry<K, V> forward(Entry<K, V> entry) {
return entry.mNext;
}
@Override
Entry<K, V> backward(Entry<K, V> entry) {
return entry.mPrevious;
}
}
private static class DescendingIterator<K, V> extends ListIterator<K, V> {
DescendingIterator(Entry<K, V> start, Entry<K, V> expectedEnd) {
super(start, expectedEnd);
}
@Override
Entry<K, V> forward(Entry<K, V> entry) {
return entry.mPrevious;
}
@Override
Entry<K, V> backward(Entry<K, V> entry) {
return entry.mNext;
}
}
private class IteratorWithAdditions implements Iterator<Map.Entry<K, V>>, SupportRemove<K, V> {
private Entry<K, V> mCurrent;
private boolean mBeforeStart = true;
@Override
public void supportRemove(@NonNull Entry<K, V> entry) {
if (entry == mCurrent) {
mCurrent = mCurrent.mPrevious;
mBeforeStart = mCurrent == null;
}
}
@Override
public boolean hasNext() {
if (mBeforeStart) {
return mStart != null;
}
return mCurrent != null && mCurrent.mNext != null;
}
@Override
public Map.Entry<K, V> next() {
if (mBeforeStart) {
mBeforeStart = false;
mCurrent = mStart;
} else {
mCurrent = mCurrent != null ? mCurrent.mNext : null;
}
return mCurrent;
}
}
interface SupportRemove<K, V> {
void supportRemove(@NonNull Entry<K, V> entry);
}
static class Entry<K, V> implements Map.Entry<K, V> {
@NonNull
final K mKey;
@NonNull
final V mValue;
Entry<K, V> mNext;
Entry<K, V> mPrevious;
Entry(@NonNull K key, @NonNull V value) {
mKey = key;
this.mValue = value;
}
@NonNull
@Override
public K getKey() {
return mKey;
}
@NonNull
@Override
public V getValue() {
return mValue;
}
@Override
public V setValue(V value) {
throw new UnsupportedOperationException("An entry modification is not supported");
}
@Override
public String toString() {
return mKey + "=" + mValue;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Entry)) {
return false;
}
Entry entry = (Entry) obj;
return mKey.equals(entry.mKey) && mValue.equals(entry.mValue);
}
@Override
public int hashCode() {
return mKey.hashCode() ^ mValue.hashCode();
}
}
}
| apache-2.0 |
googleapis/java-contact-center-insights | proto-google-cloud-contact-center-insights-v1/src/main/java/com/google/cloud/contactcenterinsights/v1/GcsSource.java | 26429 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/contactcenterinsights/v1/resources.proto
package com.google.cloud.contactcenterinsights.v1;
/**
*
*
* <pre>
* A Cloud Storage source of conversation data.
* </pre>
*
* Protobuf type {@code google.cloud.contactcenterinsights.v1.GcsSource}
*/
public final class GcsSource extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.contactcenterinsights.v1.GcsSource)
GcsSourceOrBuilder {
private static final long serialVersionUID = 0L;
// Use GcsSource.newBuilder() to construct.
private GcsSource(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GcsSource() {
audioUri_ = "";
transcriptUri_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new GcsSource();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private GcsSource(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
audioUri_ = s;
break;
}
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
transcriptUri_ = s;
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.contactcenterinsights.v1.ResourcesProto
.internal_static_google_cloud_contactcenterinsights_v1_GcsSource_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.contactcenterinsights.v1.ResourcesProto
.internal_static_google_cloud_contactcenterinsights_v1_GcsSource_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.contactcenterinsights.v1.GcsSource.class,
com.google.cloud.contactcenterinsights.v1.GcsSource.Builder.class);
}
public static final int AUDIO_URI_FIELD_NUMBER = 1;
private volatile java.lang.Object audioUri_;
/**
*
*
* <pre>
* Cloud Storage URI that points to a file that contains the conversation
* audio.
* </pre>
*
* <code>string audio_uri = 1;</code>
*
* @return The audioUri.
*/
@java.lang.Override
public java.lang.String getAudioUri() {
java.lang.Object ref = audioUri_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
audioUri_ = s;
return s;
}
}
/**
*
*
* <pre>
* Cloud Storage URI that points to a file that contains the conversation
* audio.
* </pre>
*
* <code>string audio_uri = 1;</code>
*
* @return The bytes for audioUri.
*/
@java.lang.Override
public com.google.protobuf.ByteString getAudioUriBytes() {
java.lang.Object ref = audioUri_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
audioUri_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TRANSCRIPT_URI_FIELD_NUMBER = 2;
private volatile java.lang.Object transcriptUri_;
/**
*
*
* <pre>
* Immutable. Cloud Storage URI that points to a file that contains the conversation
* transcript.
* </pre>
*
* <code>string transcript_uri = 2 [(.google.api.field_behavior) = IMMUTABLE];</code>
*
* @return The transcriptUri.
*/
@java.lang.Override
public java.lang.String getTranscriptUri() {
java.lang.Object ref = transcriptUri_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
transcriptUri_ = s;
return s;
}
}
/**
*
*
* <pre>
* Immutable. Cloud Storage URI that points to a file that contains the conversation
* transcript.
* </pre>
*
* <code>string transcript_uri = 2 [(.google.api.field_behavior) = IMMUTABLE];</code>
*
* @return The bytes for transcriptUri.
*/
@java.lang.Override
public com.google.protobuf.ByteString getTranscriptUriBytes() {
java.lang.Object ref = transcriptUri_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
transcriptUri_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(audioUri_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, audioUri_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(transcriptUri_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, transcriptUri_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(audioUri_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, audioUri_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(transcriptUri_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, transcriptUri_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.contactcenterinsights.v1.GcsSource)) {
return super.equals(obj);
}
com.google.cloud.contactcenterinsights.v1.GcsSource other =
(com.google.cloud.contactcenterinsights.v1.GcsSource) obj;
if (!getAudioUri().equals(other.getAudioUri())) return false;
if (!getTranscriptUri().equals(other.getTranscriptUri())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + AUDIO_URI_FIELD_NUMBER;
hash = (53 * hash) + getAudioUri().hashCode();
hash = (37 * hash) + TRANSCRIPT_URI_FIELD_NUMBER;
hash = (53 * hash) + getTranscriptUri().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.contactcenterinsights.v1.GcsSource parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contactcenterinsights.v1.GcsSource parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.contactcenterinsights.v1.GcsSource parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contactcenterinsights.v1.GcsSource parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.contactcenterinsights.v1.GcsSource parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contactcenterinsights.v1.GcsSource parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.contactcenterinsights.v1.GcsSource parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.contactcenterinsights.v1.GcsSource parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.contactcenterinsights.v1.GcsSource parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.contactcenterinsights.v1.GcsSource parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.contactcenterinsights.v1.GcsSource parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.contactcenterinsights.v1.GcsSource parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.contactcenterinsights.v1.GcsSource prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* A Cloud Storage source of conversation data.
* </pre>
*
* Protobuf type {@code google.cloud.contactcenterinsights.v1.GcsSource}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.contactcenterinsights.v1.GcsSource)
com.google.cloud.contactcenterinsights.v1.GcsSourceOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.contactcenterinsights.v1.ResourcesProto
.internal_static_google_cloud_contactcenterinsights_v1_GcsSource_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.contactcenterinsights.v1.ResourcesProto
.internal_static_google_cloud_contactcenterinsights_v1_GcsSource_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.contactcenterinsights.v1.GcsSource.class,
com.google.cloud.contactcenterinsights.v1.GcsSource.Builder.class);
}
// Construct using com.google.cloud.contactcenterinsights.v1.GcsSource.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
audioUri_ = "";
transcriptUri_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.contactcenterinsights.v1.ResourcesProto
.internal_static_google_cloud_contactcenterinsights_v1_GcsSource_descriptor;
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.GcsSource getDefaultInstanceForType() {
return com.google.cloud.contactcenterinsights.v1.GcsSource.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.GcsSource build() {
com.google.cloud.contactcenterinsights.v1.GcsSource result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.GcsSource buildPartial() {
com.google.cloud.contactcenterinsights.v1.GcsSource result =
new com.google.cloud.contactcenterinsights.v1.GcsSource(this);
result.audioUri_ = audioUri_;
result.transcriptUri_ = transcriptUri_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.contactcenterinsights.v1.GcsSource) {
return mergeFrom((com.google.cloud.contactcenterinsights.v1.GcsSource) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.contactcenterinsights.v1.GcsSource other) {
if (other == com.google.cloud.contactcenterinsights.v1.GcsSource.getDefaultInstance())
return this;
if (!other.getAudioUri().isEmpty()) {
audioUri_ = other.audioUri_;
onChanged();
}
if (!other.getTranscriptUri().isEmpty()) {
transcriptUri_ = other.transcriptUri_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.contactcenterinsights.v1.GcsSource parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.contactcenterinsights.v1.GcsSource) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object audioUri_ = "";
/**
*
*
* <pre>
* Cloud Storage URI that points to a file that contains the conversation
* audio.
* </pre>
*
* <code>string audio_uri = 1;</code>
*
* @return The audioUri.
*/
public java.lang.String getAudioUri() {
java.lang.Object ref = audioUri_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
audioUri_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Cloud Storage URI that points to a file that contains the conversation
* audio.
* </pre>
*
* <code>string audio_uri = 1;</code>
*
* @return The bytes for audioUri.
*/
public com.google.protobuf.ByteString getAudioUriBytes() {
java.lang.Object ref = audioUri_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
audioUri_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Cloud Storage URI that points to a file that contains the conversation
* audio.
* </pre>
*
* <code>string audio_uri = 1;</code>
*
* @param value The audioUri to set.
* @return This builder for chaining.
*/
public Builder setAudioUri(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
audioUri_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Cloud Storage URI that points to a file that contains the conversation
* audio.
* </pre>
*
* <code>string audio_uri = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearAudioUri() {
audioUri_ = getDefaultInstance().getAudioUri();
onChanged();
return this;
}
/**
*
*
* <pre>
* Cloud Storage URI that points to a file that contains the conversation
* audio.
* </pre>
*
* <code>string audio_uri = 1;</code>
*
* @param value The bytes for audioUri to set.
* @return This builder for chaining.
*/
public Builder setAudioUriBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
audioUri_ = value;
onChanged();
return this;
}
private java.lang.Object transcriptUri_ = "";
/**
*
*
* <pre>
* Immutable. Cloud Storage URI that points to a file that contains the conversation
* transcript.
* </pre>
*
* <code>string transcript_uri = 2 [(.google.api.field_behavior) = IMMUTABLE];</code>
*
* @return The transcriptUri.
*/
public java.lang.String getTranscriptUri() {
java.lang.Object ref = transcriptUri_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
transcriptUri_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Immutable. Cloud Storage URI that points to a file that contains the conversation
* transcript.
* </pre>
*
* <code>string transcript_uri = 2 [(.google.api.field_behavior) = IMMUTABLE];</code>
*
* @return The bytes for transcriptUri.
*/
public com.google.protobuf.ByteString getTranscriptUriBytes() {
java.lang.Object ref = transcriptUri_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
transcriptUri_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Immutable. Cloud Storage URI that points to a file that contains the conversation
* transcript.
* </pre>
*
* <code>string transcript_uri = 2 [(.google.api.field_behavior) = IMMUTABLE];</code>
*
* @param value The transcriptUri to set.
* @return This builder for chaining.
*/
public Builder setTranscriptUri(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
transcriptUri_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Immutable. Cloud Storage URI that points to a file that contains the conversation
* transcript.
* </pre>
*
* <code>string transcript_uri = 2 [(.google.api.field_behavior) = IMMUTABLE];</code>
*
* @return This builder for chaining.
*/
public Builder clearTranscriptUri() {
transcriptUri_ = getDefaultInstance().getTranscriptUri();
onChanged();
return this;
}
/**
*
*
* <pre>
* Immutable. Cloud Storage URI that points to a file that contains the conversation
* transcript.
* </pre>
*
* <code>string transcript_uri = 2 [(.google.api.field_behavior) = IMMUTABLE];</code>
*
* @param value The bytes for transcriptUri to set.
* @return This builder for chaining.
*/
public Builder setTranscriptUriBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
transcriptUri_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.contactcenterinsights.v1.GcsSource)
}
// @@protoc_insertion_point(class_scope:google.cloud.contactcenterinsights.v1.GcsSource)
private static final com.google.cloud.contactcenterinsights.v1.GcsSource DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.contactcenterinsights.v1.GcsSource();
}
public static com.google.cloud.contactcenterinsights.v1.GcsSource getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GcsSource> PARSER =
new com.google.protobuf.AbstractParser<GcsSource>() {
@java.lang.Override
public GcsSource parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new GcsSource(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<GcsSource> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GcsSource> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.GcsSource getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| apache-2.0 |
spring-projects/spring-data-examples | jpa/deferred/src/main/java/example/model/Customer609.java | 624 | package example.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer609 {
@Id @GeneratedValue(strategy = GenerationType.AUTO) private long id;
private String firstName;
private String lastName;
protected Customer609() {}
public Customer609(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format("Customer609[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);
}
}
| apache-2.0 |
bigdogmat/E2-Global-Print | addon/lua/entities/gmod_wire_expression2/core/custom/globalprint.lua | 6497 | --[[---------------------------------------------------------------------------
Global color printing!
-----------------------------------------------------------------------------]]
E2Lib.RegisterExtension("globalprint", false, "Allows players to print colored messages to the entire server", "This can be used to impersonate players, and or spam players.")
--[[---------------------------------------------------------------------------
Permissions
0 = everyone,
1 = admins,
2 = superadmins,
Default: 2
-----------------------------------------------------------------------------]]
local permissions = CreateConVar("globalprint_permissions", '2', bit.bor(FCVAR_ARCHIVE, FCVAR_SERVER_CAN_EXECUTE), "Set who can send global messages")
--[[---------------------------------------------------------------------------
Checks players permission
-----------------------------------------------------------------------------]]
local function check_permission(context)
local ply = context.player
-- Player left and E2 is still running?
if not IsValid(ply) then return false end
local mode = permissions:GetInt()
if mode == 0 then
return true
elseif mode == 1 and ply:IsAdmin() then
return true
elseif mode == 2 and ply:IsSuperAdmin() then
return true
end
return false
end
--[[---------------------------------------------------------------------------
Convert E2 types to strings or colors
-----------------------------------------------------------------------------]]
local types_tostring = {
e = function(ent)
if not IsValid(ent) then return '' end
return ent:IsPlayer() and ent:Nick() or tostring(ent)
end,
-- Treat vectors as colors unless they're outside the range to be colors
v = function(vec)
for k, v in ipairs(vec) do
if v < 0 or v > 255 then
return string.format("Vec (%d, %d, %d)", vec[1], vec[2], vec[3])
end
end
return Color(vec[1], vec[2], vec[3])
end,
-- Other vector types
xv2 = function(vec) return string.format("Vec (%d, %d)", vec[1], vec[2]) end,
xv4 = function(vec) return string.format("Vec (%d, %d, %d, %d)", vec[1], vec[2], vec[3], vec[4]) end,
n = tostring,
s = function(str) return str end,
}
--[[---------------------------------------------------------------------------
Build a printable table from varargs
-----------------------------------------------------------------------------]]
local function build_table_from_VarArgs(typeids, ...)
local ret = {}
for k, v in ipairs(typeids) do
if types_tostring[v] then
ret[#ret + 1] = types_tostring[v](select(k, ...))
end
end
return ret
end
--[[---------------------------------------------------------------------------
When using arrays we have less info about the data types, we have to make
some guesses
-----------------------------------------------------------------------------]]
local realtypes_tostring = {
number = types_tostring.n,
string = types_tostring.s,
entity = types_tostring.e,
Player = types_tostring.e,
table = function(tab)
for k, v in pairs(tab) do
if not isnumber(k) then return '' end
if not isnumber(v) then return '' end
if k < 1 or k > 4 then return '' end
end
if #tab == 2 then
return types_tostring.xv2(tab)
elseif #tab == 3 then
return types_tostring.v(tab)
elseif #tab == 4 then
return types_tostring.xv4(tab)
end
return ''
end,
}
--[[---------------------------------------------------------------------------
Build a printable table from an array
-----------------------------------------------------------------------------]]
local function build_table_from_Array(arr)
local ret = {}
for k, v in ipairs(arr) do
local type = type(v)
if realtypes_tostring[type] then
ret[#ret + 1] = realtypes_tostring[type](v)
end
end
return ret
end
--[[---------------------------------------------------------------------------
Network the message
-----------------------------------------------------------------------------]]
util.AddNetworkString "wire_expression2_custom_globalprint"
local function write_color_print(context, player, data)
net.Start "wire_expression2_custom_globalprint"
net.WriteUInt(#data, 8)
for k, v in ipairs(data) do
local type = isstring(v)
local func = type and net.WriteString or net.WriteColor
net.WriteBool(type)
func(v)
end
net.WriteEntity(context.player)
if player then
net.Send(player)
else
net.Broadcast()
end
end
--[[---------------------------------------------------------------------------
Send a message using an array
-----------------------------------------------------------------------------]]
local function send_color_print_Array(context, ply, arr)
local data = build_table_from_Array(arr)
write_color_print(context, ply, data)
end
--[[---------------------------------------------------------------------------
Send a message using varargs
-----------------------------------------------------------------------------]]
local function send_color_print_VarArgs(context, ply, typeids, ...)
local data = build_table_from_VarArgs(typeids, ...)
write_color_print(context, ply, data)
end
--[[---------------------------------------------------------------------------
Broadcast messages
-----------------------------------------------------------------------------]]
__e2setcost(50)
e2function void broadcastMessage(...)
if not check_permission(self) then return end
if #typeids > 255 then return end
send_color_print_VarArgs(self, nil, typeids, ...)
end
e2function void broadcastMessage(array args)
if not check_permission(self) then return end
if #args > 255 then return end
send_color_print_Array(self, nil, args)
end
--[[---------------------------------------------------------------------------
Player methods
-----------------------------------------------------------------------------]]
__e2setcost(20)
e2function void entity:printMessage(...)
if not IsValid(this) then return end
if not this:IsPlayer() then return end
if not check_permission(self) then return end
if #typeids > 255 then return end
send_color_print_VarArgs(self, this, typeids, ...)
end
e2function void entity:printMessage(array args)
if not IsValid(this) then return end
if not this:IsPlayer() then return end
if not check_permission(self) then return end
if #args > 255 then return end
send_color_print_Array(self, this, args)
end
| apache-2.0 |
leapframework/framework | base/lang/src/main/java/leap/lang/jsoup/parser/TokeniserState.java | 59352 | package leap.lang.jsoup.parser;
/**
* States and transition activations for the Tokeniser.
*/
enum TokeniserState {
Data {
// in data state, gather characters until a character reference or tag is found
void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeToAny('&', '<', nullChar);
t.emit(data);
break;
}
}
},
CharacterReferenceInData {
// from & in data
void read(Tokeniser t, CharacterReader r) {
char[] c = t.consumeCharacterReference(null, false);
if (c == null)
t.emit('&');
else
t.emit(c);
t.transition(Data);
}
},
Rcdata {
/// handles data in title, textarea etc
void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInRcdata);
break;
case '<':
t.advanceTransition(RcdataLessthanSign);
break;
case nullChar:
t.error(this);
r.advance();
t.emit(replacementChar);
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeToAny('&', '<', nullChar);
t.emit(data);
break;
}
}
},
CharacterReferenceInRcdata {
void read(Tokeniser t, CharacterReader r) {
char[] c = t.consumeCharacterReference(null, false);
if (c == null)
t.emit('&');
else
t.emit(c);
t.transition(Rcdata);
}
},
Rawtext {
void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '<':
t.advanceTransition(RawtextLessthanSign);
break;
case nullChar:
t.error(this);
r.advance();
t.emit(replacementChar);
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeToAny('<', nullChar);
t.emit(data);
break;
}
}
},
ScriptData {
void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '<':
t.advanceTransition(ScriptDataLessthanSign);
break;
case nullChar:
t.error(this);
r.advance();
t.emit(replacementChar);
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeToAny('<', nullChar);
t.emit(data);
break;
}
}
},
PLAINTEXT {
void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case nullChar:
t.error(this);
r.advance();
t.emit(replacementChar);
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeTo(nullChar);
t.emit(data);
break;
}
}
},
TagOpen {
// from < in data
void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '!':
t.advanceTransition(MarkupDeclarationOpen);
break;
case '/':
t.advanceTransition(EndTagOpen);
break;
case '?':
t.advanceTransition(BogusComment);
break;
default:
if (r.matchesLetter()) {
t.createTagPending(true);
t.transition(TagName);
} else {
t.error(this);
t.emit('<'); // char that got us here
t.transition(Data);
}
break;
}
}
},
EndTagOpen {
void read(Tokeniser t, CharacterReader r) {
if (r.isEmpty()) {
t.eofError(this);
t.emit("</");
t.transition(Data);
} else if (r.matchesLetter()) {
t.createTagPending(false);
t.transition(TagName);
} else if (r.matches('>')) {
t.error(this);
t.advanceTransition(Data);
} else {
t.error(this);
t.advanceTransition(BogusComment);
}
}
},
TagName {
// from < or </ in data, will have start or end tag pending
void read(Tokeniser t, CharacterReader r) {
// previous TagOpen state did NOT consume, will have a letter char in current
String tagName = r.consumeToAny('\t', '\n', '\r', '\f', ' ', '/', '>', nullChar).toLowerCase();
t.tagPending.appendTagName(tagName);
switch (r.consume()) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
case nullChar: // replacement
t.tagPending.appendTagName(replacementStr);
break;
case eof: // should emit pending tag?
t.eofError(this);
t.transition(Data);
// no default, as covered with above consumeToAny
}
}
},
RcdataLessthanSign {
// from < in rcdata
void read(Tokeniser t, CharacterReader r) {
if (r.matches('/')) {
t.createTempBuffer();
t.advanceTransition(RCDATAEndTagOpen);
} else if (r.matchesLetter() && !r.containsIgnoreCase("</" + t.appropriateEndTagName())) {
// diverge from spec: got a start tag, but there's no appropriate end tag (</title>), so rather than
// consuming to EOF; break out here
t.tagPending = new Token.EndTag(t.appropriateEndTagName());
t.emitTagPending();
r.unconsume(); // undo "<"
t.transition(Data);
} else {
t.emit("<");
t.transition(Rcdata);
}
}
},
RCDATAEndTagOpen {
void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
t.createTagPending(false);
t.tagPending.appendTagName(Character.toLowerCase(r.current()));
t.dataBuffer.append(Character.toLowerCase(r.current()));
t.advanceTransition(RCDATAEndTagName);
} else {
t.emit("</");
t.transition(Rcdata);
}
}
},
RCDATAEndTagName {
void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
t.tagPending.appendTagName(name.toLowerCase());
t.dataBuffer.append(name);
return;
}
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
if (t.isAppropriateEndTagToken())
t.transition(BeforeAttributeName);
else
anythingElse(t, r);
break;
case '/':
if (t.isAppropriateEndTagToken())
t.transition(SelfClosingStartTag);
else
anythingElse(t, r);
break;
case '>':
if (t.isAppropriateEndTagToken()) {
t.emitTagPending();
t.transition(Data);
}
else
anythingElse(t, r);
break;
default:
anythingElse(t, r);
}
}
private void anythingElse(Tokeniser t, CharacterReader r) {
t.emit("</" + t.dataBuffer.toString());
r.unconsume();
t.transition(Rcdata);
}
},
RawtextLessthanSign {
void read(Tokeniser t, CharacterReader r) {
if (r.matches('/')) {
t.createTempBuffer();
t.advanceTransition(RawtextEndTagOpen);
} else {
t.emit('<');
t.transition(Rawtext);
}
}
},
RawtextEndTagOpen {
void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
t.createTagPending(false);
t.transition(RawtextEndTagName);
} else {
t.emit("</");
t.transition(Rawtext);
}
}
},
RawtextEndTagName {
void read(Tokeniser t, CharacterReader r) {
handleDataEndTag(t, r, Rawtext);
}
},
ScriptDataLessthanSign {
void read(Tokeniser t, CharacterReader r) {
switch (r.consume()) {
case '/':
t.createTempBuffer();
t.transition(ScriptDataEndTagOpen);
break;
case '!':
t.emit("<!");
t.transition(ScriptDataEscapeStart);
break;
default:
t.emit("<");
r.unconsume();
t.transition(ScriptData);
}
}
},
ScriptDataEndTagOpen {
void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
t.createTagPending(false);
t.transition(ScriptDataEndTagName);
} else {
t.emit("</");
t.transition(ScriptData);
}
}
},
ScriptDataEndTagName {
void read(Tokeniser t, CharacterReader r) {
handleDataEndTag(t, r, ScriptData);
}
},
ScriptDataEscapeStart {
void read(Tokeniser t, CharacterReader r) {
if (r.matches('-')) {
t.emit('-');
t.advanceTransition(ScriptDataEscapeStartDash);
} else {
t.transition(ScriptData);
}
}
},
ScriptDataEscapeStartDash {
void read(Tokeniser t, CharacterReader r) {
if (r.matches('-')) {
t.emit('-');
t.advanceTransition(ScriptDataEscapedDashDash);
} else {
t.transition(ScriptData);
}
}
},
ScriptDataEscaped {
void read(Tokeniser t, CharacterReader r) {
if (r.isEmpty()) {
t.eofError(this);
t.transition(Data);
return;
}
switch (r.current()) {
case '-':
t.emit('-');
t.advanceTransition(ScriptDataEscapedDash);
break;
case '<':
t.advanceTransition(ScriptDataEscapedLessthanSign);
break;
case nullChar:
t.error(this);
r.advance();
t.emit(replacementChar);
break;
default:
String data = r.consumeToAny('-', '<', nullChar);
t.emit(data);
}
}
},
ScriptDataEscapedDash {
void read(Tokeniser t, CharacterReader r) {
if (r.isEmpty()) {
t.eofError(this);
t.transition(Data);
return;
}
char c = r.consume();
switch (c) {
case '-':
t.emit(c);
t.transition(ScriptDataEscapedDashDash);
break;
case '<':
t.transition(ScriptDataEscapedLessthanSign);
break;
case nullChar:
t.error(this);
t.emit(replacementChar);
t.transition(ScriptDataEscaped);
break;
default:
t.emit(c);
t.transition(ScriptDataEscaped);
}
}
},
ScriptDataEscapedDashDash {
void read(Tokeniser t, CharacterReader r) {
if (r.isEmpty()) {
t.eofError(this);
t.transition(Data);
return;
}
char c = r.consume();
switch (c) {
case '-':
t.emit(c);
break;
case '<':
t.transition(ScriptDataEscapedLessthanSign);
break;
case '>':
t.emit(c);
t.transition(ScriptData);
break;
case nullChar:
t.error(this);
t.emit(replacementChar);
t.transition(ScriptDataEscaped);
break;
default:
t.emit(c);
t.transition(ScriptDataEscaped);
}
}
},
ScriptDataEscapedLessthanSign {
void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
t.createTempBuffer();
t.dataBuffer.append(Character.toLowerCase(r.current()));
t.emit("<" + r.current());
t.advanceTransition(ScriptDataDoubleEscapeStart);
} else if (r.matches('/')) {
t.createTempBuffer();
t.advanceTransition(ScriptDataEscapedEndTagOpen);
} else {
t.emit('<');
t.transition(ScriptDataEscaped);
}
}
},
ScriptDataEscapedEndTagOpen {
void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
t.createTagPending(false);
t.tagPending.appendTagName(Character.toLowerCase(r.current()));
t.dataBuffer.append(r.current());
t.advanceTransition(ScriptDataEscapedEndTagName);
} else {
t.emit("</");
t.transition(ScriptDataEscaped);
}
}
},
ScriptDataEscapedEndTagName {
void read(Tokeniser t, CharacterReader r) {
handleDataEndTag(t, r, ScriptDataEscaped);
}
},
ScriptDataDoubleEscapeStart {
void read(Tokeniser t, CharacterReader r) {
handleDataDoubleEscapeTag(t, r, ScriptDataDoubleEscaped, ScriptDataEscaped);
}
},
ScriptDataDoubleEscaped {
void read(Tokeniser t, CharacterReader r) {
char c = r.current();
switch (c) {
case '-':
t.emit(c);
t.advanceTransition(ScriptDataDoubleEscapedDash);
break;
case '<':
t.emit(c);
t.advanceTransition(ScriptDataDoubleEscapedLessthanSign);
break;
case nullChar:
t.error(this);
r.advance();
t.emit(replacementChar);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
String data = r.consumeToAny('-', '<', nullChar);
t.emit(data);
}
}
},
ScriptDataDoubleEscapedDash {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.emit(c);
t.transition(ScriptDataDoubleEscapedDashDash);
break;
case '<':
t.emit(c);
t.transition(ScriptDataDoubleEscapedLessthanSign);
break;
case nullChar:
t.error(this);
t.emit(replacementChar);
t.transition(ScriptDataDoubleEscaped);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
t.emit(c);
t.transition(ScriptDataDoubleEscaped);
}
}
},
ScriptDataDoubleEscapedDashDash {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.emit(c);
break;
case '<':
t.emit(c);
t.transition(ScriptDataDoubleEscapedLessthanSign);
break;
case '>':
t.emit(c);
t.transition(ScriptData);
break;
case nullChar:
t.error(this);
t.emit(replacementChar);
t.transition(ScriptDataDoubleEscaped);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
t.emit(c);
t.transition(ScriptDataDoubleEscaped);
}
}
},
ScriptDataDoubleEscapedLessthanSign {
void read(Tokeniser t, CharacterReader r) {
if (r.matches('/')) {
t.emit('/');
t.createTempBuffer();
t.advanceTransition(ScriptDataDoubleEscapeEnd);
} else {
t.transition(ScriptDataDoubleEscaped);
}
}
},
ScriptDataDoubleEscapeEnd {
void read(Tokeniser t, CharacterReader r) {
handleDataDoubleEscapeTag(t,r, ScriptDataEscaped, ScriptDataDoubleEscaped);
}
},
BeforeAttributeName {
// from tagname <xxx
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break; // ignore whitespace
case '/':
t.transition(SelfClosingStartTag);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
case nullChar:
t.error(this);
t.tagPending.newAttribute();
r.unconsume();
t.transition(AttributeName);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
case '"':
case '\'':
case '<':
case '=':
t.error(this);
t.tagPending.newAttribute();
t.tagPending.appendAttributeName(c);
t.transition(AttributeName);
break;
default: // A-Z, anything else
t.tagPending.newAttribute();
r.unconsume();
t.transition(AttributeName);
}
}
},
AttributeName {
// from before attribute name
void read(Tokeniser t, CharacterReader r) {
String name = r.consumeToAny('\t', '\n', '\r', '\f', ' ', '/', '=', '>', nullChar, '"', '\'', '<');
// don't use lower case for el expression
//t.tagPending.appendAttributeName(name.toLowerCase());
t.tagPending.appendAttributeName(name);
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(AfterAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '=':
t.transition(BeforeAttributeValue);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeName(replacementChar);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
case '"':
case '\'':
case '<':
t.error(this);
t.tagPending.appendAttributeName(c);
// no default, as covered in consumeToAny
}
}
},
AfterAttributeName {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
// ignore
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '=':
t.transition(BeforeAttributeValue);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeName(replacementChar);
t.transition(AttributeName);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
case '"':
case '\'':
case '<':
t.error(this);
t.tagPending.newAttribute();
t.tagPending.appendAttributeName(c);
t.transition(AttributeName);
break;
default: // A-Z, anything else
t.tagPending.newAttribute();
r.unconsume();
t.transition(AttributeName);
}
}
},
BeforeAttributeValue {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
// ignore
break;
case '"':
t.transition(AttributeValue_doubleQuoted);
break;
case '&':
r.unconsume();
t.transition(AttributeValue_unquoted);
break;
case '\'':
t.transition(AttributeValue_singleQuoted);
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeValue(replacementChar);
t.transition(AttributeValue_unquoted);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
case '>':
t.error(this);
t.emitTagPending();
t.transition(Data);
break;
case '<':
case '=':
case '`':
t.error(this);
t.tagPending.appendAttributeValue(c);
t.transition(AttributeValue_unquoted);
break;
default:
r.unconsume();
t.transition(AttributeValue_unquoted);
}
}
},
AttributeValue_doubleQuoted {
void read(Tokeniser t, CharacterReader r) {
String value = r.consumeToAny('"', '&', nullChar);
if (value.length() > 0)
t.tagPending.appendAttributeValue(value);
char c = r.consume();
switch (c) {
case '"':
t.transition(AfterAttributeValue_quoted);
break;
case '&':
char[] ref = t.consumeCharacterReference('"', true);
if (ref != null)
t.tagPending.appendAttributeValue(ref);
else
t.tagPending.appendAttributeValue('&');
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeValue(replacementChar);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
// no default, handled in consume to any above
}
}
},
AttributeValue_singleQuoted {
void read(Tokeniser t, CharacterReader r) {
t.tagPending.setPendingAttributeQuotedCharacter('\'');
String value = r.consumeToAny('\'', '&', nullChar);
if (value.length() > 0)
t.tagPending.appendAttributeValue(value);
char c = r.consume();
switch (c) {
case '\'':
t.transition(AfterAttributeValue_quoted);
break;
case '&':
char[] ref = t.consumeCharacterReference('\'', true);
if (ref != null)
t.tagPending.appendAttributeValue(ref);
else
t.tagPending.appendAttributeValue('&');
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeValue(replacementChar);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
// no default, handled in consume to any above
}
}
},
AttributeValue_unquoted {
void read(Tokeniser t, CharacterReader r) {
t.tagPending.setPendingAttributeQuotedCharacter(null);
String value = r.consumeToAny('\t', '\n', '\r', '\f', ' ', '&', '>', nullChar, '"', '\'', '<', '=', '`');
if (value.length() > 0)
t.tagPending.appendAttributeValue(value);
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '&':
char[] ref = t.consumeCharacterReference('>', true);
if (ref != null)
t.tagPending.appendAttributeValue(ref);
else
t.tagPending.appendAttributeValue('&');
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeValue(replacementChar);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
case '"':
case '\'':
case '<':
case '=':
case '`':
t.error(this);
t.tagPending.appendAttributeValue(c);
break;
// no default, handled in consume to any above
}
}
},
// CharacterReferenceInAttributeValue state handled inline
AfterAttributeValue_quoted {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
t.error(this);
r.unconsume();
t.transition(BeforeAttributeName);
}
}
},
SelfClosingStartTag {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '>':
t.tagPending.selfClosing = true;
t.emitTagPending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
t.error(this);
t.transition(BeforeAttributeName);
}
}
},
BogusComment {
void read(Tokeniser t, CharacterReader r) {
// todo: handle bogus comment starting from eof. when does that trigger?
// rewind to capture character that lead us here
r.unconsume();
Token.Comment comment = new Token.Comment();
comment.bogus = true;
comment.data.append(r.consumeTo('>'));
// todo: replace nullChar with replaceChar
t.emit(comment);
t.advanceTransition(Data);
}
},
MarkupDeclarationOpen {
void read(Tokeniser t, CharacterReader r) {
if (r.matchConsume("--")) {
t.createCommentPending();
t.transition(CommentStart);
} else if (r.matchConsumeIgnoreCase("DOCTYPE")) {
t.setDoctypeDeclaration(r.consumedIgnroeCase("DOCTYPE"));
t.transition(Doctype);
} else if (r.matchConsume("[CDATA[")) {
// todo: should actually check current namepspace, and only non-html allows cdata. until namespace
// is implemented properly, keep handling as cdata
//} else if (!t.currentNodeInHtmlNS() && r.matchConsume("[CDATA[")) {
t.transition(CdataSection);
} else {
t.error(this);
t.advanceTransition(BogusComment); // advance so this character gets in bogus comment data's rewind
}
}
},
CommentStart {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.transition(CommentStartDash);
break;
case nullChar:
t.error(this);
t.commentPending.data.append(replacementChar);
t.transition(Comment);
break;
case '>':
t.error(this);
t.emitCommentPending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.commentPending.data.append(c);
t.transition(Comment);
}
}
},
CommentStartDash {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.transition(CommentStartDash);
break;
case nullChar:
t.error(this);
t.commentPending.data.append(replacementChar);
t.transition(Comment);
break;
case '>':
t.error(this);
t.emitCommentPending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.commentPending.data.append(c);
t.transition(Comment);
}
}
},
Comment {
void read(Tokeniser t, CharacterReader r) {
char c = r.current();
switch (c) {
case '-':
t.advanceTransition(CommentEndDash);
break;
case nullChar:
t.error(this);
r.advance();
t.commentPending.data.append(replacementChar);
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.commentPending.data.append(r.consumeToAny('-', nullChar));
}
}
},
CommentEndDash {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.transition(CommentEnd);
break;
case nullChar:
t.error(this);
t.commentPending.data.append('-').append(replacementChar);
t.transition(Comment);
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.commentPending.data.append('-').append(c);
t.transition(Comment);
}
}
},
CommentEnd {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '>':
t.emitCommentPending();
t.transition(Data);
break;
case nullChar:
t.error(this);
t.commentPending.data.append("--").append(replacementChar);
t.transition(Comment);
break;
case '!':
t.error(this);
t.transition(CommentEndBang);
break;
case '-':
t.error(this);
t.commentPending.data.append('-');
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.error(this);
t.commentPending.data.append("--").append(c);
t.transition(Comment);
}
}
},
CommentEndBang {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.commentPending.data.append("--!");
t.transition(CommentEndDash);
break;
case '>':
t.emitCommentPending();
t.transition(Data);
break;
case nullChar:
t.error(this);
t.commentPending.data.append("--!").append(replacementChar);
t.transition(Comment);
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.commentPending.data.append("--!").append(c);
t.transition(Comment);
}
}
},
Doctype {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeDoctypeName);
break;
case eof:
t.eofError(this);
t.createDoctypePending();
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.transition(BeforeDoctypeName);
}
}
},
BeforeDoctypeName {
void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
t.createDoctypePending();
t.transition(DoctypeName);
return;
}
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break; // ignore whitespace
case nullChar:
t.error(this);
t.doctypePending.name.append(replacementChar);
t.transition(DoctypeName);
break;
case eof:
t.eofError(this);
t.createDoctypePending();
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.createDoctypePending();
t.doctypePending.name.append(c);
t.transition(DoctypeName);
}
}
},
DoctypeName {
void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
//t.doctypePending.name.append(name.toLowerCase());
t.doctypePending.name.append(name);//Remove lowercase
return;
}
char c = r.consume();
switch (c) {
case '>':
t.emitDoctypePending();
t.transition(Data);
break;
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(AfterDoctypeName);
break;
case nullChar:
t.error(this);
t.doctypePending.name.append(replacementChar);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.doctypePending.name.append(c);
}
}
},
AfterDoctypeName {
void read(Tokeniser t, CharacterReader r) {
if (r.isEmpty()) {
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
return;
}
if (r.matchesAny('\t', '\n', '\r', '\f', ' '))
r.advance(); // ignore whitespace
else if (r.matches('>')) {
t.emitDoctypePending();
t.advanceTransition(Data);
} else if (r.matchConsumeIgnoreCase("PUBLIC")) {
t.transition(AfterDoctypePublicKeyword);
} else if (r.matchConsumeIgnoreCase("SYSTEM")) {
t.transition(AfterDoctypeSystemKeyword);
} else {
t.error(this);
t.doctypePending.forceQuirks = true;
t.advanceTransition(BogusDoctype);
}
}
},
AfterDoctypePublicKeyword {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeDoctypePublicIdentifier);
break;
case '"':
t.error(this);
// set public id to empty string
t.transition(DoctypePublicIdentifier_doubleQuoted);
break;
case '\'':
t.error(this);
// set public id to empty string
t.transition(DoctypePublicIdentifier_singleQuoted);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.transition(BogusDoctype);
}
}
},
BeforeDoctypePublicIdentifier {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break;
case '"':
// set public id to empty string
t.transition(DoctypePublicIdentifier_doubleQuoted);
break;
case '\'':
// set public id to empty string
t.transition(DoctypePublicIdentifier_singleQuoted);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.transition(BogusDoctype);
}
}
},
DoctypePublicIdentifier_doubleQuoted {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '"':
t.transition(AfterDoctypePublicIdentifier);
break;
case nullChar:
t.error(this);
t.doctypePending.publicIdentifier.append(replacementChar);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.doctypePending.publicIdentifier.append(c);
}
}
},
DoctypePublicIdentifier_singleQuoted {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\'':
t.transition(AfterDoctypePublicIdentifier);
break;
case nullChar:
t.error(this);
t.doctypePending.publicIdentifier.append(replacementChar);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.doctypePending.publicIdentifier.append(c);
}
}
},
AfterDoctypePublicIdentifier {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BetweenDoctypePublicAndSystemIdentifiers);
break;
case '>':
t.emitDoctypePending();
t.transition(Data);
break;
case '"':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_doubleQuoted);
break;
case '\'':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_singleQuoted);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.transition(BogusDoctype);
}
}
},
BetweenDoctypePublicAndSystemIdentifiers {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break;
case '>':
t.emitDoctypePending();
t.transition(Data);
break;
case '"':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_doubleQuoted);
break;
case '\'':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_singleQuoted);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.transition(BogusDoctype);
}
}
},
AfterDoctypeSystemKeyword {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeDoctypeSystemIdentifier);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case '"':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_doubleQuoted);
break;
case '\'':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_singleQuoted);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
}
}
},
BeforeDoctypeSystemIdentifier {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break;
case '"':
// set system id to empty string
t.transition(DoctypeSystemIdentifier_doubleQuoted);
break;
case '\'':
// set public id to empty string
t.transition(DoctypeSystemIdentifier_singleQuoted);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.transition(BogusDoctype);
}
}
},
DoctypeSystemIdentifier_doubleQuoted {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '"':
t.transition(AfterDoctypeSystemIdentifier);
break;
case nullChar:
t.error(this);
t.doctypePending.systemIdentifier.append(replacementChar);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.doctypePending.systemIdentifier.append(c);
}
}
},
DoctypeSystemIdentifier_singleQuoted {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\'':
t.transition(AfterDoctypeSystemIdentifier);
break;
case nullChar:
t.error(this);
t.doctypePending.systemIdentifier.append(replacementChar);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.doctypePending.systemIdentifier.append(c);
}
}
},
AfterDoctypeSystemIdentifier {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break;
case '>':
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.transition(BogusDoctype);
// NOT force quirks
}
}
},
BogusDoctype {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '>':
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.emitDoctypePending();
t.transition(Data);
break;
default:
// ignore char
break;
}
}
},
CdataSection {
void read(Tokeniser t, CharacterReader r) {
String data = r.consumeTo("]]>");
t.emit(data);
r.matchConsume("]]>");
t.transition(Data);
}
};
abstract void read(Tokeniser t, CharacterReader r);
private static final char nullChar = '\u0000';
private static final char replacementChar = Tokeniser.replacementChar;
private static final String replacementStr = String.valueOf(Tokeniser.replacementChar);
private static final char eof = CharacterReader.EOF;
/**
* Handles RawtextEndTagName, ScriptDataEndTagName, and ScriptDataEscapedEndTagName. Same body impl, just
* different else exit transitions.
*/
private static final void handleDataEndTag(Tokeniser t, CharacterReader r, TokeniserState elseTransition) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
t.tagPending.appendTagName(name.toLowerCase());
t.dataBuffer.append(name);
return;
}
boolean needsExitTransition = false;
if (t.isAppropriateEndTagToken() && !r.isEmpty()) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
default:
t.dataBuffer.append(c);
needsExitTransition = true;
}
} else {
needsExitTransition = true;
}
if (needsExitTransition) {
t.emit("</" + t.dataBuffer.toString());
t.transition(elseTransition);
}
}
private static final void handleDataDoubleEscapeTag(Tokeniser t, CharacterReader r, TokeniserState primary, TokeniserState fallback) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
t.dataBuffer.append(name.toLowerCase());
t.emit(name);
return;
}
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
case '/':
case '>':
if (t.dataBuffer.toString().equals("script"))
t.transition(primary);
else
t.transition(fallback);
t.emit(c);
break;
default:
r.unconsume();
t.transition(fallback);
}
}
} | apache-2.0 |
yeming1001/GankMeiZhi | app/src/androidTest/java/com/leaf/gankio/ApplicationTest.java | 346 | package com.leaf.gankio;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | apache-2.0 |
citygml4j/citygml4j | src-gen/main/java/net/opengis/citygml/generics/_2/GenericCityObjectType.java | 19578 | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.2 generiert
// Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2019.02.03 um 11:14:53 PM CET
//
package net.opengis.citygml.generics._2;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import net.opengis.citygml._2.AbstractCityObjectType;
import net.opengis.citygml._2.ImplicitRepresentationPropertyType;
import net.opengis.gml.CodeType;
import net.opengis.gml.GeometryPropertyType;
import net.opengis.gml.MultiCurvePropertyType;
/**
* Generic (user defined) city objects may be used to model features which are not covered explicitly by the
* CityGML schema. Generic objects must be used with care; they shall only be used if there is no appropiate thematic class
* available in the overall CityGML schema. Oherwise, problems concerning semantic interoperability may arise. As subclass of
* _CityObject, a generic city object inherits all attributes and relations, in particular an id, names, external references,
* and generalization relations.
*
* <p>Java-Klasse für GenericCityObjectType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="GenericCityObjectType">
* <complexContent>
* <extension base="{http://www.opengis.net/citygml/2.0}AbstractCityObjectType">
* <sequence>
* <element name="class" type="{http://www.opengis.net/gml}CodeType" minOccurs="0"/>
* <element name="function" type="{http://www.opengis.net/gml}CodeType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="usage" type="{http://www.opengis.net/gml}CodeType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="lod0Geometry" type="{http://www.opengis.net/gml}GeometryPropertyType" minOccurs="0"/>
* <element name="lod1Geometry" type="{http://www.opengis.net/gml}GeometryPropertyType" minOccurs="0"/>
* <element name="lod2Geometry" type="{http://www.opengis.net/gml}GeometryPropertyType" minOccurs="0"/>
* <element name="lod3Geometry" type="{http://www.opengis.net/gml}GeometryPropertyType" minOccurs="0"/>
* <element name="lod4Geometry" type="{http://www.opengis.net/gml}GeometryPropertyType" minOccurs="0"/>
* <element name="lod0TerrainIntersection" type="{http://www.opengis.net/gml}MultiCurvePropertyType" minOccurs="0"/>
* <element name="lod1TerrainIntersection" type="{http://www.opengis.net/gml}MultiCurvePropertyType" minOccurs="0"/>
* <element name="lod2TerrainIntersection" type="{http://www.opengis.net/gml}MultiCurvePropertyType" minOccurs="0"/>
* <element name="lod3TerrainIntersection" type="{http://www.opengis.net/gml}MultiCurvePropertyType" minOccurs="0"/>
* <element name="lod4TerrainIntersection" type="{http://www.opengis.net/gml}MultiCurvePropertyType" minOccurs="0"/>
* <element name="lod0ImplicitRepresentation" type="{http://www.opengis.net/citygml/2.0}ImplicitRepresentationPropertyType" minOccurs="0"/>
* <element name="lod1ImplicitRepresentation" type="{http://www.opengis.net/citygml/2.0}ImplicitRepresentationPropertyType" minOccurs="0"/>
* <element name="lod2ImplicitRepresentation" type="{http://www.opengis.net/citygml/2.0}ImplicitRepresentationPropertyType" minOccurs="0"/>
* <element name="lod3ImplicitRepresentation" type="{http://www.opengis.net/citygml/2.0}ImplicitRepresentationPropertyType" minOccurs="0"/>
* <element name="lod4ImplicitRepresentation" type="{http://www.opengis.net/citygml/2.0}ImplicitRepresentationPropertyType" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GenericCityObjectType", propOrder = {
"clazz",
"function",
"usage",
"lod0Geometry",
"lod1Geometry",
"lod2Geometry",
"lod3Geometry",
"lod4Geometry",
"lod0TerrainIntersection",
"lod1TerrainIntersection",
"lod2TerrainIntersection",
"lod3TerrainIntersection",
"lod4TerrainIntersection",
"lod0ImplicitRepresentation",
"lod1ImplicitRepresentation",
"lod2ImplicitRepresentation",
"lod3ImplicitRepresentation",
"lod4ImplicitRepresentation"
})
public class GenericCityObjectType
extends AbstractCityObjectType
{
@XmlElement(name = "class")
protected CodeType clazz;
protected List<CodeType> function;
protected List<CodeType> usage;
protected GeometryPropertyType lod0Geometry;
protected GeometryPropertyType lod1Geometry;
protected GeometryPropertyType lod2Geometry;
protected GeometryPropertyType lod3Geometry;
protected GeometryPropertyType lod4Geometry;
protected MultiCurvePropertyType lod0TerrainIntersection;
protected MultiCurvePropertyType lod1TerrainIntersection;
protected MultiCurvePropertyType lod2TerrainIntersection;
protected MultiCurvePropertyType lod3TerrainIntersection;
protected MultiCurvePropertyType lod4TerrainIntersection;
protected ImplicitRepresentationPropertyType lod0ImplicitRepresentation;
protected ImplicitRepresentationPropertyType lod1ImplicitRepresentation;
protected ImplicitRepresentationPropertyType lod2ImplicitRepresentation;
protected ImplicitRepresentationPropertyType lod3ImplicitRepresentation;
protected ImplicitRepresentationPropertyType lod4ImplicitRepresentation;
/**
* Ruft den Wert der clazz-Eigenschaft ab.
*
* @return
* possible object is
* {@link CodeType }
*
*/
public CodeType getClazz() {
return clazz;
}
/**
* Legt den Wert der clazz-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link CodeType }
*
*/
public void setClazz(CodeType value) {
this.clazz = value;
}
public boolean isSetClazz() {
return (this.clazz!= null);
}
/**
* Gets the value of the function property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the function property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getFunction().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CodeType }
*
*
*/
public List<CodeType> getFunction() {
if (function == null) {
function = new ArrayList<CodeType>();
}
return this.function;
}
public boolean isSetFunction() {
return ((this.function!= null)&&(!this.function.isEmpty()));
}
public void unsetFunction() {
this.function = null;
}
/**
* Gets the value of the usage property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the usage property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getUsage().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CodeType }
*
*
*/
public List<CodeType> getUsage() {
if (usage == null) {
usage = new ArrayList<CodeType>();
}
return this.usage;
}
public boolean isSetUsage() {
return ((this.usage!= null)&&(!this.usage.isEmpty()));
}
public void unsetUsage() {
this.usage = null;
}
/**
* Ruft den Wert der lod0Geometry-Eigenschaft ab.
*
* @return
* possible object is
* {@link GeometryPropertyType }
*
*/
public GeometryPropertyType getLod0Geometry() {
return lod0Geometry;
}
/**
* Legt den Wert der lod0Geometry-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link GeometryPropertyType }
*
*/
public void setLod0Geometry(GeometryPropertyType value) {
this.lod0Geometry = value;
}
public boolean isSetLod0Geometry() {
return (this.lod0Geometry!= null);
}
/**
* Ruft den Wert der lod1Geometry-Eigenschaft ab.
*
* @return
* possible object is
* {@link GeometryPropertyType }
*
*/
public GeometryPropertyType getLod1Geometry() {
return lod1Geometry;
}
/**
* Legt den Wert der lod1Geometry-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link GeometryPropertyType }
*
*/
public void setLod1Geometry(GeometryPropertyType value) {
this.lod1Geometry = value;
}
public boolean isSetLod1Geometry() {
return (this.lod1Geometry!= null);
}
/**
* Ruft den Wert der lod2Geometry-Eigenschaft ab.
*
* @return
* possible object is
* {@link GeometryPropertyType }
*
*/
public GeometryPropertyType getLod2Geometry() {
return lod2Geometry;
}
/**
* Legt den Wert der lod2Geometry-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link GeometryPropertyType }
*
*/
public void setLod2Geometry(GeometryPropertyType value) {
this.lod2Geometry = value;
}
public boolean isSetLod2Geometry() {
return (this.lod2Geometry!= null);
}
/**
* Ruft den Wert der lod3Geometry-Eigenschaft ab.
*
* @return
* possible object is
* {@link GeometryPropertyType }
*
*/
public GeometryPropertyType getLod3Geometry() {
return lod3Geometry;
}
/**
* Legt den Wert der lod3Geometry-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link GeometryPropertyType }
*
*/
public void setLod3Geometry(GeometryPropertyType value) {
this.lod3Geometry = value;
}
public boolean isSetLod3Geometry() {
return (this.lod3Geometry!= null);
}
/**
* Ruft den Wert der lod4Geometry-Eigenschaft ab.
*
* @return
* possible object is
* {@link GeometryPropertyType }
*
*/
public GeometryPropertyType getLod4Geometry() {
return lod4Geometry;
}
/**
* Legt den Wert der lod4Geometry-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link GeometryPropertyType }
*
*/
public void setLod4Geometry(GeometryPropertyType value) {
this.lod4Geometry = value;
}
public boolean isSetLod4Geometry() {
return (this.lod4Geometry!= null);
}
/**
* Ruft den Wert der lod0TerrainIntersection-Eigenschaft ab.
*
* @return
* possible object is
* {@link MultiCurvePropertyType }
*
*/
public MultiCurvePropertyType getLod0TerrainIntersection() {
return lod0TerrainIntersection;
}
/**
* Legt den Wert der lod0TerrainIntersection-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link MultiCurvePropertyType }
*
*/
public void setLod0TerrainIntersection(MultiCurvePropertyType value) {
this.lod0TerrainIntersection = value;
}
public boolean isSetLod0TerrainIntersection() {
return (this.lod0TerrainIntersection!= null);
}
/**
* Ruft den Wert der lod1TerrainIntersection-Eigenschaft ab.
*
* @return
* possible object is
* {@link MultiCurvePropertyType }
*
*/
public MultiCurvePropertyType getLod1TerrainIntersection() {
return lod1TerrainIntersection;
}
/**
* Legt den Wert der lod1TerrainIntersection-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link MultiCurvePropertyType }
*
*/
public void setLod1TerrainIntersection(MultiCurvePropertyType value) {
this.lod1TerrainIntersection = value;
}
public boolean isSetLod1TerrainIntersection() {
return (this.lod1TerrainIntersection!= null);
}
/**
* Ruft den Wert der lod2TerrainIntersection-Eigenschaft ab.
*
* @return
* possible object is
* {@link MultiCurvePropertyType }
*
*/
public MultiCurvePropertyType getLod2TerrainIntersection() {
return lod2TerrainIntersection;
}
/**
* Legt den Wert der lod2TerrainIntersection-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link MultiCurvePropertyType }
*
*/
public void setLod2TerrainIntersection(MultiCurvePropertyType value) {
this.lod2TerrainIntersection = value;
}
public boolean isSetLod2TerrainIntersection() {
return (this.lod2TerrainIntersection!= null);
}
/**
* Ruft den Wert der lod3TerrainIntersection-Eigenschaft ab.
*
* @return
* possible object is
* {@link MultiCurvePropertyType }
*
*/
public MultiCurvePropertyType getLod3TerrainIntersection() {
return lod3TerrainIntersection;
}
/**
* Legt den Wert der lod3TerrainIntersection-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link MultiCurvePropertyType }
*
*/
public void setLod3TerrainIntersection(MultiCurvePropertyType value) {
this.lod3TerrainIntersection = value;
}
public boolean isSetLod3TerrainIntersection() {
return (this.lod3TerrainIntersection!= null);
}
/**
* Ruft den Wert der lod4TerrainIntersection-Eigenschaft ab.
*
* @return
* possible object is
* {@link MultiCurvePropertyType }
*
*/
public MultiCurvePropertyType getLod4TerrainIntersection() {
return lod4TerrainIntersection;
}
/**
* Legt den Wert der lod4TerrainIntersection-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link MultiCurvePropertyType }
*
*/
public void setLod4TerrainIntersection(MultiCurvePropertyType value) {
this.lod4TerrainIntersection = value;
}
public boolean isSetLod4TerrainIntersection() {
return (this.lod4TerrainIntersection!= null);
}
/**
* Ruft den Wert der lod0ImplicitRepresentation-Eigenschaft ab.
*
* @return
* possible object is
* {@link ImplicitRepresentationPropertyType }
*
*/
public ImplicitRepresentationPropertyType getLod0ImplicitRepresentation() {
return lod0ImplicitRepresentation;
}
/**
* Legt den Wert der lod0ImplicitRepresentation-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link ImplicitRepresentationPropertyType }
*
*/
public void setLod0ImplicitRepresentation(ImplicitRepresentationPropertyType value) {
this.lod0ImplicitRepresentation = value;
}
public boolean isSetLod0ImplicitRepresentation() {
return (this.lod0ImplicitRepresentation!= null);
}
/**
* Ruft den Wert der lod1ImplicitRepresentation-Eigenschaft ab.
*
* @return
* possible object is
* {@link ImplicitRepresentationPropertyType }
*
*/
public ImplicitRepresentationPropertyType getLod1ImplicitRepresentation() {
return lod1ImplicitRepresentation;
}
/**
* Legt den Wert der lod1ImplicitRepresentation-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link ImplicitRepresentationPropertyType }
*
*/
public void setLod1ImplicitRepresentation(ImplicitRepresentationPropertyType value) {
this.lod1ImplicitRepresentation = value;
}
public boolean isSetLod1ImplicitRepresentation() {
return (this.lod1ImplicitRepresentation!= null);
}
/**
* Ruft den Wert der lod2ImplicitRepresentation-Eigenschaft ab.
*
* @return
* possible object is
* {@link ImplicitRepresentationPropertyType }
*
*/
public ImplicitRepresentationPropertyType getLod2ImplicitRepresentation() {
return lod2ImplicitRepresentation;
}
/**
* Legt den Wert der lod2ImplicitRepresentation-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link ImplicitRepresentationPropertyType }
*
*/
public void setLod2ImplicitRepresentation(ImplicitRepresentationPropertyType value) {
this.lod2ImplicitRepresentation = value;
}
public boolean isSetLod2ImplicitRepresentation() {
return (this.lod2ImplicitRepresentation!= null);
}
/**
* Ruft den Wert der lod3ImplicitRepresentation-Eigenschaft ab.
*
* @return
* possible object is
* {@link ImplicitRepresentationPropertyType }
*
*/
public ImplicitRepresentationPropertyType getLod3ImplicitRepresentation() {
return lod3ImplicitRepresentation;
}
/**
* Legt den Wert der lod3ImplicitRepresentation-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link ImplicitRepresentationPropertyType }
*
*/
public void setLod3ImplicitRepresentation(ImplicitRepresentationPropertyType value) {
this.lod3ImplicitRepresentation = value;
}
public boolean isSetLod3ImplicitRepresentation() {
return (this.lod3ImplicitRepresentation!= null);
}
/**
* Ruft den Wert der lod4ImplicitRepresentation-Eigenschaft ab.
*
* @return
* possible object is
* {@link ImplicitRepresentationPropertyType }
*
*/
public ImplicitRepresentationPropertyType getLod4ImplicitRepresentation() {
return lod4ImplicitRepresentation;
}
/**
* Legt den Wert der lod4ImplicitRepresentation-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link ImplicitRepresentationPropertyType }
*
*/
public void setLod4ImplicitRepresentation(ImplicitRepresentationPropertyType value) {
this.lod4ImplicitRepresentation = value;
}
public boolean isSetLod4ImplicitRepresentation() {
return (this.lod4ImplicitRepresentation!= null);
}
public void setFunction(List<CodeType> value) {
this.function = value;
}
public void setUsage(List<CodeType> value) {
this.usage = value;
}
}
| apache-2.0 |
JessYanCoding/AndroidAutoSize | demo/src/main/java/me/jessyan/autosize/demo/FragmentHost.java | 2106 | /*
* Copyright 2018 JessYan
*
* 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 me.jessyan.autosize.demo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import me.jessyan.autosize.internal.CustomAdapt;
/**
* ================================================
* Created by JessYan on 2018/8/25 14:39
* <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
public class FragmentHost extends AppCompatActivity implements CustomAdapt {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_host);
if (getSupportFragmentManager().findFragmentById(R.id.container1) == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container1, new CustomFragment1()).commit();
}
if (getSupportFragmentManager().findFragmentById(R.id.container2) == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container2, new CustomFragment2()).commit();
}
if (getSupportFragmentManager().findFragmentById(R.id.container3) == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container3, new CustomFragment3()).commit();
}
}
@Override
public boolean isBaseOnWidth() {
return true;
}
@Override
public float getSizeInDp() {
return 720;
}
}
| apache-2.0 |
wanlitao/FCP.Web.Framework | src/FCP.Web.Api.Tracing/Properties/AssemblyInfo.cs | 1382 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("FCP.Web.Api.Tracing")]
[assembly: AssemblyDescription("Web Api Tracing for FCP(Fluent Compute Platform)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("GreatBillows")]
[assembly: AssemblyProduct("FCP.Web.Api.Tracing")]
[assembly: AssemblyCopyright("Copyright © GreatBillows 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("29ffb24c-6d0d-4b5d-b9aa-00ea10cde225")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.1.0")]
[assembly: AssemblyFileVersion("1.2.1.0")]
| apache-2.0 |
SteelToeOSS/Samples | Management/src/AspDotNet4/CloudFoundryWeb/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs | 137 | namespace CloudFoundryWeb.Areas.HelpPage.ModelDescriptions
{
public class SimpleTypeModelDescription : ModelDescription
{
}
} | apache-2.0 |
cedral/aws-sdk-cpp | aws-cpp-sdk-iam/source/model/GetContextKeysForPrincipalPolicyResult.cpp | 2475 | /*
* 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.
*/
#include <aws/iam/model/GetContextKeysForPrincipalPolicyResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <utility>
using namespace Aws::IAM::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;
GetContextKeysForPrincipalPolicyResult::GetContextKeysForPrincipalPolicyResult()
{
}
GetContextKeysForPrincipalPolicyResult::GetContextKeysForPrincipalPolicyResult(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
*this = result;
}
GetContextKeysForPrincipalPolicyResult& GetContextKeysForPrincipalPolicyResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
const XmlDocument& xmlDocument = result.GetPayload();
XmlNode rootNode = xmlDocument.GetRootElement();
XmlNode resultNode = rootNode;
if (!rootNode.IsNull() && (rootNode.GetName() != "GetContextKeysForPrincipalPolicyResult"))
{
resultNode = rootNode.FirstChild("GetContextKeysForPrincipalPolicyResult");
}
if(!resultNode.IsNull())
{
XmlNode contextKeyNamesNode = resultNode.FirstChild("ContextKeyNames");
if(!contextKeyNamesNode.IsNull())
{
XmlNode contextKeyNamesMember = contextKeyNamesNode.FirstChild("member");
while(!contextKeyNamesMember.IsNull())
{
m_contextKeyNames.push_back(contextKeyNamesMember.GetText());
contextKeyNamesMember = contextKeyNamesMember.NextNode("member");
}
}
}
if (!rootNode.IsNull()) {
XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
m_responseMetadata = responseMetadataNode;
AWS_LOGSTREAM_DEBUG("Aws::IAM::Model::GetContextKeysForPrincipalPolicyResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
}
return *this;
}
| apache-2.0 |
venusdrogon/feilong-taglib | src/test/java/com/feilong/taglib/display/httpconcat/handler/VersionFormatterTest.java | 1819 | /*
* Copyright (C) 2008 feilong
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.feilong.taglib.display.httpconcat.handler;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.feilong.security.oneway.MD5Util;
/**
* The Class VersionFormatterTest.
*
* @author <a href="http://feitianbenyue.iteye.com/">feilong</a>
* @since 1.12.6
*/
public class VersionFormatterTest{
/**
* Test version.
*/
@Test
public void testVersion(){
assertEquals(MD5Util.encode("20180808" + VersionEncodeUtil.class.getName()), VersionFormatter.format("20180808"));
}
//---------------------------------------------------------------
/**
* Test version formatter test null.
*/
@Test
public void testVersionFormatterTestNull(){
assertEquals(EMPTY, VersionFormatter.format(null));
}
/**
* Test version formatter test empty.
*/
@Test
public void testVersionFormatterTestEmpty(){
assertEquals(EMPTY, VersionFormatter.format(""));
}
/**
* Test version formatter test blank.
*/
@Test
public void testVersionFormatterTestBlank(){
assertEquals(EMPTY, VersionFormatter.format(" "));
}
}
| apache-2.0 |
LUTAN/tensorflow | tensorflow/python/kernel_tests/losses_test.py | 58135 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for losses."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops
from tensorflow.python.framework import random_seed
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.ops.losses import losses
from tensorflow.python.ops.losses import util
from tensorflow.python.platform import test
from tensorflow.python.training import momentum as momentum_lib
class AbsoluteDifferenceLossTest(test.TestCase):
def setUp(self):
self._predictions = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
self._labels = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
def testValueErrorThrownWhenWeightIsNone(self):
with self.test_session():
with self.assertRaises(ValueError):
losses.absolute_difference(
self._predictions, self._predictions, weights=None)
def testAllCorrectNoLossWeight(self):
loss = losses.absolute_difference(self._predictions, self._predictions)
with self.test_session():
self.assertAlmostEqual(0.0, loss.eval(), 3)
def testNonZeroLoss(self):
loss = losses.absolute_difference(self._labels, self._predictions)
with self.test_session():
self.assertAlmostEqual(5.5, loss.eval(), 3)
def testNonZeroLossWithPythonScalarWeight(self):
weights = 2.3
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(5.5 * weights, loss.eval(), 3)
def testNonZeroLossWithScalarTensorWeight(self):
weights = 2.3
loss = losses.absolute_difference(self._labels, self._predictions,
constant_op.constant(weights))
with self.test_session():
self.assertAlmostEqual(5.5 * weights, loss.eval(), 3)
def testNonZeroLossWithOneDimBatchSpecificWeights(self):
weights = constant_op.constant((1.2, 0.0), shape=(2, 1))
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(5.6, loss.eval(), 3)
def testNonZeroLossWithTwoDimBatchSpecificWeights(self):
weights = constant_op.constant([1.2, 0.0], shape=[2, 1])
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(5.6, loss.eval(), 3)
def testNonZeroLossWithSampleSpecificWeights(self):
weights = constant_op.constant([3, 6, 5, 0, 4, 2], shape=[2, 3])
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(16.6, loss.eval(), 3)
def testNonZeroLossWithSampleSpecificWeightsMostZero(self):
weights = constant_op.constant([0, 0, 0, 0, 0, 2], shape=[2, 3])
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(6.0, loss.eval(), 3)
def testLossWithSampleSpecificWeightsAllZero(self):
weights = array_ops.zeros((2, 3))
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(0.0, loss.eval(), 3)
class SoftmaxCrossEntropyLossTest(test.TestCase):
def testNoneWeightRaisesValueError(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
with self.test_session():
with self.assertRaises(ValueError):
losses.softmax_cross_entropy(labels, logits, weights=None)
def testAllCorrect(self):
with self.test_session():
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
loss = losses.softmax_cross_entropy(labels, logits)
self.assertEquals('softmax_cross_entropy_loss/value', loss.op.name)
self.assertAlmostEqual(loss.eval(), 0.0, 3)
def testAllWrong(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
with self.test_session():
loss = losses.softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 10.0, 3)
def testNonZeroLossWithPythonScalarWeight(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = 2.3
with self.test_session():
loss = losses.softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(weights * 10.0, loss.eval(), 3)
def testNonZeroLossWithScalarTensorWeight(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = 2.3
with self.test_session():
loss = losses.softmax_cross_entropy(labels, logits,
constant_op.constant(weights))
self.assertAlmostEqual(weights * 10.0, loss.eval(), 3)
def testNonZeroLossWithOneDimBatchSpecificWeights(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = constant_op.constant((1.2, 3.4, 5.6))
with self.test_session():
loss = losses.softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0, loss.eval(), 3)
def testAllWrongAllWeightsMissing(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = constant_op.constant([0, 0, 0], shape=[3])
with self.test_session():
loss = losses.softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(0.0, loss.eval(), 3)
def testSomeWeightsMissing(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = constant_op.constant([1.2, 0, 0], shape=[3])
with self.test_session():
loss = losses.softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(12.0, loss.eval(), 3)
def testSoftmaxWithMeasurementSpecificWeightsRaisesException(self):
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
weights = constant_op.constant([[3, 4, 5], [2, 6, 0], [8, 0, 1]])
with self.assertRaises(ValueError):
losses.softmax_cross_entropy(labels, logits, weights=weights).eval()
def testSoftmaxLabelSmoothing(self):
with self.test_session():
# Softmax Cross Entropy Loss is:
# -\sum_i p_i \log q_i
# where for a softmax activation
# \log q_i = x_i - \log \sum_j \exp x_j
# = x_i - x_max - \log \sum_j \exp (x_j - x_max)
# For our activations, [100, -100, -100] the log partion function becomes
# \log ( exp(0) + exp(-200) + exp(-200) ) = 0
# so our log softmaxes become: [0, -200, -200]
# so our cross entropy loss is:
# -(1 - L + L/n) * 0 + 400 * L/n = 400 L/n
logits = constant_op.constant([[100.0, -100.0, -100.0]])
labels = constant_op.constant([[1, 0, 0]])
label_smoothing = 0.1
loss = losses.softmax_cross_entropy(
labels, logits, label_smoothing=label_smoothing)
self.assertEquals(loss.op.name, 'softmax_cross_entropy_loss/value')
expected_value = 400.0 * label_smoothing / 3.0
self.assertAlmostEqual(loss.eval(), expected_value, 3)
class SparseSoftmaxCrossEntropyLossTest(test.TestCase):
def testNoneWeightRaisesValueError(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0], [1], [2]])
with self.test_session():
with self.assertRaises(ValueError):
losses.sparse_softmax_cross_entropy(labels, logits, weights=None)
def testAllCorrectInt32Labels(self):
with self.test_session():
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0], [1], [2]], dtype=dtypes.int32)
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 0.0, 3)
def testAllCorrectInt64Labels(self):
with self.test_session():
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0], [1], [2]], dtype=dtypes.int64)
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 0.0, 3)
def testAllCorrectNonColumnLabels(self):
with self.test_session():
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([0, 1, 2])
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 0.0, 3)
def testAllWrongInt32Labels(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]], dtype=dtypes.int32)
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 10.0, 3)
def testAllWrongInt64Labels(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]], dtype=dtypes.int64)
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 10.0, 3)
def testAllWrongNonColumnLabels(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([2, 0, 1])
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 10.0, 3)
def testNonZeroLossWithPythonScalarWeight(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = 2.3
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(weights * 10.0, loss.eval(), 3)
def testNonZeroLossWithScalarTensorWeight(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = 2.3
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits,
constant_op.constant(weights))
self.assertAlmostEqual(weights * 10.0, loss.eval(), 3)
def testNonZeroLossWith1DTensorWeight(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = 2.3
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(
labels, logits, constant_op.constant((weights,)))
self.assertAlmostEqual(weights * 10.0, loss.eval(), 3)
def testNonZeroLossWithPlaceholderForWeights(self):
logits = constant_op.constant([[10.0, 0.0, 0.0],
[0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = array_ops.placeholder(dtypes.float32)
with self.test_session() as sess:
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
loss_val = sess.run(loss,
feed_dict={weights: ((1.2,), (3.4,), (5.6,))})
self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0, loss_val, 3)
def testNonZeroLossWithPlaceholderForLogitsLabelsAndWeights(self):
logits = array_ops.placeholder(dtypes.float32, shape=(None, 3))
labels = array_ops.placeholder(dtypes.int32, shape=(None, 1))
weights = array_ops.placeholder(dtypes.float32)
with self.test_session() as sess:
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
loss_val = sess.run(loss,
feed_dict={
logits: [[10.0, 0.0, 0.0],
[0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]],
labels: [[2], [0], [1]],
weights: ((1.2,), (3.4,), (5.6,)),
})
self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0, loss_val, 3)
def testNonZeroLossWithOneDimBatchSpecificWeights(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = constant_op.constant([1.2, 3.4, 5.6], shape=(3, 1))
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0, loss.eval(), 3)
def testNonZeroLossWithColumnWeights(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = constant_op.constant([[1.2], [3.4], [5.6]])
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0, loss.eval(), 3)
def testAllWrongAllWeightsMissing(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = constant_op.constant([0, 0, 0], shape=(3, 1))
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(0.0, loss.eval(), 3)
def testSomeWeightsMissing(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = constant_op.constant([1.2, 0, 0], shape=(3, 1))
with self.test_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(12.0, loss.eval(), 3)
def testMeasurementSpecificWeightsRaisesException(self):
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[0], [1], [2]])
weights = constant_op.constant([[3, 4, 5], [2, 6, 0], [8, 0, 1]])
with self.assertRaises(ValueError):
losses.sparse_softmax_cross_entropy(
labels, logits, weights=weights).eval()
def testInconsistentWeightSizeRaisesException(self):
"""The weight tensor has incorrect number of elements."""
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[0], [1], [2]])
weights = constant_op.constant([1.2, 3.4, 5.6, 7.8])
with self.assertRaises(ValueError):
losses.sparse_softmax_cross_entropy(
labels, logits, weights=weights).eval()
def testInconsistentLabelSizeRaisesException(self):
"""The label tensor has incorrect number of elements."""
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[0], [1], [2], [3]])
weights = constant_op.constant([1.2, 3.4, 5.6])
with self.assertRaises(ValueError):
losses.sparse_softmax_cross_entropy(
labels, logits, weights=weights).eval()
def testInconsistentWeightShapeRaisesException(self):
"""The weight tensor has incorrect shape."""
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0, -100.0],
[-100.0, -100.0, 100.0, -100.0],
[-100.0, -100.0, -100.0, 100.0]])
labels = constant_op.constant([[0], [1], [2], [3]])
weights = constant_op.constant([[1.2, 3.4], [5.6, 7.8]])
with self.assertRaises(ValueError):
losses.sparse_softmax_cross_entropy(
labels, logits, weights=weights).eval()
def testInconsistentLabelShapeRaisesException(self):
"""The label tensor has incorrect shape."""
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0, -100.0],
[-100.0, -100.0, 100.0, -100.0],
[-100.0, -100.0, -100.0, 100.0]])
labels = constant_op.constant([[0, 1], [2, 3]])
weights = constant_op.constant(1.2)
with self.assertRaisesRegexp(ValueError, 'dimension'):
losses.sparse_softmax_cross_entropy(
labels, logits, weights=weights).eval()
class SigmoidCrossEntropyLossTest(test.TestCase):
def testAllCorrectSigmoid(self):
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
loss = losses.sigmoid_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sigmoid_cross_entropy_loss/value')
self.assertAlmostEqual(0.0, loss.eval(), 3)
def testLossWithSingleDimPlaceholderForLogitsAndWeights1(self):
logits = array_ops.placeholder(dtypes.float32, shape=(None, 1))
labels = array_ops.placeholder(dtypes.float32, shape=(None, 1))
weights = array_ops.ones_like(logits, dtype=dtypes.float32)
loss = losses.sigmoid_cross_entropy(labels, logits, weights)
with self.test_session() as sess:
loss = sess.run(loss,
feed_dict={
logits: np.ones((32, 1)),
labels: np.ones((32, 1)),
})
self.assertAlmostEqual(0.313, loss, 3)
def testLossWithSingleDimPlaceholderForLogitsAndWeights2(self):
logits = array_ops.placeholder(dtypes.float32, shape=(None, 2))
labels = array_ops.placeholder(dtypes.float32, shape=(None, 2))
weights = array_ops.ones_like(logits, dtype=dtypes.float32)
loss = losses.sigmoid_cross_entropy(labels, logits, weights)
with self.test_session() as sess:
loss = sess.run(loss,
feed_dict={
logits: np.ones((32, 2)),
labels: np.ones((32, 2)),
})
self.assertAlmostEqual(0.313, loss, 3)
def testAllWrongSigmoid(self):
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
loss = losses.sigmoid_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sigmoid_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 600.0 / 9.0, 3)
def testAllWrongSigmoidWithMeasurementSpecificWeights(self):
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = constant_op.constant([[3, 4, 5], [2, 6, 0], [8, 0, 1]])
loss = losses.sigmoid_cross_entropy(labels, logits, weights)
self.assertEquals(loss.op.name, 'sigmoid_cross_entropy_loss/value')
self.assertAlmostEqual(1700.0 / 7.0, loss.eval(), 3)
def testMultiCorrectSigmoid(self):
logits = constant_op.constant([[100.0, -100.0, 100.0],
[100.0, 100.0, -100.0],
[-100.0, 100.0, 100.0]])
labels = constant_op.constant([[1, 0, 1], [1, 1, 0], [0, 1, 1]])
loss = losses.sigmoid_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sigmoid_cross_entropy_loss/value')
with self.test_session():
self.assertAlmostEqual(loss.eval(), 0.0, 3)
def testSigmoidLabelSmoothingCorrect(self):
with self.test_session():
logits = constant_op.constant([[100.0, -100.0, -100.0]])
labels = constant_op.constant([[1, 0, 1]])
# Sigmoid cross entropy loss is:
# max(x,0) - x*z + log(1 + exp(-abs(x)))
# The new labels are:
# z' = z * (1 - L) + 0.5 L
# 1 -> 1 - 0.5 L
# 0 -> 0.5 L
# here we expect:
# 1/3 * (100 - 100 * (1 - 0.5 L) + 0
# + 0 + 100 * (0.5 L) + 0
# + 0 + 100 * (1 - 0.5 L) + 0)
# = 1/3 * (100 + 50 L)
label_smoothing = 0.1
loss = losses.sigmoid_cross_entropy(
labels, logits, label_smoothing=label_smoothing)
self.assertEquals(loss.op.name, 'sigmoid_cross_entropy_loss/value')
expected_value = (100.0 + 50.0 * label_smoothing) / 3.0
self.assertAlmostEqual(loss.eval(), expected_value, 3)
def testSigmoidLabelSmoothingEqualsSoftmaxTwoLabel(self):
with self.test_session():
label_smoothing = 0.1
sigmoid_logits = constant_op.constant([[100.0, -100.0, -100.0]])
sigmoid_labels = constant_op.constant([[1, 0, 1]])
sigmoid_loss = losses.sigmoid_cross_entropy(
sigmoid_labels, sigmoid_logits, label_smoothing=label_smoothing)
softmax_logits = constant_op.constant(
[[0.0, 100.0], [100.0, 0.0], [100.0, 0.0]])
softmax_labels = constant_op.constant([[0, 1], [1, 0], [0, 1]])
softmax_loss = losses.softmax_cross_entropy(
softmax_labels, softmax_logits, label_smoothing=label_smoothing)
self.assertAlmostEqual(sigmoid_loss.eval(), softmax_loss.eval(), 3)
class LogLossTest(test.TestCase):
def setUp(self):
predictions = np.asarray([.9, .2, .2, .8, .4, .6]).reshape((2, 3))
labels = np.asarray([1.0, 0.0, 1.0, 1.0, 0.0, 0.0]).reshape((2, 3))
self._np_predictions = predictions
self._np_labels = labels
epsilon = 1e-7
self._expected_losses = np.multiply(
labels, np.log(predictions + epsilon)) + np.multiply(
1 - labels, np.log(1 - predictions + epsilon))
self._predictions = constant_op.constant(predictions)
self._labels = constant_op.constant(labels)
def testValueErrorThrownWhenWeightIsNone(self):
with self.test_session():
with self.assertRaises(ValueError):
losses.log_loss(self._labels, self._labels, weights=None)
def testAllCorrectNoLossWeight(self):
loss = losses.log_loss(self._labels, self._labels)
with self.test_session():
self.assertAlmostEqual(0.0, loss.eval(), 3)
def testAllCorrectNoLossWeightWithPlaceholder(self):
tf_predictions = array_ops.placeholder(
dtypes.float32, shape=self._np_labels.shape)
loss = losses.log_loss(self._labels, tf_predictions)
with self.test_session():
self.assertAlmostEqual(
0.0, loss.eval(feed_dict={tf_predictions: self._np_labels}), 3)
def testNonZeroLoss(self):
loss = losses.log_loss(self._labels, self._predictions)
with self.test_session():
self.assertAlmostEqual(-np.sum(self._expected_losses) / 6.0,
loss.eval(), 3)
def testNonZeroLossWithPythonScalarWeight(self):
weights = 2.3
loss = losses.log_loss(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(weights * -np.sum(self._expected_losses) / 6.0,
loss.eval(), 3)
def testNonZeroLossWithScalarTensorWeight(self):
weights = 2.3
loss = losses.log_loss(self._labels, self._predictions,
constant_op.constant(weights))
with self.test_session():
self.assertAlmostEqual(weights * -np.sum(self._expected_losses) / 6.0,
loss.eval(), 3)
def testNonZeroLossWithScalarTensorWeightAndPlaceholder(self):
tf_predictions = array_ops.placeholder(
dtypes.float32, shape=self._np_predictions.shape)
weights = 2.3
loss = losses.log_loss(self._labels, tf_predictions,
constant_op.constant(weights))
with self.test_session() as sess:
loss = sess.run(loss, feed_dict={tf_predictions: self._np_predictions})
self.assertAlmostEqual(weights * -np.sum(self._expected_losses) / 6.0,
loss, 3)
def testNonZeroLossWithScalarTensorWeightAndPlaceholderWithRankOnly(self):
tf_predictions = array_ops.placeholder(dtypes.float32, shape=[None, None])
weights = 2.3
loss = losses.log_loss(self._labels, tf_predictions,
constant_op.constant(weights))
with self.test_session() as sess:
loss = sess.run(loss, feed_dict={tf_predictions: self._np_predictions})
self.assertAlmostEqual(weights * -np.sum(self._expected_losses) / 6.0,
loss, 3)
def testNonZeroLossWithOneDimBatchSpecificWeights(self):
weights = constant_op.constant((1.2, 3.4), shape=(2, 1))
expected_losses = np.multiply(
self._expected_losses,
np.asarray([1.2, 1.2, 1.2, 3.4, 3.4, 3.4]).reshape((2, 3)))
loss = losses.log_loss(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(-np.sum(expected_losses) / 6.0, loss.eval(), 3)
def testNonZeroLossWithOneDimBatchSpecificWeightsSomeZero(self):
weights = constant_op.constant((1.2, 0), shape=(2, 1))
expected_losses = np.multiply(self._expected_losses,
np.asarray([1.2, 1.2, 1.2, 0, 0, 0]).reshape(
(2, 3)))
loss = losses.log_loss(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(-np.sum(expected_losses) / 3.0, loss.eval(), 3)
def testNonZeroLossWithTwoDimBatchSpecificWeightsSomeZero(self):
weights = constant_op.constant([1.2, 0], shape=[2, 1])
expected_losses = np.multiply(self._expected_losses,
np.asarray([1.2, 1.2, 1.2, 0, 0, 0]).reshape(
(2, 3)))
loss = losses.log_loss(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(-np.sum(expected_losses) / 3.0, loss.eval(), 3)
def testWeightsWithSameNumDimsButWrongShapeThrowsException(self):
weights = constant_op.constant(np.random.normal(size=(2, 4)), shape=[2, 4])
with self.test_session():
with self.assertRaises(ValueError):
losses.log_loss(self._labels, self._predictions, weights)
def testNonZeroLossWithMeasurementSpecificWeights(self):
weights = np.array([3, 6, 5, 0, 4, 2]).reshape((2, 3))
expected_losses = np.multiply(self._expected_losses, weights)
loss = losses.log_loss(
self._labels,
self._predictions,
constant_op.constant(
weights, shape=(2, 3)))
with self.test_session():
self.assertAlmostEqual(-np.sum(expected_losses) / 5.0, loss.eval(), 3)
def testNonZeroLossWithMeasurementSpecificWeightsWithPlaceholder(self):
weights = np.array([3, 6, 5, 0, 4, 2]).reshape((2, 3))
expected_losses = np.multiply(self._expected_losses, weights)
tf_predictions = array_ops.placeholder(dtypes.float32, shape=[2, 3])
loss = losses.log_loss(
self._labels,
tf_predictions,
constant_op.constant(
weights, shape=(2, 3)))
with self.test_session() as sess:
loss = sess.run(loss, feed_dict={tf_predictions: self._np_predictions})
self.assertAlmostEqual(-np.sum(expected_losses) / 5.0, loss, 3)
def testNonZeroLossWithSampleSpecificWeightsMostZero(self):
weights = np.array([0, 0, 0, 0, 0, 2]).reshape((2, 3))
expected_losses = np.multiply(self._expected_losses, weights)
loss = losses.log_loss(
self._labels,
self._predictions,
constant_op.constant(
weights, shape=(2, 3)))
with self.test_session():
self.assertAlmostEqual(-np.sum(expected_losses), loss.eval(), 3)
def testNonZeroLossWithSampleSpecificWeightsMostZeroWithPlaceholder(self):
weights = np.array([0, 0, 0, 0, 0, 2]).reshape((2, 3))
expected_losses = np.multiply(self._expected_losses, weights)
tf_predictions = array_ops.placeholder(dtypes.float32, shape=[2, 3])
tf_weights = constant_op.constant(weights, shape=(2, 3))
loss = losses.log_loss(self._labels, tf_predictions, tf_weights)
with self.test_session() as sess:
loss = sess.run(loss, feed_dict={tf_predictions: self._np_predictions})
self.assertAlmostEqual(-np.sum(expected_losses), loss, 3)
def testLossWithSampleSpecificWeightsAllZero(self):
tf_weights = array_ops.zeros(shape=(2, 3))
loss = losses.log_loss(self._labels, self._predictions, tf_weights)
with self.test_session():
self.assertAlmostEqual(0.0, loss.eval(), 3)
class HingeLossTest(test.TestCase):
def testIncompatibleShapes(self):
with self.test_session():
logits = constant_op.constant([[-1.0], [2.1]])
labels = constant_op.constant([0.0, 1.0])
with self.assertRaises(ValueError):
_ = losses.hinge_loss(labels, logits).eval()
def testAllOutsideMargin(self):
with self.test_session():
logits = constant_op.constant([1.2, -1.4, -1.0, 2.1])
labels = constant_op.constant([1.0, 0.0, 0.0, 1.0])
loss = losses.hinge_loss(labels, logits)
self.assertAllClose(loss.eval(), 0.0, atol=1e-3)
def testSomeInsideMargin(self):
with self.test_session():
logits = constant_op.constant([[-0.7], [-1.4], [1.4], [0.6]])
labels = constant_op.constant([[0.0], [0.0], [1.0], [1.0]])
loss = losses.hinge_loss(labels, logits)
# Examples 1 and 4 are on the correct side of the hyperplane but within
# the margin so they incur some (small) loss.
self.assertAllClose(loss.eval(), 0.175, atol=1e-3)
def testSomeMisclassified(self):
with self.test_session():
logits = constant_op.constant([[[1.2], [0.4], [-1.0], [-1.1]]])
labels = constant_op.constant([[[1.0], [0.0], [0.0], [1.0]]])
loss = losses.hinge_loss(labels, logits)
# Examples 2 and 4 are on the wrong side of the hyperplane so they incur
# some (fairly large) loss.
self.assertAllClose(loss.eval(), 0.875, atol=1e-3)
class HuberLossTest(test.TestCase):
def testIncompatibleShapes(self):
with self.test_session():
predictions = constant_op.constant([[-1.0], [2.1]])
labels = constant_op.constant([0.0, 1.0])
with self.assertRaises(ValueError):
_ = losses.huber_loss(labels, predictions).eval()
def testAllQuadratic(self):
with self.test_session():
predictions = constant_op.constant([1.5, -1.4, -1.0, 0.0])
labels = constant_op.constant([1.0, -1.0, 0.0, 0.5])
loss = losses.huber_loss(labels, predictions)
self.assertAllClose(loss.eval(),
0.5 * (0.25 + 0.16 + 1.0 + 0.25) / 4., atol=1e-5)
def testAllLinear(self):
with self.test_session():
predictions = constant_op.constant([1.5, -1.4, -1.0, 0.0])
labels = constant_op.constant([0.0, 1.0, 0.0, 1.5])
loss = losses.huber_loss(labels, predictions)
self.assertAllClose(loss.eval(),
(1.5 + 2.4 + 1.0 + 1.5) / 4. - 0.5, atol=1e-5)
def testMixedQuadraticLinear(self):
with self.test_session():
predictions = constant_op.constant([[1.5, -1.4, -1.0, 0.0],
[1.5, -1.4, -1.0, 0.0]])
labels = constant_op.constant([[1.0, -1.0, 0.0, 0.5],
[0.0, 1.0, 0.0, 1.5]])
loss = losses.huber_loss(labels, predictions)
quadratic = 0.5 * (0.25 + 0.16 + 1.0 + 0.25) / 4.
linear = (1.5 + 2.4 + 1.0 + 1.5) / 4. - 0.5
expected_loss = (quadratic + linear) / 2.
self.assertAllClose(loss.eval(), expected_loss, atol=1e-5)
class MeanSquaredErrorTest(test.TestCase):
def setUp(self):
self._predictions = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
self._labels = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
def testValueErrorThrownWhenWeightIsNone(self):
with self.test_session():
with self.assertRaises(ValueError):
losses.mean_squared_error(
self._predictions, self._predictions, weights=None)
def testScalar(self):
with self.test_session():
self.assertEqual(
0.0,
losses.mean_squared_error(predictions=constant_op.constant(0),
labels=constant_op.constant(0)).eval())
def testAllCorrectNoLossWeight(self):
loss = losses.mean_squared_error(self._predictions, self._predictions)
with self.test_session():
self.assertAlmostEqual(0.0, loss.eval(), 3)
def testNonZeroLoss(self):
loss = losses.mean_squared_error(self._labels, self._predictions)
with self.test_session():
self.assertAlmostEqual(49.5, loss.eval(), 3)
def testNonZeroLossWithPythonScalarWeight(self):
weights = 2.3
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(49.5 * weights, loss.eval(), 3)
def testNonZeroLossWithScalarTensorWeight(self):
weights = 2.3
loss = losses.mean_squared_error(self._labels, self._predictions,
constant_op.constant(weights))
with self.test_session():
self.assertAlmostEqual(49.5 * weights, loss.eval(), 3)
def testNonZeroLossWithOneDimBatchSpecificWeights(self):
weights = constant_op.constant([1.2, 3.4], shape=(2, 1))
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(767.8 / 6.0, loss.eval(), 3)
def testNonZeroLossWithTwoDimBatchSpecificWeights(self):
weights = constant_op.constant([1.2, 3.4], shape=[2, 1])
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(767.8 / 6.0, loss.eval(), 3)
def testNonZeroLossWithSampleSpecificWeights(self):
weights = constant_op.constant([3, 6, 5, 0, 4, 2], shape=[2, 3])
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(587 / 5.0, loss.eval(), 3)
def testNonZeroLossWithSampleSpecificWeightsMostZero(self):
weights = constant_op.constant([0, 0, 0, 0, 0, 2], shape=[2, 3])
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(18.0, loss.eval(), 3)
def testLossWithSampleSpecificWeightsAllZero(self):
weights = array_ops.zeros((2, 3))
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.test_session():
self.assertAlmostEqual(0.0, loss.eval(), 3)
class MeanPairwiseSquaredErrorTest(test.TestCase):
def setUp(self):
self._predictions = np.array([[4, 8, 12], [8, 1, 3]])
self._labels = np.array([[1, 9, 2], [-5, -5, 7]])
batch_size, dims = self._labels.shape
# Compute the expected loss 'manually'.
total = np.zeros((batch_size,))
for b in range(batch_size):
for i in range(dims):
for j in range(dims):
x = self._predictions[b, i].item() - self._predictions[b, j].item()
y = self._labels[b, i].item() - self._labels[b, j].item()
diff = (x - y)
total[b] += (diff * diff)
self._expected_losses = np.divide(total, 9.0)
def testValueErrorThrownWhenWeightIsNone(self):
with self.test_session():
with self.assertRaises(ValueError):
losses.mean_pairwise_squared_error(
predictions=constant_op.constant(self._labels),
labels=constant_op.constant(self._labels),
weights=None)
def _test_valid_weights(
self, labels, predictions, expected_loss, weights=1.0):
with self.test_session():
static_inputs_op = losses.mean_pairwise_squared_error(
predictions=predictions, labels=labels, weights=weights)
self.assertAlmostEqual(expected_loss, static_inputs_op.eval(), places=3)
predictions_placeholder = array_ops.placeholder(
dtypes.float32, shape=np.asarray(predictions.shape))
labels_placeholder = array_ops.placeholder(
dtypes.int32, shape=np.asarray(labels.shape))
weights_placeholder = array_ops.placeholder(
dtypes.float32, shape=np.asarray(weights).shape)
dynamic_inputs_op = losses.mean_pairwise_squared_error(
predictions=predictions_placeholder,
labels=labels_placeholder,
weights=weights_placeholder)
feed_dict = {
predictions_placeholder: predictions,
labels_placeholder: labels,
weights_placeholder: weights,
}
self.assertAlmostEqual(
expected_loss, dynamic_inputs_op.eval(feed_dict=feed_dict), places=3)
def testAllCorrectNoLossWeight(self):
self._test_valid_weights(
self._labels, self._labels, expected_loss=0.0)
def testNonZeroLoss(self):
self._test_valid_weights(
self._labels, self._predictions,
expected_loss=np.sum(self._expected_losses))
def testGradientWithZeroWeight(self):
with ops.Graph().as_default():
random_seed.set_random_seed(0)
inputs = array_ops.ones((2, 3))
weights = variable_scope.get_variable(
'weights',
shape=[3, 4],
initializer=init_ops.truncated_normal_initializer())
predictions = math_ops.matmul(inputs, weights)
optimizer = momentum_lib.MomentumOptimizer(
learning_rate=0.001, momentum=0.9)
loss = losses.mean_pairwise_squared_error(predictions, predictions, 0)
gradients_to_variables = optimizer.compute_gradients(loss)
init_op = variables.global_variables_initializer()
with self.test_session() as sess:
sess.run(init_op)
for grad, _ in gradients_to_variables:
np_grad = sess.run(grad)
self.assertFalse(np.isnan(np_grad).any())
def testNonZeroLossWithPythonScalarWeight(self):
weight = 2.3
self._test_valid_weights(
self._labels, self._predictions,
expected_loss=weight * np.sum(self._expected_losses),
weights=weight)
def testNonZeroLossWithScalarTensorWeight(self):
weights = 2.3
loss = losses.mean_pairwise_squared_error(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
weights=constant_op.constant(weights))
with self.test_session():
self.assertAlmostEqual(weights * np.sum(self._expected_losses),
loss.eval(), 3)
def testNonZeroLossWithScalarZeroWeight(self):
self._test_valid_weights(
self._labels, self._predictions, expected_loss=0.0, weights=0.0)
def test3d(self):
labels = np.array([
[[1, 9, 2], [12, 11, 10], [9, 8, 7]],
[[-5, -5, 7], [6, 5, 4], [3, 2, 1]],
])
predictions = np.array([
[[4, 8, 12], [1, 2, 3], [4, 5, 6]],
[[8, 1, 3], [7, 8, 9], [10, 11, 12]],
])
self._test_valid_weights(
labels, predictions, expected_loss=122.22222)
def test3dWeightedScalar(self):
labels = np.array([
[[1, 9, 2], [12, 11, 10], [9, 8, 7]],
[[-5, -5, 7], [6, 5, 4], [3, 2, 1]],
])
predictions = np.array([
[[4, 8, 12], [1, 2, 3], [4, 5, 6]],
[[8, 1, 3], [7, 8, 9], [10, 11, 12]],
])
weight = 3.0
self._test_valid_weights(
labels, predictions, expected_loss=weight * 122.22222,
weights=weight)
def _test_invalid_weights(
self, labels, predictions, weights=1.0):
expected_error_msg = 'weights can not be broadcast to values'
# Static check.
with self.assertRaisesRegexp(ValueError, expected_error_msg):
losses.mean_pairwise_squared_error(
predictions=predictions, labels=labels, weights=weights)
# Dynamic check.
predictions_placeholder = array_ops.placeholder(dtypes.float32)
labels_placeholder = array_ops.placeholder(dtypes.int32)
weights_placeholder = array_ops.placeholder(dtypes.float32)
dynamic_inputs_op = losses.mean_pairwise_squared_error(
predictions=predictions_placeholder,
labels=labels_placeholder,
weights=weights_placeholder)
with self.test_session():
with self.assertRaisesRegexp(errors_impl.OpError, expected_error_msg):
dynamic_inputs_op.eval(feed_dict={
predictions_placeholder: predictions,
labels_placeholder: labels,
weights_placeholder: weights,
})
def testInvalid3dWeighted2x0(self):
labels = np.array([
[[1, 9, 2], [12, 11, 10], [9, 8, 7]],
[[-5, -5, 7], [6, 5, 4], [3, 2, 1]],
])
predictions = np.array([
[[4, 8, 12], [1, 2, 3], [4, 5, 6]],
[[8, 1, 3], [7, 8, 9], [10, 11, 12]],
])
self._test_invalid_weights(
labels, predictions, weights=np.asarray((1.2, 3.4)))
def test3dWeighted2x3x3(self):
labels = np.array([
[[1, 9, 2], [12, 11, 10], [9, 8, 7]],
[[-5, -5, 7], [6, 5, 4], [3, 2, 1]],
])
predictions = np.array([
[[4, 8, 12], [1, 2, 3], [4, 5, 6]],
[[8, 1, 3], [7, 8, 9], [10, 11, 12]],
])
self._test_valid_weights(
# TODO(ptucker): This doesn't look right.
labels, predictions, expected_loss=9 * 122.22222,
weights=np.ones((2, 3, 3)))
def testLossWithAllZeroBatchSpecificWeights(self):
self._test_valid_weights(
self._labels, self._predictions, expected_loss=0.0,
weights=np.zeros((2, 1)))
def testLossIsAssociativeAcrossBatchElements(self):
with ops.Graph().as_default():
random_seed.set_random_seed(0)
height = 3
width = 4
shape = (1, height, width, 1)
labels0 = random_ops.random_uniform(
shape, minval=0, maxval=1, dtype=dtypes.float32)
predictions0 = random_ops.random_uniform(
shape, minval=0, maxval=1, dtype=dtypes.float32)
labels1 = random_ops.random_uniform(
shape, minval=0, maxval=1, dtype=dtypes.float32)
predictions1 = random_ops.random_uniform(
shape, minval=0, maxval=1, dtype=dtypes.float32)
loss0 = losses.mean_pairwise_squared_error(
labels=labels0,
predictions=predictions0)
loss1 = losses.mean_pairwise_squared_error(
labels=labels1,
predictions=predictions1)
loss0_1 = losses.mean_pairwise_squared_error(
labels=array_ops.concat([labels0, labels1], 0),
predictions=array_ops.concat([predictions0, predictions1], 0))
with self.test_session() as session:
loss0, loss1, loss0_1 = session.run([loss0, loss1, loss0_1])
self.assertTrue(loss0 > 0)
self.assertTrue(loss1 > 0)
self.assertAlmostEqual(loss0 + loss1, loss0_1, 5)
class CosineDistanceLossTest(test.TestCase):
def setUp(self):
self._predictions = np.asarray([
[1, 0, 0], # Batch 1
[0, 0, -1],
[1, 0, 0], # Batch 2
[1, 0, 0],
[0, 0, -1], # Batch 3
[1, 0, 0]
]).reshape((3, 2, 3))
self._labels = np.asarray([[1, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0],
[0, 0, 1], [0, 1, 0]]).reshape((3, 2, 3))
def testValueErrorThrownWhenWeightIsNone(self):
with self.test_session():
with self.assertRaises(ValueError):
losses.cosine_distance(
predictions=constant_op.constant(self._labels),
labels=constant_op.constant(self._labels),
dim=2,
weights=None)
def testAllCorrectNoWeights(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._labels),
labels=constant_op.constant(self._labels),
dim=2)
with self.test_session():
self.assertAlmostEqual(0, loss.eval(), 5)
def testPartiallyCorrectWithIntegerValues(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
dim=2)
with self.test_session():
self.assertAlmostEqual(1, loss.eval(), 5)
def testPartiallyCorrectFloatingPointValues(self):
predictions = np.matrix(
('0.819031913261206 0.567041924552012 0.087465312324590;'
'-0.665139432070255 -0.739487441769973 -0.103671883216994;'
'0.707106781186548 -0.707106781186548 0'))
labels = np.matrix(('0.819031913261206 0.567041924552012 0.087465312324590;'
'0.665139432070255 0.739487441769973 0.103671883216994;'
'0.707106781186548 0.707106781186548 0'))
tf_preds = constant_op.constant(
predictions, shape=(3, 1, 3), dtype=dtypes.float32)
tf_labels = constant_op.constant(
labels, shape=(3, 1, 3), dtype=dtypes.float32)
loss = losses.cosine_distance(tf_labels, tf_preds, dim=2)
with self.test_session():
self.assertAlmostEqual(1.0, loss.eval(), 5)
def testSampleSpecificWeights(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
dim=2,
weights=np.asarray((1, 0, 0)).reshape((3, 1, 1)))
with self.test_session():
self.assertEqual(1.0, loss.eval())
def testMeasurementSpecificWeights(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
dim=2,
weights=constant_op.constant(
[1, 0, 0, 1, 1, 1], shape=(3, 2, 1)))
with self.test_session():
self.assertEqual(3.0 / 4.0, loss.eval())
def testMeasurementSpecificWeightsWithPlaceholderWithShape(self):
tf_predictions = array_ops.placeholder(
dtypes.float32, shape=self._labels.shape)
loss = losses.cosine_distance(
predictions=tf_predictions,
labels=constant_op.constant(self._labels),
dim=2,
weights=constant_op.constant(
[1, 0, 0, 1, 1, 1], shape=(3, 2, 1)))
with self.test_session() as sess:
loss = sess.run(loss, feed_dict={tf_predictions: self._predictions})
self.assertEqual(3.0 / 4.0, loss)
def testZeroLossWhenAllSampleSpecificWeightsAreZero(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
dim=2,
weights=array_ops.zeros((3, 1, 1)))
with self.test_session():
self.assertEqual(0, loss.eval())
def testZeroLossWhenAllMeasurementSpecificWeightsAreZero(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
dim=2,
weights=array_ops.zeros((3, 2, 1)))
with self.test_session():
self.assertEqual(0, loss.eval())
class AddLossTest(test.TestCase):
def testNoCollectLossesBatch2(self):
logits = constant_op.constant([[1.2, 0.4, -1.0, -1.1]] * 2)
labels = constant_op.constant([[1.0, 0.0, 0.0, 1.0]] * 2)
self.assertFalse(util.get_losses())
losses.absolute_difference(logits, labels, loss_collection=None)
losses.log_loss(logits, labels, loss_collection=None)
losses.mean_squared_error(logits, labels, loss_collection=None)
losses.sigmoid_cross_entropy(logits, labels, loss_collection=None)
losses.softmax_cross_entropy(logits, labels, loss_collection=None)
self.assertFalse(util.get_losses())
class ComputeWeightedLossTest(test.TestCase):
def setUp(self):
self._shape = (3, 2, 4)
raw_losses = np.zeros(self._shape)
next_loss = 0.0
for i in range(self._shape[0]):
for j in range(self._shape[1]):
for k in range(self._shape[2]):
raw_losses[i][j][k] = next_loss
next_loss += 1.0
raw_losses.setflags(write=False)
self._raw_losses = raw_losses
def testUnweighted(self):
for reduction in losses.Reduction.all():
with ops.Graph().as_default() as g:
self.assertEqual(0, len(util.get_losses()))
raw_losses = self._raw_losses
unweighted_losses = (
losses.compute_weighted_loss(raw_losses, reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((1, 1, 1)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((1, 1, 4)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((1, 2, 1)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((1, 2, 4)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((3, 1, 1)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((3, 1, 4)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((3, 2, 1)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones(self._shape), reduction=reduction)
)
self.assertEqual(9, len(util.get_losses()))
with self.test_session(g):
for unweighted_loss in unweighted_losses:
if reduction == losses.Reduction.WEIGHTED_SUM:
self.assertAllClose(
np.sum(self._raw_losses), unweighted_loss.eval())
else: # losses.Reduction.WEIGHTED_SUM_BY_NONZERO_WEIGHTS
self.assertAllClose(
np.mean(self._raw_losses), unweighted_loss.eval())
def testScalarWeight(self):
with ops.Graph().as_default():
self.assertEqual(0, len(util.get_losses()))
weight = 17.0
weighted_loss = losses.compute_weighted_loss(
self._raw_losses, weights=weight)
self.assertEqual(1, len(util.get_losses()))
with self.test_session():
self.assertAllClose(
np.mean(weight * self._raw_losses), weighted_loss.eval())
def _test_invalid_weights(self, weights):
with ops.Graph().as_default():
self.assertEqual(0, len(util.get_losses()))
expected_error_msg = 'weights can not be broadcast to values'
# Static check.
with self.assertRaisesRegexp(ValueError, expected_error_msg):
losses.compute_weighted_loss(self._raw_losses, weights=weights)
# Dynamic check.
weights_placeholder = array_ops.placeholder(dtypes.float32)
weighted_loss = losses.compute_weighted_loss(
self._raw_losses, weights=weights_placeholder)
self.assertEqual(1, len(util.get_losses()))
with self.test_session():
with self.assertRaisesRegexp(errors_impl.OpError, expected_error_msg):
weighted_loss.eval(feed_dict={weights_placeholder: weights})
def testInvalidWeightTooManyDims(self):
self._test_invalid_weights(np.zeros(shape=(2, 2, 2, 2)))
def testInvalidWeightMismatchedDim(self):
with ops.Graph().as_default():
raw_losses = array_ops.reshape(self._raw_losses, shape=(3, 2, 4, 1))
weights = np.ones(shape=(3, 2, 4, 2))
expected_error_msg = 'weights can not be broadcast to values'
self.assertEqual(0, len(util.get_losses()))
# Static check.
with self.assertRaisesRegexp(ValueError, expected_error_msg):
losses.compute_weighted_loss(raw_losses, weights=weights)
# Dynamic check.
weights_placeholder = array_ops.placeholder(dtypes.float32)
weighted_loss = losses.compute_weighted_loss(
raw_losses, weights=weights_placeholder)
self.assertEqual(1, len(util.get_losses()))
with self.test_session():
with self.assertRaisesRegexp(errors_impl.OpError, expected_error_msg):
weighted_loss.eval(feed_dict={weights_placeholder: weights})
def testInvalid3Weight(self):
self._test_invalid_weights((17.0, 5.0, 2.0))
def testInvalid3x1Weight(self):
self._test_invalid_weights(((17.0,), (5.0,), (2.0,),))
def testInvalid3x2Weight(self):
self._test_invalid_weights((
(17.0, 3.0),
(5.0, 31.0),
(2.0, 7.0),))
def testInvalid1x2Weight(self):
self._test_invalid_weights((17.0, 3.0,),)
def testInvalidScalar1DWeight(self):
self._test_invalid_weights((17.0,),)
def _test_valid_weights(self, weights):
for reduction in losses.Reduction.all():
with ops.Graph().as_default() as g:
self.assertEqual(0, len(util.get_losses()))
weighted_loss = losses.compute_weighted_loss(
self._raw_losses, weights=weights, reduction=reduction)
self.assertEqual(1, len(util.get_losses()))
with self.test_session(g):
weighted_losses = weights * self._raw_losses
weighted_sum = np.sum(weighted_losses)
if reduction == losses.Reduction.WEIGHTED_SUM:
self.assertAllClose(weighted_sum, weighted_loss.eval())
else: # losses.Reduction.WEIGHTED_SUM_BY_NONZERO_WEIGHTS
broadcast_weights = weights * np.ones_like(self._raw_losses)
self.assertAllClose(
weighted_sum / np.count_nonzero(broadcast_weights),
weighted_loss.eval())
def test1x1x1Weight(self):
self._test_valid_weights((((17.0,),),))
def test1x2x1Weight(self):
self._test_valid_weights((((17.0,), (3.0,),),))
def test1x1x4Weight(self):
self._test_valid_weights((((17.0, 0.0, 2.0, 5.0),),))
def test3x1x1Weight(self):
self._test_valid_weights((((17.0,),), ((5.0,),), ((2.0,),),))
def test3x2x1Weight(self):
self._test_valid_weights((
((17.0,), (3.0,)),
((5.0,), (31.0,)),
((2.0,), (7.0,)),
))
def test3x1x4Weight(self):
self._test_valid_weights((
((17.0, 0.0, 2.0, 5.0),),
((5.0, 31.0, 17.0, 5.0),),
((7.0, 3.0, 11.0, 5.0),),
))
def test1x2x4Weight(self):
self._test_valid_weights(((
(17.0, 0.0, 2.0, 5.0),
(3.0, 13.0, 11.0, 2.0),
),))
def test3x2x4Weight(self):
self._test_valid_weights((
((17.0, 0.0, 2.0, 5.0), (3.0, 13.0, 11.0, 2.0),),
((5.0, 31.0, 17.0, 5.0), (13.0, 3.0, 0.0, 11.0),),
((0.0, 3.0, 11.0, 5.0), (13.0, 11.0, 1.0, 7.0),),
))
if __name__ == '__main__':
test.main()
| apache-2.0 |
emullaraj/ebay-sdk-php | src/DTS/eBaySDK/Shopping/Types/SalesTaxType.php | 2681 | <?php
/**
* THE CODE IN THIS FILE WAS GENERATED FROM THE EBAY WSDL USING THE PROJECT:
*
* https://github.com/davidtsadler/ebay-api-sdk-php
*
* Copyright 2014 David T. Sadler
*
* 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.
*/
namespace DTS\eBaySDK\Shopping\Types;
/**
*
* @property double $SalesTaxPercent
* @property string $SalesTaxState
* @property boolean $ShippingIncludedInTax
* @property \DTS\eBaySDK\Shopping\Types\AmountType $SalesTaxAmount
*/
class SalesTaxType extends \DTS\eBaySDK\Types\BaseType
{
/**
* @var array Properties belonging to objects of this class.
*/
private static $propertyTypes = array(
'SalesTaxPercent' => array(
'type' => 'double',
'unbound' => false,
'attribute' => false,
'elementName' => 'SalesTaxPercent'
),
'SalesTaxState' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'SalesTaxState'
),
'ShippingIncludedInTax' => array(
'type' => 'boolean',
'unbound' => false,
'attribute' => false,
'elementName' => 'ShippingIncludedInTax'
),
'SalesTaxAmount' => array(
'type' => 'DTS\eBaySDK\Shopping\Types\AmountType',
'unbound' => false,
'attribute' => false,
'elementName' => 'SalesTaxAmount'
)
);
/**
* @param array $values Optional properties and values to assign to the object.
*/
public function __construct(array $values = array())
{
list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);
parent::__construct($parentValues);
if (!array_key_exists(__CLASS__, self::$properties)) {
self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
}
if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
self::$xmlNamespaces[__CLASS__] = 'urn:ebay:apis:eBLBaseComponents';
}
$this->setValues(__CLASS__, $childValues);
}
}
| apache-2.0 |
mdproctor/drools | drools-core/src/main/java/org/drools/core/command/runtime/process/SignalEventCommand.java | 4636 | /*
* Copyright 2010 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.drools.core.command.runtime.process;
import org.drools.core.command.impl.ExecutableCommand;
import org.drools.core.command.impl.RegistryContext;
import org.drools.core.xml.jaxb.util.JaxbUnknownAdapter;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.internal.command.Context;
import org.kie.internal.command.ProcessInstanceIdCommand;
import org.kie.internal.jaxb.CorrelationKeyXmlAdapter;
import org.kie.internal.process.CorrelationAwareProcessRuntime;
import org.kie.internal.process.CorrelationKey;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class SignalEventCommand implements ExecutableCommand<Void>, ProcessInstanceIdCommand {
/** Generated serial version UID */
private static final long serialVersionUID = 2134028686669740220L;
@XmlAttribute(name="process-instance-id")
private long processInstanceId = -1;
@XmlElement(name = "correlation-key", required = false)
@XmlJavaTypeAdapter(value = CorrelationKeyXmlAdapter.class)
private CorrelationKey correlationKey;
@XmlAttribute(name="event-type", required=true)
private String eventType;
@XmlElement(name="event")
@XmlJavaTypeAdapter(JaxbUnknownAdapter.class)
private Object event;
public SignalEventCommand() {
}
public SignalEventCommand(String eventType,
Object event) {
this.eventType = eventType;
this.event = event;
}
public SignalEventCommand(long processInstanceId,
String eventType,
Object event) {
this.processInstanceId = processInstanceId;
this.eventType = eventType;
this.event = event;
}
@Override
public Long getProcessInstanceId() {
return processInstanceId;
}
@Override
public void setProcessInstanceId(Long processInstanceId) {
this.processInstanceId = processInstanceId;
}
public CorrelationKey getCorrelationKey() {
return correlationKey;
}
public void setCorrelationKey( CorrelationKey correlationKey ) {
this.correlationKey = correlationKey;
}
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public Object getEvent() {
return event;
}
public void setEvent(Object event) {
this.event = event;
}
public Void execute(Context context) {
KieSession ksession = ((RegistryContext) context).lookup( KieSession.class );
if (processInstanceId == -1 && correlationKey == null) {
ksession.signalEvent(eventType, event);
} else {
ProcessInstance processInstance;
if( correlationKey != null ) {
processInstance = ((CorrelationAwareProcessRuntime) ksession).getProcessInstance(correlationKey);
} else {
processInstance = ksession.getProcessInstance(processInstanceId);
}
if (processInstance != null) {
processInstance.signalEvent(eventType, event);
}
}
return null;
}
public String toString() {
if (processInstanceId == -1 && correlationKey == null) {
return "ksession.signalEvent(" + eventType + ", " + event + ");";
} else if (correlationKey != null) {
return "ksession.signalEvent(" + correlationKey + ", " + eventType + ", " + event + ");";
} else {
return "ksession.signalEvent(" + processInstanceId + ", " + eventType + ", " + event + ");";
}
}
}
| apache-2.0 |
GoogleCloudPlatform/kafka-pubsub-emulator | src/main/java/com/google/cloud/partners/pubsub/kafka/PubsubEmulatorServer.java | 5971 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.partners.pubsub.kafka;
import static io.grpc.health.v1.HealthCheckResponse.ServingStatus.SERVING;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.google.cloud.partners.pubsub.kafka.common.AdminGrpc;
import com.google.cloud.partners.pubsub.kafka.config.ConfigurationManager;
import com.google.common.flogger.FluentLogger;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.pubsub.v1.PublisherGrpc;
import com.google.pubsub.v1.SubscriberGrpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.services.HealthStatusManager;
import java.io.File;
import java.io.IOException;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* An implementation of the Cloud Pub/Sub service built on top of Apache Kafka's messaging system.
*/
@Singleton
public class PubsubEmulatorServer {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final int MAX_MESSAGE_SIZE = 1000 * 1000 * 10; // 10MB
private final PublisherService publisher;
private final SubscriberService subscriber;
private final HealthStatusManager healthStatusManager;
private final Server server;
@Inject
public PubsubEmulatorServer(
ConfigurationManager configurationManager,
PublisherService publisher,
SubscriberService subscriber,
AdminService admin,
HealthStatusManager healthStatusManager) {
this.publisher = publisher;
this.subscriber = subscriber;
this.healthStatusManager = healthStatusManager;
ServerBuilder builder =
ServerBuilder.forPort(configurationManager.getServer().getPort())
.addService(publisher)
.addService(subscriber)
.addService(admin)
.addService(healthStatusManager.getHealthService())
.maxInboundMessageSize(MAX_MESSAGE_SIZE);
if (configurationManager.getServer().hasSecurity()) {
builder.useTransportSecurity(
new File(configurationManager.getServer().getSecurity().getCertificateChainFile()),
new File(configurationManager.getServer().getSecurity().getPrivateKeyFile()));
}
server = builder.build();
}
/**
* Initialize and start the PubsubEmulatorServer.
*
* <p>To set an external configuration file must be considered argument
* `configuration.location=/to/path/application.yaml` the properties will be merged.
*/
public static void main(String[] args) {
Args argObject = new Args();
JCommander jCommander = JCommander.newBuilder().addObject(argObject).build();
jCommander.parse(args);
if (argObject.help) {
jCommander.usage();
return;
}
Injector injector =
Guice.createInjector(new DefaultModule(argObject.configurationFile, argObject.pubSubFile));
PubsubEmulatorServer pubsubEmulatorServer = injector.getInstance(PubsubEmulatorServer.class);
try {
pubsubEmulatorServer.start();
pubsubEmulatorServer.blockUntilShutdown();
} catch (IOException | InterruptedException e) {
logger.atSevere().withCause(e).log("Unexpected server failure");
}
}
/** Start the server and add a hook that calls {@link #stop()} when the JVM is shutting down. */
public void start() throws IOException {
server.start();
startHealthcheckServices();
logger.atInfo().log("PubsubEmulatorServer started on port %d", server.getPort());
Runtime.getRuntime()
.addShutdownHook(
new Thread(
() -> {
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
System.err.println(
"*** shutting down gRPC PubsubEmulatorServer since JVM is shutting down");
PubsubEmulatorServer.this.stop();
System.err.println("*** server shut down");
}));
}
/** Stop serving requests, then shutdown Publisher and Subscriber services. */
public void stop() {
if (server != null) {
server.shutdownNow();
}
publisher.shutdown();
subscriber.shutdown();
}
/** Await termination on the main thread since the gRPC library uses daemon threads. */
public void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
/** Add status information to healthcheck for each service. */
private void startHealthcheckServices() {
healthStatusManager.setStatus(PublisherGrpc.SERVICE_NAME, SERVING);
healthStatusManager.setStatus(SubscriberGrpc.SERVICE_NAME, SERVING);
healthStatusManager.setStatus(AdminGrpc.SERVICE_NAME, SERVING);
}
@Parameters(separators = "=")
private static final class Args {
/** Command-line arguments. */
@Parameter(
names = {"-c", "--configuration-file"},
required = true,
description = "Path to a JSON-formatted configuration file for the server.")
private String configurationFile;
@Parameter(
names = {"-p", "--pubsub-repository-file"},
required = true,
description = "Path to a JSON-formatted PubSub configuration repository file.")
private String pubSubFile;
@Parameter(
names = {"--help"},
help = true)
private boolean help = false;
}
}
| apache-2.0 |
wzzlYwzzl/kdashboard | src/app/frontend/userlist/userlist_stateconfig.js | 1386 | import {actionbarViewName} from 'chrome/chrome_state';
import {breadcrumbsConfig} from 'common/components/breadcrumbs/breadcrumbs_service';
import {UserListController} from './userlist_controller';
import {stateName, stateUrl} from './userlist_state';
// import {stateName as userlogin} from 'userlogin/userlogin_state';
import {UserListActionBarController} from './userlistactionbar_controller';
/**
* Configures states for the service view.
*
* @param {!ui.router.$stateProvider} $stateProvider
* @ngInject
*/
export default function stateConfig($stateProvider) {
$stateProvider.state(stateName, {
url: stateUrl,
resolve: {
'userList': resolveUserList,
},
data: {
[breadcrumbsConfig]: {
'label': '用户',
},
},
views: {
'': {
controller: UserListController,
controllerAs: '$ctrl',
templateUrl: 'userlist/userlist.html',
},
[actionbarViewName]: {
controller: UserListActionBarController,
controllerAs: 'ctrl',
templateUrl: 'userlist/userlistactionbar.html',
},
},
});
}
/**
* @param {!angular.$resource} $resource
* @return {!angular.$q.Promise}
* @ngInject
*/
export function resolveUserList($resource) {
/** @type {!angular.Resource<!backendApi.UserList>} */
let resource = $resource('api/v1/users');
return resource.get().$promise;
}
| apache-2.0 |
liquidarmour/ct-calculations | src/main/scala/uk/gov/hmrc/ct/box/ValidatableBox.scala | 13729 | /*
* Copyright 2017 HM Revenue & Customs
*
* 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 uk.gov.hmrc.ct.box
import java.util.regex.Pattern
import org.joda.time.LocalDate
import uk.gov.hmrc.ct.box.ValidatableBox._
import uk.gov.hmrc.ct.box.retriever.BoxRetriever
import uk.gov.hmrc.ct.ct600.v3.retriever.RepaymentsBoxRetriever
import uk.gov.hmrc.ct.domain.ValidationConstants._
import uk.gov.hmrc.ct.utils.DateImplicits._
trait ValidatableBox[T <: BoxRetriever] extends Validators {
// Taken from PostCodeType on http://www.hmrc.gov.uk/schemas/core-v2-0.xsd
protected val postCodeRegex = """(GIR 0AA)|((([A-Z][0-9][0-9]?)|(([A-Z][A-HJ-Y][0-9][0-9]?)|(([A-Z][0-9][A-Z])|([A-Z][A-HJ-Y][0-9]?[A-Z])))) [0-9][A-Z]{2})"""
def validate(boxRetriever: T): Set[CtValidation]
protected def validateBooleanAsMandatory(boxId: String, box: OptionalBooleanIdBox)(): Set[CtValidation] = {
box.value match {
case None => Set(CtValidation(Some(boxId), s"error.$boxId.required"))
case _ => Set()
}
}
protected def validateBooleanAsTrue(boxId: String, box: OptionalBooleanIdBox)(): Set[CtValidation] = {
box.value match {
case None | Some(false) => Set(CtValidation(Some(boxId), s"error.$boxId.required"))
case _ => Set()
}
}
protected def validateIntegerAsMandatory(boxId: String, box: OptionalIntIdBox)(): Set[CtValidation] = {
box.value match {
case None => Set(CtValidation(Some(boxId), s"error.$boxId.required"))
case _ => Set()
}
}
protected def validateStringAsMandatory(boxId: String, box: OptionalStringIdBox)(): Set[CtValidation] = {
box.value match {
case None => Set(CtValidation(Some(boxId), s"error.$boxId.required"))
case Some(x) if x.isEmpty => Set(CtValidation(Some(boxId), s"error.$boxId.required"))
case _ => Set()
}
}
protected def validateAsMandatory[U](box: CtValue[U] with CtBoxIdentifier)(): Set[CtValidation] = {
box.value match {
case None => Set(CtValidation(Some(box.id), s"error.${box.id}.required"))
case Some(x:String) if x.isEmpty => Set(CtValidation(Some(boxId), s"error.$boxId.required"))
case _ => Set()
}
}
protected def validateStringAsMandatoryIfPAYEEQ1False(boxRetriever: RepaymentsBoxRetriever, boxId: String, box: OptionalStringIdBox)(): Set[CtValidation] = {
val payeeq1 = boxRetriever.payeeQ1()
if (!payeeq1.value.getOrElse(true)) {
validateStringAsMandatory(boxId, box)
} else Set()
}
protected def validateAllFilledOrEmptyStrings(boxId: String, allBoxes: Set[CtValue[String]])(): Set[CtValidation] = {
val allEmpty = allBoxes.count(_.value.isEmpty) == allBoxes.size
val allNonEmpty = allBoxes.count(_.value.nonEmpty) == allBoxes.size
passIf(allEmpty || allNonEmpty) {
Set(CtValidation(Some(boxId), s"error.$boxId.allornone"))
}
}
protected def validateAllFilledOrEmptyStringsForBankDetails(boxRetriever: RepaymentsBoxRetriever, boxId: String)(): Set[CtValidation] = {
val bankDetailsBoxGroup:Set[CtValue[String]] = Set(
boxRetriever.b920(),
boxRetriever.b925(),
boxRetriever.b930(),
boxRetriever.b935()
)
validateAllFilledOrEmptyStrings(boxId, bankDetailsBoxGroup)
}
protected def validateStringAsBlank(boxId: String, box: OptionalStringIdBox)(): Set[CtValidation] = {
box.value match {
case None => Set()
case Some(x) if x.isEmpty => Set()
case _ => Set(CtValidation(Some(boxId), s"error.$boxId.nonBlankValue"))
}
}
protected def validateDateAsMandatory(boxId: String, box: OptionalDateIdBox)(): Set[CtValidation] = {
validateDateAsMandatory(boxId, box.value, boxId): Set[CtValidation]
}
protected def validateDateAsMandatory(boxId: String, date: Option[LocalDate], messageId: String)(): Set[CtValidation] = {
date match {
case None => Set(CtValidation(Some(boxId), s"error.$messageId.required"))
case _ => Set()
}
}
protected def validateDateAsBlank(boxId: String, box: OptionalDateIdBox)(): Set[CtValidation] = {
box.value match {
case None => Set()
case _ => Set(CtValidation(Some(boxId), s"error.$boxId.nonBlankValue"))
}
}
protected def validateDateAsBefore(boxId: String, box: OptionalDateIdBox, dateToCompare: LocalDate)(): Set[CtValidation] = {
box.value match {
case None => Set()
case Some(date) if date < dateToCompare => Set()
case _ => Set(CtValidation(Some(boxId), s"error.$boxId.not.before"))
}
}
protected def validateDateAsAfter(boxId: String, box: OptionalDateIdBox, dateToCompare: LocalDate)(): Set[CtValidation] = {
box.value match {
case None => Set()
case Some(date) if date > dateToCompare => Set()
case _ => Set(CtValidation(Some(boxId), s"error.$boxId.not.after"))
}
}
protected def validateDateAsBetweenInclusive(boxId: String, box: OptionalDateIdBox, minDate: LocalDate, maxDate: LocalDate)(): Set[CtValidation] = {
validateDateAsBetweenInclusive(boxId, box.value, minDate, maxDate, boxId)
}
protected def validateDateAsBetweenInclusive(boxId: String, date: Option[LocalDate], minDate: LocalDate, maxDate: LocalDate, messageId: String)(): Set[CtValidation] = {
date match {
case None => Set()
case Some(d) if d < minDate.toDateTimeAtStartOfDay.toLocalDate || d > maxDate.plusDays(1).toDateTimeAtStartOfDay.minusSeconds(1).toLocalDate =>
Set(CtValidation(Some(boxId), s"error.$messageId.not.betweenInclusive", Some(Seq(toErrorArgsFormat(minDate), toErrorArgsFormat(maxDate)))))
case _ => Set()
}
}
protected def validateIntegerAsBlank(boxId: String, box: OptionalIntIdBox)(): Set[CtValidation] = {
box.value match {
case None => Set()
case _ => Set(CtValidation(Some(boxId), s"error.$boxId.nonBlankValue"))
}
}
protected def validateIntegerRange(boxId: String, box: OptionalIntIdBox, min: Int, max: Int)(): Set[CtValidation] = {
box.value match {
case Some(x) => {
passIf (min <= x && x <= max) {
Set(CtValidation(Some(boxId), s"error.$boxId.outOfRange", Some(Seq(commaForThousands(min), commaForThousands(max)))))
}
}
case _ => Set()
}
}
protected def validateZeroOrPositiveBigDecimal(box: OptionalBigDecimalIdBox)(): Set[CtValidation] = {
box.value match {
case Some(x) if x < BigDecimal(0) => Set(CtValidation(Some(box.id), s"error.${box.id}.mustBeZeroOrPositive"))
case _ => Set()
}
}
protected def validateZeroOrPositiveInteger(box: OptionalIntIdBox)(): Set[CtValidation] = {
box.value match {
case Some(x) if x < 0 => Set(CtValidation(Some(box.id), s"error.${box.id}.mustBeZeroOrPositive"))
case _ => Set()
}
}
protected def validatePositiveBigDecimal(box: OptionalBigDecimalIdBox)(): Set[CtValidation] = {
box.value match {
case Some(x) if x <= 0 => Set(CtValidation(Some(box.id), s"error.${box.id}.mustBePositive"))
case _ => Set()
}
}
protected def validatePositiveInteger(box: OptionalIntIdBox)(): Set[CtValidation] = {
box.value match {
case Some(x) if x <= 0 => Set(CtValidation(Some(box.id), s"error.${box.id}.mustBePositive"))
case _ => Set()
}
}
protected def validateOptionalIntegerAsEqualTo(box: CtBoxIdentifier with CtOptionalInteger, equalToBox: CtBoxIdentifier with CtOptionalInteger): Set[CtValidation] = {
if (box.orZero != equalToBox.orZero)
Set(CtValidation(Some(box.id), s"error.${box.id}.mustEqual.${equalToBox.id}"))
else
Set.empty
}
protected def validateOptionalStringByRegex(boxId: String, box: OptionalStringIdBox, regex: String)(): Set[CtValidation] = {
box.value match {
case Some(x) if x.nonEmpty => {
passIf (x.matches(regex)) {
Set(CtValidation(Some(boxId), s"error.$boxId.regexFailure"))
}
}
case _ => Set()
}
}
protected def validateRawStringByRegex(boxId: String, value: String, errorCodeBoxId: String, regex: String)(): Set[CtValidation] = {
passIf (value.matches(regex)) {
Set(CtValidation(Some(boxId), s"error.$errorCodeBoxId.regexFailure"))
}
}
protected def validateStringByRegex(boxId: String, box: StringIdBox, regex: String)(): Set[CtValidation] = {
passIf (box.value.isEmpty || box.value.matches(regex)) {
Set(CtValidation(Some(boxId), s"error.$boxId.regexFailure"))
}
}
protected def validateCoHoStringReturnIllegalChars(boxId: String, box: OptionalStringIdBox)(): Set[CtValidation] = {
box.value match {
case Some(x) if x.nonEmpty => {
validateCoHoStringReturnIllegalChars(boxId, x)
}
case _ => Set()
}
}
protected def validateCohoNameField(boxId: String, box: StringIdBox)(): Set[CtValidation] = {
validateStringByRegex(boxId, box, ValidCoHoNamesCharacters)
}
protected def validateCohoOptionalNameField(boxId: String, box: OptionalStringIdBox)(): Set[CtValidation] = {
validateOptionalStringByRegex(boxId, box, ValidCoHoNamesCharacters)
}
protected def validateCoHoStringReturnIllegalChars(boxId: String, value: String, errorCodeBoxId: Option[String] = None)(): Set[CtValidation] = {
def getIllegalCharacters(x: String): String = {
val p = Pattern.compile(ValidCoHoCharacters)
val m = p.matcher(x)
val allMatchedCharsPluses = m.replaceAll("+")
(allMatchedCharsPluses.toSet filterNot (_ == '+')).mkString(" ")
}
val errorCode = errorCodeBoxId.getOrElse(boxId)
val illegalChars = getIllegalCharacters(value)
passIf (illegalChars.isEmpty) {
Set(CtValidation(Some(boxId), s"error.$errorCode.regexFailure", Some(Seq(illegalChars))))
}
}
protected def validateOptionalStringByLength(boxId: String, box: OptionalStringIdBox, min: Int, max: Int)(): Set[CtValidation] = {
box.value match {
case Some(x) => validateNotEmptyStringByLength(boxId, x, min, max)
case _ => Set()
}
}
protected def validateStringByLength(boxId: String, box: StringIdBox, min:Int, max:Int)(): Set[CtValidation] = {
validateNotEmptyStringByLength(boxId, box.value, min, max)
}
def validateNotEmptyStringByLength(boxId: String, value: String, min: Int, max: Int)(): Set[CtValidation] = {
failIf (value.nonEmpty && value.size < min || value.size > max) {
Set(CtValidation(Some(boxId), s"error.$boxId.text.sizeRange", Some(Seq(min.toString, max.toString))))
}
}
def validateStringByLength(boxId: String, value: String, errorCodeId: String, min: Int, max: Int)(): Set[CtValidation] = {
failIf (value.size < min || value.size > max) {
Set(CtValidation(Some(boxId), s"error.$errorCodeId.text.sizeRange", Some(Seq(min.toString, max.toString))))
}
}
@Deprecated
def validateStringMaxLength(boxId: String, value: String, max: Int)(): Set[CtValidation] = {
failIf (value.size > max) {
Set(CtValidation(Some(boxId), s"error.$boxId.max.length", Some(Seq(commaForThousands(max)))))
}
}
def validatePostcode(boxId: String, box: OptionalStringIdBox)(): Set[CtValidation] = {
validatePostcodeLength(boxId, box) ++ validatePostcodeRegex(boxId, box)
}
private def validatePostcodeLength(boxId: String, box: OptionalStringIdBox): Set[CtValidation] = {
box.value match {
case Some(x) if x.nonEmpty && x.size < 6 || x.size > 8 => Set(CtValidation(Some(boxId), s"error.$boxId.invalidPostcode"))
case _ => Set()
}
}
private def validatePostcodeRegex(boxId: String, box: OptionalStringIdBox): Set[CtValidation] = {
validateOptionalStringByRegex(boxId, box, postCodeRegex) match {
case x if x.isEmpty => Set()
case _ => Set(CtValidation(Some(boxId), s"error.$boxId.invalidPostcode"))
}
}
protected def atLeastOneBoxHasValue(boxId: String, boxes: OptionalCtValue[_]*)(): Set[CtValidation] = {
if (noValue(boxes)) {
Set(CtValidation(boxId = None, s"error.$boxId.one.box.required"))
} else {
Set.empty
}
}
private def noValue(values: Seq[OptionalCtValue[_]]): Boolean = {
values.forall(_.noValue)
}
}
object ValidatableBox {
val ValidNonForeignLessRestrictiveCharacters = "[A-Za-z0-9 ,\\.\\(\\)/&'\\-\"!%\\*_\\+:@<>\\?=;]*"
val ValidNonForeignMoreRestrictiveCharacters = "[A-Za-z0-9 ,\\.\\(\\)/&'\\-\"]*"
val ValidCoHoCharacters = "[a-zA-Z0-9‘’’&@£$€¥\\\\,.;:\\s!?/“”\"*=#%+<>»«_'(){}\\[\\]\\r-]*" // Based on the comment from CATO-4027
val SortCodeValidChars = """^[0-9]{6}$"""
val AccountNumberValidChars = """^[0-9]{8}$"""
val StandardCohoTextFieldLimit = 20000
val StandardCohoNameFieldLimit = 40
val ValidCoHoNamesCharacters = "[A-Za-z\\-'\\. \\,]*" // Based on the comment from CATO-3881
def commaForThousands(i: Int) = f"$i%,d"
type OptionalBooleanIdBox = OptionalCtValue[Boolean] with CtBoxIdentifier
type OptionalIntIdBox = OptionalCtValue[Int] with CtBoxIdentifier
type OptionalStringIdBox = OptionalCtValue[String] with CtBoxIdentifier
type StringIdBox = CtValue[String] with CtBoxIdentifier
type OptionalDateIdBox = OptionalCtValue[LocalDate] with CtBoxIdentifier
type OptionalBigDecimalIdBox = OptionalCtValue[BigDecimal] with CtBoxIdentifier
}
| apache-2.0 |
capitalone/Hydrograph | hydrograph.engine/hydrograph.engine.core/src/main/java/hydrograph/engine/core/component/generator/S3FileTransferEntityGenerator.java | 3968 | /*******************************************************************************
* Copyright 2017 Capital One Services, LLC and Bitwise, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package hydrograph.engine.core.component.generator;
import hydrograph.engine.core.component.entity.RunFileTransferEntity;
import hydrograph.engine.core.component.entity.base.AssemblyEntityBase;
import hydrograph.engine.core.component.generator.base.CommandComponentGeneratorBase;
import hydrograph.engine.jaxb.commandtypes.S3FileTransfer;
import hydrograph.engine.jaxb.commontypes.TypeBaseComponent;
/**
* Created for S3FileTransferEntityGenerator on 9/7/2017.
*/
public class S3FileTransferEntityGenerator extends CommandComponentGeneratorBase {
private S3FileTransfer s3FileTransfer;
private RunFileTransferEntity runFileTransferEntity;
public S3FileTransferEntityGenerator (TypeBaseComponent typeCommandComponent) {
super(typeCommandComponent);
}
@Override
public void castComponentFromBase(TypeBaseComponent baseComponent) {
s3FileTransfer=(S3FileTransfer)baseComponent;
}
@Override
public void createEntity() {
runFileTransferEntity=new RunFileTransferEntity();
}
@Override
public void initializeEntity() {
if(s3FileTransfer.getFileOperation().getDownload()!=null)
runFileTransferEntity.setFileOperation("download");
else
runFileTransferEntity.setFileOperation("upload");
if(s3FileTransfer.getCrediationalPropertiesFile()!=null){
runFileTransferEntity.setCrediationalPropertiesFile(s3FileTransfer.getCrediationalPropertiesFile());
}
else{
runFileTransferEntity.setAccessKeyID(s3FileTransfer.getAccessKeyID());
runFileTransferEntity.setSecretAccessKey(s3FileTransfer.getSecretAccessKey());
}
runFileTransferEntity.setLocalPath(s3FileTransfer.getLocalPath());
runFileTransferEntity.setBucketName(s3FileTransfer.getBucketName());
if(s3FileTransfer.getFolderNameInBucket()!=null)
runFileTransferEntity.setFolder_name_in_bucket(s3FileTransfer.getFolderNameInBucket());
runFileTransferEntity.setRegion(s3FileTransfer.getRegion());
if(s3FileTransfer.getKeyName()!=null)
runFileTransferEntity.setKeyName(s3FileTransfer.getKeyName());
if(s3FileTransfer.getTimeOut()!=null)
runFileTransferEntity.setTimeOut(s3FileTransfer.getTimeOut().getValue().intValue());
if (s3FileTransfer.getRetryAfterDuration()!=null)
runFileTransferEntity.setRetryAfterDuration(s3FileTransfer.getRetryAfterDuration().getValue().intValue());
if (s3FileTransfer.getRetryAttempt()!=null)
runFileTransferEntity.setRetryAttempt(s3FileTransfer.getRetryAttempt().getValue().intValue());
runFileTransferEntity.setEncoding( s3FileTransfer.getEncoding() != null ? s3FileTransfer.getEncoding().getValue().value() : "UTF-8");
if(s3FileTransfer.isFailOnError()!=null){
runFileTransferEntity.setFailOnError(s3FileTransfer.isFailOnError());
}
if(s3FileTransfer.getOverwritemode()!=null){
runFileTransferEntity.setOverwrite(s3FileTransfer.getOverwritemode());
}
}
@Override
public AssemblyEntityBase getEntity() {
return runFileTransferEntity;
}
}
| apache-2.0 |
dbflute-test/dbflute-test-active-hangar | src/main/java/org/docksidestage/hangar/dbflute/bsbhv/pmbean/BsResolvedPackageNamePmb.java | 15907 | package org.docksidestage.hangar.dbflute.bsbhv.pmbean;
import java.util.*;
import org.dbflute.outsidesql.typed.*;
import org.dbflute.jdbc.*;
import org.dbflute.outsidesql.PmbCustodial;
import org.dbflute.util.DfTypeUtil;
import org.docksidestage.hangar.dbflute.allcommon.*;
import org.docksidestage.hangar.dbflute.exbhv.*;
/**
* The base class for typed parameter-bean of ResolvedPackageName. <br>
* This is related to "<span style="color: #AD4747">whitebox:pmbean:selectResolvedPackageName</span>" on MemberBhv.
* @author DBFlute(AutoGenerator)
*/
public class BsResolvedPackageNamePmb implements ExecuteHandlingPmb<MemberBhv>, FetchBean {
// ===================================================================================
// Attribute
// =========
/** The parameter of string1. */
protected String _string1;
/** The parameter of integer1. */
protected Integer _integer1;
/** The parameter of bigDecimal1. */
protected java.math.BigDecimal _bigDecimal1;
/** The parameter of bigDecimal2. */
protected java.math.BigDecimal _bigDecimal2;
/** The parameter of date1. */
protected java.time.LocalDate _date1;
/** The parameter of date2. */
protected java.util.Date _date2;
/** The parameter of date3. */
protected java.sql.Date _date3;
/** The parameter of time1. */
protected java.sql.Time _time1;
/** The parameter of time2. */
protected java.sql.Time _time2;
/** The parameter of timestamp1. */
protected java.time.LocalDateTime _timestamp1;
/** The parameter of timestamp2. */
protected java.sql.Timestamp _timestamp2;
/** The parameter of list1. */
protected List<String> _list1;
/** The parameter of list2. */
protected java.util.List<String> _list2;
/** The parameter of map1. */
protected Map<String, String> _map1;
/** The parameter of map2. */
protected java.util.Map<String, String> _map2;
/** The parameter of cdef. */
protected org.docksidestage.hangar.dbflute.allcommon.CDef _cdef;
/** The parameter of cdefFlg. */
protected org.docksidestage.hangar.dbflute.allcommon.CDef.Flg _cdefFlg;
/** The parameter of bytes. */
protected byte[] _bytes;
/** The max size of safety result. */
protected int _safetyMaxResultSize;
/** The time-zone for filtering e.g. from-to. (NullAllowed: if null, default zone) */
protected TimeZone _timeZone;
// ===================================================================================
// Constructor
// ===========
/**
* Constructor for the typed parameter-bean of ResolvedPackageName. <br>
* This is related to "<span style="color: #AD4747">whitebox:pmbean:selectResolvedPackageName</span>" on MemberBhv.
*/
public BsResolvedPackageNamePmb() {
}
// ===================================================================================
// Typed Implementation
// ====================
/**
* {@inheritDoc}
*/
public String getOutsideSqlPath() { return "whitebox:pmbean:selectResolvedPackageName"; }
// ===================================================================================
// Safety Result
// =============
/**
* {@inheritDoc}
*/
public void checkSafetyResult(int safetyMaxResultSize) {
_safetyMaxResultSize = safetyMaxResultSize;
}
/**
* {@inheritDoc}
*/
public int getSafetyMaxResultSize() {
return _safetyMaxResultSize;
}
// ===================================================================================
// Assist Helper
// =============
// -----------------------------------------------------
// String
// ------
protected String filterStringParameter(String value) { return isEmptyStringParameterAllowed() ? value : convertEmptyToNull(value); }
protected boolean isEmptyStringParameterAllowed() { return DBFluteConfig.getInstance().isEmptyStringParameterAllowed(); }
protected String convertEmptyToNull(String value) { return PmbCustodial.convertEmptyToNull(value); }
// -----------------------------------------------------
// Date
// ----
protected Date toUtilDate(Object date) { return PmbCustodial.toUtilDate(date, _timeZone); }
protected <DATE> DATE toLocalDate(Date date, Class<DATE> localType) { return PmbCustodial.toLocalDate(date, localType, chooseRealTimeZone()); }
protected TimeZone chooseRealTimeZone() { return PmbCustodial.chooseRealTimeZone(_timeZone); }
/**
* Set time-zone, basically for LocalDate conversion. <br>
* Normally you don't need to set this, you can adjust other ways. <br>
* (DBFlute system's time-zone is used as default)
* @param timeZone The time-zone for filtering. (NullAllowed: if null, default zone)
*/
public void zone(TimeZone timeZone) { _timeZone = timeZone; }
// -----------------------------------------------------
// by Option Handling
// ------------------
// might be called by option handling
protected <NUMBER extends Number> NUMBER toNumber(Object obj, Class<NUMBER> type) { return PmbCustodial.toNumber(obj, type); }
protected Boolean toBoolean(Object obj) { return PmbCustodial.toBoolean(obj); }
@SuppressWarnings("unchecked")
protected <ELEMENT> ArrayList<ELEMENT> newArrayList(ELEMENT... elements) { return PmbCustodial.newArrayList(elements); }
// ===================================================================================
// Basic Override
// ==============
/**
* @return The display string of all parameters. (NotNull)
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(DfTypeUtil.toClassTitle(this)).append(":");
sb.append(xbuildColumnString());
return sb.toString();
}
protected String xbuildColumnString() {
final String dm = ", ";
final StringBuilder sb = new StringBuilder();
sb.append(dm).append(_string1);
sb.append(dm).append(_integer1);
sb.append(dm).append(_bigDecimal1);
sb.append(dm).append(_bigDecimal2);
sb.append(dm).append(_date1);
sb.append(dm).append(PmbCustodial.formatUtilDate(_date2, _timeZone, "yyyy-MM-dd"));
sb.append(dm).append(_date3);
sb.append(dm).append(_time1);
sb.append(dm).append(_time2);
sb.append(dm).append(_timestamp1);
sb.append(dm).append(_timestamp2);
sb.append(dm).append(_list1);
sb.append(dm).append(_list2);
sb.append(dm).append(_map1);
sb.append(dm).append(_map2);
sb.append(dm).append(_cdef);
sb.append(dm).append(_cdefFlg);
sb.append(dm).append(PmbCustodial.formatByteArray(_bytes));
if (sb.length() > 0) { sb.delete(0, dm.length()); }
sb.insert(0, "{").append("}");
return sb.toString();
}
// ===================================================================================
// Accessor
// ========
/**
* [get] string1 <br>
* @return The value of string1. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public String getString1() {
return filterStringParameter(_string1);
}
/**
* [set] string1 <br>
* @param string1 The value of string1. (NullAllowed)
*/
public void setString1(String string1) {
_string1 = string1;
}
/**
* [get] integer1 <br>
* @return The value of integer1. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public Integer getInteger1() {
return _integer1;
}
/**
* [set] integer1 <br>
* @param integer1 The value of integer1. (NullAllowed)
*/
public void setInteger1(Integer integer1) {
_integer1 = integer1;
}
/**
* [get] bigDecimal1 <br>
* @return The value of bigDecimal1. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public java.math.BigDecimal getBigDecimal1() {
return _bigDecimal1;
}
/**
* [set] bigDecimal1 <br>
* @param bigDecimal1 The value of bigDecimal1. (NullAllowed)
*/
public void setBigDecimal1(java.math.BigDecimal bigDecimal1) {
_bigDecimal1 = bigDecimal1;
}
/**
* [get] bigDecimal2 <br>
* @return The value of bigDecimal2. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public java.math.BigDecimal getBigDecimal2() {
return _bigDecimal2;
}
/**
* [set] bigDecimal2 <br>
* @param bigDecimal2 The value of bigDecimal2. (NullAllowed)
*/
public void setBigDecimal2(java.math.BigDecimal bigDecimal2) {
_bigDecimal2 = bigDecimal2;
}
/**
* [get] date1 <br>
* @return The value of date1. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public java.time.LocalDate getDate1() {
return _date1;
}
/**
* [set] date1 <br>
* @param date1 The value of date1. (NullAllowed)
*/
public void setDate1(java.time.LocalDate date1) {
_date1 = date1;
}
/**
* [get] date2 <br>
* @return The value of date2. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public java.util.Date getDate2() {
return toUtilDate(_date2);
}
/**
* [set] date2 <br>
* @param date2 The value of date2. (NullAllowed)
*/
public void setDate2(java.util.Date date2) {
_date2 = date2;
}
/**
* [get] date3 <br>
* @return The value of date3. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public java.sql.Date getDate3() {
return _date3;
}
/**
* [set] date3 <br>
* @param date3 The value of date3. (NullAllowed)
*/
public void setDate3(java.sql.Date date3) {
_date3 = date3;
}
/**
* [get] time1 <br>
* @return The value of time1. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public java.sql.Time getTime1() {
return _time1;
}
/**
* [set] time1 <br>
* @param time1 The value of time1. (NullAllowed)
*/
public void setTime1(java.sql.Time time1) {
_time1 = time1;
}
/**
* [get] time2 <br>
* @return The value of time2. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public java.sql.Time getTime2() {
return _time2;
}
/**
* [set] time2 <br>
* @param time2 The value of time2. (NullAllowed)
*/
public void setTime2(java.sql.Time time2) {
_time2 = time2;
}
/**
* [get] timestamp1 <br>
* @return The value of timestamp1. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public java.time.LocalDateTime getTimestamp1() {
return _timestamp1;
}
/**
* [set] timestamp1 <br>
* @param timestamp1 The value of timestamp1. (NullAllowed)
*/
public void setTimestamp1(java.time.LocalDateTime timestamp1) {
_timestamp1 = timestamp1;
}
/**
* [get] timestamp2 <br>
* @return The value of timestamp2. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public java.sql.Timestamp getTimestamp2() {
return _timestamp2;
}
/**
* [set] timestamp2 <br>
* @param timestamp2 The value of timestamp2. (NullAllowed)
*/
public void setTimestamp2(java.sql.Timestamp timestamp2) {
_timestamp2 = timestamp2;
}
/**
* [get] list1 <br>
* @return The value of list1. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public List<String> getList1() {
return _list1;
}
/**
* [set] list1 <br>
* @param list1 The value of list1. (NullAllowed)
*/
public void setList1(List<String> list1) {
_list1 = list1;
}
/**
* [get] list2 <br>
* @return The value of list2. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public java.util.List<String> getList2() {
return _list2;
}
/**
* [set] list2 <br>
* @param list2 The value of list2. (NullAllowed)
*/
public void setList2(java.util.List<String> list2) {
_list2 = list2;
}
/**
* [get] map1 <br>
* @return The value of map1. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public Map<String, String> getMap1() {
return _map1;
}
/**
* [set] map1 <br>
* @param map1 The value of map1. (NullAllowed)
*/
public void setMap1(Map<String, String> map1) {
_map1 = map1;
}
/**
* [get] map2 <br>
* @return The value of map2. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public java.util.Map<String, String> getMap2() {
return _map2;
}
/**
* [set] map2 <br>
* @param map2 The value of map2. (NullAllowed)
*/
public void setMap2(java.util.Map<String, String> map2) {
_map2 = map2;
}
/**
* [get] cdef <br>
* @return The value of cdef. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public org.docksidestage.hangar.dbflute.allcommon.CDef getCdef() {
return _cdef;
}
/**
* [set] cdef <br>
* @param cdef The value of cdef. (NullAllowed)
*/
public void setCdef(org.docksidestage.hangar.dbflute.allcommon.CDef cdef) {
_cdef = cdef;
}
/**
* [get] cdefFlg <br>
* @return The value of cdefFlg. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public org.docksidestage.hangar.dbflute.allcommon.CDef.Flg getCdefFlg() {
return _cdefFlg;
}
/**
* [set] cdefFlg <br>
* @param cdefFlg The value of cdefFlg. (NullAllowed)
*/
public void setCdefFlg(org.docksidestage.hangar.dbflute.allcommon.CDef.Flg cdefFlg) {
_cdefFlg = cdefFlg;
}
/**
* [get] bytes <br>
* @return The value of bytes. (NullAllowed, NotEmptyString(when String): if empty string, returns null)
*/
public byte[] getBytes() {
return _bytes;
}
/**
* [set] bytes <br>
* @param bytes The value of bytes. (NullAllowed)
*/
public void setBytes(byte[] bytes) {
_bytes = bytes;
}
}
| apache-2.0 |
pegasus-isi/pegasus | packages/pegasus-python/src/Pegasus/db/admin/versions/v9.py | 1223 | #!/usr/bin/env python
#
# Copyright 2017-2021 University Of Southern California
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import logging
from Pegasus.db.admin.versions.base_version import BaseVersion
DB_VERSION = 9
log = logging.getLogger(__name__)
class Version(BaseVersion):
def __init__(self, connection):
super().__init__(connection)
def update(self, force=False):
"""
:param force:
:return:
"""
log.info("Updating to version %s" % DB_VERSION)
# this update is not necessary any longer
def downgrade(self, force=False):
"""
Downgrade is not necessary as integrity_meta table does not affect the system"
"""
| apache-2.0 |
cschuff/openui5 | src/sap.uxap/test/sap/uxap/qunit/js/ObjectPageSection.qunit.js | 14417 | /*global QUnit,sinon*/
(function ($, QUnit, sinon, Importance) {
"use strict";
jQuery.sap.registerModulePath("view", "./view");
jQuery.sap.registerModulePath("sap.uxap.testblocks", "./blocks");
jQuery.sap.require("sap.uxap.ObjectPageSubSection");
jQuery.sap.require("sap.uxap.ObjectPageSection");
jQuery.sap.require("sap.uxap.ObjectPageSectionBase");
sinon.config.useFakeTimers = true;
QUnit.module("aatTest");
QUnit.test("ObjectPageSection", function (assert) {
var ObjectPageSectionView = sap.ui.xmlview("UxAP-13_objectPageSection", {
viewName: "view.UxAP-13_ObjectPageSection"
});
ObjectPageSectionView.placeAt('qunit-fixture');
sap.ui.getCore().applyChanges();
// get the object page section
// By default title is not centered, CSS:0120061532 0001349139 2014
var oSectionWithTwoSubSection = ObjectPageSectionView.byId("SectionWithSubSection");
assert.strictEqual(oSectionWithTwoSubSection.$().find(".sapUxAPObjectPageSectionHeader").text(), "", "My first section title never visible");
// Test by finding own class
assert.strictEqual(oSectionWithTwoSubSection.$().find('.mysubsectiontotest').length == 2, true, "Section with two SubSections");
var oSectionWithOneSubSection = ObjectPageSectionView.byId("SectionWithoneSubSection");
assert.strictEqual(oSectionWithOneSubSection.$().find(".sapUxAPObjectPageSectionTitle").text(), "My third subSection Title", "Section with one SubSections");
// Test by finding own class
assert.strictEqual(oSectionWithOneSubSection.$().find(".mysubsectiontotest").length == 1, true, "Section with one SubSections");
var oSectionWithoutSubSection = ObjectPageSectionView.byId("SectionWithoutSubSection");
assert.strictEqual(oSectionWithoutSubSection.$().find(".sapUxAPObjectPageSectionHeader").length, 0, "My third section title without subsection");
// Test by finding own class
assert.strictEqual(oSectionWithoutSubSection.$().find(".mysubsectiontotest").length == 0, true, "Section without SubSection");
// get the object page SubSection
var oSubsection = ObjectPageSectionView.byId("subsection1");
assert.strictEqual(oSubsection.getTitle(), "My first subSection Title", "My first subSection Title");
var oSubsection2 = ObjectPageSectionView.byId("subsection2");
assert.strictEqual(oSubsection2.getTitle(), "My second subSection Title", "My second subSection Title");
var oSubsection3 = ObjectPageSectionView.byId("subsection3");
assert.strictEqual(oSubsection3.$().find(".sapUxAPObjectPageSectionHeader").length, 0, "My third section without subsections");
ObjectPageSectionView.destroy();
});
var SectionBasePrototype = sap.uxap.ObjectPageSectionBase.prototype,
SectionPrototype = sap.uxap.ObjectPageSection.prototype;
QUnit.module("Section/SubSection Importance");
QUnit.test("Section with title has button placeholders", function (assert) {
var oObjectPageLayout = new sap.uxap.ObjectPageLayout("page02", {
sections: new sap.uxap.ObjectPageSection({
subSections: [
new sap.uxap.ObjectPageSubSection({
title: "Title",
blocks: [new sap.m.Text({text: "test"})]
})
]
})
});
oObjectPageLayout.placeAt('qunit-fixture');
sap.ui.getCore().applyChanges();
var $section = oObjectPageLayout.getSections()[0].$();
assert.strictEqual($section.find('.sapUxAPObjectPageSectionHeader .sapUiHiddenPlaceholder').length, 2, "subsection has 2 hidden placeholders");
oObjectPageLayout.destroy();
});
QUnit.test("Section without title has no button placeholders", function (assert) {
var oObjectPageLayout = new sap.uxap.ObjectPageLayout("page02", {
sections: new sap.uxap.ObjectPageSection({
showTitle: false,
subSections: [
new sap.uxap.ObjectPageSubSection({
title: "Title",
blocks: [new sap.m.Text({text: "test"})]
})
]
})
});
oObjectPageLayout.placeAt('qunit-fixture');
sap.ui.getCore().applyChanges();
var $section = oObjectPageLayout.getSections()[0].$();
assert.strictEqual($section.find('.sapUxAPObjectPageSectionHeader .sapUiHiddenPlaceholder').length, 0, "subsection has no hidden placeholders");
oObjectPageLayout.destroy();
});
QUnit.test("Section with dynamically added title has button placeholders", function (assert) {
var oObjectPageLayout = new sap.uxap.ObjectPageLayout("page02", {
sections: new sap.uxap.ObjectPageSection({
showTitle: false,
subSections: [
new sap.uxap.ObjectPageSubSection({
title: "Title",
blocks: [new sap.m.Text({text: "test"})]
})
]
})
});
oObjectPageLayout.placeAt('qunit-fixture');
oObjectPageLayout.getSections()[0].setShowTitle(true);
sap.ui.getCore().applyChanges();
var $section = oObjectPageLayout.getSections()[0].$();
assert.strictEqual($section.find('.sapUxAPObjectPageSectionHeader .sapUiHiddenPlaceholder').length, 2, "subsection has hidden placeholders");
oObjectPageLayout.destroy();
});
QUnit.test("Default state for hiding/showing the content", function (assert) {
var oMockSection = {
getImportance: sinon.stub().returns(Importance.High)
};
SectionBasePrototype.init.call(oMockSection);
assert.strictEqual(SectionBasePrototype._getIsHidden.call(oMockSection), false,
"The section/subSection content should be initialized as visible");
assert.strictEqual(SectionBasePrototype._shouldBeHidden.call(oMockSection), false,
"When the section has high importance then it should never be hidden");
});
QUnit.test("Section title display/hide", function (assert) {
var oObjectPageLayout = new sap.uxap.ObjectPageLayout({
sections: new sap.uxap.ObjectPageSection({
title: "Title",
subSections: [
new sap.uxap.ObjectPageSubSection({
blocks: [new sap.m.Text({text: "test"})]
})
]
})
}),
oFirstSection = oObjectPageLayout.getSections()[0],
$oFirstSection;
// Arrange
oObjectPageLayout.placeAt('qunit-fixture');
sap.ui.getCore().applyChanges();
$oFirstSection = oFirstSection.$();
// Assert
assert.strictEqual($oFirstSection.hasClass("sapUxAPObjectPageSectionNoTitle"), false,
"The correct styling is applied");
// Act
oFirstSection.setShowTitle(false);
sap.ui.getCore().applyChanges();
$oFirstSection = oFirstSection.$();
// Assert
assert.strictEqual($oFirstSection.hasClass("sapUxAPObjectPageSectionNoTitle"), true,
"The correct styling is applied");
// Act
oFirstSection.setShowTitle(true);
sap.ui.getCore().applyChanges();
$oFirstSection = oFirstSection.$();
// Assert
assert.strictEqual($oFirstSection.hasClass("sapUxAPObjectPageSectionNoTitle"), false,
"The correct styling is applied");
oObjectPageLayout.destroy();
});
QUnit.test("Behavior with different importance levels", function (assert) {
var fnGenerateTest = function (sImportance, sCurrentImportanceLevel, bExpectToBeHidden, assert) {
var sShouldBeHidden = "The section should be hidden",
sShouldBeVisible = "The section should be visible",
oMockSection = {
setImportance: function (sImportance) {
this.getImportance = sinon.stub().returns(sImportance);
}
};
oMockSection.setImportance(sImportance);
SectionBasePrototype.init.call(oMockSection);
oMockSection._sCurrentLowestImportanceLevelToShow = sCurrentImportanceLevel;
assert.strictEqual(SectionBasePrototype._shouldBeHidden.call(oMockSection), bExpectToBeHidden,
bExpectToBeHidden ? sShouldBeHidden : sShouldBeVisible);
};
fnGenerateTest(Importance.Low, Importance.Low, false, assert);
fnGenerateTest(Importance.Medium, Importance.Low, false, assert);
fnGenerateTest(Importance.High, Importance.Low, false, assert);
fnGenerateTest(Importance.Low, Importance.Medium, true, assert);
fnGenerateTest(Importance.Medium, Importance.Medium, false, assert);
fnGenerateTest(Importance.High, Importance.Medium, false, assert);
fnGenerateTest(Importance.Low, Importance.High, true, assert);
fnGenerateTest(Importance.Medium, Importance.High, true, assert);
fnGenerateTest(Importance.High, Importance.High, false, assert);
});
QUnit.test("Deciding the lowest importance level to show", function (assert) {
var fnGenerateTest = function (sDevice, sExpectedImportance, assert) {
assert.strictEqual(SectionPrototype._determineTheLowestLevelOfImportanceToShow(sDevice), sExpectedImportance,
"On " + sDevice + " show " + sExpectedImportance + " importance and above content");
};
fnGenerateTest("Phone", Importance.High, assert);
fnGenerateTest("Tablet", Importance.Medium, assert);
fnGenerateTest("Desktop", Importance.Low, assert);
assert.strictEqual(SectionPrototype._determineTheLowestLevelOfImportanceToShow("Desktop", true), Importance.High,
"On Desktop you can override the default behaviour and show only High priorities");
});
QUnit.test("Updating the show/hide state", function (assert) {
var toggleSpy = sinon.spy(),
jQueryObject = {
children: sinon.stub().returns({
toggle: toggleSpy
})
},
oMockSection = {
_getObjectPageLayout: sinon.stub().returns(null),
_sContainerSelector: '.someClass',
_getIsHidden: sinon.stub().returns(this._isHidden),
setImportance: function (sImportance) {
this.getImportance = sinon.stub().returns(sImportance);
},
_updateShowHideState: sinon.spy(),
$: sinon.stub().returns(jQueryObject)
};
SectionBasePrototype.init.call(this);
oMockSection._isHidden = true;
SectionBasePrototype._expandSection.call(oMockSection);
assert.ok(oMockSection._updateShowHideState.calledWith(false));
assert.ok(!oMockSection._getIsHidden());
SectionBasePrototype._showHideContent.call(oMockSection);
assert.ok(oMockSection._updateShowHideState.calledWith(true));
assert.ok(!oMockSection._getIsHidden());
SectionBasePrototype._updateShowHideState.call(oMockSection, true);
assert.ok(jQueryObject.children.calledWith(oMockSection._sContainerSelector));
assert.ok(jQueryObject.children().toggle.calledWith(false));
SectionBasePrototype._updateShowHideState.call(oMockSection, false);
assert.ok(jQueryObject.children.calledWith(oMockSection._sContainerSelector));
assert.ok(jQueryObject.children().toggle.calledWith(true));
});
QUnit.test("Section show/hide all button text and visibility", function (assert) {
var oButton = new sap.m.Button({
visible: false,
text: "initialText"
}),
sExpectedText = "someText",
oSectionStub = {
_getShowHideAllButton: sinon.stub().returns(oButton),
_getShouldDisplayShowHideAllButton: sinon.stub().returns(true),
_getShowHideAllButtonText: sinon.stub().returns(sExpectedText)
};
SectionPrototype._updateShowHideAllButton.call(oSectionStub, true);
assert.ok(oButton.getVisible());
assert.ok(oButton.getText(sExpectedText));
oButton.setText("otherText");
oSectionStub._getShouldDisplayShowHideAllButton = sinon.stub().returns(false);
SectionPrototype._updateShowHideAllButton.call(oSectionStub, false);
assert.ok(!oButton.getVisible());
assert.ok(oButton.getText(sExpectedText));
oButton.destroy();
});
QUnit.test("Section show/hide button text and visibility", function (assert) {
var oButton = new sap.m.Button({
visible: false,
text: "initialText"
}),
sExpectedText = "someText",
oSectionStub = {
_getShowHideButton: sinon.stub().returns(oButton),
_getShowHideButtonText: sinon.stub().returns(sExpectedText),
_shouldBeHidden: sinon.stub().returns(true)
};
SectionPrototype._updateShowHideButton.call(oSectionStub, true);
assert.ok(oButton.getVisible());
assert.ok(oButton.getText(sExpectedText));
oButton.setText("otherText");
oSectionStub._shouldBeHidden = sinon.stub().returns(false);
SectionPrototype._updateShowHideButton.call(oSectionStub, false);
assert.ok(!oButton.getVisible());
assert.ok(oButton.getText(sExpectedText));
oButton.destroy();
});
QUnit.test("Testing ObjectPageSubSection._getClosestSection", function (assert) {
var ObjectPageSectionView = sap.ui.xmlview("UxAP-13_objectPageSection", {
viewName: "view.UxAP-13_ObjectPageSection"
}),
oSectionWithTwoSubSection = ObjectPageSectionView.byId("SectionWithSubSection"),
oFirstSubSection = oSectionWithTwoSubSection.getSubSections()[0],
fnGetClosestSection = sap.uxap.ObjectPageSection._getClosestSection;
assert.equal(fnGetClosestSection(oFirstSubSection).getId(), oSectionWithTwoSubSection.getId());
assert.equal(fnGetClosestSection(oSectionWithTwoSubSection).getId(), oSectionWithTwoSubSection.getId());
ObjectPageSectionView.destroy();
});
QUnit.module("Accessibility", {
beforeEach: function() {
this.ObjectPageSectionView = sap.ui.xmlview("UxAP-13_objectPageSection", {
viewName: "view.UxAP-13_ObjectPageSection"
});
this.ObjectPageSectionView.placeAt('qunit-fixture');
sap.ui.getCore().applyChanges();
},
afterEach: function() {
this.ObjectPageSectionView.destroy();
}
});
QUnit.test("Test aria-labelledby attribute", function (assert) {
var oFirstSection = this.ObjectPageSectionView.byId("SectionWithSubSection"),
sFirstSectionAriaLabelledBy = oFirstSection.$().attr("aria-labelledby"),
oSectionWithoutTitle = this.ObjectPageSectionView.byId("SectionWithNoTitleAndTwoSubSections"),
sSectionWithoutTitleAriaLabel = oSectionWithoutTitle.$().attr("aria-labelledby"),
oLastSection = this.ObjectPageSectionView.byId("SectionWithNoTitleAndOneSubSection"),
sLastSectionAriaLabelledBy = oLastSection.$().attr("aria-labelledby"),
sSectionText = sap.uxap.ObjectPageSection._getLibraryResourceBundle().getText("SECTION_CONTROL_NAME");
// assert
assert.strictEqual(sap.ui.getCore().byId(sFirstSectionAriaLabelledBy).getText(),
oFirstSection._getTitle() + " " + sSectionText, "aria-labelledby is set properly");
assert.strictEqual(sap.ui.getCore().byId(sSectionWithoutTitleAriaLabel).getText(),
sSectionText, "sections without title are labelled by 'Section' texts");
assert.strictEqual(sap.ui.getCore().byId(sLastSectionAriaLabelledBy).getText(),
oLastSection._getTitle() + " " + sSectionText, "aria-labelledby is set properly");
// act
oFirstSection.setTitle("New title");
// assert
assert.strictEqual(sap.ui.getCore().byId(sFirstSectionAriaLabelledBy).getText(),
oFirstSection._getTitle() + " " + sSectionText, "aria-labelledby is updated properly");
});
}(jQuery, QUnit, sinon, sap.uxap.Importance));
| apache-2.0 |
hmrc/ct-calculations | src/main/scala/uk/gov/hmrc/ct/version/CoHoVersions.scala | 925 | /*
* Copyright 2021 HM Revenue & Customs
*
* 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 uk.gov.hmrc.ct.version
object CoHoVersions {
case object FRSSE2008 extends Version {
override def name: String = "FRSSE-2008"
}
case object FRS102 extends Version {
override def name: String = "FRS-102"
}
case object FRS105 extends Version {
override def name: String = "FRS-105"
}
}
| apache-2.0 |
lalvarezcu/subjectsplus | ckeditor/plugins/subsplus_cat_link/dialogs/subsplus_cat_link.js | 8551 | /**
* The subsplus_cat_link dialog definition.
*
*/
function html_entity_decode(str)
{
var ta=document.createElement("textarea");
ta.innerHTML=str.replace(/</g,"<").replace(/>/g,">");
return ta.value;
}
// Our dialog definition.
CKEDITOR.dialog.add( 'subsplus_cat_linkDialog', function( editor ) {
return {
// Basic properties of the dialog window: title, minimum size.
title: html_entity_decode(editor['lang']['subsplus_cat_link.Title']),
minWidth: 700,
minHeight: 200,
resizable: CKEDITOR.DIALOG_RESIZE_NONE,
//buttons
buttons: [CKEDITOR.dialog.cancelButton],
// Dialog window contents definition.
contents: [
{
// Definition of the Link to Subject Heading Settings dialog tab (page).
id: 'tab-sub-head',
label: editor.lang['subsplus_cat_link.Tab1Label'],
// The tab contents.
elements: [
{
// Text input field for the Prefix text.
type: 'text',
id: 'prefix',
label: editor.lang['subsplus_cat_link.Tab1Prefix']
},
{
// Text input field for the Subject Heading title (explanation).
type: 'text',
id: 'terms',
label: editor.lang['subsplus_cat_link.Tab1Subject']
},
{
// html hint (explanation).
type: 'html',
html: '<p><strong>' + editor.lang['subsplus_cat_link.Tab1HtmlStrong'] + '</strong> ' + editor.lang['subsplus_cat_link.Tab1Html'] + '</p><blockquote>PN 1997 - Screenplays - see <span class="linkie">Motion picture plays</span><br>TR 899 <span class="linkie">Motion Pictures--Editing<span></span></span></blockquote>'
},
{
// html break
type: 'html',
html: '<div></div>'
},
{
//button to add link to subject heading
type: 'button',
id: 'sub-head-button',
label: editor.lang['subsplus_cat_link.Tab1Button'],
title: editor.lang['subsplus_cat_link.Tab1Button'],
className: 'cke_dialog_ui_button cke_dialog_ui_button_ok',
onClick: function()
{
var dialog = this._.dialog;
var lstrPrefix = dialog.getValueOf( 'tab-sub-head', 'prefix' );
var lstrSubject = dialog.getValueOf( 'tab-sub-head', 'terms' );
//validate the input
if(lstrSubject == '')
{
alert(html_entity_decode(editor.lang['subsplus_cat_link.Tab1ValidateAlert']));
}else{
//create token
var lstrToken = "{{cat}, {" + lstrSubject + "},{" + lstrPrefix + "},{subject}}";
// Finally, inserts the element at the editor caret position.
editor.insertHtml( ' <span class="subsplus_cat_link" style="background: #E488B6;" contentEditable=false>' + lstrToken + '</span> ' );
//close dialog box
CKEDITOR.dialog.getCurrent().hide()
}
}
}
]
},
{
// Definition of the Link to Keyword Search Results Settings dialog tab (page).
id: 'tab-key-sea',
label: editor.lang['subsplus_cat_link.Tab2Label'],
// The tab contents.
elements: [
{
// Text input field for the keywords text.
type: 'text',
id: 'keywords',
label: editor.lang['subsplus_cat_link.Tab2Keywords']
},
{
// Text input field for the html hint (explanation).
type: 'html',
html: '<span style="font-size: 10px;">E.g., ' + editor.lang['subsplus_cat_link.Tab2EG'] + '</span>'
},
{
// html break
type: 'html',
html: '<div></div>'
},
{
//button to add link to subject heading
type: 'button',
id: 'key-sea-button',
label: editor.lang['subsplus_cat_link.Tab2Button'],
title: editor.lang['subsplus_cat_link.Tab2Button'],
className: 'cke_dialog_ui_button cke_dialog_ui_button_ok',
onClick: function()
{
var dialog = this._.dialog;
var lstrKeyword = dialog.getValueOf( 'tab-key-sea', 'keywords' );
//validate the input
if(lstrKeyword == '')
{
alert(html_entity_decode(editor.lang['subsplus_cat_link.Tab2ValidateAlert']));
}else{
//create token
var lstrToken = "{{cat}, {" + lstrKeyword + "},{" + lstrKeyword + "},{keywords}}";
// Finally, inserts the element at the editor caret position.
editor.insertHtml( ' <span class="subsplus_cat_link" style="background: #E488B6;" contentEditable=false>' + lstrToken + '</span> ' );
//close dialog box
CKEDITOR.dialog.getCurrent().hide()
}
}
}
]
},
{
// Definition of the Link to Call Number (DVDs and Reserves only in Voyager) Settings dialog tab (page).
id: 'tab-call-num',
label: editor.lang['subsplus_cat_link.Tab3Label'],
// The tab contents.
elements: [
{
// Text input field for the Call Number text.
type: 'text',
id: 'call_number',
label: editor.lang['subsplus_cat_link.Tab3CallNum']
},
{
// Text input field for the Title or link Text text.
type: 'text',
id: 'cn_label',
label: editor.lang['subsplus_cat_link.Tab3Text']
},
{
// html break
type: 'html',
html: '<div></div>'
},
{
//button to add link to subject heading
type: 'button',
id: 'key-sea-button',
label: editor.lang['subsplus_cat_link.Tab3Button'],
title: editor.lang['subsplus_cat_link.Tab3Button'],
className: 'cke_dialog_ui_button cke_dialog_ui_button_ok',
onClick: function()
{
var dialog = this._.dialog;
var lstrCallNum = dialog.getValueOf( 'tab-call-num', 'call_number' );
var lstrLabel = dialog.getValueOf( 'tab-call-num', 'cn_label' );
//validate the input
if(lstrCallNum == '' && lstrLabel == '')
{
alert(html_entity_decode(editor.lang['subsplus_cat_link.Tab3ValidateCallLabel']));
}else if(lstrCallNum == '')
{
alert(html_entity_decode(editor.lang['subsplus_cat_link.Tab3ValidateCall']));
}else if(lstrLabel == '')
{
alert(html_entity_decode(editor.lang['subsplus_cat_link.Tab3ValidateLabel']));
}else{
//create token
var lstrToken = "{{cat}, {" + lstrCallNum + "},{" + lstrLabel + "},{call_num}}";
// Finally, inserts the element at the editor caret position.
editor.insertHtml( ' <span class="subsplus_cat_link" style="background: #E488B6;" contentEditable=false>' + lstrToken + '</span> ' );
//close dialog box
CKEDITOR.dialog.getCurrent().hide()
}
}
}
]
},
{
// Definition of the Link to Bib Record dialog tab (page).
id: 'tab-bib-num',
label: editor.lang['subsplus_cat_link.Tab4Label'],
// The tab contents.
elements: [
{
// Text input field for the bib record text.
type: 'text',
id: 'bib',
label: editor.lang['subsplus_cat_link.Tab4Text']
},
{
// Text input field for the html hint (explanation).
type: 'html',
html: '<span style="font-size: 10px;">E.g., ' + editor.lang['subsplus_cat_link.Tab4EG'] + '</span>'
},
{
// Text input field for the Title or link Text text.
type: 'text',
id: 'bib_label',
label: editor.lang['subsplus_cat_link.Tab4Title']
},
{
// html break
type: 'html',
html: '<div></div>'
},
{
//button to add link to subject heading
type: 'button',
id: 'bib-num-button',
label: editor.lang['subsplus_cat_link.Tab4Button'],
title: editor.lang['subsplus_cat_link.Tab4Button'],
className: 'cke_dialog_ui_button cke_dialog_ui_button_ok',
onClick: function()
{
var dialog = this._.dialog;
var lstrBib = dialog.getValueOf( 'tab-bib-num', 'bib' );
var lstrLabel = dialog.getValueOf( 'tab-bib-num', 'bib_label' );
//validate the input
if(lstrBib == '' && lstrLabel == '')
{
alert(html_entity_decode(editor.lang['subsplus_cat_link.Tab4ValidateAlertBoth']));
}else if(lstrBib == '')
{
alert(html_entity_decode(editor.lang['subsplus_cat_link.Tab4ValidateAlertBib']));
}else if(lstrLabel == '')
{
alert(html_entity_decode(editor.lang['subsplus_cat_link.Tab4ValidateAlertTitle']));
}else{
//create token
var lstrToken = "{{cat}, {" + lstrBib + "},{" + lstrLabel + "},{bib}}";
// Finally, inserts the element at the editor caret position.
editor.insertHtml( ' <span class="subsplus_cat_link" style="background: #E488B6;" contentEditable=false>' + lstrToken + '</span> ' );
//close dialog box
CKEDITOR.dialog.getCurrent().hide()
}
}
}
]
}
]
};
}); | apache-2.0 |
rnpandya/adam | adam-core/src/main/scala/org/bdgenomics/adam/algorithms/smithwaterman/SmithWatermanGapScoringFromFn.scala | 2307 | /**
* Licensed to Big Data Genomics (BDG) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The BDG 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.bdgenomics.adam.algorithms.smithwaterman
abstract class SmithWatermanGapScoringFromFn(
xSequence: String,
ySequence: String,
scoreFn: (Int, Int, Char, Char) => Double)
extends SmithWaterman(xSequence, ySequence) {
def buildScoringMatrix(): (Array[Array[Double]], Array[Array[Char]]) = {
val y = ySequence.length
val x = xSequence.length
val scoreMatrix = new Array[Array[Double]](x + 1)
val moveMatrix = new Array[Array[Char]](x + 1)
for (i <- 0 to x) {
scoreMatrix(i) = new Array[Double](y + 1)
moveMatrix(i) = new Array[Char](y + 1)
}
// set row/col 0 to 0
for (i <- 0 to x) {
scoreMatrix(i)(0) = 0.0
moveMatrix(i)(0) = 'T'
}
for (j <- 0 to y) {
scoreMatrix(0)(j) = 0.0
moveMatrix(0)(j) = 'T'
}
// score matrix
for (i <- 1 to x) {
for (j <- 1 to y) {
val m = scoreMatrix(i - 1)(j - 1) + scoreFn(i, j, xSequence(i - 1), ySequence(j - 1))
val d = scoreMatrix(i - 1)(j) + scoreFn(i, j, xSequence(i - 1), '_')
val in = scoreMatrix(i)(j - 1) + scoreFn(i, j, '_', ySequence(j - 1))
val (scoreUpdate, moveUpdate) = if (m >= d && m >= in && m > 0.0) {
(m, 'B')
} else if (d >= in && d > 0.0) {
(d, 'J')
} else if (in > 0.0) {
(in, 'I')
} else {
(0.0, 'T')
}
scoreMatrix(i)(j) = scoreUpdate
moveMatrix(i)(j) = moveUpdate
}
}
(scoreMatrix, moveMatrix)
}
}
| apache-2.0 |
cf-platform-eng/aws-pcf-quickstart | ci/create-stack.py | 5159 | # aws-pcf-quickstart
#
# Copyright (c) 2017-Present Pivotal Software, Inc. All Rights Reserved.
#
# This program and the accompanying materials are made available under
# the terms of the 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 datetime
import json
import sys
import time
import boto3
import botocore.exceptions
import os
import random
import yaml
def select_random_region():
with open("./cloudformation/supported_regions.yml") as f:
region_list = yaml.load(f).get('supported_regions')
# our prod-ish stuff is in west-1, don't use that
region_list.remove("us-west-1")
secure_random = random.SystemRandom()
region = secure_random.choice(region_list)
print("Stack will be created in {} to run integration".format(region))
return region
def describe_stack_status(cloudformation_client, stack_id):
describe_response = cloudformation_client.describe_stacks(
StackName=stack_id)
stack = describe_response.get("Stacks")[0]
return stack.get('StackStatus')
def create_stack(template_path: str, aws_region: str):
password = os.environ['AWS_CF_PASSWORD']
domain = os.environ['AWS_CF_DOMAIN']
hostedzoneid = os.environ['AWS_CF_HOSTEDZONEID']
pcfkeypair = os.environ['AWS_CF_PCFKEYPAIR']
pivnettoken = os.environ['AWS_CF_PIVNETTOKEN']
aws_access_key_id = os.environ['AWS_ACCESS_KEY_ID']
aws_secret_access_key = os.environ['AWS_SECRET_ACCESS_KEY']
deploymentsize = os.environ['AWS_CF_DEPLOYMENT_SIZE']
sslcertificatearn = os.environ[aws_region.upper().replace(
'-', '_') + '_SSLCERTIFICATEARN']
parameters = [
{"ParameterKey": "OpsManagerIngress", "ParameterValue": "0.0.0.0/0"},
# {"ParameterKey": "RdsPassword", "ParameterValue": password},
# {"ParameterKey": "RdsUsername", "ParameterValue": "admin"},
{"ParameterKey": "SSLCertificateARN", "ParameterValue": sslcertificatearn},
{"ParameterKey": "PivnetToken", "ParameterValue": pivnettoken},
{"ParameterKey": "AdminEmail", "ParameterValue": "noreply@pivotal.io"},
{"ParameterKey": "HostedZoneId", "ParameterValue": hostedzoneid},
{"ParameterKey": "Domain", "ParameterValue": domain},
{"ParameterKey": "OpsManagerAdminPassword", "ParameterValue": password},
{"ParameterKey": "PCFKeyPair", "ParameterValue": pcfkeypair},
{"ParameterKey": "ForwardLogOutput", "ParameterValue": "true"},
{"ParameterKey": "DeploymentSize", "ParameterValue": deploymentsize},
{"ParameterKey": "SkipSSLValidation", "ParameterValue": "true"},
{"ParameterKey": "QSS3BucketName",
"ParameterValue": "aws-1click-pcf-quickstart-templates"},
{"ParameterKey": "AcceptEULA", "ParameterValue": "Yes"},
]
client = boto3.client(
service_name='cloudformation', region_name=aws_region, aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key
)
with open(template_path, 'r') as template_file:
template = template_file.read()
stack_name = "pcf-int-{}".format(
int(datetime.datetime.now().timestamp()))
create_response = client.create_stack(
StackName=stack_name,
TemplateBody=template,
Parameters=parameters,
Capabilities=[
'CAPABILITY_IAM',
],
DisableRollback=False, # for debug purposes
)
stack_id = create_response.get("StackId")
print("Created stack: {}".format(stack_id))
stack_metadata = {
"stack_id": stack_id,
"region": aws_region,
"ssl_cert_arn": sslcertificatearn
}
with open('stackid', 'w') as file:
json.dump(stack_metadata, file)
stack_status = describe_stack_status(client, stack_id)
while stack_status == 'CREATE_IN_PROGRESS':
time.sleep(60)
try:
stack_status = describe_stack_status(client, stack_id)
print("Checking status got {}".format(stack_status))
except botocore.exceptions.EndpointConnectionError as e:
print("Hopefully AWS endpoint is coming back!", e)
print("Final status {}".format(stack_status))
if stack_status != "CREATE_COMPLETE":
print("Stack creation did not complete, exiting...")
sys.exit(1)
else:
sys.exit(0)
if __name__ == "__main__":
template_path = sys.argv[1]
if len(sys.argv) > 2:
aws_region = sys.argv[2]
else:
aws_region = select_random_region()
create_stack(template_path, aws_region)
| apache-2.0 |
ederign/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-client-common/src/test/java/org/kie/workbench/common/stunner/core/client/session/command/impl/DeleteSelectionSessionCommandTest.java | 2020 | /*
* Copyright 2017 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.stunner.core.client.session.command.impl;
import javax.enterprise.event.Event;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.core.client.canvas.event.selection.CanvasClearSelectionEvent;
import org.kie.workbench.common.stunner.core.client.event.keyboard.KeyboardEvent;
import org.kie.workbench.common.stunner.core.client.session.ClientFullSession;
import org.kie.workbench.common.stunner.core.client.session.command.AbstractClientSessionCommand;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class DeleteSelectionSessionCommandTest extends BaseSessionCommandKeyboardTest {
@Mock
private Event<CanvasClearSelectionEvent> canvasClearSelectionEventEvent;
@Override
protected AbstractClientSessionCommand<ClientFullSession> getCommand() {
return new DeleteSelectionSessionCommand(sessionCommandManager,
canvasCommandFactory,
canvasClearSelectionEventEvent);
}
@Override
protected KeyboardEvent.Key[] getExpectedKeys() {
return new KeyboardEvent.Key[]{KeyboardEvent.Key.DELETE};
}
@Override
protected KeyboardEvent.Key[] getUnexpectedKeys() {
return new KeyboardEvent.Key[]{KeyboardEvent.Key.ESC};
}
}
| apache-2.0 |
rishuatgithub/MLPy | tf/linear_regression_tf.py | 892 | # Linear Regression model using tensorflow - Rishu Shrivastava
import tensorflow as tf
#Model parameters
W=tf.Variable([.3], dtype=tf.float32)
b=tf.Variable([-.3], dtype=tf.float32)
#Input and Output parameters
x=tf.placeholder(tf.float32)
y=tf.placeholder(tf.float32)
linear_model=W*x + b
#calculate loss - Sum of squared error
loss = tf.reduce_sum(tf.square(linear_model - y))
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
# training data
x_train = [1, 2, 3, 4]
y_train = [0, -1, -2, -3]
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init) # reset values to wrong
for i in range(1000):
sess.run(train, {x: x_train, y: y_train})
# evaluate training accuracy
curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train})
print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))
| apache-2.0 |
spohnan/geowave | core/store/src/main/java/org/locationtech/geowave/core/store/data/field/FieldUtils.java | 4950 | /**
* Copyright (c) 2013-2019 Contributors to the Eclipse Foundation
*
* <p> See the NOTICE file distributed with this work for additional information regarding copyright
* ownership. All rights reserved. This program and the accompanying materials are made available
* under the terms of the Apache License, Version 2.0 which accompanies this distribution and is
* available at http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package org.locationtech.geowave.core.store.data.field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.locationtech.geowave.core.index.SPIServiceRegistry;
import org.locationtech.geowave.core.store.util.GenericTypeResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class has a set of convenience methods to determine the appropriate field reader and writer
* for a given field type (Class)
*/
public class FieldUtils {
public static final byte SERIALIZATION_VERSION = 0x1;
private static final Logger LOGGER = LoggerFactory.getLogger(FieldUtils.class);
private static Map<Class<?>, FieldReader<?>> fieldReaderRegistry = null;
private static Map<Class<?>, FieldWriter<?, ?>> fieldWriterRegistry = null;
private static synchronized Map<Class<?>, FieldReader<?>> getRegisteredFieldReaders() {
if (fieldReaderRegistry == null) {
initRegistry();
}
return fieldReaderRegistry;
}
private static synchronized Map<Class<?>, FieldWriter<?, ?>> getRegisteredFieldWriters() {
if (fieldWriterRegistry == null) {
initRegistry();
}
return fieldWriterRegistry;
}
private static synchronized void initRegistry() {
fieldReaderRegistry = new HashMap<>();
fieldWriterRegistry = new HashMap<>();
final Iterator<FieldSerializationProviderSpi> serializationProviders =
new SPIServiceRegistry(FieldSerializationProviderSpi.class).load(
FieldSerializationProviderSpi.class);
while (serializationProviders.hasNext()) {
final FieldSerializationProviderSpi<?> serializationProvider = serializationProviders.next();
if (serializationProvider != null) {
final Class<?> type =
GenericTypeResolver.resolveTypeArgument(
serializationProvider.getClass(),
FieldSerializationProviderSpi.class);
final FieldReader<?> reader = serializationProvider.getFieldReader();
if (reader != null) {
if (fieldReaderRegistry.containsKey(type)) {
LOGGER.warn(
"Field reader already registered for " + type + "; not able to add " + reader);
} else {
fieldReaderRegistry.put(type, reader);
}
}
final FieldWriter<?, ?> writer = serializationProvider.getFieldWriter();
if (writer != null) {
if (fieldWriterRegistry.containsKey(type)) {
LOGGER.warn(
"Field writer already registered for " + type + "; not able to add " + writer);
} else {
fieldWriterRegistry.put(type, writer);
}
}
}
}
}
@SuppressWarnings("unchecked")
public static <T> FieldReader<T> getDefaultReaderForClass(final Class<T> myClass) {
final Map<Class<?>, FieldReader<?>> internalFieldReaders = getRegisteredFieldReaders();
// try concrete class
final FieldReader<T> reader = (FieldReader<T>) internalFieldReaders.get(myClass);
if (reader != null) {
return reader;
}
// if the concrete class lookup failed, try inheritance
return (FieldReader<T>) getAssignableValueFromClassMap(myClass, internalFieldReaders);
}
@SuppressWarnings("unchecked")
public static <T> FieldWriter<?, T> getDefaultWriterForClass(final Class<T> myClass) {
final Map<Class<?>, FieldWriter<?, ?>> internalFieldWriters = getRegisteredFieldWriters();
// try concrete class
final FieldWriter<?, T> writer = (FieldWriter<?, T>) internalFieldWriters.get(myClass);
if (writer != null) {
return writer;
} // if the concrete class lookup failed, try inheritance
return (FieldWriter<?, T>) getAssignableValueFromClassMap(myClass, internalFieldWriters);
}
public static <T> T getAssignableValueFromClassMap(
final Class<?> myClass,
final Map<Class<?>, T> classToAssignableValueMap) {
// loop through the map to discover the first class that is assignable
// from myClass
for (final Entry<Class<?>, T> candidate : classToAssignableValueMap.entrySet()) {
if (candidate.getKey().isAssignableFrom(myClass)) {
return candidate.getValue();
}
}
return null;
}
public static <RowType, FieldType> FieldWriter<RowType, FieldType> getDefaultWriterForClass(
final Class<FieldType> myClass,
final FieldVisibilityHandler<RowType, Object> visibilityHandler) {
return new BasicWriter<>(getDefaultWriterForClass(myClass), visibilityHandler);
}
}
| apache-2.0 |
darranl/directory-shared | ldap/codec/core/src/test/java/org/apache/directory/api/ldap/codec/search/controls/PSearchControlTest.java | 8482 | /*
* 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.directory.api.ldap.codec.search.controls;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.nio.ByteBuffer;
import com.mycila.junit.concurrent.Concurrency;
import com.mycila.junit.concurrent.ConcurrentJunitRunner;
import org.apache.directory.api.asn1.DecoderException;
import org.apache.directory.api.ldap.codec.controls.search.persistentSearch.PersistentSearchDecorator;
import org.apache.directory.api.ldap.codec.osgi.AbstractCodecServiceTest;
import org.apache.directory.api.ldap.model.message.controls.ChangeType;
import org.apache.directory.api.ldap.model.message.controls.PersistentSearch;
import org.apache.directory.api.util.Strings;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test the PSearchControlTest codec
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
@RunWith(ConcurrentJunitRunner.class)
@Concurrency()
public class PSearchControlTest extends AbstractCodecServiceTest
{
/**
* Test encoding of a PSearchControl.
* @throws Exception on error
*/
@Test
public void testEncodePSearchControl() throws Exception
{
ByteBuffer bb = ByteBuffer.allocate( 0x0B );
bb.put( new byte[]
{
0x30, 0x09, // PersistentSearch ::= SEQUENCE {
0x02,
0x01,
0x01, // changeTypes INTEGER,
0x01,
0x01,
0x00, // changesOnly BOOLEAN,
0x01,
0x01,
0x00 // returnECs BOOLEAN
} );
String expected = Strings.dumpBytes( bb.array() );
bb.flip();
PersistentSearchDecorator decorator = new PersistentSearchDecorator( codec );
PersistentSearch ctrl = ( PersistentSearch ) decorator.getDecorated();
ctrl.setChangesOnly( false );
ctrl.setReturnECs( false );
ctrl.setChangeTypes( 1 );
bb = decorator.encode( ByteBuffer.allocate( decorator.computeLength() ) );
String decoded = Strings.dumpBytes( bb.array() );
assertEquals( expected, decoded );
}
/**
* Test the decoding of a PSearchControl with combined changes types
*/
@Test
public void testDecodeModifyDNRequestSuccessChangeTypesAddModDN() throws Exception
{
ByteBuffer bb = ByteBuffer.allocate( 0x0b );
bb.put( new byte[]
{
0x30, 0x09, // PersistentSearch ::= SEQUENCE {
0x02,
0x01,
0x09, // changeTypes INTEGER,
0x01,
0x01,
0x00, // changesOnly BOOLEAN,
0x01,
0x01,
0x00 // returnECs BOOLEAN
} );
bb.flip();
PersistentSearchDecorator decorator = new PersistentSearchDecorator( codec );
PersistentSearch ctrl = ( PersistentSearch ) decorator.decode( bb.array() );
int changeTypes = ctrl.getChangeTypes();
assertTrue( ChangeType.ADD.presentIn( changeTypes ) );
assertTrue( ChangeType.MODDN.presentIn( changeTypes ) );
assertEquals( false, ctrl.isChangesOnly() );
assertEquals( false, ctrl.isReturnECs() );
}
/**
* Test the decoding of a PSearchControl with a changes types which
* value is 0
*/
@Test(expected = DecoderException.class)
public void testDecodeModifyDNRequestSuccessChangeTypes0() throws Exception
{
ByteBuffer bb = ByteBuffer.allocate( 0x0b );
bb.put( new byte[]
{
0x30, 0x09, // PersistentSearch ::= SEQUENCE {
0x02,
0x01,
0x00, // changeTypes INTEGER,
0x01,
0x01,
0x00, // changesOnly BOOLEAN,
0x01,
0x01,
0x00 // returnECs BOOLEAN
} );
bb.flip();
PersistentSearchDecorator decorator = new PersistentSearchDecorator( codec );
decorator.decode( bb.array() );
}
/**
* Test the decoding of a PSearchControl with a changes types which
* value is above 15
*/
@Test(expected = DecoderException.class)
public void testDecodeModifyDNRequestSuccessChangeTypes22() throws Exception
{
ByteBuffer bb = ByteBuffer.allocate( 0x0b );
bb.put( new byte[]
{
0x30, 0x09, // PersistentSearch ::= SEQUENCE {
0x02,
0x01,
0x22, // changeTypes INTEGER,
0x01,
0x01,
0x00, // changesOnly BOOLEAN,
0x01,
0x01,
0x00 // returnECs BOOLEAN
} );
bb.flip();
PersistentSearchDecorator decorator = new PersistentSearchDecorator( codec );
decorator.decode( bb.array() );
}
/**
* Test the decoding of a PSearchControl with a null sequence
*/
@Test(expected = DecoderException.class)
public void testDecodeModifyDNRequestSuccessNullSequence() throws Exception
{
ByteBuffer bb = ByteBuffer.allocate( 0x02 );
bb.put( new byte[]
{
0x30, 0x00, // PersistentSearch ::= SEQUENCE {
} );
bb.flip();
PersistentSearchDecorator decorator = new PersistentSearchDecorator( codec );
decorator.decode( bb.array() );
}
/**
* Test the decoding of a PSearchControl without changeTypes
*/
@Test(expected = DecoderException.class)
public void testDecodeModifyDNRequestSuccessWithoutChangeTypes() throws Exception
{
ByteBuffer bb = ByteBuffer.allocate( 0x08 );
bb.put( new byte[]
{
0x30, 0x06, // PersistentSearch ::= SEQUENCE {
0x01,
0x01,
0x00, // changesOnly BOOLEAN,
0x01,
0x01,
0x00 // returnECs BOOLEAN
} );
bb.flip();
PersistentSearchDecorator decorator = new PersistentSearchDecorator( codec );
decorator.decode( bb.array() );
}
/**
* Test the decoding of a PSearchControl without changeOnly
*/
@Test(expected = DecoderException.class)
public void testDecodeModifyDNRequestSuccessWithoutChangesOnly() throws Exception
{
ByteBuffer bb = ByteBuffer.allocate( 0x08 );
bb.put( new byte[]
{
0x30, 0x06, // PersistentSearch ::= SEQUENCE {
0x02,
0x01,
0x01, // changeTypes INTEGER,
0x01,
0x01,
0x00 // returnECs BOOLEAN
} );
bb.flip();
PersistentSearchDecorator decorator = new PersistentSearchDecorator( codec );
decorator.decode( bb.array() );
}
/**
* Test the decoding of a PSearchControl without returnECs
*/
@Test(expected = DecoderException.class)
public void testDecodeModifyDNRequestSuccessWithoutReturnECs() throws Exception
{
ByteBuffer bb = ByteBuffer.allocate( 0x08 );
bb.put( new byte[]
{
0x30, 0x06, // PersistentSearch ::= SEQUENCE {
0x02,
0x01,
0x01, // changeTypes INTEGER,
0x01,
0x01,
0x00, // changesOnly BOOLEAN,
} );
bb.flip();
PersistentSearchDecorator decorator = new PersistentSearchDecorator( codec );
decorator.decode( bb.array() );
}
}
| apache-2.0 |
google/eslint-closure | packages/eslint-plugin-closure/dist/closure-eslint-plugin.js | 113881 | var c = c || {};
c.global = this;
c.isDef = function(a) {
return void 0 !== a;
};
c.exportPath_ = function(a, b, d) {
a = a.split(".");
d = d || c.global;
a[0] in d || !d.execScript || d.execScript("var " + a[0]);
for (var e;a.length && (e = a.shift());) {
!a.length && c.isDef(b) ? d[e] = b : d = d[e] ? d[e] : d[e] = {};
}
};
c.define = function(a, b) {
c.exportPath_(a, b);
};
c.DEBUG = !1;
c.LOCALE = "en";
c.TRUSTED_SITE = !0;
c.STRICT_MODE_COMPATIBLE = !1;
c.DISALLOW_TEST_ONLY_CODE = !c.DEBUG;
c.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING = !1;
c.provide = function(a) {
if (c.isInModuleLoader_()) {
throw Error("goog.provide can not be used within a goog.module.");
}
c.constructNamespace_(a);
};
c.constructNamespace_ = function(a, b) {
c.exportPath_(a, b);
};
c.VALID_MODULE_RE_ = /^[a-zA-Z_$][a-zA-Z0-9._$]*$/;
c.module = function(a) {
if (!c.isString(a) || !a || -1 == a.search(c.VALID_MODULE_RE_)) {
throw Error("Invalid module identifier");
}
if (!c.isInModuleLoader_()) {
throw Error("Module " + a + " has been loaded incorrectly. Note, modules cannot be loaded as normal scripts. They require some kind of pre-processing step. You're likely trying to load a module via a script tag or as a part of a concatenated bundle without rewriting the module. For more info see: https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.");
}
if (c.moduleLoaderState_.moduleName) {
throw Error("goog.module may only be called once per module.");
}
c.moduleLoaderState_.moduleName = a;
};
c.module.get = function(a) {
return c.module.getInternal_(a);
};
c.module.getInternal_ = function() {
};
c.moduleLoaderState_ = null;
c.isInModuleLoader_ = function() {
return null != c.moduleLoaderState_;
};
c.module.declareLegacyNamespace = function() {
c.moduleLoaderState_.declareLegacyNamespace = !0;
};
c.setTestOnly = function(a) {
if (c.DISALLOW_TEST_ONLY_CODE) {
throw a = a || "", Error("Importing test-only code into non-debug environment" + (a ? ": " + a : "."));
}
};
c.forwardDeclare = function() {
};
c.getObjectByName = function(a, b) {
a = a.split(".");
b = b || c.global;
for (var d;d = a.shift();) {
if (c.isDefAndNotNull(b[d])) {
b = b[d];
} else {
return null;
}
}
return b;
};
c.globalize = function(a, b) {
b = b || c.global;
for (var d in a) {
b[d] = a[d];
}
};
c.addDependency = function(a, b, d, e) {
if (c.DEPENDENCIES_ENABLED) {
var f;
a = a.replace(/\\/g, "/");
var g = c.dependencies_;
e && "boolean" !== typeof e || (e = e ? {module:"goog"} : {});
for (var h = 0;f = b[h];h++) {
g.nameToPath[f] = a, g.loadFlags[a] = e;
}
for (e = 0;b = d[e];e++) {
a in g.requires || (g.requires[a] = {}), g.requires[a][b] = !0;
}
}
};
c.ENABLE_DEBUG_LOADER = !0;
c.logToConsole_ = function(a) {
c.global.console && c.global.console.error(a);
};
c.require = function() {
};
c.basePath = "";
c.nullFunction = function() {
};
c.abstractMethod = function() {
throw Error("unimplemented abstract method");
};
c.addSingletonGetter = function(a) {
a.getInstance = function() {
if (a.instance_) {
return a.instance_;
}
c.DEBUG && (c.instantiatedSingletons_[c.instantiatedSingletons_.length] = a);
return a.instance_ = new a;
};
};
c.instantiatedSingletons_ = [];
c.LOAD_MODULE_USING_EVAL = !0;
c.SEAL_MODULE_EXPORTS = c.DEBUG;
c.loadedModules_ = {};
c.DEPENDENCIES_ENABLED = !1;
c.TRANSPILE = "detect";
c.TRANSPILER = "transpile.js";
c.DEPENDENCIES_ENABLED && (c.dependencies_ = {loadFlags:{}, nameToPath:{}, requires:{}, visited:{}, written:{}, deferred:{}}, c.inHtmlDocument_ = function() {
var a = c.global.document;
return null != a && "write" in a;
}, c.findBasePath_ = function() {
if (c.isDef(c.global.CLOSURE_BASE_PATH)) {
c.basePath = c.global.CLOSURE_BASE_PATH;
} else {
if (c.inHtmlDocument_()) {
for (var a = c.global.document.getElementsByTagName("SCRIPT"), b = a.length - 1;0 <= b;--b) {
var d = a[b].src, e = d.lastIndexOf("?"), e = -1 == e ? d.length : e;
if ("base.js" == d.substr(e - 7, 7)) {
c.basePath = d.substr(0, e - 7);
break;
}
}
}
}
}, c.importScript_ = function(a, b) {
(c.global.CLOSURE_IMPORT_SCRIPT || c.writeScriptTag_)(a, b) && (c.dependencies_.written[a] = !0);
}, c.IS_OLD_IE_ = !(c.global.atob || !c.global.document || !c.global.document.all), c.importProcessedScript_ = function(a, b, d) {
c.importScript_("", 'goog.retrieveAndExec_("' + a + '", ' + b + ", " + d + ");");
}, c.queuedModules_ = [], c.wrapModule_ = function(a, b) {
return c.LOAD_MODULE_USING_EVAL && c.isDef(c.global.JSON) ? "goog.loadModule(" + c.global.JSON.stringify(b + "\n//# sourceURL=" + a + "\n") + ");" : 'goog.loadModule(function(exports) {"use strict";' + b + "\n;return exports});\n//# sourceURL=" + a + "\n";
}, c.loadQueuedModules_ = function() {
var a = c.queuedModules_.length;
if (0 < a) {
var b = c.queuedModules_;
c.queuedModules_ = [];
for (var d = 0;d < a;d++) {
c.maybeProcessDeferredPath_(b[d]);
}
}
}, c.maybeProcessDeferredDep_ = function(a) {
c.isDeferredModule_(a) && c.allDepsAreAvailable_(a) && (a = c.getPathFromDeps_(a), c.maybeProcessDeferredPath_(c.basePath + a));
}, c.isDeferredModule_ = function(a) {
var b = (a = c.getPathFromDeps_(a)) && c.dependencies_.loadFlags[a] || {}, d = b.lang || "es3";
return a && ("goog" == b.module || c.needsTranspile_(d)) ? c.basePath + a in c.dependencies_.deferred : !1;
}, c.allDepsAreAvailable_ = function(a) {
if ((a = c.getPathFromDeps_(a)) && a in c.dependencies_.requires) {
for (var b in c.dependencies_.requires[a]) {
if (!c.isProvided_(b) && !c.isDeferredModule_(b)) {
return !1;
}
}
}
return !0;
}, c.maybeProcessDeferredPath_ = function(a) {
if (a in c.dependencies_.deferred) {
var b = c.dependencies_.deferred[a];
delete c.dependencies_.deferred[a];
c.globalEval(b);
}
}, c.loadModuleFromUrl = function(a) {
c.retrieveAndExec_(a, !0, !1);
}, c.writeScriptSrcNode_ = function(a) {
c.global.document.write('<script type="text/javascript" src="' + a + '">\x3c/script>');
}, c.appendScriptSrcNode_ = function(a) {
var b = c.global.document, d = b.createElement("script");
d.type = "text/javascript";
d.src = a;
d.defer = !1;
d.async = !1;
b.head.appendChild(d);
}, c.writeScriptTag_ = function(a, b) {
if (c.inHtmlDocument_()) {
var d = c.global.document;
if (!c.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING && "complete" == d.readyState) {
if (/\bdeps.js$/.test(a)) {
return !1;
}
throw Error('Cannot write "' + a + '" after document load');
}
void 0 === b ? c.IS_OLD_IE_ ? (b = " onreadystatechange='goog.onScriptLoad_(this, " + ++c.lastNonModuleScriptIndex_ + ")' ", d.write('<script type="text/javascript" src="' + a + '"' + b + ">\x3c/script>")) : c.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING ? c.appendScriptSrcNode_(a) : c.writeScriptSrcNode_(a) : d.write('<script type="text/javascript">' + b + "\x3c/script>");
return !0;
}
return !1;
}, c.needsTranspile_ = function(a) {
if ("always" == c.TRANSPILE) {
return !0;
}
if ("never" == c.TRANSPILE) {
return !1;
}
c.requiresTranspilation_ || (c.requiresTranspilation_ = c.createRequiresTranspilation_());
if (a in c.requiresTranspilation_) {
return c.requiresTranspilation_[a];
}
throw Error("Unknown language mode: " + a);
}, c.createRequiresTranspilation_ = function() {
function a(a, b) {
e ? d[a] = !0 : b() ? d[a] = !1 : e = d[a] = !0;
}
function b(a) {
try {
return !!eval(a);
} catch (g) {
return !1;
}
}
var d = {es3:!1}, e = !1;
a("es5", function() {
return b("[1,].length==1");
});
a("es6", function() {
return b('(()=>{"use strict";class X{constructor(){if(new.target!=String)throw 1;this.x=42}}let q=Reflect.construct(X,[],String);if(q.x!=42||!(q instanceof String))throw 1;for(const a of[2,3]){if(a==2)continue;function f(z={a}){let a=0;return z.a}{function f(){return 0;}}return f()==3}})()');
});
a("es6-impl", function() {
return !0;
});
a("es7", function() {
return b("2 ** 2 == 4");
});
a("es8", function() {
return b("async () => 1, true");
});
return d;
}, c.requiresTranspilation_ = null, c.lastNonModuleScriptIndex_ = 0, c.onScriptLoad_ = function(a, b) {
"complete" == a.readyState && c.lastNonModuleScriptIndex_ == b && c.loadQueuedModules_();
return !0;
}, c.writeScripts_ = function(a) {
function b(a) {
if (!(a in f.written || a in f.visited)) {
f.visited[a] = !0;
if (a in f.requires) {
for (var g in f.requires[a]) {
if (!c.isProvided_(g)) {
if (g in f.nameToPath) {
b(f.nameToPath[g]);
} else {
throw Error("Undefined nameToPath for " + g);
}
}
}
}
a in e || (e[a] = !0, d.push(a));
}
}
var d = [], e = {}, f = c.dependencies_;
b(a);
for (a = 0;a < d.length;a++) {
var g = d[a];
c.dependencies_.written[g] = !0;
}
var h = c.moduleLoaderState_;
c.moduleLoaderState_ = null;
for (a = 0;a < d.length;a++) {
if (g = d[a]) {
var k = f.loadFlags[g] || {}, l = c.needsTranspile_(k.lang || "es3");
"goog" == k.module || l ? c.importProcessedScript_(c.basePath + g, "goog" == k.module, l) : c.importScript_(c.basePath + g);
} else {
throw c.moduleLoaderState_ = h, Error("Undefined script input");
}
}
c.moduleLoaderState_ = h;
}, c.getPathFromDeps_ = function(a) {
return a in c.dependencies_.nameToPath ? c.dependencies_.nameToPath[a] : null;
}, c.findBasePath_(), c.global.CLOSURE_NO_DEPS || c.importScript_(c.basePath + "deps.js"));
c.loadModule = function(a) {
var b = c.moduleLoaderState_;
try {
c.moduleLoaderState_ = {moduleName:void 0, declareLegacyNamespace:!1};
var d;
if (c.isFunction(a)) {
d = a.call(void 0, {});
} else {
if (c.isString(a)) {
d = c.loadModuleFromSource_.call(void 0, a);
} else {
throw Error("Invalid module definition");
}
}
var e = c.moduleLoaderState_.moduleName;
if (!c.isString(e) || !e) {
throw Error('Invalid module name "' + e + '"');
}
c.moduleLoaderState_.declareLegacyNamespace ? c.constructNamespace_(e, d) : c.SEAL_MODULE_EXPORTS && Object.seal && c.isObject(d) && Object.seal(d);
c.loadedModules_[e] = d;
} finally {
c.moduleLoaderState_ = b;
}
};
c.loadModuleFromSource_ = function(a) {
eval(a);
return {};
};
c.normalizePath_ = function(a) {
a = a.split("/");
for (var b = 0;b < a.length;) {
"." == a[b] ? a.splice(b, 1) : b && ".." == a[b] && a[b - 1] && ".." != a[b - 1] ? a.splice(--b, 2) : b++;
}
return a.join("/");
};
c.loadFileSync_ = function(a) {
if (c.global.CLOSURE_LOAD_FILE_SYNC) {
return c.global.CLOSURE_LOAD_FILE_SYNC(a);
}
try {
var b = new c.global.XMLHttpRequest;
b.open("get", a, !1);
b.send();
return 0 == b.status || 200 == b.status ? b.responseText : null;
} catch (d) {
return null;
}
};
c.retrieveAndExec_ = function() {
};
c.transpile_ = function(a, b) {
var d = c.global.$jscomp;
d || (c.global.$jscomp = d = {});
var e = d.transpile;
if (!e) {
var f = c.basePath + c.TRANSPILER, g = c.loadFileSync_(f);
if (g) {
eval(g + "\n//# sourceURL=" + f);
if (c.global.$gwtExport && c.global.$gwtExport.$jscomp && !c.global.$gwtExport.$jscomp.transpile) {
throw Error('The transpiler did not properly export the "transpile" method. $gwtExport: ' + JSON.stringify(c.global.$gwtExport));
}
c.global.$jscomp.transpile = c.global.$gwtExport.$jscomp.transpile;
d = c.global.$jscomp;
e = d.transpile;
}
}
e || (e = d.transpile = function(a, b) {
c.logToConsole_(b + " requires transpilation but no transpiler was found.");
return a;
});
return e(a, b);
};
c.typeOf = function(a) {
var b = typeof a;
if ("object" == b) {
if (a) {
if (a instanceof Array) {
return "array";
}
if (a instanceof Object) {
return b;
}
var d = Object.prototype.toString.call(a);
if ("[object Window]" == d) {
return "object";
}
if ("[object Array]" == d || "number" == typeof a.length && "undefined" != typeof a.splice && "undefined" != typeof a.propertyIsEnumerable && !a.propertyIsEnumerable("splice")) {
return "array";
}
if ("[object Function]" == d || "undefined" != typeof a.call && "undefined" != typeof a.propertyIsEnumerable && !a.propertyIsEnumerable("call")) {
return "function";
}
} else {
return "null";
}
} else {
if ("function" == b && "undefined" == typeof a.call) {
return "object";
}
}
return b;
};
c.isNull = function(a) {
return null === a;
};
c.isDefAndNotNull = function(a) {
return null != a;
};
c.isArray = function(a) {
return "array" == c.typeOf(a);
};
c.isArrayLike = function(a) {
var b = c.typeOf(a);
return "array" == b || "object" == b && "number" == typeof a.length;
};
c.isDateLike = function(a) {
return c.isObject(a) && "function" == typeof a.getFullYear;
};
c.isString = function(a) {
return "string" == typeof a;
};
c.isBoolean = function(a) {
return "boolean" == typeof a;
};
c.isNumber = function(a) {
return "number" == typeof a;
};
c.isFunction = function(a) {
return "function" == c.typeOf(a);
};
c.isObject = function(a) {
var b = typeof a;
return "object" == b && null != a || "function" == b;
};
c.getUid = function(a) {
return a[c.UID_PROPERTY_] || (a[c.UID_PROPERTY_] = ++c.uidCounter_);
};
c.hasUid = function(a) {
return !!a[c.UID_PROPERTY_];
};
c.removeUid = function(a) {
null !== a && "removeAttribute" in a && a.removeAttribute(c.UID_PROPERTY_);
try {
delete a[c.UID_PROPERTY_];
} catch (b) {
}
};
c.UID_PROPERTY_ = "closure_uid_" + (1E9 * Math.random() >>> 0);
c.uidCounter_ = 0;
c.getHashCode = c.getUid;
c.removeHashCode = c.removeUid;
c.cloneObject = function(a) {
var b = c.typeOf(a);
if ("object" == b || "array" == b) {
if (a.clone) {
return a.clone();
}
var b = "array" == b ? [] : {}, d;
for (d in a) {
b[d] = c.cloneObject(a[d]);
}
return b;
}
return a;
};
c.bindNative_ = function(a, b, d) {
return a.call.apply(a.bind, arguments);
};
c.bindJs_ = function(a, b, d) {
if (!a) {
throw Error();
}
if (2 < arguments.length) {
var e = Array.prototype.slice.call(arguments, 2);
return function() {
var d = Array.prototype.slice.call(arguments);
Array.prototype.unshift.apply(d, e);
return a.apply(b, d);
};
}
return function() {
return a.apply(b, arguments);
};
};
c.bind = function(a, b, d) {
Function.prototype.bind && -1 != Function.prototype.bind.toString().indexOf("native code") ? c.bind = c.bindNative_ : c.bind = c.bindJs_;
return c.bind.apply(null, arguments);
};
c.partial = function(a, b) {
var d = Array.prototype.slice.call(arguments, 1);
return function() {
var b = d.slice();
b.push.apply(b, arguments);
return a.apply(this, b);
};
};
c.mixin = function(a, b) {
for (var d in b) {
a[d] = b[d];
}
};
c.now = c.TRUSTED_SITE && Date.now || function() {
return +new Date;
};
c.globalEval = function(a) {
if (c.global.execScript) {
c.global.execScript(a, "JavaScript");
} else {
if (c.global.eval) {
if (null == c.evalWorksForGlobals_) {
if (c.global.eval("var _evalTest_ = 1;"), "undefined" != typeof c.global._evalTest_) {
try {
delete c.global._evalTest_;
} catch (e) {
}
c.evalWorksForGlobals_ = !0;
} else {
c.evalWorksForGlobals_ = !1;
}
}
if (c.evalWorksForGlobals_) {
c.global.eval(a);
} else {
var b = c.global.document, d = b.createElement("SCRIPT");
d.type = "text/javascript";
d.defer = !1;
d.appendChild(b.createTextNode(a));
b.body.appendChild(d);
b.body.removeChild(d);
}
} else {
throw Error("goog.globalEval not available");
}
}
};
c.evalWorksForGlobals_ = null;
c.getCssName = function(a, b) {
function d(a) {
a = a.split("-");
for (var b = [], d = 0;d < a.length;d++) {
b.push(e(a[d]));
}
return b.join("-");
}
function e(a) {
return c.cssNameMapping_[a] || a;
}
if ("." == String(a).charAt(0)) {
throw Error('className passed in goog.getCssName must not start with ".". You passed: ' + a);
}
var f;
f = c.cssNameMapping_ ? "BY_WHOLE" == c.cssNameMappingStyle_ ? e : d : function(a) {
return a;
};
a = b ? a + "-" + f(b) : f(a);
return c.global.CLOSURE_CSS_NAME_MAP_FN ? c.global.CLOSURE_CSS_NAME_MAP_FN(a) : a;
};
c.setCssNameMapping = function(a, b) {
c.cssNameMapping_ = a;
c.cssNameMappingStyle_ = b;
};
c.getMsg = function(a, b) {
b && (a = a.replace(/\{\$([^}]+)}/g, function(a, e) {
return null != b && e in b ? b[e] : a;
}));
return a;
};
c.getMsgWithFallback = function(a) {
return a;
};
c.exportSymbol = function(a, b, d) {
c.exportPath_(a, b, d);
};
c.exportProperty = function(a, b, d) {
a[b] = d;
};
c.inherits = function(a, b) {
function d() {
}
d.prototype = b.prototype;
a.superClass_ = b.prototype;
a.prototype = new d;
a.prototype.constructor = a;
a.base = function(a, d, g) {
for (var e = Array(arguments.length - 2), f = 2;f < arguments.length;f++) {
e[f - 2] = arguments[f];
}
return b.prototype[d].apply(a, e);
};
};
c.base = function(a, b, d) {
var e = arguments.callee.caller;
if (c.STRICT_MODE_COMPATIBLE || c.DEBUG && !e) {
throw Error("arguments.caller not defined. goog.base() cannot be used with strict mode code. See http://www.ecma-international.org/ecma-262/5.1/#sec-C");
}
if (e.superClass_) {
for (var f = Array(arguments.length - 1), g = 1;g < arguments.length;g++) {
f[g - 1] = arguments[g];
}
return e.superClass_.constructor.apply(a, f);
}
f = Array(arguments.length - 2);
for (g = 2;g < arguments.length;g++) {
f[g - 2] = arguments[g];
}
for (var g = !1, h = a.constructor;h;h = h.superClass_ && h.superClass_.constructor) {
if (h.prototype[b] === e) {
g = !0;
} else {
if (g) {
return h.prototype[b].apply(a, f);
}
}
}
if (a[b] === e) {
return a.constructor.prototype[b].apply(a, f);
}
throw Error("goog.base called from a method of one name to a method of a different name");
};
c.scope = function(a) {
if (c.isInModuleLoader_()) {
throw Error("goog.scope is not supported within a goog.module.");
}
a.call(c.global);
};
c.defineClass = function(a, b) {
var d = b.constructor, e = b.statics;
d && d != Object.prototype.constructor || (d = function() {
throw Error("cannot instantiate an interface (no constructor defined).");
});
d = c.defineClass.createSealingConstructor_(d, a);
a && c.inherits(d, a);
delete b.constructor;
delete b.statics;
c.defineClass.applyProperties_(d.prototype, b);
null != e && (e instanceof Function ? e(d) : c.defineClass.applyProperties_(d, e));
return d;
};
c.defineClass.SEAL_CLASS_INSTANCES = c.DEBUG;
c.defineClass.createSealingConstructor_ = function(a, b) {
function d() {
var b = a.apply(this, arguments) || this;
b[c.UID_PROPERTY_] = b[c.UID_PROPERTY_];
this.constructor === d && e && Object.seal instanceof Function && Object.seal(b);
return b;
}
if (!c.defineClass.SEAL_CLASS_INSTANCES) {
return a;
}
var e = !c.defineClass.isUnsealable_(b);
return d;
};
c.defineClass.isUnsealable_ = function(a) {
return a && a.prototype && a.prototype[c.UNSEALABLE_CONSTRUCTOR_PROPERTY_];
};
c.defineClass.OBJECT_PROTOTYPE_FIELDS_ = "constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");
c.defineClass.applyProperties_ = function(a, b) {
for (var d in b) {
Object.prototype.hasOwnProperty.call(b, d) && (a[d] = b[d]);
}
for (var e = 0;e < c.defineClass.OBJECT_PROTOTYPE_FIELDS_.length;e++) {
d = c.defineClass.OBJECT_PROTOTYPE_FIELDS_[e], Object.prototype.hasOwnProperty.call(b, d) && (a[d] = b[d]);
}
};
c.tagUnsealableClass = function() {
};
c.UNSEALABLE_CONSTRUCTOR_PROPERTY_ = "goog_defineClass_legacy_unsealable";
var q = {UnderscoreForm:{CONSTANT:"constant", LEADING:"leading", NO_UNDERSCORE:"no_underscore", MIDDLE:"middle", OPT_PREFIX:"opt_prefix", TRAILING:"trailing", VAR_ARGS:"var_args"}};
function v(a, b) {
return a.loc.end.line === b.loc.start.line;
}
var w = {categorizeUnderscoredIdentifier:function(a) {
return "" === a || 0 === a.length ? q.UnderscoreForm.NO_UNDERSCORE : a.toUpperCase() === a ? q.UnderscoreForm.CONSTANT : -1 === a.indexOf("_") ? q.UnderscoreForm.NO_UNDERSCORE : "var_args" === a ? q.UnderscoreForm.VAR_ARGS : "opt_" === a.substring(0, 4) && "opt_" != a ? q.UnderscoreForm.OPT_PREFIX : "_" === a[0] ? q.UnderscoreForm.LEADING : "_" === a[a.length - 1] ? q.UnderscoreForm.TRAILING : q.UnderscoreForm.MIDDLE;
}, escapeRegexp:function(a) {
return String(a).replace(/[\\^$*+?.()|[\]{}]/g, "\\$&");
}, isUnderscored:function(a) {
return -1 < a.indexOf("_");
}, isNodeConstructorFunction:function(a) {
return "FunctionExpression" === a.type && a.parent && "MethodDefinition" === a.parent.type && "constructor" === a.parent.kind;
}, isNodeClassType:function(a) {
return "ClassExpression" === a.type || "ClassDeclaration" === a.type;
}, isNodeGetterFunction:function(a) {
return "FunctionExpression" === a.type && a.parent && "Property" === a.parent.type && "get" === a.parent.kind;
}, isNodeOneLine:function(a) {
return v(a, a);
}, isNodeSetterFunction:function(a) {
return "FunctionExpression" === a.type && a.parent && "Property" === a.parent.type && "set" === a.parent.kind;
}, isValidPrefix:function(a, b) {
return a.startsWith(b) ? a === b || "." === a[b.length] : !1;
}, isTruthy:function(a) {
return !!a;
}, nodesEndOnSameLine:function(a, b) {
return a.loc.end.line === b.loc.end.line;
}, nodesShareOneLine:v, nodesStartOnSameLine:function(a, b) {
return a.loc.start.line === b.loc.start.line;
}};
var y = {allowVarArgs:!1, allowOptPrefix:!1, allowLeadingUnderscore:!0, allowTrailingUnderscore:!0, checkObjectProperties:!0};
function z(a, b) {
function d(a) {
return Object.assign(g, {message:a});
}
function e(e, g) {
return A(e, a, b) ? f : d(g);
}
var f = {node:a, message:"", hasError:!1}, g = {node:a, message:"", hasError:!0};
switch(w.categorizeUnderscoredIdentifier(a.name)) {
case q.UnderscoreForm.CONSTANT:
return f;
case q.UnderscoreForm.LEADING:
return b.allowLeadingUnderscore ? e(a.name.replace(/^_+/g, "").replace(/_+$/g, ""), "Identifier '" + a.name + "' is not in camel case after the leading underscore.") : d("Leading underscores are not allowed in '" + a.name + "'.");
case q.UnderscoreForm.NO_UNDERSCORE:
return f;
case q.UnderscoreForm.MIDDLE:
return e(a.name, "Identifier '" + a.name + "' is not in camel case.");
case q.UnderscoreForm.OPT_PREFIX:
return b.allowOptPrefix ? e(a.name.replace(/^opt_/g, ""), "Identifier '" + a.name + "' is not in camel case after the opt_ prefix.") : d("The opt_ prefix is not allowed in '" + a.name + "'.");
case q.UnderscoreForm.TRAILING:
return b.allowTrailingUnderscore ? e(a.name.replace(/^_+/g, "").replace(/_+$/g, ""), "Identifier '" + a.name + "' is not in camel case before the trailing underscore.") : d("Trailing underscores are not allowed in '" + a.name + "'.");
case q.UnderscoreForm.VAR_ARGS:
return b.allowVarArgs ? f : d("The var_args identifier is not allowed.");
default:
throw Error("Unknown undercore form: " + a.name);
}
}
function A(a, b, d) {
var e = b.parent;
if (!w.isUnderscored(a)) {
return !0;
}
switch(e.type) {
case "MemberExpression":
e = b.parent;
if (!d.checkObjectProperties) {
return !0;
}
if (e.property === b) {
return e.parent && "AssignmentExpression" === e.parent.type ? e.parent.right === e : !0;
}
break;
case "Property":
e = b.parent;
if (!d.checkObjectProperties || e.parent && "ObjectPattern" === e.parent.type && e.key === b && e.value !== b) {
return !0;
}
break;
case "CallExpression":
return !0;
}
return !1;
}
;c.debug = {};
c.debug.Error = function(a) {
if (Error.captureStackTrace) {
Error.captureStackTrace(this, c.debug.Error);
} else {
var b = Error().stack;
b && (this.stack = b);
}
a && (this.message = String(a));
this.reportErrorToServer = !0;
};
c.inherits(c.debug.Error, Error);
c.debug.Error.prototype.name = "CustomError";
c.dom = {};
c.dom.NodeType = {ELEMENT:1, ATTRIBUTE:2, TEXT:3, CDATA_SECTION:4, ENTITY_REFERENCE:5, ENTITY:6, PROCESSING_INSTRUCTION:7, COMMENT:8, DOCUMENT:9, DOCUMENT_TYPE:10, DOCUMENT_FRAGMENT:11, NOTATION:12};
c.string = {};
c.string.DETECT_DOUBLE_ESCAPING = !1;
c.string.FORCE_NON_DOM_HTML_UNESCAPING = !1;
c.string.Unicode = {NBSP:"\u00a0"};
c.string.startsWith = function(a, b) {
return 0 == a.lastIndexOf(b, 0);
};
c.string.endsWith = function(a, b) {
var d = a.length - b.length;
return 0 <= d && a.indexOf(b, d) == d;
};
c.string.caseInsensitiveStartsWith = function(a, b) {
return 0 == c.string.caseInsensitiveCompare(b, a.substr(0, b.length));
};
c.string.caseInsensitiveEndsWith = function(a, b) {
return 0 == c.string.caseInsensitiveCompare(b, a.substr(a.length - b.length, b.length));
};
c.string.caseInsensitiveEquals = function(a, b) {
return a.toLowerCase() == b.toLowerCase();
};
c.string.subs = function(a, b) {
for (var d = a.split("%s"), e = "", f = Array.prototype.slice.call(arguments, 1);f.length && 1 < d.length;) {
e += d.shift() + f.shift();
}
return e + d.join("%s");
};
c.string.collapseWhitespace = function(a) {
return a.replace(/[\s\xa0]+/g, " ").replace(/^\s+|\s+$/g, "");
};
c.string.isEmptyOrWhitespace = function(a) {
return /^[\s\xa0]*$/.test(a);
};
c.string.isEmptyString = function(a) {
return 0 == a.length;
};
c.string.isEmpty = c.string.isEmptyOrWhitespace;
c.string.isEmptyOrWhitespaceSafe = function(a) {
return c.string.isEmptyOrWhitespace(c.string.makeSafe(a));
};
c.string.isEmptySafe = c.string.isEmptyOrWhitespaceSafe;
c.string.isBreakingWhitespace = function(a) {
return !/[^\t\n\r ]/.test(a);
};
c.string.isAlpha = function(a) {
return !/[^a-zA-Z]/.test(a);
};
c.string.isNumeric = function(a) {
return !/[^0-9]/.test(a);
};
c.string.isAlphaNumeric = function(a) {
return !/[^a-zA-Z0-9]/.test(a);
};
c.string.isSpace = function(a) {
return " " == a;
};
c.string.isUnicodeChar = function(a) {
return 1 == a.length && " " <= a && "~" >= a || "\u0080" <= a && "\ufffd" >= a;
};
c.string.stripNewlines = function(a) {
return a.replace(/(\r\n|\r|\n)+/g, " ");
};
c.string.canonicalizeNewlines = function(a) {
return a.replace(/(\r\n|\r|\n)/g, "\n");
};
c.string.normalizeWhitespace = function(a) {
return a.replace(/\xa0|\s/g, " ");
};
c.string.normalizeSpaces = function(a) {
return a.replace(/\xa0|[ \t]+/g, " ");
};
c.string.collapseBreakingSpaces = function(a) {
return a.replace(/[\t\r\n ]+/g, " ").replace(/^[\t\r\n ]+|[\t\r\n ]+$/g, "");
};
c.string.trim = c.TRUSTED_SITE && String.prototype.trim ? function(a) {
return a.trim();
} : function(a) {
return a.replace(/^[\s\xa0]+|[\s\xa0]+$/g, "");
};
c.string.trimLeft = function(a) {
return a.replace(/^[\s\xa0]+/, "");
};
c.string.trimRight = function(a) {
return a.replace(/[\s\xa0]+$/, "");
};
c.string.caseInsensitiveCompare = function(a, b) {
a = String(a).toLowerCase();
b = String(b).toLowerCase();
return a < b ? -1 : a == b ? 0 : 1;
};
c.string.numberAwareCompare_ = function(a, b, d) {
if (a == b) {
return 0;
}
if (!a) {
return -1;
}
if (!b) {
return 1;
}
for (var e = a.toLowerCase().match(d), f = b.toLowerCase().match(d), g = Math.min(e.length, f.length), h = 0;h < g;h++) {
d = e[h];
var k = f[h];
if (d != k) {
return a = parseInt(d, 10), !isNaN(a) && (b = parseInt(k, 10), !isNaN(b) && a - b) ? a - b : d < k ? -1 : 1;
}
}
return e.length != f.length ? e.length - f.length : a < b ? -1 : 1;
};
c.string.intAwareCompare = function(a, b) {
return c.string.numberAwareCompare_(a, b, /\d+|\D+/g);
};
c.string.floatAwareCompare = function(a, b) {
return c.string.numberAwareCompare_(a, b, /\d+|\.\d+|\D+/g);
};
c.string.numerateCompare = c.string.floatAwareCompare;
c.string.urlEncode = function(a) {
return encodeURIComponent(String(a));
};
c.string.urlDecode = function(a) {
return decodeURIComponent(a.replace(/\+/g, " "));
};
c.string.newLineToBr = function(a, b) {
return a.replace(/(\r\n|\r|\n)/g, b ? "<br />" : "<br>");
};
c.string.htmlEscape = function(a, b) {
if (b) {
a = a.replace(c.string.AMP_RE_, "&").replace(c.string.LT_RE_, "<").replace(c.string.GT_RE_, ">").replace(c.string.QUOT_RE_, """).replace(c.string.SINGLE_QUOTE_RE_, "'").replace(c.string.NULL_RE_, "�"), c.string.DETECT_DOUBLE_ESCAPING && (a = a.replace(c.string.E_RE_, "e"));
} else {
if (!c.string.ALL_RE_.test(a)) {
return a;
}
-1 != a.indexOf("&") && (a = a.replace(c.string.AMP_RE_, "&"));
-1 != a.indexOf("<") && (a = a.replace(c.string.LT_RE_, "<"));
-1 != a.indexOf(">") && (a = a.replace(c.string.GT_RE_, ">"));
-1 != a.indexOf('"') && (a = a.replace(c.string.QUOT_RE_, """));
-1 != a.indexOf("'") && (a = a.replace(c.string.SINGLE_QUOTE_RE_, "'"));
-1 != a.indexOf("\x00") && (a = a.replace(c.string.NULL_RE_, "�"));
c.string.DETECT_DOUBLE_ESCAPING && -1 != a.indexOf("e") && (a = a.replace(c.string.E_RE_, "e"));
}
return a;
};
c.string.AMP_RE_ = /&/g;
c.string.LT_RE_ = /</g;
c.string.GT_RE_ = />/g;
c.string.QUOT_RE_ = /"/g;
c.string.SINGLE_QUOTE_RE_ = /'/g;
c.string.NULL_RE_ = /\x00/g;
c.string.E_RE_ = /e/g;
c.string.ALL_RE_ = c.string.DETECT_DOUBLE_ESCAPING ? /[\x00&<>"'e]/ : /[\x00&<>"']/;
c.string.unescapeEntities = function(a) {
return c.string.contains(a, "&") ? !c.string.FORCE_NON_DOM_HTML_UNESCAPING && "document" in c.global ? c.string.unescapeEntitiesUsingDom_(a) : c.string.unescapePureXmlEntities_(a) : a;
};
c.string.unescapeEntitiesWithDocument = function(a, b) {
return c.string.contains(a, "&") ? c.string.unescapeEntitiesUsingDom_(a, b) : a;
};
c.string.unescapeEntitiesUsingDom_ = function(a, b) {
var d = {"&":"&", "<":"<", ">":">", """:'"'}, e;
e = b ? b.createElement("div") : c.global.document.createElement("div");
return a.replace(c.string.HTML_ENTITY_PATTERN_, function(a, b) {
var f = d[a];
if (f) {
return f;
}
"#" == b.charAt(0) && (b = Number("0" + b.substr(1)), isNaN(b) || (f = String.fromCharCode(b)));
f || (e.innerHTML = a + " ", f = e.firstChild.nodeValue.slice(0, -1));
return d[a] = f;
});
};
c.string.unescapePureXmlEntities_ = function(a) {
return a.replace(/&([^;]+);/g, function(a, d) {
switch(d) {
case "amp":
return "&";
case "lt":
return "<";
case "gt":
return ">";
case "quot":
return '"';
default:
return "#" != d.charAt(0) || (d = Number("0" + d.substr(1)), isNaN(d)) ? a : String.fromCharCode(d);
}
});
};
c.string.HTML_ENTITY_PATTERN_ = /&([^;\s<&]+);?/g;
c.string.whitespaceEscape = function(a, b) {
return c.string.newLineToBr(a.replace(/ /g, "  "), b);
};
c.string.preserveSpaces = function(a) {
return a.replace(/(^|[\n ]) /g, "$1" + c.string.Unicode.NBSP);
};
c.string.stripQuotes = function(a, b) {
for (var d = b.length, e = 0;e < d;e++) {
var f = 1 == d ? b : b.charAt(e);
if (a.charAt(0) == f && a.charAt(a.length - 1) == f) {
return a.substring(1, a.length - 1);
}
}
return a;
};
c.string.truncate = function(a, b, d) {
d && (a = c.string.unescapeEntities(a));
a.length > b && (a = a.substring(0, b - 3) + "...");
d && (a = c.string.htmlEscape(a));
return a;
};
c.string.truncateMiddle = function(a, b, d, e) {
d && (a = c.string.unescapeEntities(a));
if (e && a.length > b) {
e > b && (e = b);
var f = a.length - e;
a = a.substring(0, b - e) + "..." + a.substring(f);
} else {
a.length > b && (e = Math.floor(b / 2), f = a.length - e, a = a.substring(0, e + b % 2) + "..." + a.substring(f));
}
d && (a = c.string.htmlEscape(a));
return a;
};
c.string.specialEscapeChars_ = {"\x00":"\\0", "\b":"\\b", "\f":"\\f", "\n":"\\n", "\r":"\\r", "\t":"\\t", "\x0B":"\\x0B", '"':'\\"', "\\":"\\\\", "<":"<"};
c.string.jsEscapeCache_ = {"'":"\\'"};
c.string.quote = function(a) {
a = String(a);
for (var b = ['"'], d = 0;d < a.length;d++) {
var e = a.charAt(d), f = e.charCodeAt(0);
b[d + 1] = c.string.specialEscapeChars_[e] || (31 < f && 127 > f ? e : c.string.escapeChar(e));
}
b.push('"');
return b.join("");
};
c.string.escapeString = function(a) {
for (var b = [], d = 0;d < a.length;d++) {
b[d] = c.string.escapeChar(a.charAt(d));
}
return b.join("");
};
c.string.escapeChar = function(a) {
if (a in c.string.jsEscapeCache_) {
return c.string.jsEscapeCache_[a];
}
if (a in c.string.specialEscapeChars_) {
return c.string.jsEscapeCache_[a] = c.string.specialEscapeChars_[a];
}
var b, d = a.charCodeAt(0);
if (31 < d && 127 > d) {
b = a;
} else {
if (256 > d) {
if (b = "\\x", 16 > d || 256 < d) {
b += "0";
}
} else {
b = "\\u", 4096 > d && (b += "0");
}
b += d.toString(16).toUpperCase();
}
return c.string.jsEscapeCache_[a] = b;
};
c.string.contains = function(a, b) {
return -1 != a.indexOf(b);
};
c.string.caseInsensitiveContains = function(a, b) {
return c.string.contains(a.toLowerCase(), b.toLowerCase());
};
c.string.countOf = function(a, b) {
return a && b ? a.split(b).length - 1 : 0;
};
c.string.removeAt = function(a, b, d) {
var e = a;
0 <= b && b < a.length && 0 < d && (e = a.substr(0, b) + a.substr(b + d, a.length - b - d));
return e;
};
c.string.remove = function(a, b) {
return a.replace(b, "");
};
c.string.removeAll = function(a, b) {
b = new RegExp(c.string.regExpEscape(b), "g");
return a.replace(b, "");
};
c.string.replaceAll = function(a, b, d) {
b = new RegExp(c.string.regExpEscape(b), "g");
return a.replace(b, d.replace(/\$/g, "$$$$"));
};
c.string.regExpEscape = function(a) {
return String(a).replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, "\\$1").replace(/\x08/g, "\\x08");
};
c.string.repeat = String.prototype.repeat ? function(a, b) {
return a.repeat(b);
} : function(a, b) {
return Array(b + 1).join(a);
};
c.string.padNumber = function(a, b, d) {
a = c.isDef(d) ? a.toFixed(d) : String(a);
d = a.indexOf(".");
-1 == d && (d = a.length);
return c.string.repeat("0", Math.max(0, b - d)) + a;
};
c.string.makeSafe = function(a) {
return null == a ? "" : String(a);
};
c.string.buildString = function(a) {
return Array.prototype.join.call(arguments, "");
};
c.string.getRandomString = function() {
return Math.floor(2147483648 * Math.random()).toString(36) + Math.abs(Math.floor(2147483648 * Math.random()) ^ c.now()).toString(36);
};
c.string.compareVersions = function(a, b) {
var d = 0;
a = c.string.trim(String(a)).split(".");
b = c.string.trim(String(b)).split(".");
for (var e = Math.max(a.length, b.length), f = 0;0 == d && f < e;f++) {
var g = a[f] || "", h = b[f] || "";
do {
g = /(\d*)(\D*)(.*)/.exec(g) || ["", "", "", ""];
h = /(\d*)(\D*)(.*)/.exec(h) || ["", "", "", ""];
if (0 == g[0].length && 0 == h[0].length) {
break;
}
var d = 0 == g[1].length ? 0 : parseInt(g[1], 10), k = 0 == h[1].length ? 0 : parseInt(h[1], 10), d = c.string.compareElements_(d, k) || c.string.compareElements_(0 == g[2].length, 0 == h[2].length) || c.string.compareElements_(g[2], h[2]), g = g[3], h = h[3];
} while (0 == d);
}
return d;
};
c.string.compareElements_ = function(a, b) {
return a < b ? -1 : a > b ? 1 : 0;
};
c.string.hashCode = function(a) {
for (var b = 0, d = 0;d < a.length;++d) {
b = 31 * b + a.charCodeAt(d) >>> 0;
}
return b;
};
c.string.uniqueStringCounter_ = 2147483648 * Math.random() | 0;
c.string.createUniqueString = function() {
return "goog_" + c.string.uniqueStringCounter_++;
};
c.string.toNumber = function(a) {
var b = Number(a);
return 0 == b && c.string.isEmptyOrWhitespace(a) ? NaN : b;
};
c.string.isLowerCamelCase = function(a) {
return /^[a-z]+([A-Z][a-z]*)*$/.test(a);
};
c.string.isUpperCamelCase = function(a) {
return /^([A-Z][a-z]*)+$/.test(a);
};
c.string.toCamelCase = function(a) {
return String(a).replace(/\-([a-z])/g, function(a, d) {
return d.toUpperCase();
});
};
c.string.toSelectorCase = function(a) {
return String(a).replace(/([A-Z])/g, "-$1").toLowerCase();
};
c.string.toTitleCase = function(a, b) {
b = c.isString(b) ? c.string.regExpEscape(b) : "\\s";
return a.replace(new RegExp("(^" + (b ? "|[" + b + "]+" : "") + ")([a-z])", "g"), function(a, b, f) {
return b + f.toUpperCase();
});
};
c.string.capitalize = function(a) {
return String(a.charAt(0)).toUpperCase() + String(a.substr(1)).toLowerCase();
};
c.string.parseInt = function(a) {
isFinite(a) && (a = String(a));
return c.isString(a) ? /^\s*-?0x/i.test(a) ? parseInt(a, 16) : parseInt(a, 10) : NaN;
};
c.string.splitLimit = function(a, b, d) {
a = a.split(b);
for (var e = [];0 < d && a.length;) {
e.push(a.shift()), d--;
}
a.length && e.push(a.join(b));
return e;
};
c.string.lastComponent = function(a, b) {
if (b) {
"string" == typeof b && (b = [b]);
} else {
return a;
}
for (var d = -1, e = 0;e < b.length;e++) {
if ("" != b[e]) {
var f = a.lastIndexOf(b[e]);
f > d && (d = f);
}
}
return -1 == d ? a : a.slice(d + 1);
};
c.string.editDistance = function(a, b) {
var d = [], e = [];
if (a == b) {
return 0;
}
if (!a.length || !b.length) {
return Math.max(a.length, b.length);
}
for (var f = 0;f < b.length + 1;f++) {
d[f] = f;
}
for (f = 0;f < a.length;f++) {
e[0] = f + 1;
for (var g = 0;g < b.length;g++) {
e[g + 1] = Math.min(e[g] + 1, d[g + 1] + 1, d[g] + Number(a[f] != b[g]));
}
for (g = 0;g < d.length;g++) {
d[g] = e[g];
}
}
return e[b.length];
};
c.asserts = {};
c.asserts.ENABLE_ASSERTS = c.DEBUG;
c.asserts.AssertionError = function(a, b) {
b.unshift(a);
c.debug.Error.call(this, c.string.subs.apply(null, b));
b.shift();
this.messagePattern = a;
};
c.inherits(c.asserts.AssertionError, c.debug.Error);
c.asserts.AssertionError.prototype.name = "AssertionError";
c.asserts.DEFAULT_ERROR_HANDLER = function(a) {
throw a;
};
c.asserts.errorHandler_ = c.asserts.DEFAULT_ERROR_HANDLER;
c.asserts.doAssertFailure_ = function(a, b, d, e) {
var f = "Assertion failed";
if (d) {
var f = f + (": " + d), g = e;
} else {
a && (f += ": " + a, g = b);
}
a = new c.asserts.AssertionError("" + f, g || []);
c.asserts.errorHandler_(a);
};
c.asserts.setErrorHandler = function(a) {
c.asserts.ENABLE_ASSERTS && (c.asserts.errorHandler_ = a);
};
c.asserts.assert = function(a, b, d) {
c.asserts.ENABLE_ASSERTS && !a && c.asserts.doAssertFailure_("", null, b, Array.prototype.slice.call(arguments, 2));
return a;
};
c.asserts.fail = function(a, b) {
c.asserts.ENABLE_ASSERTS && c.asserts.errorHandler_(new c.asserts.AssertionError("Failure" + (a ? ": " + a : ""), Array.prototype.slice.call(arguments, 1)));
};
c.asserts.assertNumber = function(a, b, d) {
c.asserts.ENABLE_ASSERTS && !c.isNumber(a) && c.asserts.doAssertFailure_("Expected number but got %s: %s.", [c.typeOf(a), a], b, Array.prototype.slice.call(arguments, 2));
return a;
};
c.asserts.assertString = function(a, b, d) {
c.asserts.ENABLE_ASSERTS && !c.isString(a) && c.asserts.doAssertFailure_("Expected string but got %s: %s.", [c.typeOf(a), a], b, Array.prototype.slice.call(arguments, 2));
return a;
};
c.asserts.assertFunction = function(a, b, d) {
c.asserts.ENABLE_ASSERTS && !c.isFunction(a) && c.asserts.doAssertFailure_("Expected function but got %s: %s.", [c.typeOf(a), a], b, Array.prototype.slice.call(arguments, 2));
return a;
};
c.asserts.assertObject = function(a, b, d) {
c.asserts.ENABLE_ASSERTS && !c.isObject(a) && c.asserts.doAssertFailure_("Expected object but got %s: %s.", [c.typeOf(a), a], b, Array.prototype.slice.call(arguments, 2));
return a;
};
c.asserts.assertArray = function(a, b, d) {
c.asserts.ENABLE_ASSERTS && !c.isArray(a) && c.asserts.doAssertFailure_("Expected array but got %s: %s.", [c.typeOf(a), a], b, Array.prototype.slice.call(arguments, 2));
return a;
};
c.asserts.assertBoolean = function(a, b, d) {
c.asserts.ENABLE_ASSERTS && !c.isBoolean(a) && c.asserts.doAssertFailure_("Expected boolean but got %s: %s.", [c.typeOf(a), a], b, Array.prototype.slice.call(arguments, 2));
return a;
};
c.asserts.assertElement = function(a, b, d) {
!c.asserts.ENABLE_ASSERTS || c.isObject(a) && a.nodeType == c.dom.NodeType.ELEMENT || c.asserts.doAssertFailure_("Expected Element but got %s: %s.", [c.typeOf(a), a], b, Array.prototype.slice.call(arguments, 2));
return a;
};
c.asserts.assertInstanceof = function(a, b, d, e) {
!c.asserts.ENABLE_ASSERTS || a instanceof b || c.asserts.doAssertFailure_("Expected instanceof %s but got %s.", [c.asserts.getType_(b), c.asserts.getType_(a)], d, Array.prototype.slice.call(arguments, 3));
return a;
};
c.asserts.assertObjectPrototypeIsIntact = function() {
for (var a in Object.prototype) {
c.asserts.fail(a + " should not be enumerable in Object.prototype.");
}
};
c.asserts.getType_ = function(a) {
return a instanceof Function ? a.displayName || a.name || "unknown type name" : a instanceof Object ? a.constructor.displayName || a.constructor.name || Object.prototype.toString.call(a) : null === a ? "null" : typeof a;
};
c.functions = {};
c.functions.constant = function(a) {
return function() {
return a;
};
};
c.functions.FALSE = c.functions.constant(!1);
c.functions.TRUE = c.functions.constant(!0);
c.functions.NULL = c.functions.constant(null);
c.functions.identity = function(a) {
return a;
};
c.functions.error = function(a) {
return function() {
throw Error(a);
};
};
c.functions.fail = function(a) {
return function() {
throw a;
};
};
c.functions.lock = function(a, b) {
b = b || 0;
return function() {
return a.apply(this, Array.prototype.slice.call(arguments, 0, b));
};
};
c.functions.nth = function(a) {
return function() {
return arguments[a];
};
};
c.functions.partialRight = function(a, b) {
var d = Array.prototype.slice.call(arguments, 1);
return function() {
var b = Array.prototype.slice.call(arguments);
b.push.apply(b, d);
return a.apply(this, b);
};
};
c.functions.withReturnValue = function(a, b) {
return c.functions.sequence(a, c.functions.constant(b));
};
c.functions.equalTo = function(a, b) {
return function(d) {
return b ? a == d : a === d;
};
};
c.functions.compose = function(a, b) {
var d = arguments, e = d.length;
return function() {
var a;
e && (a = d[e - 1].apply(this, arguments));
for (var b = e - 2;0 <= b;b--) {
a = d[b].call(this, a);
}
return a;
};
};
c.functions.sequence = function(a) {
var b = arguments, d = b.length;
return function() {
for (var a, f = 0;f < d;f++) {
a = b[f].apply(this, arguments);
}
return a;
};
};
c.functions.and = function(a) {
var b = arguments, d = b.length;
return function() {
for (var a = 0;a < d;a++) {
if (!b[a].apply(this, arguments)) {
return !1;
}
}
return !0;
};
};
c.functions.or = function(a) {
var b = arguments, d = b.length;
return function() {
for (var a = 0;a < d;a++) {
if (b[a].apply(this, arguments)) {
return !0;
}
}
return !1;
};
};
c.functions.not = function(a) {
return function() {
return !a.apply(this, arguments);
};
};
c.functions.create = function(a, b) {
function d() {
}
d.prototype = a.prototype;
var e = new d;
a.apply(e, Array.prototype.slice.call(arguments, 1));
return e;
};
c.functions.CACHE_RETURN_VALUE = !0;
c.functions.cacheReturnValue = function(a) {
var b = !1, d;
return function() {
if (!c.functions.CACHE_RETURN_VALUE) {
return a();
}
b || (d = a(), b = !0);
return d;
};
};
c.functions.once = function(a) {
var b = a;
return function() {
if (b) {
var a = b;
b = null;
a();
}
};
};
c.functions.debounce = function(a, b, d) {
d && (a = c.bind(a, d));
var e = null;
return function(d) {
c.global.clearTimeout(e);
var f = arguments;
e = c.global.setTimeout(function() {
a.apply(null, f);
}, b);
};
};
c.functions.throttle = function(a, b, d) {
function e() {
g = c.global.setTimeout(f, b);
a.apply(null, k);
}
function f() {
g = null;
h && (h = !1, e());
}
d && (a = c.bind(a, d));
var g = null, h = !1, k = [];
return function(a) {
k = arguments;
g ? h = !0 : e();
};
};
c.array = {};
c.NATIVE_ARRAY_PROTOTYPES = c.TRUSTED_SITE;
c.array.ASSUME_NATIVE_FUNCTIONS = !1;
c.array.peek = function(a) {
return a[a.length - 1];
};
c.array.last = c.array.peek;
c.array.indexOf = c.NATIVE_ARRAY_PROTOTYPES && (c.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.indexOf) ? function(a, b, d) {
c.asserts.assert(null != a.length);
return Array.prototype.indexOf.call(a, b, d);
} : function(a, b, d) {
d = null == d ? 0 : 0 > d ? Math.max(0, a.length + d) : d;
if (c.isString(a)) {
return c.isString(b) && 1 == b.length ? a.indexOf(b, d) : -1;
}
for (;d < a.length;d++) {
if (d in a && a[d] === b) {
return d;
}
}
return -1;
};
c.array.lastIndexOf = c.NATIVE_ARRAY_PROTOTYPES && (c.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.lastIndexOf) ? function(a, b, d) {
c.asserts.assert(null != a.length);
return Array.prototype.lastIndexOf.call(a, b, null == d ? a.length - 1 : d);
} : function(a, b, d) {
d = null == d ? a.length - 1 : d;
0 > d && (d = Math.max(0, a.length + d));
if (c.isString(a)) {
return c.isString(b) && 1 == b.length ? a.lastIndexOf(b, d) : -1;
}
for (;0 <= d;d--) {
if (d in a && a[d] === b) {
return d;
}
}
return -1;
};
c.array.forEach = c.NATIVE_ARRAY_PROTOTYPES && (c.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.forEach) ? function(a, b, d) {
c.asserts.assert(null != a.length);
Array.prototype.forEach.call(a, b, d);
} : function(a, b, d) {
for (var e = a.length, f = c.isString(a) ? a.split("") : a, g = 0;g < e;g++) {
g in f && b.call(d, f[g], g, a);
}
};
c.array.forEachRight = function(a, b, d) {
for (var e = a.length, f = c.isString(a) ? a.split("") : a, e = e - 1;0 <= e;--e) {
e in f && b.call(d, f[e], e, a);
}
};
c.array.filter = c.NATIVE_ARRAY_PROTOTYPES && (c.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.filter) ? function(a, b, d) {
c.asserts.assert(null != a.length);
return Array.prototype.filter.call(a, b, d);
} : function(a, b, d) {
for (var e = a.length, f = [], g = 0, h = c.isString(a) ? a.split("") : a, k = 0;k < e;k++) {
if (k in h) {
var l = h[k];
b.call(d, l, k, a) && (f[g++] = l);
}
}
return f;
};
c.array.map = c.NATIVE_ARRAY_PROTOTYPES && (c.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.map) ? function(a, b, d) {
c.asserts.assert(null != a.length);
return Array.prototype.map.call(a, b, d);
} : function(a, b, d) {
for (var e = a.length, f = Array(e), g = c.isString(a) ? a.split("") : a, h = 0;h < e;h++) {
h in g && (f[h] = b.call(d, g[h], h, a));
}
return f;
};
c.array.reduce = c.NATIVE_ARRAY_PROTOTYPES && (c.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduce) ? function(a, b, d, e) {
c.asserts.assert(null != a.length);
e && (b = c.bind(b, e));
return Array.prototype.reduce.call(a, b, d);
} : function(a, b, d, e) {
var f = d;
c.array.forEach(a, function(d, h) {
f = b.call(e, f, d, h, a);
});
return f;
};
c.array.reduceRight = c.NATIVE_ARRAY_PROTOTYPES && (c.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduceRight) ? function(a, b, d, e) {
c.asserts.assert(null != a.length);
c.asserts.assert(null != b);
e && (b = c.bind(b, e));
return Array.prototype.reduceRight.call(a, b, d);
} : function(a, b, d, e) {
var f = d;
c.array.forEachRight(a, function(d, h) {
f = b.call(e, f, d, h, a);
});
return f;
};
c.array.some = c.NATIVE_ARRAY_PROTOTYPES && (c.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.some) ? function(a, b, d) {
c.asserts.assert(null != a.length);
return Array.prototype.some.call(a, b, d);
} : function(a, b, d) {
for (var e = a.length, f = c.isString(a) ? a.split("") : a, g = 0;g < e;g++) {
if (g in f && b.call(d, f[g], g, a)) {
return !0;
}
}
return !1;
};
c.array.every = c.NATIVE_ARRAY_PROTOTYPES && (c.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.every) ? function(a, b, d) {
c.asserts.assert(null != a.length);
return Array.prototype.every.call(a, b, d);
} : function(a, b, d) {
for (var e = a.length, f = c.isString(a) ? a.split("") : a, g = 0;g < e;g++) {
if (g in f && !b.call(d, f[g], g, a)) {
return !1;
}
}
return !0;
};
c.array.count = function(a, b, d) {
var e = 0;
c.array.forEach(a, function(a, g, h) {
b.call(d, a, g, h) && ++e;
}, d);
return e;
};
c.array.find = function(a, b, d) {
b = c.array.findIndex(a, b, d);
return 0 > b ? null : c.isString(a) ? a.charAt(b) : a[b];
};
c.array.findIndex = function(a, b, d) {
for (var e = a.length, f = c.isString(a) ? a.split("") : a, g = 0;g < e;g++) {
if (g in f && b.call(d, f[g], g, a)) {
return g;
}
}
return -1;
};
c.array.findRight = function(a, b, d) {
b = c.array.findIndexRight(a, b, d);
return 0 > b ? null : c.isString(a) ? a.charAt(b) : a[b];
};
c.array.findIndexRight = function(a, b, d) {
for (var e = a.length, f = c.isString(a) ? a.split("") : a, e = e - 1;0 <= e;e--) {
if (e in f && b.call(d, f[e], e, a)) {
return e;
}
}
return -1;
};
c.array.contains = function(a, b) {
return 0 <= c.array.indexOf(a, b);
};
c.array.isEmpty = function(a) {
return 0 == a.length;
};
c.array.clear = function(a) {
if (!c.isArray(a)) {
for (var b = a.length - 1;0 <= b;b--) {
delete a[b];
}
}
a.length = 0;
};
c.array.insert = function(a, b) {
c.array.contains(a, b) || a.push(b);
};
c.array.insertAt = function(a, b, d) {
c.array.splice(a, d, 0, b);
};
c.array.insertArrayAt = function(a, b, d) {
c.partial(c.array.splice, a, d, 0).apply(null, b);
};
c.array.insertBefore = function(a, b, d) {
var e;
2 == arguments.length || 0 > (e = c.array.indexOf(a, d)) ? a.push(b) : c.array.insertAt(a, b, e);
};
c.array.remove = function(a, b) {
b = c.array.indexOf(a, b);
var d;
(d = 0 <= b) && c.array.removeAt(a, b);
return d;
};
c.array.removeLast = function(a, b) {
b = c.array.lastIndexOf(a, b);
return 0 <= b ? (c.array.removeAt(a, b), !0) : !1;
};
c.array.removeAt = function(a, b) {
c.asserts.assert(null != a.length);
return 1 == Array.prototype.splice.call(a, b, 1).length;
};
c.array.removeIf = function(a, b, d) {
b = c.array.findIndex(a, b, d);
return 0 <= b ? (c.array.removeAt(a, b), !0) : !1;
};
c.array.removeAllIf = function(a, b, d) {
var e = 0;
c.array.forEachRight(a, function(f, g) {
b.call(d, f, g, a) && c.array.removeAt(a, g) && e++;
});
return e;
};
c.array.concat = function(a) {
return Array.prototype.concat.apply(Array.prototype, arguments);
};
c.array.join = function(a) {
return Array.prototype.concat.apply(Array.prototype, arguments);
};
c.array.toArray = function(a) {
var b = a.length;
if (0 < b) {
for (var d = Array(b), e = 0;e < b;e++) {
d[e] = a[e];
}
return d;
}
return [];
};
c.array.clone = c.array.toArray;
c.array.extend = function(a, b) {
for (var d = 1;d < arguments.length;d++) {
var e = arguments[d];
if (c.isArrayLike(e)) {
var f = a.length || 0, g = e.length || 0;
a.length = f + g;
for (var h = 0;h < g;h++) {
a[f + h] = e[h];
}
} else {
a.push(e);
}
}
};
c.array.splice = function(a, b, d, e) {
c.asserts.assert(null != a.length);
return Array.prototype.splice.apply(a, c.array.slice(arguments, 1));
};
c.array.slice = function(a, b, d) {
c.asserts.assert(null != a.length);
return 2 >= arguments.length ? Array.prototype.slice.call(a, b) : Array.prototype.slice.call(a, b, d);
};
c.array.removeDuplicates = function(a, b, d) {
function e(a) {
return c.isObject(a) ? "o" + c.getUid(a) : (typeof a).charAt(0) + a;
}
b = b || a;
d = d || e;
for (var f = {}, g = 0, h = 0;h < a.length;) {
var k = a[h++], l = d(k);
Object.prototype.hasOwnProperty.call(f, l) || (f[l] = !0, b[g++] = k);
}
b.length = g;
};
c.array.binarySearch = function(a, b, d) {
return c.array.binarySearch_(a, d || c.array.defaultCompare, !1, b);
};
c.array.binarySelect = function(a, b, d) {
return c.array.binarySearch_(a, b, !0, void 0, d);
};
c.array.binarySearch_ = function(a, b, d, e, f) {
for (var g = 0, h = a.length, k;g < h;) {
var l = g + h >> 1, u;
u = d ? b.call(f, a[l], l, a) : b(e, a[l]);
0 < u ? g = l + 1 : (h = l, k = !u);
}
return k ? g : ~g;
};
c.array.sort = function(a, b) {
a.sort(b || c.array.defaultCompare);
};
c.array.stableSort = function(a, b) {
for (var d = Array(a.length), e = 0;e < a.length;e++) {
d[e] = {index:e, value:a[e]};
}
var f = b || c.array.defaultCompare;
c.array.sort(d, function(a, b) {
return f(a.value, b.value) || a.index - b.index;
});
for (e = 0;e < a.length;e++) {
a[e] = d[e].value;
}
};
c.array.sortByKey = function(a, b, d) {
var e = d || c.array.defaultCompare;
c.array.sort(a, function(a, d) {
return e(b(a), b(d));
});
};
c.array.sortObjectsByKey = function(a, b, d) {
c.array.sortByKey(a, function(a) {
return a[b];
}, d);
};
c.array.isSorted = function(a, b, d) {
b = b || c.array.defaultCompare;
for (var e = 1;e < a.length;e++) {
var f = b(a[e - 1], a[e]);
if (0 < f || 0 == f && d) {
return !1;
}
}
return !0;
};
c.array.equals = function(a, b, d) {
if (!c.isArrayLike(a) || !c.isArrayLike(b) || a.length != b.length) {
return !1;
}
var e = a.length;
d = d || c.array.defaultCompareEquality;
for (var f = 0;f < e;f++) {
if (!d(a[f], b[f])) {
return !1;
}
}
return !0;
};
c.array.compare3 = function(a, b, d) {
d = d || c.array.defaultCompare;
for (var e = Math.min(a.length, b.length), f = 0;f < e;f++) {
var g = d(a[f], b[f]);
if (0 != g) {
return g;
}
}
return c.array.defaultCompare(a.length, b.length);
};
c.array.defaultCompare = function(a, b) {
return a > b ? 1 : a < b ? -1 : 0;
};
c.array.inverseDefaultCompare = function(a, b) {
return -c.array.defaultCompare(a, b);
};
c.array.defaultCompareEquality = function(a, b) {
return a === b;
};
c.array.binaryInsert = function(a, b, d) {
d = c.array.binarySearch(a, b, d);
return 0 > d ? (c.array.insertAt(a, b, -(d + 1)), !0) : !1;
};
c.array.binaryRemove = function(a, b, d) {
b = c.array.binarySearch(a, b, d);
return 0 <= b ? c.array.removeAt(a, b) : !1;
};
c.array.bucket = function(a, b, d) {
for (var e = {}, f = 0;f < a.length;f++) {
var g = a[f], h = b.call(d, g, f, a);
c.isDef(h) && (e[h] || (e[h] = [])).push(g);
}
return e;
};
c.array.toObject = function(a, b, d) {
var e = {};
c.array.forEach(a, function(f, g) {
e[b.call(d, f, g, a)] = f;
});
return e;
};
c.array.range = function(a, b, d) {
var e = [], f = 0, g = a;
d = d || 1;
void 0 !== b && (f = a, g = b);
if (0 > d * (g - f)) {
return [];
}
if (0 < d) {
for (a = f;a < g;a += d) {
e.push(a);
}
} else {
for (a = f;a > g;a += d) {
e.push(a);
}
}
return e;
};
c.array.repeat = function(a, b) {
for (var d = [], e = 0;e < b;e++) {
d[e] = a;
}
return d;
};
c.array.flatten = function(a) {
for (var b = [], d = 0;d < arguments.length;d++) {
var e = arguments[d];
if (c.isArray(e)) {
for (var f = 0;f < e.length;f += 8192) {
for (var g = c.array.slice(e, f, f + 8192), g = c.array.flatten.apply(null, g), h = 0;h < g.length;h++) {
b.push(g[h]);
}
}
} else {
b.push(e);
}
}
return b;
};
c.array.rotate = function(a, b) {
c.asserts.assert(null != a.length);
a.length && (b %= a.length, 0 < b ? Array.prototype.unshift.apply(a, a.splice(-b, b)) : 0 > b && Array.prototype.push.apply(a, a.splice(0, -b)));
return a;
};
c.array.moveItem = function(a, b, d) {
c.asserts.assert(0 <= b && b < a.length);
c.asserts.assert(0 <= d && d < a.length);
b = Array.prototype.splice.call(a, b, 1);
Array.prototype.splice.call(a, d, 0, b[0]);
};
c.array.zip = function(a) {
if (!arguments.length) {
return [];
}
for (var b = [], d = arguments[0].length, e = 1;e < arguments.length;e++) {
arguments[e].length < d && (d = arguments[e].length);
}
for (e = 0;e < d;e++) {
for (var f = [], g = 0;g < arguments.length;g++) {
f.push(arguments[g][e]);
}
b.push(f);
}
return b;
};
c.array.shuffle = function(a, b) {
b = b || Math.random;
for (var d = a.length - 1;0 < d;d--) {
var e = Math.floor(b() * (d + 1)), f = a[d];
a[d] = a[e];
a[e] = f;
}
};
c.array.copyByIndex = function(a, b) {
var d = [];
c.array.forEach(b, function(b) {
d.push(a[b]);
});
return d;
};
c.array.concatMap = function(a, b, d) {
return c.array.concat.apply([], c.array.map(a, b, d));
};
c.object = {};
c.object.is = function(a, b) {
return a === b ? 0 !== a || 1 / a === 1 / b : a !== a && b !== b;
};
c.object.forEach = function(a, b, d) {
for (var e in a) {
b.call(d, a[e], e, a);
}
};
c.object.filter = function(a, b, d) {
var e = {}, f;
for (f in a) {
b.call(d, a[f], f, a) && (e[f] = a[f]);
}
return e;
};
c.object.map = function(a, b, d) {
var e = {}, f;
for (f in a) {
e[f] = b.call(d, a[f], f, a);
}
return e;
};
c.object.some = function(a, b, d) {
for (var e in a) {
if (b.call(d, a[e], e, a)) {
return !0;
}
}
return !1;
};
c.object.every = function(a, b, d) {
for (var e in a) {
if (!b.call(d, a[e], e, a)) {
return !1;
}
}
return !0;
};
c.object.getCount = function(a) {
var b = 0, d;
for (d in a) {
b++;
}
return b;
};
c.object.getAnyKey = function(a) {
for (var b in a) {
return b;
}
};
c.object.getAnyValue = function(a) {
for (var b in a) {
return a[b];
}
};
c.object.contains = function(a, b) {
return c.object.containsValue(a, b);
};
c.object.getValues = function(a) {
var b = [], d = 0, e;
for (e in a) {
b[d++] = a[e];
}
return b;
};
c.object.getKeys = function(a) {
var b = [], d = 0, e;
for (e in a) {
b[d++] = e;
}
return b;
};
c.object.getValueByKeys = function(a, b) {
for (var d = c.isArrayLike(b), e = d ? b : arguments, d = d ? 0 : 1;d < e.length && (a = a[e[d]], c.isDef(a));d++) {
}
return a;
};
c.object.containsKey = function(a, b) {
return null !== a && b in a;
};
c.object.containsValue = function(a, b) {
for (var d in a) {
if (a[d] == b) {
return !0;
}
}
return !1;
};
c.object.findKey = function(a, b, d) {
for (var e in a) {
if (b.call(d, a[e], e, a)) {
return e;
}
}
};
c.object.findValue = function(a, b, d) {
return (b = c.object.findKey(a, b, d)) && a[b];
};
c.object.isEmpty = function(a) {
for (var b in a) {
return !1;
}
return !0;
};
c.object.clear = function(a) {
for (var b in a) {
delete a[b];
}
};
c.object.remove = function(a, b) {
var d;
(d = b in a) && delete a[b];
return d;
};
c.object.add = function(a, b, d) {
if (null !== a && b in a) {
throw Error('The object already contains the key "' + b + '"');
}
c.object.set(a, b, d);
};
c.object.get = function(a, b, d) {
return null !== a && b in a ? a[b] : d;
};
c.object.set = function(a, b, d) {
a[b] = d;
};
c.object.setIfUndefined = function(a, b, d) {
return b in a ? a[b] : a[b] = d;
};
c.object.setWithReturnValueIfNotSet = function(a, b, d) {
if (b in a) {
return a[b];
}
d = d();
return a[b] = d;
};
c.object.equals = function(a, b) {
for (var d in a) {
if (!(d in b) || a[d] !== b[d]) {
return !1;
}
}
for (d in b) {
if (!(d in a)) {
return !1;
}
}
return !0;
};
c.object.clone = function(a) {
var b = {}, d;
for (d in a) {
b[d] = a[d];
}
return b;
};
c.object.unsafeClone = function(a) {
var b = c.typeOf(a);
if ("object" == b || "array" == b) {
if (c.isFunction(a.clone)) {
return a.clone();
}
var b = "array" == b ? [] : {}, d;
for (d in a) {
b[d] = c.object.unsafeClone(a[d]);
}
return b;
}
return a;
};
c.object.transpose = function(a) {
var b = {}, d;
for (d in a) {
b[a[d]] = d;
}
return b;
};
c.object.PROTOTYPE_FIELDS_ = "constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");
c.object.extend = function(a, b) {
for (var d, e, f = 1;f < arguments.length;f++) {
e = arguments[f];
for (d in e) {
a[d] = e[d];
}
for (var g = 0;g < c.object.PROTOTYPE_FIELDS_.length;g++) {
d = c.object.PROTOTYPE_FIELDS_[g], Object.prototype.hasOwnProperty.call(e, d) && (a[d] = e[d]);
}
}
};
c.object.create = function(a) {
var b = arguments.length;
if (1 == b && c.isArray(arguments[0])) {
return c.object.create.apply(null, arguments[0]);
}
if (b % 2) {
throw Error("Uneven number of arguments");
}
for (var d = {}, e = 0;e < b;e += 2) {
d[arguments[e]] = arguments[e + 1];
}
return d;
};
c.object.createSet = function(a) {
var b = arguments.length;
if (1 == b && c.isArray(arguments[0])) {
return c.object.createSet.apply(null, arguments[0]);
}
for (var d = {}, e = 0;e < b;e++) {
d[arguments[e]] = !0;
}
return d;
};
c.object.createImmutableView = function(a) {
var b = a;
Object.isFrozen && !Object.isFrozen(a) && (b = Object.create(a), Object.freeze(b));
return b;
};
c.object.isImmutableView = function(a) {
return !!Object.isFrozen && Object.isFrozen(a);
};
c.math = {};
c.math.randomInt = function(a) {
return Math.floor(Math.random() * a);
};
c.math.uniformRandom = function(a, b) {
return a + Math.random() * (b - a);
};
c.math.clamp = function(a, b, d) {
return Math.min(Math.max(a, b), d);
};
c.math.modulo = function(a, b) {
a %= b;
return 0 > a * b ? a + b : a;
};
c.math.lerp = function(a, b, d) {
return a + d * (b - a);
};
c.math.nearlyEquals = function(a, b, d) {
return Math.abs(a - b) <= (d || 1E-6);
};
c.math.standardAngle = function(a) {
return c.math.modulo(a, 360);
};
c.math.standardAngleInRadians = function(a) {
return c.math.modulo(a, 2 * Math.PI);
};
c.math.toRadians = function(a) {
return a * Math.PI / 180;
};
c.math.toDegrees = function(a) {
return 180 * a / Math.PI;
};
c.math.angleDx = function(a, b) {
return b * Math.cos(c.math.toRadians(a));
};
c.math.angleDy = function(a, b) {
return b * Math.sin(c.math.toRadians(a));
};
c.math.angle = function(a, b, d, e) {
return c.math.standardAngle(c.math.toDegrees(Math.atan2(e - b, d - a)));
};
c.math.angleDifference = function(a, b) {
a = c.math.standardAngle(b) - c.math.standardAngle(a);
180 < a ? a -= 360 : -180 >= a && (a = 360 + a);
return a;
};
c.math.sign = function(a) {
return 0 < a ? 1 : 0 > a ? -1 : a;
};
c.math.longestCommonSubsequence = function(a, b, d, e) {
d = d || function(a, b) {
return a == b;
};
e = e || function(b) {
return a[b];
};
for (var f = a.length, g = b.length, h = [], k = 0;k < f + 1;k++) {
h[k] = [], h[k][0] = 0;
}
for (var l = 0;l < g + 1;l++) {
h[0][l] = 0;
}
for (k = 1;k <= f;k++) {
for (l = 1;l <= g;l++) {
d(a[k - 1], b[l - 1]) ? h[k][l] = h[k - 1][l - 1] + 1 : h[k][l] = Math.max(h[k - 1][l], h[k][l - 1]);
}
}
for (var u = [], k = f, l = g;0 < k && 0 < l;) {
d(a[k - 1], b[l - 1]) ? (u.unshift(e(k - 1, l - 1)), k--, l--) : h[k - 1][l] > h[k][l - 1] ? k-- : l--;
}
return u;
};
c.math.sum = function(a) {
return c.array.reduce(arguments, function(a, d) {
return a + d;
}, 0);
};
c.math.average = function(a) {
return c.math.sum.apply(null, arguments) / arguments.length;
};
c.math.sampleVariance = function(a) {
var b = arguments.length;
if (2 > b) {
return 0;
}
var d = c.math.average.apply(null, arguments);
return c.math.sum.apply(null, c.array.map(arguments, function(a) {
return Math.pow(a - d, 2);
})) / (b - 1);
};
c.math.standardDeviation = function(a) {
return Math.sqrt(c.math.sampleVariance.apply(null, arguments));
};
c.math.isInt = function(a) {
return isFinite(a) && 0 == a % 1;
};
c.math.isFiniteNumber = function(a) {
return isFinite(a) && !isNaN(a);
};
c.math.isNegativeZero = function(a) {
return 0 == a && 0 > 1 / a;
};
c.math.log10Floor = function(a) {
if (0 < a) {
var b = Math.round(Math.log(a) * Math.LOG10E);
return b - (parseFloat("1e" + b) > a ? 1 : 0);
}
return 0 == a ? -Infinity : NaN;
};
c.math.safeFloor = function(a, b) {
c.asserts.assert(!c.isDef(b) || 0 < b);
return Math.floor(a + (b || 2E-15));
};
c.math.safeCeil = function(a, b) {
c.asserts.assert(!c.isDef(b) || 0 < b);
return Math.ceil(a - (b || 2E-15));
};
c.iter = {};
c.iter.StopIteration = "StopIteration" in c.global ? c.global.StopIteration : {message:"StopIteration", stack:""};
c.iter.Iterator = function() {
};
c.iter.Iterator.prototype.next = function() {
throw c.iter.StopIteration;
};
c.iter.Iterator.prototype.__iterator__ = function() {
return this;
};
c.iter.toIterator = function(a) {
if (a instanceof c.iter.Iterator) {
return a;
}
if ("function" == typeof a.__iterator__) {
return a.__iterator__(!1);
}
if (c.isArrayLike(a)) {
var b = 0, d = new c.iter.Iterator;
d.next = function() {
for (;;) {
if (b >= a.length) {
throw c.iter.StopIteration;
}
if (b in a) {
return a[b++];
}
b++;
}
};
return d;
}
throw Error("Not implemented");
};
c.iter.forEach = function(a, b, d) {
if (c.isArrayLike(a)) {
try {
c.array.forEach(a, b, d);
} catch (e) {
if (e !== c.iter.StopIteration) {
throw e;
}
}
} else {
a = c.iter.toIterator(a);
try {
for (;;) {
b.call(d, a.next(), void 0, a);
}
} catch (e) {
if (e !== c.iter.StopIteration) {
throw e;
}
}
}
};
c.iter.filter = function(a, b, d) {
var e = c.iter.toIterator(a);
a = new c.iter.Iterator;
a.next = function() {
for (;;) {
var a = e.next();
if (b.call(d, a, void 0, e)) {
return a;
}
}
};
return a;
};
c.iter.filterFalse = function(a, b, d) {
return c.iter.filter(a, c.functions.not(b), d);
};
c.iter.range = function(a, b, d) {
var e = 0, f = a, g = d || 1;
1 < arguments.length && (e = a, f = b);
if (0 == g) {
throw Error("Range step argument must not be zero");
}
var h = new c.iter.Iterator;
h.next = function() {
if (0 < g && e >= f || 0 > g && e <= f) {
throw c.iter.StopIteration;
}
var a = e;
e += g;
return a;
};
return h;
};
c.iter.join = function(a, b) {
return c.iter.toArray(a).join(b);
};
c.iter.map = function(a, b, d) {
var e = c.iter.toIterator(a);
a = new c.iter.Iterator;
a.next = function() {
var a = e.next();
return b.call(d, a, void 0, e);
};
return a;
};
c.iter.reduce = function(a, b, d, e) {
var f = d;
c.iter.forEach(a, function(a) {
f = b.call(e, f, a);
});
return f;
};
c.iter.some = function(a, b, d) {
a = c.iter.toIterator(a);
try {
for (;;) {
if (b.call(d, a.next(), void 0, a)) {
return !0;
}
}
} catch (e) {
if (e !== c.iter.StopIteration) {
throw e;
}
}
return !1;
};
c.iter.every = function(a, b, d) {
a = c.iter.toIterator(a);
try {
for (;;) {
if (!b.call(d, a.next(), void 0, a)) {
return !1;
}
}
} catch (e) {
if (e !== c.iter.StopIteration) {
throw e;
}
}
return !0;
};
c.iter.chain = function(a) {
return c.iter.chainFromIterable(arguments);
};
c.iter.chainFromIterable = function(a) {
var b = c.iter.toIterator(a);
a = new c.iter.Iterator;
var d = null;
a.next = function() {
for (;;) {
if (null == d) {
var a = b.next();
d = c.iter.toIterator(a);
}
try {
return d.next();
} catch (f) {
if (f !== c.iter.StopIteration) {
throw f;
}
d = null;
}
}
};
return a;
};
c.iter.dropWhile = function(a, b, d) {
var e = c.iter.toIterator(a);
a = new c.iter.Iterator;
var f = !0;
a.next = function() {
for (;;) {
var a = e.next();
if (!f || !b.call(d, a, void 0, e)) {
return f = !1, a;
}
}
};
return a;
};
c.iter.takeWhile = function(a, b, d) {
var e = c.iter.toIterator(a);
a = new c.iter.Iterator;
a.next = function() {
var a = e.next();
if (b.call(d, a, void 0, e)) {
return a;
}
throw c.iter.StopIteration;
};
return a;
};
c.iter.toArray = function(a) {
if (c.isArrayLike(a)) {
return c.array.toArray(a);
}
a = c.iter.toIterator(a);
var b = [];
c.iter.forEach(a, function(a) {
b.push(a);
});
return b;
};
c.iter.equals = function(a, b, d) {
a = c.iter.zipLongest({}, a, b);
var e = d || c.array.defaultCompareEquality;
return c.iter.every(a, function(a) {
return e(a[0], a[1]);
});
};
c.iter.nextOrValue = function(a, b) {
try {
return c.iter.toIterator(a).next();
} catch (d) {
if (d != c.iter.StopIteration) {
throw d;
}
return b;
}
};
c.iter.product = function(a) {
if (c.array.some(arguments, function(a) {
return !a.length;
}) || !arguments.length) {
return new c.iter.Iterator;
}
var b = new c.iter.Iterator, d = arguments, e = c.array.repeat(0, d.length);
b.next = function() {
if (e) {
for (var a = c.array.map(e, function(a, b) {
return d[b][a];
}), b = e.length - 1;0 <= b;b--) {
c.asserts.assert(e);
if (e[b] < d[b].length - 1) {
e[b]++;
break;
}
if (0 == b) {
e = null;
break;
}
e[b] = 0;
}
return a;
}
throw c.iter.StopIteration;
};
return b;
};
c.iter.cycle = function(a) {
var b = c.iter.toIterator(a), d = [], e = 0;
a = new c.iter.Iterator;
var f = !1;
a.next = function() {
var a = null;
if (!f) {
try {
return a = b.next(), d.push(a), a;
} catch (h) {
if (h != c.iter.StopIteration || c.array.isEmpty(d)) {
throw h;
}
f = !0;
}
}
a = d[e];
e = (e + 1) % d.length;
return a;
};
return a;
};
c.iter.count = function(a, b) {
var d = a || 0, e = c.isDef(b) ? b : 1;
a = new c.iter.Iterator;
a.next = function() {
var a = d;
d += e;
return a;
};
return a;
};
c.iter.repeat = function(a) {
var b = new c.iter.Iterator;
b.next = c.functions.constant(a);
return b;
};
c.iter.accumulate = function(a) {
var b = c.iter.toIterator(a), d = 0;
a = new c.iter.Iterator;
a.next = function() {
return d += b.next();
};
return a;
};
c.iter.zip = function(a) {
var b = arguments, d = new c.iter.Iterator;
if (0 < b.length) {
var e = c.array.map(b, c.iter.toIterator);
d.next = function() {
return c.array.map(e, function(a) {
return a.next();
});
};
}
return d;
};
c.iter.zipLongest = function(a, b) {
var d = c.array.slice(arguments, 1), e = new c.iter.Iterator;
if (0 < d.length) {
var f = c.array.map(d, c.iter.toIterator);
e.next = function() {
var b = !1, d = c.array.map(f, function(d) {
var e;
try {
e = d.next(), b = !0;
} catch (u) {
if (u !== c.iter.StopIteration) {
throw u;
}
e = a;
}
return e;
});
if (!b) {
throw c.iter.StopIteration;
}
return d;
};
}
return e;
};
c.iter.compress = function(a, b) {
var d = c.iter.toIterator(b);
return c.iter.filter(a, function() {
return !!d.next();
});
};
c.iter.GroupByIterator_ = function(a, b) {
this.iterator = c.iter.toIterator(a);
this.keyFunc = b || c.functions.identity;
};
c.inherits(c.iter.GroupByIterator_, c.iter.Iterator);
c.iter.GroupByIterator_.prototype.next = function() {
for (;this.currentKey == this.targetKey;) {
this.currentValue = this.iterator.next(), this.currentKey = this.keyFunc(this.currentValue);
}
this.targetKey = this.currentKey;
return [this.currentKey, this.groupItems_(this.targetKey)];
};
c.iter.GroupByIterator_.prototype.groupItems_ = function(a) {
for (var b = [];this.currentKey == a;) {
b.push(this.currentValue);
try {
this.currentValue = this.iterator.next();
} catch (d) {
if (d !== c.iter.StopIteration) {
throw d;
}
break;
}
this.currentKey = this.keyFunc(this.currentValue);
}
return b;
};
c.iter.groupBy = function(a, b) {
return new c.iter.GroupByIterator_(a, b);
};
c.iter.starMap = function(a, b, d) {
var e = c.iter.toIterator(a);
a = new c.iter.Iterator;
a.next = function() {
var a = c.iter.toArray(e.next());
return b.apply(d, c.array.concat(a, void 0, e));
};
return a;
};
c.iter.tee = function(a, b) {
function d() {
var a = e.next();
c.array.forEach(f, function(b) {
b.push(a);
});
}
var e = c.iter.toIterator(a);
a = c.isNumber(b) ? b : 2;
var f = c.array.map(c.array.range(a), function() {
return [];
});
return c.array.map(f, function(a) {
var b = new c.iter.Iterator;
b.next = function() {
c.array.isEmpty(a) && d();
c.asserts.assert(!c.array.isEmpty(a));
return a.shift();
};
return b;
});
};
c.iter.enumerate = function(a, b) {
return c.iter.zip(c.iter.count(b), a);
};
c.iter.limit = function(a, b) {
c.asserts.assert(c.math.isInt(b) && 0 <= b);
var d = c.iter.toIterator(a);
a = new c.iter.Iterator;
var e = b;
a.next = function() {
if (0 < e--) {
return d.next();
}
throw c.iter.StopIteration;
};
return a;
};
c.iter.consume = function(a, b) {
c.asserts.assert(c.math.isInt(b) && 0 <= b);
for (a = c.iter.toIterator(a);0 < b--;) {
c.iter.nextOrValue(a, null);
}
return a;
};
c.iter.slice = function(a, b, d) {
c.asserts.assert(c.math.isInt(b) && 0 <= b);
a = c.iter.consume(a, b);
c.isNumber(d) && (c.asserts.assert(c.math.isInt(d) && d >= b), a = c.iter.limit(a, d - b));
return a;
};
c.iter.hasDuplicates_ = function(a) {
var b = [];
c.array.removeDuplicates(a, b);
return a.length != b.length;
};
c.iter.permutations = function(a, b) {
a = c.iter.toArray(a);
b = c.isNumber(b) ? b : a.length;
b = c.array.repeat(a, b);
b = c.iter.product.apply(void 0, b);
return c.iter.filter(b, function(a) {
return !c.iter.hasDuplicates_(a);
});
};
c.iter.combinations = function(a, b) {
function d(a) {
return e[a];
}
var e = c.iter.toArray(a);
a = c.iter.range(e.length);
b = c.iter.permutations(a, b);
var f = c.iter.filter(b, function(a) {
return c.array.isSorted(a);
});
b = new c.iter.Iterator;
b.next = function() {
return c.array.map(f.next(), d);
};
return b;
};
c.iter.combinationsWithReplacement = function(a, b) {
function d(a) {
return e[a];
}
var e = c.iter.toArray(a);
a = c.array.range(e.length);
b = c.array.repeat(a, b);
b = c.iter.product.apply(void 0, b);
var f = c.iter.filter(b, function(a) {
return c.array.isSorted(a);
});
b = new c.iter.Iterator;
b.next = function() {
return c.array.map(f.next(), d);
};
return b;
};
c.structs = {};
c.structs.Map = function(a, b) {
this.map_ = {};
this.keys_ = [];
this.version_ = this.count_ = 0;
var d = arguments.length;
if (1 < d) {
if (d % 2) {
throw Error("Uneven number of arguments");
}
for (var e = 0;e < d;e += 2) {
this.set(arguments[e], arguments[e + 1]);
}
} else {
a && this.addAll(a);
}
};
c.structs.Map.prototype.getCount = function() {
return this.count_;
};
c.structs.Map.prototype.getValues = function() {
this.cleanupKeysArray_();
for (var a = [], b = 0;b < this.keys_.length;b++) {
a.push(this.map_[this.keys_[b]]);
}
return a;
};
c.structs.Map.prototype.getKeys = function() {
this.cleanupKeysArray_();
return this.keys_.concat();
};
c.structs.Map.prototype.containsKey = function(a) {
return c.structs.Map.hasKey_(this.map_, a);
};
c.structs.Map.prototype.containsValue = function(a) {
for (var b = 0;b < this.keys_.length;b++) {
var d = this.keys_[b];
if (c.structs.Map.hasKey_(this.map_, d) && this.map_[d] == a) {
return !0;
}
}
return !1;
};
c.structs.Map.prototype.equals = function(a, b) {
if (this === a) {
return !0;
}
if (this.count_ != a.getCount()) {
return !1;
}
b = b || c.structs.Map.defaultEquals;
this.cleanupKeysArray_();
for (var d, e = 0;d = this.keys_[e];e++) {
if (!b(this.get(d), a.get(d))) {
return !1;
}
}
return !0;
};
c.structs.Map.defaultEquals = function(a, b) {
return a === b;
};
c.structs.Map.prototype.isEmpty = function() {
return 0 == this.count_;
};
c.structs.Map.prototype.clear = function() {
this.map_ = {};
this.version_ = this.count_ = this.keys_.length = 0;
};
c.structs.Map.prototype.remove = function(a) {
return c.structs.Map.hasKey_(this.map_, a) ? (delete this.map_[a], this.count_--, this.version_++, this.keys_.length > 2 * this.count_ && this.cleanupKeysArray_(), !0) : !1;
};
c.structs.Map.prototype.cleanupKeysArray_ = function() {
if (this.count_ != this.keys_.length) {
for (var a = 0, b = 0;a < this.keys_.length;) {
var d = this.keys_[a];
c.structs.Map.hasKey_(this.map_, d) && (this.keys_[b++] = d);
a++;
}
this.keys_.length = b;
}
if (this.count_ != this.keys_.length) {
for (var e = {}, b = a = 0;a < this.keys_.length;) {
d = this.keys_[a], c.structs.Map.hasKey_(e, d) || (this.keys_[b++] = d, e[d] = 1), a++;
}
this.keys_.length = b;
}
};
c.structs.Map.prototype.get = function(a, b) {
return c.structs.Map.hasKey_(this.map_, a) ? this.map_[a] : b;
};
c.structs.Map.prototype.set = function(a, b) {
c.structs.Map.hasKey_(this.map_, a) || (this.count_++, this.keys_.push(a), this.version_++);
this.map_[a] = b;
};
c.structs.Map.prototype.addAll = function(a) {
var b;
a instanceof c.structs.Map ? (b = a.getKeys(), a = a.getValues()) : (b = c.object.getKeys(a), a = c.object.getValues(a));
for (var d = 0;d < b.length;d++) {
this.set(b[d], a[d]);
}
};
c.structs.Map.prototype.forEach = function(a, b) {
for (var d = this.getKeys(), e = 0;e < d.length;e++) {
var f = d[e], g = this.get(f);
a.call(b, g, f, this);
}
};
c.structs.Map.prototype.clone = function() {
return new c.structs.Map(this);
};
c.structs.Map.prototype.transpose = function() {
for (var a = new c.structs.Map, b = 0;b < this.keys_.length;b++) {
var d = this.keys_[b];
a.set(this.map_[d], d);
}
return a;
};
c.structs.Map.prototype.toObject = function() {
this.cleanupKeysArray_();
for (var a = {}, b = 0;b < this.keys_.length;b++) {
var d = this.keys_[b];
a[d] = this.map_[d];
}
return a;
};
c.structs.Map.prototype.getKeyIterator = function() {
return this.__iterator__(!0);
};
c.structs.Map.prototype.getValueIterator = function() {
return this.__iterator__(!1);
};
c.structs.Map.prototype.__iterator__ = function(a) {
this.cleanupKeysArray_();
var b = 0, d = this.version_, e = this, f = new c.iter.Iterator;
f.next = function() {
if (d != e.version_) {
throw Error("The map has changed since the iterator was created");
}
if (b >= e.keys_.length) {
throw c.iter.StopIteration;
}
var f = e.keys_[b++];
return a ? f : e.map_[f];
};
return f;
};
c.structs.Map.hasKey_ = function(a, b) {
return Object.prototype.hasOwnProperty.call(a, b);
};
var B = require("lodash.ismatchwith");
function D(a) {
return function(b) {
return F(b, a);
};
}
function F(a, b) {
var d = {};
return B(a, b, function(a, b) {
if ("function" === typeof b) {
return a = b(a), c.isObject(a) && c.object.extend(d, a), !!a;
}
}) ? d : !1;
}
var H = {extractAST:function(a, b) {
return function(d) {
var e = {};
e[a] = d;
"object" === typeof b && (b = D(b));
if ("function" === typeof b) {
d = b(d);
if ("object" === typeof d) {
return c.object.extend(e, d), e;
}
if (!d) {
return !1;
}
}
return e;
};
}, isASTMatch:F, matchesAST:D, matchesASTLength:function(a) {
var b = D(a);
return function(d) {
return c.isArray(d) && c.isArray(a) && d.length === a.length ? b(d) : !1;
};
}};
function J(a, b) {
for (a = a.parent;!b(a) && "Program" !== a.type;) {
a = a.parent;
}
return b(a) ? a : null;
}
function N(a, b) {
var d = b || "literal";
return H.isASTMatch(a, {type:"Literal", value:function(a) {
return "string" === typeof a && H.extractAST(d)(a);
}});
}
var O = {GoogDependencyMatch:void 0, findAncestor:J, findAncestorOfType:function(a, b) {
return J(a, function(a) {
return a.type == b;
});
}, getFullyQualifedName:function(a) {
for (var b = a.name;a.parent && "MemberExpression" == a.parent.type;) {
a = a.parent, b += "." + a.property.name;
}
return b;
}, isLoop:function(a) {
return /^(?:DoWhile|For|ForIn|ForOf|While)Statement$/.test(a.type);
}, isFunction:function(a) {
return /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/.test(a.type);
}, matchExtractBareGoogRequire:function(a) {
return H.isASTMatch(a, {type:"ExpressionStatement", expression:{type:"CallExpression", callee:{type:"MemberExpression", object:{type:"Identifier", name:"goog"}, property:{type:"Identifier", name:"require"}}, arguments:[function(a) {
return N(a, "source");
}]}});
}, matchExtractGoogProvide:function(a) {
return H.isASTMatch(a, {type:"ExpressionStatement", expression:{type:"CallExpression", callee:{type:"MemberExpression", object:{type:"Identifier", name:"goog"}, property:{type:"Identifier", name:"provide"}}, arguments:[function(a) {
return N(a, "source");
}]}});
}, matchExtractDirective:function(a) {
return H.isASTMatch(a, {type:"ExpressionStatement", expression:function(a) {
return N(a, "directive");
}});
}, matchExtractStringLiteral:N, matchStringLiteral:function(a) {
return H.isASTMatch(a, {type:"Literal", value:function(a) {
return "string" === typeof a;
}});
}};
function aa(a) {
return " " == a || "\t" == a;
}
function ba(a) {
return "\t" == a;
}
function P(a, b, d, e) {
a = e ? b.getLastToken(a) : b.getFirstToken(a);
b = Array.from(b.getText(a, a.loc.start.column));
a = b.slice(0, b.findIndex(c.functions.not(aa)));
b = a.filter(c.string.isSpace).length;
a = a.filter(ba).length;
return {space:b, tab:a, goodChar:"space" === d ? b : a, badChar:"space" === d ? a : b};
}
function Q(a, b, d) {
b = !0 === d ? b.getLastToken(a, 1) : b.getTokenBefore(a);
return (!0 === d ? a.loc.end.line : a.loc.start.line) !== (b ? b.loc.end.line : -1);
}
function R(a, b) {
return !!b && b.parent.loc.start.line === a.loc.start.line && 1 < b.parent.declarations.length;
}
function ca(a) {
if ("CallExpression" !== a.parent.type) {
return !1;
}
a = a.parent;
if ("MemberExpression" !== a.callee.type) {
return !1;
}
a = a.callee;
if ("Identifier" !== a.object.type || "Identifier" !== a.property.type) {
return !1;
}
var b = a.property;
return "goog" === a.object.name && "scope" === b.name;
}
function da(a) {
return a.declarations.reduce(function(b, d) {
var e = b[b.length - 1];
(d.loc.start.line !== a.loc.start.line && !e || e && e.loc.start.line !== d.loc.start.line) && b.push(d);
return b;
}, []);
}
function ea(a) {
var b = {indentSize:4, indentType:"space", indentOptions:{SwitchCase:0, VariableDeclarator:{var:1, let:1, const:1}, outerIIFEBody:-1, MemberExpression:-1, FunctionDeclaration:{parameters:-1, body:1}, FunctionExpression:{parameters:-1, body:1}}}, d = b.indentOptions;
if (0 < a.length && ("tab" == a[0] ? (b.indentSize = 1, b.indentType = "tab") : "number" === typeof a[0] && (b.indentSize = a[0], b.indentType = "space"), a[1])) {
a = a[1];
d.SwitchCase = a.SwitchCase || 0;
if ("number" === typeof a.VariableDeclarator) {
var e = a.VariableDeclarator;
d.VariableDeclarator = {var:e, let:e, const:e};
} else {
"object" === typeof a.VariableDeclarator && Object.assign(d.VariableDeclarator, a.VariableDeclarator);
}
"number" === typeof a.outerIIFEBody && (d.outerIIFEBody = a.outerIIFEBody);
"number" === typeof a.MemberExpression && (d.MemberExpression = a.MemberExpression);
"object" === typeof a.FunctionDeclaration && Object.assign(d.FunctionDeclaration, a.FunctionDeclaration);
"object" === typeof a.FunctionExpression && Object.assign(d.FunctionExpression, a.FunctionExpression);
}
return b;
}
;var fa = require("doctrine");
function S(a) {
return "NullableLiteral" === a.type || "AllLiteral" === a.type || "NullLiteral" === a.type || "UndefinedLiteral" === a.type || "VoidLiteral" === a.type || "StringLiteralType" === a.type || "NumericLiteralType" === a.type;
}
function ga(a) {
return S(a) || "NameExpression" === a.type;
}
function T(a, b) {
b(a);
if (!ga(a)) {
switch(a.type) {
case "ArrayType":
a.elements.forEach(function(a) {
return T(a, b);
});
break;
case "RecordType":
a.fields.forEach(function(a) {
return T(a, b);
});
break;
case "FunctionType":
a.this && T(a.this, b);
a.params.forEach(function(a) {
return T(a, b);
});
a.result && T(a.result, b);
break;
case "FieldType":
a.value && T(a.value, b);
break;
case "ParameterType":
case "RestType":
case "NonNullableType":
case "OptionalType":
case "NullableType":
T(a.expression, b);
break;
case "TypeApplication":
T(a.expression, b);
a.applications.forEach(function(a) {
return T(a, b);
});
break;
case "UnionType":
a.elements.forEach(function(a) {
return T(a, b);
});
break;
default:
throw Error("Unrecoginized tag type: " + a + ".");
}
}
}
function U(a) {
return "Block" === a.type && "*" === a.value.charAt(0);
}
function ha(a) {
var b = ["FunctionExpression", "ArrowFunctionExpression", "ClassExpression"];
return H.isASTMatch(a, {type:"VariableDeclaration", declarations:[{type:"VariableDeclarator", init:function(a) {
return !!a && -1 !== b.indexOf(a.type);
}}]});
}
var W = {getJSDocComment:function(a) {
return !a.leadingComments || 0 == a.leadingComments.length || ha(a) ? null : a.leadingComments.filter(U).reverse().pop() || null;
}, hasTypeInformation:function(a) {
var b = "type typedef record const private package protected public export".split(" ");
return a.tags.some(function(a) {
return c.array.contains(b, a.title);
});
}, isLiteral:S, isVoid:function(a) {
var b = "NameExpression" == a.type && "void" == a.name;
return "VoidLiteral" == a.type || b;
}, isJSDocComment:U, parseComment:function(a) {
try {
return fa.parse(a, {strict:!0, unwrap:!0, sloppy:!0});
} catch (b) {
if (b instanceof Error && /braces/i.test(b.message)) {
throw Error("JSDoc type missing brace.");
}
throw Error("JSDoc syntax error.");
}
}, traverseTags:T};
var ia = require("doctrine");
function X(a) {
return !c.isDefAndNotNull(a.type) || W.isVoid(a.type) || "UndefinedLiteral" === a.type.type;
}
var ja = "string number boolean Object Array Map Set".split(" ");
function Y(a, b) {
b.type && W.traverseTags(b.type, function(b) {
"NameExpression" === b.type && (b = b.name, -1 === ja.indexOf(b) && a.markVariableAsUsed(b));
});
}
;function ka(a) {
return !!O.matchExtractDirective(a);
}
function la(a, b) {
for (var d = 0;d < b.length;++d) {
if (!a(b[d])) {
return b.slice(0, d);
}
}
return b.slice();
}
;var Z = {rules:{}};
c.exportProperty(Z, "rules", {});
c.exportProperty(Z.rules, "camelcase", {meta:{docs:{description:"check identifiers for camel case with options for opt_ prefix and var_args identifiers", category:"Stylistic Issues", recommended:!0}, schema:[{type:"object", properties:{allowVarArgs:{type:"boolean"}, allowOptPrefix:{type:"boolean"}, allowLeadingUnderscore:{type:"boolean"}, allowTrailingUnderscore:{type:"boolean"}, checkObjectProperties:{type:"boolean"}}, additionalProperties:!1}]}, create:function(a) {
var b = Object.assign({}, y, a.options[0] || {});
return {Identifier:function(d) {
d = z(d, b);
d.hasError && a.report({node:d.node, message:d.message});
}};
}});
c.exportProperty(Z.rules, "indent", {meta:{docs:{description:"enforce consistent indentation", category:"Stylistic Issues", recommended:!1}, fixable:"whitespace", schema:[{oneOf:[{enum:["tab"]}, {type:"integer", minimum:0}]}, {type:"object", properties:{SwitchCase:{type:"integer", minimum:0}, VariableDeclarator:{oneOf:[{type:"integer", minimum:0}, {type:"object", properties:{var:{type:"integer", minimum:0}, let:{type:"integer", minimum:0}, const:{type:"integer", minimum:0}}}]}, outerIIFEBody:{type:"integer",
minimum:0}, MemberExpression:{type:"integer", minimum:0}, FunctionDeclaration:{type:"object", properties:{parameters:{oneOf:[{type:"integer", minimum:0}, {enum:["first"]}]}, body:{type:"integer", minimum:0}}}, FunctionExpression:{type:"object", properties:{parameters:{oneOf:[{type:"integer", minimum:0}, {enum:["first"]}]}, body:{type:"integer", minimum:0}}}}, additionalProperties:!1}]}, create:function(a) {
function b(a, b, d) {
var e = "space" + (1 === b ? "" : "s"), f = "tab" + (1 === d ? "" : "s");
return "Expected indentation of " + (a + " " + t + (1 === a ? "" : "s")) + " but" + (" found " + (0 < b && 0 < d ? b + " " + e + " and " + (d + " " + f) : 0 < b ? "space" === t ? b : b + " " + e : 0 < d ? "tab" === t ? d : d + " " + f : "0") + ".");
}
function d(d, e, f, g, h, k) {
var ma = ("space" === t ? " " : "\t").repeat(e), G = k ? [d.range[1] - f - g - 1, d.range[1] - 1] : [d.range[0] - f - g, d.range[0]];
a.report({node:d, loc:h, message:b(e, f, g), fix:function(a) {
return a.replaceTextRange(G, ma);
}});
}
function e(a, b) {
var e = P(a, m, t, !1);
"ArrayExpression" === a.type || "ObjectExpression" === a.type || e.goodChar === b && 0 === e.badChar || !Q(a, m) || d(a, b, e.space, e.tab);
}
function f(a, b) {
a.forEach(function(a) {
return e(a, b);
});
}
function g(a, b) {
var e = m.getLastToken(a), f = P(e, m, t, !0);
f.goodChar === b && 0 === f.badChar || !Q(a, m, !0) || d(a, b, f.space, f.tab, {start:{line:e.loc.start.line, column:e.loc.start.column}}, !0);
}
function h(a) {
var b = P(a, m, t).goodChar, d = a.parent;
if ("Property" === d.type || "ArrayExpression" === d.type) {
b = P(a, m, t, !1).goodChar;
} else {
if ("CallExpression" === d.type) {
var e;
e = 1 <= d.arguments.length ? d.arguments[0].loc.end.line > d.arguments[0].loc.start.line : !1;
e && w.isNodeOneLine(d.callee) && !Q(a, m) && (b = P(d, m, t).goodChar);
}
}
return b;
}
function k(a) {
var b = a.body, d = h(a), e = p, f;
if (f = -1 !== n.outerIIFEBody) {
if (ca(a)) {
f = !0;
} else {
var g = a.parent;
f = g.parent;
if ("CallExpression" !== g.type || g.callee !== a) {
f = !1;
} else {
for (;"UnaryExpression" === f.type || "AssignmentExpression" === f.type || "LogicalExpression" === f.type || "SequenceExpression" === f.type || "VariableDeclarator" === f.type;) {
if ("UnaryExpression" === f.type) {
if (g = f, "!" === g.operator || "~" === g.operator || "+" === g.operator || "-" === g.operator) {
f = f.parent;
} else {
break;
}
} else {
f = f.parent;
}
}
f = ("ExpressionStatement" === f.type || "VariableDeclaration" === f.type) && f.parent && "Program" === f.parent.type;
}
}
}
f ? e = n.outerIIFEBody * p : "FunctionExpression" === a.type ? e = n.FunctionExpression.body * p : "FunctionDeclaration" === a.type && (e = n.FunctionDeclaration.body * p);
d += e;
(f = O.findAncestorOfType(a, "VariableDeclarator")) && R(a, f) && (d += p * n.VariableDeclarator[f.parent.kind]);
x(b, d, d - e);
}
function l(a) {
if (!w.isNodeOneLine(a)) {
var b = a.body;
a = h(a);
x(b, a + p, a);
}
}
function u(a) {
var b = a.parent, e = O.findAncestorOfType(a, "VariableDeclarator"), f = P(b, m, t).goodChar;
if (Q(a, m)) {
if (e) {
if (b === e) {
e === e.parent.declarations[0] && (f += p * n.VariableDeclarator[e.parent.kind]);
} else {
if ("ObjectExpression" === b.type || "ArrayExpression" === b.type || "CallExpression" === b.type || "ArrowFunctionExpression" === b.type || "NewExpression" === b.type || "LogicalExpression" === b.type) {
f += p;
}
}
} else {
var g;
g = "ArrayExpression" !== b.type ? !1 : b.elements[0] ? "ObjectExpression" === b.elements[0].type && b.elements[0].loc.start.line === b.loc.start.line : !1;
g || "MemberExpression" === b.type || "ExpressionStatement" === b.type || "AssignmentExpression" === b.type || "Property" === b.type || (f += p);
}
b = f + p;
g = P(a, m, t, !1);
g.goodChar === f && 0 === g.badChar || !Q(a, m) || d(a, f, g.space, g.tab, {start:{line:a.loc.start.line, column:a.loc.start.column}});
} else {
f = P(a, m, t).goodChar, b = f + p;
}
R(a, e) && (b += p * n.VariableDeclarator[e.parent.kind]);
return b;
}
function x(a, b, d) {
w.isNodeOneLine(a) || (f(a.body, b), g(a, d));
}
function r(a) {
var b = P(a, m, t).goodChar, d = b + p;
"BlockStatement" === a.body.type ? x(a.body, d, b) : f([a.body], d);
}
function C(a, b, d) {
"first" === d && a.params.length ? f(a.params.slice(1), a.params[0].loc.start.column) : f(a.params, b * d);
}
function I(a, b) {
a = "SwitchStatement" === a.type ? a : a.parent;
if (M[a.loc.start.line]) {
return M[a.loc.start.line];
}
"undefined" === typeof b && (b = P(a, m, t).goodChar);
b = 0 < a.cases.length && 0 === n.SwitchCase ? b : b + p * n.SwitchCase;
return M[a.loc.start.line] = b;
}
var E = ea(a.options), t = E.indentType, p = E.indentSize, n = E.indentOptions, m = a.getSourceCode(), M = {};
return {Program:function(a) {
f(a.body, 0);
}, ClassDeclaration:l, ClassExpression:l, BlockStatement:function(a) {
if (!w.isNodeOneLine(a) && ("BlockStatement" == a.parent.type || "Program" == a.parent.type)) {
var b = P(a, m, t).goodChar;
x(a, b + p, b);
}
}, DoWhileStatement:r, ForStatement:r, ForInStatement:r, ForOfStatement:r, WhileStatement:r, WithStatement:r, IfStatement:function(a) {
var b = P(a, m, t).goodChar, d = b + p;
"BlockStatement" !== a.consequent.type ? w.nodesStartOnSameLine(a, a.consequent) || e(a.consequent, d) : (f(a.consequent.body, d), g(a.consequent, b));
if (a.alternate) {
var h = m.getTokenBefore(a.alternate);
e(h, b);
"BlockStatement" !== a.alternate.type ? w.nodesStartOnSameLine(a.alternate, h) || e(a.alternate, d) : (f(a.alternate.body, d), g(a.alternate, b));
}
}, VariableDeclaration:function(a) {
if (!w.nodesStartOnSameLine(a.declarations[0], a.declarations[a.declarations.length - 1])) {
var b = da(a), d = P(a, m, t).goodChar, e = b[b.length - 1], d = d + p * n.VariableDeclarator[a.kind];
f(b, d);
m.getLastToken(a).loc.end.line <= e.loc.end.line || (b = m.getTokenBefore(e), "," === b.value ? g(a, P(b, m, t).goodChar) : g(a, d - p));
}
}, ObjectExpression:function(a) {
if (!w.isNodeOneLine(a)) {
var b = a.properties;
if (!(0 < b.length && w.nodesStartOnSameLine(b[0], a))) {
var d = u(a);
f(b, d);
g(a, d - p);
}
}
}, ArrayExpression:function(a) {
if (!w.isNodeOneLine(a)) {
var b = a.elements.filter(function(a) {
return null != a;
});
if (!(0 < b.length && w.nodesStartOnSameLine(b[0], a))) {
var d = u(a);
f(b, d);
g(a, d - p);
}
}
}, MemberExpression:function(a) {
if (-1 !== n.MemberExpression && !w.isNodeOneLine(a) && !O.findAncestorOfType(a, "VariableDeclarator") && !O.findAncestorOfType(a, "AssignmentExpression")) {
var b = P(a, m, t).goodChar + p * n.MemberExpression, d = [a.property];
a = m.getTokenBefore(a.property);
"Punctuator" === a.type && "." === a.value && d.push(a);
f(d, b);
}
}, SwitchStatement:function(a) {
var b = P(a, m, t).goodChar, d = I(a, b);
f(a.cases, d);
g(a, b);
}, SwitchCase:function(a) {
if (!w.isNodeOneLine(a)) {
var b = I(a);
f(a.consequent, b + p);
}
}, ArrowFunctionExpression:function(a) {
w.isNodeOneLine(a) || "BlockStatement" === a.body.type && k(a);
}, FunctionDeclaration:function(a) {
w.isNodeOneLine(a) || (-1 !== n.FunctionDeclaration.parameters && C(a, p, n.FunctionDeclaration.parameters), k(a));
}, FunctionExpression:function(a) {
w.isNodeOneLine(a) || (-1 !== n.FunctionExpression.parameters && C(a, p, n.FunctionExpression.parameters), k(a));
}};
}});
c.exportProperty(Z.rules, "inline-comment-spacing", {meta:{docs:{description:"enforce consistent spacing before the `//` at line end", category:"Stylistic Issues", recommended:!1}, fixable:"whitespace", schema:[{type:"integer", minimum:0, maximum:5}]}, create:function(a) {
var b = null == a.options[0] ? 1 : a.options[0];
return {LineComment:function(d) {
var e = a.getSourceCode();
e.getComments(d);
e = e.getTokenBefore(d, 1) || e.getTokenOrCommentBefore(d);
if (null != e && w.nodesShareOneLine(d, e)) {
var f = d.start - e.end;
f < b && a.report({node:d, message:"Expected at least " + b + " " + (1 === b ? "space" : "spaces") + " before inline comment.", fix:function(a) {
var e = Array(b - f + 1).join(" ");
return a.insertTextBefore(d, e);
}});
}
}};
}});
c.exportProperty(Z.rules, "jsdoc", {meta:{docs:{description:"enforce valid JSDoc comments", category:"Possible Errors", recommended:!0}, schema:[{type:"object", properties:{prefer:{type:"object", additionalProperties:{type:"string"}}, preferType:{type:"object", additionalProperties:{type:"string"}}, requireReturn:{type:"boolean"}, requireParamDescription:{type:"boolean"}, requireReturnDescription:{type:"boolean"}, matchDescription:{type:"string"}, requireReturnType:{type:"boolean"}}, additionalProperties:!1}]},
create:function(a) {
function b(a) {
f.push({returnPresent:"ArrowFunctionExpression" === a.type && "BlockStatement" !== a.body.type || w.isNodeClassType(a)});
}
function d(b, d) {
W.traverseTags(d, function(d) {
if ("NameExpression" === d.type) {
d = d.name;
var e = C[d];
e && a.report({node:b, message:"Use '" + e + "' instead of '" + d + "'."});
}
});
}
function e(b) {
var e = g.getJSDocComment(b), p = f.pop(), n = Object.create(null), m = !1, E = !1, C = !1, G = !1, V = !1, K;
if (e) {
try {
K = ia.parse(e.value, {strict:!0, unwrap:!0, sloppy:!0});
} catch (na) {
/braces/i.test(na.message) ? a.report({node:e, message:"JSDoc type missing brace."}) : a.report({node:e, message:"JSDoc syntax error."});
return;
}
K.tags.forEach(function(b) {
switch(b.title.toLowerCase()) {
case "param":
case "arg":
case "argument":
b.type || a.report({node:e, message:"Missing JSDoc parameter type for '" + b.name + "'."});
!b.description && u && a.report({node:e, message:"Missing JSDoc parameter description for " + ("'" + b.name + "'.")});
n[b.name] ? a.report({node:e, message:"Duplicate JSDoc parameter '" + b.name + "'."}) : -1 === b.name.indexOf(".") && (n[b.name] = 1);
break;
case "return":
case "returns":
m = !0;
l || p.returnPresent || !c.isNull(b.type) && X(b) || V ? (r && !b.type && a.report({node:e, message:"Missing JSDoc return type."}), X(b) || b.description || !x || a.report({node:e, message:"Missing JSDoc return description."})) : a.report({node:e, message:"Unexpected @{{title}} tag; function has no return statement.", data:{title:b.title}});
break;
case "constructor":
case "class":
E = !0;
break;
case "override":
case "inheritdoc":
G = !0;
break;
case "abstract":
case "virtual":
V = !0;
break;
case "interface":
C = !0;
}
k.containsKey(b.title) && b.title != k.get(b.title) && a.report({node:e, message:"Use @{{name}} instead.", data:{name:k.get(b.title)}});
Y(a, b);
I && b.type && d(e, b.type);
});
G || m || E || C || w.isNodeGetterFunction(b) || w.isNodeSetterFunction(b) || w.isNodeConstructorFunction(b) || w.isNodeClassType(b) || (l || p.returnPresent) && a.report({node:e, message:"Missing JSDoc @return for function."});
var L = Object.keys(n);
b.params && b.params.forEach(function(b, d) {
"AssignmentPattern" === b.type && (b = b.left);
var f = b.name;
"Identifier" === b.type && (L[d] && f !== L[d] ? a.report({node:e, message:"Expected JSDoc for '" + f + "' but found " + ("'" + L[d] + "'.")}) : n[f] || G || a.report({node:e, message:"Missing JSDoc for parameter '" + f + "'."}));
});
h.matchDescription && ((new RegExp(h.matchDescription)).test(K.description) || a.report({node:e, message:"JSDoc description does not satisfy the regex pattern."}));
}
}
var f = [], g = a.getSourceCode(), h = a.options[0] || {}, k = new c.structs.Map(h.prefer), l = !1 !== h.requireReturn, u = !1 !== h.requireParamDescription, x = !1 !== h.requireReturnDescription, r = !1 !== h.requireReturnType, C = h.preferType || {}, I = 0 !== Object.keys(C).length;
return {ArrowFunctionExpression:b, FunctionExpression:b, FunctionDeclaration:b, ClassExpression:b, ClassDeclaration:b, "ArrowFunctionExpression:exit":e, "FunctionExpression:exit":e, "FunctionDeclaration:exit":e, "ClassExpression:exit":e, "ClassDeclaration:exit":e, ReturnStatement:function(a) {
var b = f[f.length - 1];
b && !c.isNull(a.argument) && (b.returnPresent = !0);
}, VariableDeclaration:function(b) {
if (1 === b.declarations.length) {
var d = W.getJSDocComment(b);
if (d) {
var e;
try {
e = W.parseComment(d.value);
} catch (n) {
return;
}
b = b.declarations[0];
"Identifier" === b.id.type && (b = b.id.name, W.hasTypeInformation(e) && a.markVariableAsUsed(b), e.tags.forEach(function(b) {
Y(a, b);
}));
}
}
}};
}});
c.exportProperty(Z.rules, "no-undef", {meta:{docs:{description:"disallow the use of undeclared variables unless mentioned in `/*global */` comments", category:"Variables", recommended:!0}, schema:[{type:"object", properties:{typeof:{type:"boolean"}}, additionalProperties:!1}]}, create:function(a) {
var b = a.options[0], d = b && !0 === b.typeof || !1, e = [], f = [];
return {Program:function(a) {
e = a.body.map(O.matchExtractBareGoogRequire).filter(function(a) {
return !!a;
}).map(function(a) {
return a.source;
});
f = a.body.map(O.matchExtractGoogProvide).filter(function(a) {
return !!a;
}).map(function(a) {
return a.source;
});
}, "Program:exit":function() {
function b(a) {
return f.some(function(b) {
return w.isValidPrefix(a, b);
});
}
function h(a) {
return e.some(function(b) {
return w.isValidPrefix(a, b);
});
}
a.getScope().through.forEach(function(e) {
e = e.identifier;
var f = O.getFullyQualifedName(e), g;
if (g = !d) {
g = e.parent, g = "UnaryExpression" === g.type && "typeof" === g.operator;
}
g || b(f) || h(f) || a.report({node:e, message:"'" + e.name + "' is not defined."});
});
}};
}});
c.exportProperty(Z.rules, "no-unused-expressions", {meta:{docs:{description:"disallow unused expressions", category:"Best Practices", recommended:!1}, schema:[{type:"object", properties:{allowShortCircuit:{type:"boolean"}, allowTernary:{type:"boolean"}}, additionalProperties:!1}]}, create:function(a) {
function b(a) {
if (f && "ConditionalExpression" === a.type) {
return b(a.consequent) && b(a.alternate);
}
if (e && "LogicalExpression" === a.type) {
return b(a.right);
}
var d = /^(?:Assignment|Call|New|Update|Yield|Await)Expression$/.test(a.type);
a = "UnaryExpression" === a.type && 0 <= ["delete", "void"].indexOf(a.operator);
return d || a;
}
var d = a.options[0] || {}, e = d.allowShortCircuit || !1, f = d.allowTernary || !1;
return {ExpressionStatement:function(d) {
var e;
if (e = !b(d.expression)) {
var f = a.getAncestors();
e = f[f.length - 1];
f = f[f.length - 2];
f = "BlockStatement" === e.type && /Function/.test(f.type);
e = "Program" === e.type || f ? c.array.contains(la(ka, e.body), d) : !1;
e = !e;
}
if (e) {
var g;
if (e = W.getJSDocComment(d)) {
try {
var u = W.parseComment(e.value);
g = W.hasTypeInformation(u);
} catch (x) {
g = !1;
}
} else {
g = !1;
}
e = !g;
}
e && a.report({node:d, message:"Expected an assignment or function call and instead saw an expression."});
}};
}});
c.exportProperty(Z.rules, "no-unused-vars", {meta:{docs:{description:"disallow unused variables", category:"Variables", recommended:!0}, schema:[{oneOf:[{enum:["all", "local"]}, {type:"object", properties:{vars:{enum:["all", "local"]}, varsIgnorePattern:{type:"string"}, args:{enum:["all", "after-used", "none"]}, argsIgnorePattern:{type:"string"}, caughtErrors:{enum:["all", "none"]}, caughtErrorsIgnorePattern:{type:"string"}, allowUnusedTypes:{type:"boolean"}}}]}]}, create:function(a) {
function b(a, b) {
return a.range[0] >= b.range[0] && a.range[1] <= b.range[1];
}
function d(a, d) {
var e = a;
for (a = a.parent;a && b(a, d);) {
switch(a.type) {
case "SequenceExpression":
var f = a;
if (f.expressions[f.expressions.length - 1] !== e) {
return !1;
}
break;
case "CallExpression":
case "NewExpression":
return a.callee !== e;
case "AssignmentExpression":
case "TaggedTemplateExpression":
case "YieldExpression":
return !0;
default:
if (u.test(a.type)) {
return !0;
}
}
e = a;
a = a.parent;
}
return !1;
}
function e(a) {
var e = a.defs.filter(function(a) {
return "FunctionName" === a.type;
}).map(function(a) {
return a.node;
}), f = 0 < e.length, g = null;
return a.references.some(function(a) {
var h;
h = a.identifier.parent;
"VariableDeclarator" === h.type && (h = h.parent.parent);
h = "ForInStatement" !== h.type ? !1 : (h = "BlockStatement" === h.body.type ? h.body.body[0] : h.body) ? "ReturnStatement" === h.type : !1;
if (h) {
return !0;
}
h = g;
var k = a.identifier, l = k.parent, m = l.parent, x;
if (x = a.isRead()) {
!(l = "AssignmentExpression" === l.type && "ExpressionStatement" === m.type && l.left === k || "UpdateExpression" === l.type && "ExpressionStatement" === m.type) && (l = h && b(k, h)) && (k = O.findAncestor(k, O.isFunction), l = !(k && b(k, h) && d(k, h))), x = l;
}
h = x;
k = g;
l = a.identifier;
m = l.parent;
x = m.parent;
var r;
if (!(r = a.from.variableScope !== a.resolved.scope.variableScope)) {
b: {
for (r = l;r;) {
if (O.isLoop(r)) {
r = !0;
break b;
}
if (O.isFunction(r)) {
break;
}
r = r.parent;
}
r = !1;
}
}
g = k && b(l, k) ? k : "AssignmentExpression" !== m.type || "ExpressionStatement" !== x.type || l !== m.left || r ? null : m.right;
if (h = a.isRead() && !h) {
if (h = f) {
a: {
for (a = a.from;a;) {
if (0 <= e.indexOf(a.block)) {
h = !0;
break a;
}
a = a.upper;
}
h = !1;
}
}
h = !h;
}
return h;
});
}
function f(b) {
var d = b.defs[0];
return d.index === d.node.params.length - 1 || k.argsIgnorePattern && (d = a.getDeclaredVariables(d.node), d.slice(d.indexOf(b) + 1).every(function(a) {
return 0 === a.references.length && k.argsIgnorePattern && k.argsIgnorePattern.test(a.name);
})) ? !0 : !1;
}
function g(a, b) {
var d = a.variables, h = a.childScopes, l, r;
if ("TDZ" !== a.type && ("global" !== a.type || "all" === k.vars)) {
for (l = 0, r = d.length;l < r;++l) {
var p = d[l];
if (!("class" === a.type && a.block.id === p.identifiers[0] || a.functionExpressionScope || p.eslintUsed || "function" === a.type && "arguments" === p.name && 0 === p.identifiers.length)) {
var n = p.defs[0];
if (n) {
var m = n.type;
if ("CatchClause" === m) {
if ("none" === k.caughtErrors) {
continue;
}
if (k.caughtErrorsIgnorePattern && k.caughtErrorsIgnorePattern.test(n.name.name)) {
continue;
}
}
if ("Parameter" === m) {
if ("Property" === n.node.parent.type && "set" === n.node.parent.kind) {
continue;
}
if ("none" === k.args) {
continue;
}
if (k.argsIgnorePattern && k.argsIgnorePattern.test(n.name.name)) {
continue;
}
if ("after-used" === k.args && !f(p)) {
continue;
}
} else {
if (k.varsIgnorePattern && k.varsIgnorePattern.test(n.name.name)) {
continue;
}
}
}
if (n = !e(p)) {
a: {
if (n = p.defs[0]) {
m = n.node;
if ("VariableDeclarator" === m.type) {
m = m.parent;
} else {
if ("Parameter" === n.type) {
n = !1;
break a;
}
}
n = 0 === m.parent.type.indexOf("Export");
} else {
n = !1;
}
}
n = !n;
}
n && b.push(p);
}
}
}
l = 0;
for (r = h.length;l < r;++l) {
g(h[l], b);
}
return b;
}
function h(a) {
var b = a.eslintExplicitGlobalComment, d = b.loc.start;
a = new RegExp("[\\s,]" + w.escapeRegexp(a.name) + "(?:$|[\\s,:])", "g");
a.lastIndex = b.value.indexOf("global") + 6;
a = (a = a.exec(b.value)) ? a.index + 1 : 0;
var b = b.value.slice(0, a), e = (b.match(/\n/g) || []).length;
a = 0 < e ? a - (1 + b.lastIndexOf("\n")) : a + (d.column + 2);
return {start:{line:d.line + e, column:a}};
}
var k = {vars:"all", args:"after-used", caughtErrors:"none", allowUnusedTypes:!1}, l = a.options[0];
l && (c.isString(l) ? k.vars = l : (k.vars = l.vars || k.vars, k.args = l.args || k.args, k.caughtErrors = l.caughtErrors || k.caughtErrors, l.varsIgnorePattern && (k.varsIgnorePattern = new RegExp(l.varsIgnorePattern)), l.argsIgnorePattern && (k.argsIgnorePattern = new RegExp(l.argsIgnorePattern)), l.caughtErrorsIgnorePattern && (k.caughtErrorsIgnorePattern = new RegExp(l.caughtErrorsIgnorePattern)), l.allowUnusedTypes && (k.allowUnusedTypes = l.allowUnusedTypes)));
var u = /(?:Statement|Declaration)$/;
return {"Program:exit":function(b) {
g(a.getScope(), []).forEach(function(d) {
d.eslintExplicitGlobal ? a.report({node:b, loc:h(d), message:"'{{name}}' is defined but never used.", data:d}) : 0 < d.defs.length && a.report({node:d.identifiers[0], message:"'{{name}}' is defined but never used.", data:d});
});
}};
}});
module.exports = Z;
| apache-2.0 |
lzf-lamer/TODO | app/src/main/java/com/wonder/todotest_mvp/taskdetail/TaskDetailPresenter.java | 4040 | package com.wonder.todotest_mvp.taskdetail;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.google.common.base.Strings;
import com.wonder.todotest_mvp.data.Task;
import com.wonder.todotest_mvp.data.source.TasksDataSource;
import com.wonder.todotest_mvp.data.source.TasksRepository;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Created by wonder on 2016/11/30.
*/
public class TaskDetailPresenter implements TaskDetailContract.Presenter{
private final TasksRepository mTasksRepository;
private final TaskDetailContract.View mTaskDetailView;
@Nullable
private String mTaskId;
public TaskDetailPresenter(@Nullable String taskId,
@NonNull TasksRepository tasksRepository,
@NonNull TaskDetailContract.View taskDetailView){
mTaskId = taskId;
mTasksRepository = checkNotNull(tasksRepository, "tasksRepository cannot be null!");
mTaskDetailView = checkNotNull(taskDetailView, "taskDetailView cannot be null!");
}
@Override
public void loadTask() {
if(mTaskDetailView.isActive()){
openTask();
}
}
private void openTask(){
if(Strings.isNullOrEmpty(mTaskId)){
mTaskDetailView.showMissingTask();
return;
}
if(mTaskDetailView.isActive()){
mTaskDetailView.showLoadingIndicator(true);
}
mTasksRepository.getTask(mTaskId, new TasksDataSource.GetTaskCallback() {
@Override
public void onTaskLoaded(Task task) {
if(!mTaskDetailView.isActive()){
return;
}
mTaskDetailView.showLoadingIndicator(false);
if(null == task){
mTaskDetailView.showMissingTask();
}else{
showTask(task);
}
}
@Override
public void onDataNotAvailable() {
if(!mTaskDetailView.isActive()){
return;
}
mTaskDetailView.showMissingTask();
}
});
}
@Override
public void editTask() {
if(Strings.isNullOrEmpty(mTaskId)){
mTaskDetailView.showMissingTask();
return;
}
mTaskDetailView.showEditTask(mTaskId);
}
@Override
public void deleteTask() {
if(Strings.isNullOrEmpty(mTaskId)){
mTaskDetailView.showMissingTask();
return;
}
mTasksRepository.deleteTask(mTaskId);
mTaskDetailView.showTaskDeleted();
}
@Override
public void completeTask() {
if(Strings.isNullOrEmpty(mTaskId)){
mTaskDetailView.showMissingTask();
return;
}
mTasksRepository.completeTask(mTaskId);
mTaskDetailView.showTaskMarkedComplete();
}
@Override
public void activateTask() {
if(Strings.isNullOrEmpty(mTaskId)){
mTaskDetailView.showMissingTask();
return;
}
mTasksRepository.activateTask(mTaskId);
mTaskDetailView.showTaskMarkedActive();
}
private void showTask(@NonNull Task task){
String title = task.getTitle();
String description = task.getDescription();
if(Strings.isNullOrEmpty(title)){
mTaskDetailView.hideTitle();
}else{
mTaskDetailView.showTitle(title);
}
if(Strings.isNullOrEmpty(description)){
mTaskDetailView.hideDescription();
}else{
mTaskDetailView.showDescription(description);
}
mTaskDetailView.showCompletionStatus(task.isCompleted());
}
@Override
public void setTaskId(String taskId) {
mTaskId = taskId;
if(null == taskId){
mTaskDetailView.showMissingTask();
}
}
@Override
public String getTaskId() {
return mTaskId;
}
}
| apache-2.0 |
omahaprogrammer/authserver | src/main/java/com/pazdev/authserver/model/Profile.java | 14526 | /*
* Copyright 2016 Jonathan Paz <jonathan@pazdev.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pazdev.authserver.model;
import java.io.Serializable;
import java.time.Instant;
import java.time.LocalDate;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Jonathan Paz <jonathan@pazdev.com>
*/
@Entity
@Table(name = "profile", uniqueConstraints = {
@UniqueConstraint(columnNames = {"sub"})})
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Profile.findAll", query = "SELECT p FROM Profile p")
, @NamedQuery(name = "Profile.findById", query = "SELECT p FROM Profile p WHERE p.id = :id")
, @NamedQuery(name = "Profile.findBySub", query = "SELECT p FROM Profile p WHERE p.sub = :sub")
, @NamedQuery(name = "Profile.findByPreferredUsername", query = "SELECT p FROM Profile p WHERE p.preferredUsername = :preferredUsername")
, @NamedQuery(name = "Profile.findByWebsite", query = "SELECT p FROM Profile p WHERE p.website = :website")
, @NamedQuery(name = "Profile.findByEmail", query = "SELECT p FROM Profile p WHERE p.email = :email")
, @NamedQuery(name = "Profile.findByEmailVerified", query = "SELECT p FROM Profile p WHERE p.emailVerified = :emailVerified")
, @NamedQuery(name = "Profile.findByGender", query = "SELECT p FROM Profile p WHERE p.gender = :gender")
, @NamedQuery(name = "Profile.findByBirthdate", query = "SELECT p FROM Profile p WHERE p.birthdate = :birthdate")
, @NamedQuery(name = "Profile.findByZoneinfo", query = "SELECT p FROM Profile p WHERE p.zoneinfo = :zoneinfo")
, @NamedQuery(name = "Profile.findByLocale", query = "SELECT p FROM Profile p WHERE p.locale = :locale")
, @NamedQuery(name = "Profile.findByPhoneNumber", query = "SELECT p FROM Profile p WHERE p.phoneNumber = :phoneNumber")
, @NamedQuery(name = "Profile.findByPhoneNumberVerified", query = "SELECT p FROM Profile p WHERE p.phoneNumberVerified = :phoneNumberVerified")
, @NamedQuery(name = "Profile.findByAddressFormatted", query = "SELECT p FROM Profile p WHERE p.addressFormatted = :addressFormatted")
, @NamedQuery(name = "Profile.findByAddressStreetAddress", query = "SELECT p FROM Profile p WHERE p.addressStreetAddress = :addressStreetAddress")
, @NamedQuery(name = "Profile.findByAddressLocality", query = "SELECT p FROM Profile p WHERE p.addressLocality = :addressLocality")
, @NamedQuery(name = "Profile.findByAddressRegion", query = "SELECT p FROM Profile p WHERE p.addressRegion = :addressRegion")
, @NamedQuery(name = "Profile.findByAddressPostalCode", query = "SELECT p FROM Profile p WHERE p.addressPostalCode = :addressPostalCode")
, @NamedQuery(name = "Profile.findByAddressCountry", query = "SELECT p FROM Profile p WHERE p.addressCountry = :addressCountry")
, @NamedQuery(name = "Profile.findByUpdatedAt", query = "SELECT p FROM Profile p WHERE p.updatedAt = :updatedAt")})
public class Profile implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id", nullable = false)
private Integer id;
@Basic(optional = false)
@NotNull
@Column(name = "sub", nullable = false)
private String sub;
@Column(name = "profile_name")
private String profileName;
@Column(name = "given_name")
private String givenName;
@Column(name = "family_name")
private String familyName;
@Column(name = "middle_name")
private String middleName;
@Column(name = "nickname")
private String nickname;
@Basic(optional = false)
@NotNull
@Column(name = "preferred_username", nullable = false)
private String preferredUsername;
@Basic(optional = false)
@NotNull
@Lob
@Column(name = "password_bytes", nullable = false)
private byte[] passwordBytes;
@Basic(optional = false)
@NotNull
@Lob
@Column(name = "salt", nullable = false)
private byte[] salt;
@Basic(optional = false)
@NotNull
@Column(name = "rounds")
private int rounds;
@JoinColumn(name = "picture", referencedColumnName = "id")
@ManyToOne(optional = false)
private UploadedContent picture;
@Column(name = "website")
private String website;
// @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
@Column(name = "email")
private String email;
@Basic(optional = false)
@NotNull
@Column(name = "email_verified", nullable = false)
private boolean emailVerified;
@Column(name = "gender")
private String gender;
@Column(name = "birthdate")
private LocalDate birthdate;
@Column(name = "zoneinfo")
private String zoneinfo;
@Column(name = "locale")
private String locale;
@Column(name = "phone_number")
private String phoneNumber;
@Basic(optional = false)
@NotNull
@Column(name = "phone_number_verified", nullable = false)
private boolean phoneNumberVerified;
@Column(name = "address_formatted")
private String addressFormatted;
@Column(name = "address_street_address")
private String addressStreetAddress;
@Column(name = "address_locality")
private String addressLocality;
@Column(name = "address_region")
private String addressRegion;
@Column(name = "address_postal_code")
private String addressPostalCode;
@Column(name = "address_country")
private String addressCountry;
@Column(name = "updated_at")
private Instant updatedAt;
@OneToMany(mappedBy = "accountId")
private Set<ProfileAttribute> profileAttributeSet;
@OneToMany(mappedBy = "profileId")
private Set<ProfileAddress> profileAddressSet;
@OneToMany(mappedBy = "profileId")
private Set<Client> clientSet;
@OneToMany(mappedBy = "profileId")
private Set<SessionInfo> sessionInfoSet;
public Profile() {
}
public Profile(Integer id) {
this.id = id;
}
public Profile(Integer id, String sub, String preferredUsername, byte[] passwordBytes, byte[] salt, Integer rounds, boolean emailVerified, boolean phoneNumberVerified) {
this.id = id;
this.sub = sub;
this.preferredUsername = preferredUsername;
this.passwordBytes = passwordBytes;
this.salt = salt;
this.rounds = rounds;
this.emailVerified = emailVerified;
this.phoneNumberVerified = phoneNumberVerified;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSub() {
return sub;
}
public void setSub(String sub) {
this.sub = sub;
}
public String getPreferredUsername() {
return preferredUsername;
}
public void setPreferredUsername(String preferredUsername) {
this.preferredUsername = preferredUsername;
}
public byte[] getPasswordBytes() {
return passwordBytes;
}
public void setPasswordBytes(byte[] passwordBytes) {
this.passwordBytes = passwordBytes;
}
public byte[] getSalt() {
return salt;
}
public void setSalt(byte[] salt) {
this.salt = salt;
}
public int getRounds() {
return rounds;
}
public void setRounds(int rounds) {
this.rounds = rounds;
}
public UploadedContent getPicture() {
return picture;
}
public void setPicture(UploadedContent picture) {
this.picture = picture;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean getEmailVerified() {
return emailVerified;
}
public void setEmailVerified(boolean emailVerified) {
this.emailVerified = emailVerified;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public LocalDate getBirthdate() {
return birthdate;
}
public void setBirthdate(LocalDate birthdate) {
this.birthdate = birthdate;
}
public String getZoneinfo() {
return zoneinfo;
}
public void setZoneinfo(String zoneinfo) {
this.zoneinfo = zoneinfo;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public boolean getPhoneNumberVerified() {
return phoneNumberVerified;
}
public void setPhoneNumberVerified(boolean phoneNumberVerified) {
this.phoneNumberVerified = phoneNumberVerified;
}
public String getAddressFormatted() {
return addressFormatted;
}
public void setAddressFormatted(String addressFormatted) {
this.addressFormatted = addressFormatted;
}
public String getAddressStreetAddress() {
return addressStreetAddress;
}
public void setAddressStreetAddress(String addressStreetAddress) {
this.addressStreetAddress = addressStreetAddress;
}
public String getAddressLocality() {
return addressLocality;
}
public void setAddressLocality(String addressLocality) {
this.addressLocality = addressLocality;
}
public String getAddressRegion() {
return addressRegion;
}
public void setAddressRegion(String addressRegion) {
this.addressRegion = addressRegion;
}
public String getAddressPostalCode() {
return addressPostalCode;
}
public void setAddressPostalCode(String addressPostalCode) {
this.addressPostalCode = addressPostalCode;
}
public String getAddressCountry() {
return addressCountry;
}
public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}
public Instant getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Instant updatedAt) {
this.updatedAt = updatedAt;
}
@XmlTransient
public Set<ProfileAttribute> getProfileAttributeSet() {
return profileAttributeSet;
}
public void setProfileAttributeSet(Set<ProfileAttribute> profileAttributeSet) {
this.profileAttributeSet = profileAttributeSet;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Profile)) {
return false;
}
Profile other = (Profile) object;
return !((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id)));
}
@Override
public String toString() {
return "com.pazdev.authserver.Profile[ id=" + id + " ]";
}
@XmlTransient
public Set<ProfileAddress> getProfileAddressSet() {
return profileAddressSet;
}
public void setProfileAddressSet(Set<ProfileAddress> profileAddressSet) {
this.profileAddressSet = profileAddressSet;
}
@XmlTransient
public Set<Client> getClientSet() {
return clientSet;
}
public void setClientSet(Set<Client> clientSet) {
this.clientSet = clientSet;
}
public String getProfileName() {
return profileName;
}
public void setProfileName(String profileName) {
this.profileName = profileName;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
@XmlTransient
public Set<SessionInfo> getSessionInfoSet() {
return sessionInfoSet;
}
public void setSessionInfoSet(Set<SessionInfo> sessionInfoSet) {
this.sessionInfoSet = sessionInfoSet;
}
}
| apache-2.0 |
eekboom/gerrit-intellij-plugin | src/main/java/com/urswolfer/intellij/plugin/gerrit/ui/diff/RemoveCommentAction.java | 3126 | /*
* Copyright 2013 Urs Wolfer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.urswolfer.intellij.plugin.gerrit.ui.diff;
import com.google.gerrit.extensions.client.Comment;
import com.google.gerrit.extensions.common.ChangeInfo;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.util.Consumer;
import com.urswolfer.intellij.plugin.gerrit.rest.GerritUtil;
/**
* @author Urs Wolfer
*/
@SuppressWarnings("ComponentNotRegistered") // added with code
public class RemoveCommentAction extends AnAction implements DumbAware {
private final CommentsDiffTool commentsDiffTool;
private final Editor editor;
private final GerritUtil gerritUtil;
private final ChangeInfo changeInfo;
private final Comment comment;
private final String revisionId;
private final RangeHighlighter lineHighlighter;
private final RangeHighlighter rangeHighlighter;
public RemoveCommentAction(CommentsDiffTool commentsDiffTool,
Editor editor,
GerritUtil gerritUtil,
ChangeInfo changeInfo,
Comment comment,
String revisionId,
RangeHighlighter lineHighlighter,
RangeHighlighter rangeHighlighter) {
super("Remove", "Remove selected comment", AllIcons.Actions.Delete);
this.commentsDiffTool = commentsDiffTool;
this.comment = comment;
this.gerritUtil = gerritUtil;
this.changeInfo = changeInfo;
this.revisionId = revisionId;
this.lineHighlighter = lineHighlighter;
this.editor = editor;
this.rangeHighlighter = rangeHighlighter;
}
@Override
public void actionPerformed(AnActionEvent e) {
final Project project = e.getData(PlatformDataKeys.PROJECT);
gerritUtil.deleteDraftComment(changeInfo._number, revisionId, comment.id, project,
new Consumer<Void>() {
@Override
public void consume(Void aVoid) {
commentsDiffTool.removeComment(project, editor, lineHighlighter, rangeHighlighter);
}
});
}
}
| apache-2.0 |
efalder413/civitas-pervia | src/Civitas/Bundle/AppBundle/Tests/Controller/SettingsControllerTest.php | 168 | <?php
namespace Civitas\Bundle\AppBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class SettingsControllerTest extends WebTestCase
{
}
| apache-2.0 |
paragbaxi/qualysguard_scan_new_assets | qualysguard_scan_new_assets.py | 4446 | # Parse map XML for live but not scannable IPs.
import argparse
import csv
import datetime
from collections import defaultdict
import logging
import os
import qualysapi
from lxml import objectify
#
# Begin
#
# Declare the command line flags/options we want to allow.
parser = argparse.ArgumentParser(description = 'Parse QualysGuard VM map XML for live but not scannable IPs.')
parser.add_argument('-a', '--asset_group',
help = 'Asset group to add IPs to.')
# parser.add_argument('-e', '--exclude',
# default = 'exclude.csv',
# help = 'FUTURE: IPs to exclude from adding to the subscription.')
parser.add_argument('-f', '--file_ip_list',
default = '%s_live_not_scannable.csv' % (datetime.datetime.now().strftime('%Y-%m-%d.%H-%M-%S')),
help = 'CSV to output of live, not scannable IPs.')
parser.add_argument('-m', '--map',
help = 'Map XML to find live not scannable IPs.')
parser.add_argument('-s', '--subscribe', action = 'store_true',
help = 'Automatically add IPs to subscription.')
parser.add_argument('-v', '--debug', action = 'store_true',
help = 'Outputs additional information to log.')
parser.add_argument('--config',
help = 'Configuration for Qualys connector.')
# Parse arguments.
args = parser.parse_args()# Create log directory.
# Validate input.
if not (args.map or \
args.subscribe_from_csv):
parser.print_help()
exit()
# Create log directory.
PATH_LOG = 'log'
if not os.path.exists(PATH_LOG):
os.makedirs(PATH_LOG)
# Set log options.
LOG_FILENAME = '%s/%s-%s.log' % (PATH_LOG,
__file__,
datetime.datetime.now().strftime('%Y-%m-%d.%H-%M-%S'))
# Make a global logging object.
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# This handler writes everything to a file.
logger_file = logging.FileHandler(LOG_FILENAME)
logger_file.setFormatter(logging.Formatter("%(asctime)s %(name)-12s %(levelname)s %(funcName)s %(lineno)d %(message)s"))
logger_file.setLevel(logging.INFO)
if c_args.verbose:
logger_file.setLevel(logging.DEBUG)
logger.addHandler(logger_file)
# This handler prints to screen.
logger_console = logging.StreamHandler(sys.stdout)
logger_console.setLevel(logging.ERROR)
logger.addHandler(logger_console)
#
# Read in XML map.
with open(args.map) as xml_file:
xml_output = xml_file.read()
tree = objectify.fromstring(xml_output)
# Find live, not scannable IPs.
count = 0
subscribe_me = set()
with open(args.file_ip_list, 'wb') as csvfile:
csvwriter = csv.writer(csvfile,
quoting=csv.QUOTE_ALL)
# Write header to CSV.
csvwriter.writerow(['IP', 'Hostname', 'NetBIOS', 'OS'])
# Add each host.
for host in tree.HOST_LIST.HOST:
# Skip to next host if host is already in subscription.
if host.SCANNABLE == 1:
continue
# Skip to next host if host is not alive.
if host.LIVE == 0:
continue
# Grab IP.
ip = str(host.IP)
# Grab Hostname.
hostname = ''
try:
hostname = str(host.HOSTNAME)
except AttributeError, e:
logging.debug('%s: No hostname.' % (ip, str(e)))
# Grab NetBIOS.
netbios = ''
try:
netbios = str(host.NETBIOS)
except AttributeError, e:
logging.debug('%s: No NetBIOS.' % (ip, str(e)))
# Grab OS.
os = ''
try:
os = str(host.OS)
except AttributeError, e:
logging.debug('%s: No OS.' % (ip, str(e)))
# Write to CSV.
csvwriter.writerow([ip, hostname, netbios, os])
# Increment number of hosts found.
count += 1
# Store ip in set.
subscribe_me.add(ip)
# All data stored. Print out to files.
print 'Number of live, not scannable hosts found: %s' % str(count)
print 'Host details successfully written to %s.' % args.file_ip_list
# Subscribe IPs, if requested.
if not args.subscribe:
exit()
if c_args.config:
qgc = qualysapi.connect(c_args.config)
else:
qgc = qualysapi.connect()
# Combine IPs to comma-delimited string.
formatted_ips_to_subscribe = ','.join(subscribe_me)
# Subscribe IPs.
qgc = qualysapi.connect('asset_ip.php',{'action': 'add', 'host_ips': formatted_ips_to_subscribe})
exit()
| apache-2.0 |
xehoth/OnlineJudgeCodes | BZOJ/BZOJ1061.cpp | 2885 | /**
* Copyright (c) 2017, xehoth
* All rights reserved.
* 「BZOJ 1061」26-03-2017
*
* @author xehoth
*/
#include <bits/stdc++.h>
inline int read() {
static const int IN_LEN = 1000000;
static char buf[IN_LEN], *h, *t;
if (h == t) {
t = (h = buf) + fread(buf, 1, IN_LEN, stdin);
if (h == t) return -1;
}
return *h++;
}
template <class T>
inline bool read(T &x) {
static bool iosig = 0;
static char c;
for (iosig = 0, c = read(); !isdigit(c); c = read()) {
if (c == -1) return false;
if (c == '-') iosig = 1;
}
for (x = 0; isdigit(c); c = read()) x = (x + (x << 2) << 1) + (c ^ '0');
if (iosig) x = -x;
return true;
}
const int OUT_LEN = 10000000;
char obuf[OUT_LEN], *oh = obuf;
inline void print(const char c) {
if (oh == obuf + OUT_LEN) fwrite(obuf, 1, OUT_LEN, stdout), oh = obuf;
*oh++ = c;
}
template <class T>
inline void print(T x) {
static int buf[30], cnt;
if (!x)
print('0');
else {
if (x < 0) print('-'), x = -x;
for (cnt = 0; x; x /= 10) buf[++cnt] = x % 10 + 48;
while (cnt) print((char)buf[cnt--]);
}
}
inline void flush() { fwrite(obuf, 1, oh - obuf, stdout); }
#define long long long
const int MAXN = 1005;
const int MAXM = 1e4 + 5;
double a[MAXM][MAXN];
int q[MAXN];
int n, m;
int id[MAXN << 1];
const double EPS = 1e-7;
const double INF = 1e15;
inline void pivot(int l, int e) {
std::swap(id[n + l], id[e]);
double t = a[l][e];
a[l][e] = 1;
for (register int j = 0; j <= n; j++) a[l][j] /= t;
register int p = 0;
for (register int j = 0; j <= n; j++)
if (std::abs(a[l][j]) > EPS) q[++p] = j;
for (register int i = 0; i <= m; i++) {
if (i != l && std::abs(a[i][e]) > EPS) {
t = a[i][e], a[i][e] = 0;
for (register int j = 1; j <= p; j++) a[i][q[j]] -= t * a[l][q[j]];
}
}
}
inline void simplex() {
while (true) {
register int l = 0, e = 0;
double min = INF;
for (register int j = 1; j <= n; j++) {
if (a[0][j] > EPS) {
e = j;
break;
}
}
if (!e) break;
for (register int i = 1; i <= m; i++)
if (a[i][e] > EPS && a[i][0] / a[i][e] < min)
min = a[i][0] / a[i][e], l = i;
if (!l) {
// puts("Unbounded");
return; // false;
}
pivot(l, e);
}
// return true;
}
int main() {
// freopen("in.in", "r", stdin);
read(n), read(m);
for (register int i = 1, t; i <= n; i++) read(t), a[0][i] = t;
for (register int i = 1, x, y, z; i <= m; i++) {
read(x), read(y), read(z);
for (register int j = x; j <= y; j++) a[i][j] = 1;
a[i][0] = z;
}
simplex();
print(int(-a[0][0] + 0.5));
flush();
return 0;
}
| apache-2.0 |
cloudera/Impala | be/src/runtime/bufferpool/free-list-test.cc | 5990 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <cstdlib>
#include <random>
#include "common/object-pool.h"
#include "runtime/bufferpool/free-list.h"
#include "runtime/bufferpool/system-allocator.h"
#include "runtime/test-env.h"
#include "service/fe-support.h"
#include "testutil/gtest-util.h"
#include "testutil/rand-util.h"
#include "common/names.h"
namespace impala {
class FreeListTest : public ::testing::Test {
protected:
virtual void SetUp() override {
test_env_.reset(new TestEnv);
ASSERT_OK(test_env_->Init());
allocator_ = obj_pool_.Add(new SystemAllocator(MIN_BUFFER_LEN));
RandTestUtil::SeedRng("FREE_LIST_TEST_SEED", &rng_);
}
virtual void TearDown() override {
allocator_ = nullptr;
obj_pool_.Clear();
}
void AllocateBuffers(
int num_buffers, int64_t buffer_len, vector<BufferHandle>* buffers) {
for (int i = 0; i < num_buffers; ++i) {
BufferHandle buffer;
ASSERT_OK(allocator_->Allocate(buffer_len, &buffer));
buffers->push_back(move(buffer));
}
}
vector<const void*> GetSortedAddrs(const vector<BufferHandle>& buffers) {
vector<const void*> addrs;
for (const BufferHandle& buffer : buffers) addrs.push_back(buffer.data());
std::sort(addrs.begin(), addrs.end());
return addrs;
}
void AddFreeBuffers(FreeList* list, vector<BufferHandle>* buffers) {
for (BufferHandle& buffer : *buffers) {
list->AddFreeBuffer(move(buffer));
}
buffers->clear();
}
void FreeBuffers(vector<BufferHandle>&& buffers) {
for (BufferHandle& buffer : buffers) {
allocator_->Free(move(buffer));
}
}
const static int MIN_BUFFER_LEN = 1024;
boost::scoped_ptr<TestEnv> test_env_;
/// Per-test random number generator. Seeded before every test.
std::mt19937 rng_;
/// Pool for objects with per-test lifetime. Cleared after every test.
ObjectPool obj_pool_;
/// The buffer allocator, owned by 'obj_pool_'.
SystemAllocator* allocator_;
};
const int FreeListTest::MIN_BUFFER_LEN;
// Functional test for a small free list.
TEST_F(FreeListTest, SmallList) {
const int LIST_SIZE = 2;
FreeList small_list;
// PopFreeBuffer() on empty list returns false.
BufferHandle buffer;
ASSERT_FALSE(small_list.PopFreeBuffer(&buffer));
ASSERT_FALSE(small_list.PopFreeBuffer(&buffer));
// Add various numbers of buffers to the free list and check that they're
// either freed or returned in the order expected.
for (int num_buffers = 0; num_buffers <= LIST_SIZE + 2; ++num_buffers) {
for (int attempt = 0; attempt < 10; ++attempt) {
LOG(INFO) << "num_buffers " << num_buffers << " attempt " << attempt;
vector<BufferHandle> buffers;
AllocateBuffers(num_buffers, MIN_BUFFER_LEN, &buffers);
// Keep track of the addresses so we can validate the buffer order.
const vector<const void*> addrs = GetSortedAddrs(buffers);
// Try shuffling to make sure we don't always just add in ascending order.
std::shuffle(buffers.begin(), buffers.end(), rng_);
AddFreeBuffers(&small_list, &buffers);
// Shrink list down to LIST_SIZE.
FreeBuffers(
small_list.GetBuffersToFree(max<int64_t>(0, small_list.Size() - LIST_SIZE)));
// The LIST_SIZE buffers with the lowest address should be retained, and the
// remaining buffers should have been freed.
for (int i = 0; i < min(num_buffers, LIST_SIZE); ++i) {
ASSERT_TRUE(small_list.PopFreeBuffer(&buffer)) << i;
ASSERT_EQ(addrs[i], buffer.data()) << i;
buffers.push_back(move(buffer));
}
ASSERT_FALSE(small_list.PopFreeBuffer(&buffer));
FreeBuffers(move(buffers));
}
}
}
// Functional test that makes sure the free lists return buffers in ascending order
TEST_F(FreeListTest, ReturnOrder) {
const int LIST_SIZE = 100;
FreeList list;
for (int num_buffers = 50; num_buffers <= 400; num_buffers *= 2) {
for (int attempt = 0; attempt < 5; ++attempt) {
LOG(INFO) << "num_buffers " << num_buffers << " attempt " << attempt;
vector<BufferHandle> buffers;
AllocateBuffers(num_buffers, MIN_BUFFER_LEN, &buffers);
// Keep track of the addresses so we can validate the buffer order.
const vector<const void*> addrs = GetSortedAddrs(buffers);
// Try shuffling to make sure we don't always just add in ascending order.
std::shuffle(buffers.begin(), buffers.end(), rng_);
AddFreeBuffers(&list, &buffers);
// Free buffers. Only the buffers with the high addresses should be freed.
FreeBuffers(list.GetBuffersToFree(max<int64_t>(0, list.Size() - LIST_SIZE)));
// Validate that the buffers with lowest addresses are returned in ascending order.
BufferHandle buffer;
for (int i = 0; i < min(LIST_SIZE, num_buffers); ++i) {
ASSERT_TRUE(list.PopFreeBuffer(&buffer));
ASSERT_EQ(addrs[i], buffer.data()) << i;
allocator_->Free(move(buffer));
}
ASSERT_FALSE(list.PopFreeBuffer(&buffer));
}
}
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
impala::InitCommonRuntime(argc, argv, true, impala::TestInfo::BE_TEST);
impala::InitFeSupport();
return RUN_ALL_TESTS();
}
| apache-2.0 |
SkygearIO/skygear-server | pkg/auth/dependency/forgotpassword/store_impl.go | 1637 | package forgotpassword
import (
"context"
"encoding/json"
"fmt"
"time"
goredis "github.com/gomodule/redigo/redis"
"github.com/skygeario/skygear-server/pkg/core/errors"
"github.com/skygeario/skygear-server/pkg/core/redis"
)
type StoreImpl struct {
Context context.Context
}
var _ Store = &StoreImpl{}
func (s *StoreImpl) Create(code *Code) (err error) {
bytes, err := json.Marshal(code)
if err != nil {
return
}
conn := redis.GetConn(s.Context)
key := codeKey(code.CodeHash)
_, err = goredis.String(conn.Do("SET", key, bytes, "PX", codeExpire(code), "NX"))
if errors.Is(err, goredis.ErrNil) {
err = errors.Newf("duplicated forgot password code: %w", err)
return
}
return
}
func (s *StoreImpl) Update(code *Code) (err error) {
bytes, err := json.Marshal(code)
if err != nil {
return
}
conn := redis.GetConn(s.Context)
key := codeKey(code.CodeHash)
_, err = goredis.String(conn.Do("SET", key, bytes, "PX", codeExpire(code), "XX"))
if errors.Is(err, goredis.ErrNil) {
err = errors.Newf("non-existent forgot password code: %w", err)
return
}
return
}
func (s *StoreImpl) Get(codeHash string) (code *Code, err error) {
conn := redis.GetConn(s.Context)
key := codeKey(codeHash)
data, err := goredis.Bytes(conn.Do("GET", key))
if errors.Is(err, goredis.ErrNil) {
err = ErrInvalidCode
return
} else if err != nil {
return
}
err = json.Unmarshal(data, &code)
return
}
func codeKey(codeHash string) string {
return fmt.Sprintf("forgotpassword-code:%s", codeHash)
}
func codeExpire(code *Code) int64 {
d := code.ExpireAt.Sub(code.CreatedAt)
return int64(d / time.Millisecond)
}
| apache-2.0 |
tatematsu/Michelle-iOS | Resources/order_hatsukaichi.js | 5551 | stageWidth = Titanium.Platform.displayCaps.platformWidth;
// フォームを表示するビュー作成
var formView = Ti.UI.createView({
top: 0
});
/* 廿日市店の予約ウィンドウ */
Ti.UI.currentWindow.addEventListener('open',function(e){
//やりたい事
var selected_hotel = 1;
var hatsu_reserve_label = Ti.UI.createLabel({
text:'金曜のみ宿泊・休憩受付可能/土日祝日は受付ておりません。',
width: stageWidth*0.9,
top: 10,
color:'#333333'
});
var hatsu_date_tf = Ti.UI.createTextField({
color:'#333333',
hintText:'ご予約希望日',
height:35,
top:60,
left: 30,
width: 250,
borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});
var hatsu_time_tf = Ti.UI.createTextField({
color:'#333333',
hintText:'ご希望時間帯',
height:35,
top: 100,
left: 30,
width: 250,
borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});
var hatsu_name_tf = Ti.UI.createTextField({
color:'#333333',
hintText:'お名前',
height:35,
top: 150,
left: 30,
width: 250,
borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});
var hatsu_tel_tf = Ti.UI.createTextField({
color:'#333333',
hintText:'携帯番号(ハイフンなし)',
height:35,
top: 190,
left: 30,
width: 250,
borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});
var hatsu_email_tf = Ti.UI.createTextField({
color:'#333333',
hintText:'ご連絡メールアドレス',
height:35,
top: 230,
left: 30,
width: 250,
borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});
var hatsu_btn = Ti.UI.createButton({
title:'廿日市店で予約する',
top: 270,
left: 100,
width: 200,
height: 50
});
var hatsu_cancel_btn = Ti.UI.createButton({
title:'戻る',
top: 270,
left: 30,
width: 100,
height: 50
});
// フォームパーツをビューに追加
formView.add(hatsu_reserve_label);
formView.add(hatsu_time_tf);
formView.add(hatsu_date_tf);
formView.add(hatsu_name_tf);
formView.add(hatsu_email_tf);
formView.add(hatsu_tel_tf);
formView.add(hatsu_btn);
formView.add(hatsu_cancel_btn);
//キャンセル
hatsu_cancel_btn.addEventListener('click', function(e){
Ti.UI.currentWindow.close();
});
// 送信ボタン押下時の処理
hatsu_btn.addEventListener('click', function(e){
reserve_date = hatsu_date_tf.getValue();
reserve_time = hatsu_time_tf.getValue();
reserve_name = hatsu_name_tf.getValue();
reserve_email = hatsu_email_tf.getValue();
reserve_tel = hatsu_tel_tf.getValue();
try{
if( reserve_date == "" ){
//alert('empty date');
var er = new Error("日付が入力されていません。");
throw er;
}
if( reserve_time == "" ){
//alert('empty time');
var er = new Error("時間帯が入力されていません。");
throw er; }
if( reserve_name == "" ){
//alert('empty email');
var er = new Error("お名前が入力されていません。");
throw er;
}
if( reserve_email == "" ){
//alert('empty email');
var er = new Error("メールアドレスが入力されていません。");
throw er;
}
if (!reserve_email.match(/^[A-Za-z0-9]+[\w-]+@[\w\.-]+\.\w{2,}$/)){
var er = new Error("メールアドレスをご確認ください。");
throw er;
}
if( reserve_tel == "" ){
//alert('empty email');
var er = new Error("電話番号が入力されていません。");
throw er;
}
if ( !reserve_tel.match(/^[0-9]{11}$/) ){
var er = new Error("電話番号をご確認ください。");
throw er;
}
// オブジェクトを生成
var xhr = Ti.Network.createHTTPClient();
//パラメータ作成
var url_param = "?reserve_hotel="+selected_hotel
+"&reserve_date="+reserve_date
+"&reserve_time="+reserve_time
+"&reserve_name="+reserve_name
+"&reserve_email="+reserve_email
+"&reserve_tel="+reserve_tel;
//Ti.API.info(url_param);
// データダウンロード時のイベント処理
xhr.onload = function() {
//JSON形式レスポンス取得
var json = JSON.parse(this.responseText);
//alert(json);
if( json.status == 1 ){
var thanks_dialog = Ti.UI.createAlertDialog();
thanks_dialog.setTitle('ラ・ミッシェル廿日市店へのご予約ありがとうございました。\nご予約内容を確認・ご手配の後ご連絡をいたします。\n何卒よろしくお願いいたします。');
thanks_dialog.setMessage(e.message);
thanks_dialog.show();
/*
Ti.UI.currentWindow.remove(tableView);
thanksView.add(thanks_label);
Ti.UI.currentWindow.add(thanksView);*/
//正常に登録できたら、サンクスメッセージ
Ti.UI.currentWindow.close();
//正常に登録できたら、サンクスメッセージ
}else{
//var er = new Error("サーバエラーで予約が出来ませんでした。");
//throw er;
}
};
xhr.onerror = function(error){
//Ti.API.info(error[0]);
};
//xhr.timeout = 5000; // 結果が5秒返ってこなかったらエラーにする
xhr.open('GET','http://www.la-michelle.com/wp-content/themes/michelle-grp/reserve_mobile.php'+url_param);
xhr.send();
}catch(e){
//alert(e.message);
var err_dialog = Titanium.UI.createAlertDialog();
err_dialog.setTitle('入力エラーです。');
err_dialog.setMessage(e.message);
err_dialog.show();
// Ti.UI.currentWindow.close();
}finally{
}
});
Ti.UI.currentWindow.add(formView);
}); | apache-2.0 |
westman2000/MVPCAndroid | mvpc_rx/src/main/java/corp/wmsoft/android/lib/mvpcrx/delegate/MVPCDelegate.java | 4654 | package corp.wmsoft.android.lib.mvpcrx.delegate;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import java.lang.ref.WeakReference;
import corp.wmsoft.android.lib.mvpcrx.presenter.IMVPCPresenter;
import corp.wmsoft.android.lib.mvpcrx.presenter.factory.IMVPCPresenterFactory;
import corp.wmsoft.android.lib.mvpcrx.presenter.loader.MVPCPresenterLoader;
import corp.wmsoft.android.lib.mvpcrx.view.IMVPCView;
/**
* Created on 8/18/16 at 11:21 AM.
*
* <p>
* This class represents a delegate which you can use to extend Mvp's support to any class.
* <p>
* When using an {@link MVPCDelegate}, lifecycle methods which should be proxied to the delegate:
* <ul>
* <li>{@link #onCreate(Context, LoaderManager, IMVPCPresenterFactory, int, ICallback)} inside onCreate() for Activity, inside onActivityCreated() for Fragments or inside view constructor</li>
* <li>{@link IMVPCPresenter#attachView(IMVPCView)} : inside onStart() and onResume() of Fragment, inside onStart() of Activity, inside onAttachedToWindow for View</li>
* <li>{@link #onDetachView()}: inside onStop() for Activity, inside onStop() for Fragment, inside onDetachedFromWindow() for View</li>
* </ul>
* <p>
* Every {@link Object} can only be linked with one {@link MVPCDelegate} instance
*
* @author westman2000
*/
public class MVPCDelegate<V extends IMVPCView, P extends IMVPCPresenter<V>> implements IMVPCDelegate<V, P>, LoaderManager.LoaderCallbacks<P> {
/**/
private P mPresenter;
/**/
private WeakReference<Context> mWeakContext;
/**/
private IMVPCPresenterFactory<V, P> mPresenterFactory;
/**/
private ICallback<V, P> mCallback;
/**
*
* @param context {@link Context}
* @param supportLoaderManager {@link LoaderManager}
* @param presenterFactory instance of {@link IMVPCPresenterFactory}
* @param uniqueIdentifier application globally identifier for {@link android.view.View}'s and context identifier for {@link android.app.Activity} and {@link android.support.v4.app.Fragment}
* @param callback {@link IMVPCDelegate.ICallback} if you want to receive callbacks of presenter lifecycle
*/
@Override
public void onCreate(Context context, LoaderManager supportLoaderManager, IMVPCPresenterFactory<V, P> presenterFactory, int uniqueIdentifier, ICallback<V, P> callback) {
this.mWeakContext = new WeakReference<>(context);
this.mPresenterFactory = presenterFactory;
this.mCallback = callback;
supportLoaderManager.initLoader(uniqueIdentifier, null, this);
}
@Override
public Loader<P> onCreateLoader(int id, Bundle args) {
if (mWeakContext != null && mWeakContext.get() != null)
return new MVPCPresenterLoader<>(mWeakContext.get(), mPresenterFactory);
return null;
}
@Override
public void onLoadFinished(Loader<P> loader, P presenter) {
setPresenter(presenter);
if (mCallback != null)
mCallback.onInitializePresenter(presenter);
}
@Override
public void onLoaderReset(Loader<P> loader) {
onDestroy();
}
/**
*
* @param view view that implements {@link IMVPCView}
* @param callback {@link IMVPCDelegate.ICallback} if you want to receive callbacks of presenter lifecycle. must be set again after {@link MVPCDelegate#onDetachView()}
*/
@Override
public void onAttachView(V view, ICallback<V, P> callback) {
if (mPresenter != null && !mPresenter.isViewAttached())
mPresenter.attachView(view);
this.mCallback = callback;
}
@Override
public void onDetachView() {
detachViewIfNeeded();
}
@Override
public P getPresenter() {
if (mPresenter == null)
throw new NullPointerException("Presenter not ready. Please wait before requesting Presenter");
return mPresenter;
}
private void onDestroy() {
if (mCallback != null)
mCallback.onDestroyPresenter();
detachViewIfNeeded();
setPresenter(null);
}
private void detachViewIfNeeded() {
if (mPresenter != null && mPresenter.isViewAttached())
mPresenter.detachView();
clean();
mPresenterFactory = null;
mCallback = null;
}
private void setPresenter(P presenter) {
this.mPresenter = presenter;
}
private void clean() {
if (mWeakContext != null) {
mWeakContext.clear();
mWeakContext = null;
}
}
}
| apache-2.0 |
vishnus1224/RxJavaTeamworkClient | TeamworkApiDemo/app/src/main/java/com/vishnus1224/teamworkapidemo/manager/LatestActivityDataManager.java | 3474 | package com.vishnus1224.teamworkapidemo.manager;
import com.vishnus1224.teamworkapidemo.model.LatestActivityDto;
import com.vishnus1224.teamworkapidemo.model.ProjectDto;
import com.vishnus1224.teamworkapidemo.repository.BaseRepository;
import com.vishnus1224.teamworkapidemo.subscriber.EmptySubscriber;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
/**
* Created by vishnu on 31/08/16.
*/
public class LatestActivityDataManager implements DataManager<LatestActivityDto> {
private BaseRepository latestActivityRepository;
private BaseRepository latestActivityRealmRepository;
private Subscription databaseSubscription;
private Subscription cloudSubscription;
@Inject
public LatestActivityDataManager(@Named("activityRepo") BaseRepository latestActivityRepository,
@Named("activityRealmRepo") BaseRepository latestActivityRealmRepository) {
this.latestActivityRepository = latestActivityRepository;
this.latestActivityRealmRepository = latestActivityRealmRepository;
}
@Override
public void getAllItems(Subscriber<List<LatestActivityDto>> databaseSubscriber, final Subscriber<List<LatestActivityDto>> cloudSubscriber) {
final Observable<List<ProjectDto>> cloudObservable = latestActivityRepository.getAllItems()
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(new Action1<List<LatestActivityDto>>() {
@Override
public void call(List<LatestActivityDto> latestActivityModels) {
latestActivityRealmRepository.addAll(latestActivityModels);
cloudSubscription = latestActivityRealmRepository.getAllItems().subscribe(cloudSubscriber);
}
}).doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
cloudSubscriber.onError(throwable);
}
});
databaseSubscription = latestActivityRealmRepository.getAllItems()
.doOnCompleted(new Action0() {
@Override
public void call() {
cloudObservable.subscribe(new EmptySubscriber<List<ProjectDto>>());
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(databaseSubscriber);
}
@Override
public void searchItems(String queryString, Subscriber<List<LatestActivityDto>> subscriber) {
latestActivityRealmRepository.searchItems(queryString)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
@Override
public void unSubscribe() {
unSubscribeIfNotAlreadyDone(databaseSubscription);
unSubscribeIfNotAlreadyDone(cloudSubscription);
}
private void unSubscribeIfNotAlreadyDone(Subscription subscription){
if(subscription != null && !subscription.isUnsubscribed()){
subscription.unsubscribe();
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-servicediscovery/src/main/java/com/amazonaws/services/servicediscovery/model/GetInstanceRequest.java | 5310 | /*
* Copyright 2017-2022 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.
*/
package com.amazonaws.services.servicediscovery.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetInstance" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetInstanceRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The ID of the service that the instance is associated with.
* </p>
*/
private String serviceId;
/**
* <p>
* The ID of the instance that you want to get information about.
* </p>
*/
private String instanceId;
/**
* <p>
* The ID of the service that the instance is associated with.
* </p>
*
* @param serviceId
* The ID of the service that the instance is associated with.
*/
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
/**
* <p>
* The ID of the service that the instance is associated with.
* </p>
*
* @return The ID of the service that the instance is associated with.
*/
public String getServiceId() {
return this.serviceId;
}
/**
* <p>
* The ID of the service that the instance is associated with.
* </p>
*
* @param serviceId
* The ID of the service that the instance is associated with.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetInstanceRequest withServiceId(String serviceId) {
setServiceId(serviceId);
return this;
}
/**
* <p>
* The ID of the instance that you want to get information about.
* </p>
*
* @param instanceId
* The ID of the instance that you want to get information about.
*/
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
/**
* <p>
* The ID of the instance that you want to get information about.
* </p>
*
* @return The ID of the instance that you want to get information about.
*/
public String getInstanceId() {
return this.instanceId;
}
/**
* <p>
* The ID of the instance that you want to get information about.
* </p>
*
* @param instanceId
* The ID of the instance that you want to get information about.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetInstanceRequest withInstanceId(String instanceId) {
setInstanceId(instanceId);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getServiceId() != null)
sb.append("ServiceId: ").append(getServiceId()).append(",");
if (getInstanceId() != null)
sb.append("InstanceId: ").append(getInstanceId());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetInstanceRequest == false)
return false;
GetInstanceRequest other = (GetInstanceRequest) obj;
if (other.getServiceId() == null ^ this.getServiceId() == null)
return false;
if (other.getServiceId() != null && other.getServiceId().equals(this.getServiceId()) == false)
return false;
if (other.getInstanceId() == null ^ this.getInstanceId() == null)
return false;
if (other.getInstanceId() != null && other.getInstanceId().equals(this.getInstanceId()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getServiceId() == null) ? 0 : getServiceId().hashCode());
hashCode = prime * hashCode + ((getInstanceId() == null) ? 0 : getInstanceId().hashCode());
return hashCode;
}
@Override
public GetInstanceRequest clone() {
return (GetInstanceRequest) super.clone();
}
}
| apache-2.0 |
terrancesnyder/oozie-hadoop2 | core/src/main/java/org/apache/oozie/action/control/StartActionExecutor.java | 1085 | /**
* 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.oozie.action.control;
/**
* Action executor for START control node.
*/
public class StartActionExecutor extends ControlNodeActionExecutor {
public static final String TYPE = ":START:";
public StartActionExecutor() {
super(TYPE);
}
}
| apache-2.0 |
jabelai/Neverland | J2EE/BaseTools/src/main/java/com/oppo/base/apk/entity/LockProperty.java | 1736 | package com.oppo.base.apk.entity;
/**
*
* ClassName:LockProperty
* Function:锁屏相关属性
* @author 80036381
* @version
* @since Ver 1.1
* @Date 2011-7-18 下午03:08:03
* @see
*/
public class LockProperty {
private String name; //锁屏名称
private String author; //锁屏作者
private String version;//锁屏版本
private String resolution; //锁屏支持的分辨率
private String description; //锁屏描述
private String thumbnail; //该锁屏展示给用户的小缩略图
private String thumbLeft; //第一张预览图片
private String thumbRight; //第二章预览图片
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getResolution() {
return resolution;
}
public void setResolution(String resolution) {
this.resolution = resolution;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getThumbLeft() {
return thumbLeft;
}
public void setThumbLeft(String thumbLeft) {
this.thumbLeft = thumbLeft;
}
public String getThumbRight() {
return thumbRight;
}
public void setThumbRight(String thumbRight) {
this.thumbRight = thumbRight;
}
}
| apache-2.0 |
yzzslow0/Ec2m | ec/src/main/java/com/example/ec/fragment/Fragment1.java | 2643 | package com.example.ec.fragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.ec.R;
public class Fragment1 extends LazyLoadFragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Fragment1() {
// Required empty public constructor
}
public static Fragment1 newInstance(String param1, String param2) {
Fragment1 fragment = new Fragment1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
// public void prepareFetchData() {
// if (isVisibleToUser && isViewInitiated && !isDataInitiated) {
// isDataInitiated = true;
// fetchData();
// }
// }
//
// private void fetchData() {
// //加载数据,刷新View
// }
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| apache-2.0 |
jior/glaf | workspace/glaf-base/src/main/java/com/glaf/base/modules/branch/springmvc/BranchDeptRoleController.java | 4008 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.glaf.base.modules.branch.springmvc;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.glaf.base.modules.sys.model.SysDepartment;
import com.glaf.base.modules.sys.query.SysDepartmentQuery;
import com.glaf.base.modules.sys.service.ComplexUserService;
import com.glaf.base.modules.sys.service.SysDepartmentService;
import com.glaf.base.modules.sys.service.SysDeptRoleService;
import com.glaf.base.modules.sys.service.SysRoleService;
import com.glaf.base.modules.sys.service.SysTreeService;
import com.glaf.base.utils.ParamUtil;
import com.glaf.core.config.ViewProperties;
import com.glaf.core.util.RequestUtils;
@Controller("/branch/deptRole")
@RequestMapping("/branch/deptRole.do")
public class BranchDeptRoleController {
protected static final Log logger = LogFactory
.getLog(BranchDeptRoleController.class);
protected ComplexUserService complexUserService;
protected SysDepartmentService sysDepartmentService;
protected SysDeptRoleService sysDeptRoleService;
protected SysRoleService sysRoleService;
protected SysTreeService sysTreeService;
@javax.annotation.Resource
public void setComplexUserService(ComplexUserService complexUserService) {
this.complexUserService = complexUserService;
}
@javax.annotation.Resource
public void setSysDepartmentService(
SysDepartmentService sysDepartmentService) {
this.sysDepartmentService = sysDepartmentService;
}
@javax.annotation.Resource
public void setSysDeptRoleService(SysDeptRoleService sysDeptRoleService) {
this.sysDeptRoleService = sysDeptRoleService;
}
@javax.annotation.Resource
public void setSysRoleService(SysRoleService sysRoleService) {
this.sysRoleService = sysRoleService;
}
@javax.annotation.Resource
public void setSysTreeService(SysTreeService sysTreeService) {
this.sysTreeService = sysTreeService;
}
/**
* 显示部门角色列表
*
* @param request
* @param modelMap
* @return
*/
@RequestMapping
public ModelAndView showList(HttpServletRequest request, ModelMap modelMap) {
RequestUtils.setRequestParameterToAttribute(request);
long deptId = ParamUtil.getIntParameter(request, "deptId", 0);
SysDepartment department = sysDepartmentService
.getSysDepartment(deptId);
request.setAttribute("department", department);
String actorId = RequestUtils.getActorId(request);
List<Long> nodeIds = complexUserService
.getUserManageBranchNodeIds(actorId);
SysDepartmentQuery query = new SysDepartmentQuery();
query.nodeIds(nodeIds);
request.setAttribute("list", sysRoleService.getSysRolesOfDepts(query));
String x_view = ViewProperties.getString("deptRole.showList");
if (StringUtils.isNotEmpty(x_view)) {
return new ModelAndView(x_view, modelMap);
}
// 显示列表页面
return new ModelAndView("/modules/branch/deptRole/deptRole_list",
modelMap);
}
} | apache-2.0 |
agwlvssainokuni/springapp | example-web/src/main/java/cherry/example/web/basic/ex90/BasicEx90LoadForm.java | 977 | /*
* Copyright 2014,2015 agwlvssainokuni
*
* 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 cherry.example.web.basic.ex90;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class BasicEx90LoadForm extends BasicEx90LoadFormBase {
private static final long serialVersionUID = 1L;
}
| apache-2.0 |
tobych/django-feature-flipper | featureflipper_example/views.py | 1100 | from django.shortcuts import render_to_response
from django.template import RequestContext
from featureflipper.models import Feature
from featureflipper.signals import feature_defaulted
# We use the feature_defaulted signal to print a simple message
# warning that a feature has been defaulted to disabled. You might
# instead raise an exception here (to help avoid bugs in templates),
# or add the feature to the database.
def my_callback(sender, **kwargs):
print "Feature '%s' defaulted!" % kwargs['feature']
# Uncomment the following line to enable this:
# feature_defaulted.connect(my_callback)
def index(request):
# We'll include all the features, just so we can show all the details in the page
feature_list = Feature.objects.all()
# Below, we'll also include the features_panel in the context.
# 'features' will already be added to the context by the middleware.
return render_to_response('featureflipper_example/index.html',
{'features_panel': request.features_panel, 'feature_list': feature_list},
context_instance=RequestContext(request))
| apache-2.0 |
davcamer/clients | projects-for-testing/struts/apps/faces-example1/src/main/java/org/apache/struts/webapp/example/Constants.java | 1825 | /*
* $Id: Constants.java 471754 2006-11-06 14:55:09Z husted $
*
* 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.struts.webapp.example;
/**
* Manifest constants for the example application.
*
* @author Craig R. McClanahan
* @version $Rev: 471754 $ $Date: 2006-11-06 15:55:09 +0100 (Lun, 06 nov 2006) $
*/
public final class Constants {
/**
* The package name for this application.
*/
public static final String Package = "org.apache.struts.webapp.example";
/**
* The application scope attribute under which our user database
* is stored.
*/
public static final String DATABASE_KEY = "database";
/**
* The session scope attribute under which the Subscription object
* currently selected by our logged-in User is stored.
*/
public static final String SUBSCRIPTION_KEY = "subscription";
/**
* The session scope attribute under which the User object
* for the currently logged in user is stored.
*/
public static final String USER_KEY = "user";
}
| apache-2.0 |
ggranum/datagen-api | core/src/main/java/com/fetherbrik/datagen/core/StringChainGenerator.java | 403 | package com.fetherbrik.datagen.core;
import java.util.List;
public class StringChainGenerator extends ChainGenerator<String> {
public StringChainGenerator(List<Generator<String>> chain) {
super(chain);
}
@Override public String next() {
StringBuilder b = new StringBuilder();
for (Generator<String> gen : chain()) {
b.append(gen.next());
}
return b.toString();
}
}
| apache-2.0 |
bhb27/KA27 | app/src/main/java/com/grarak/kerneladiutor/utils/database/JsonDB.java | 3641 | /*
* Copyright (C) 2015 Willi Ye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.grarak.kerneladiutor.utils.database;
import com.grarak.kerneladiutor.utils.Utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by willi on 15.04.15.
*/
public abstract class JsonDB {
/**
* JSON Objects
*/
private JSONObject databaseMain;
private JSONArray databaseItems;
/**
* JSON file location
*/
private final String path;
/**
* JSON Database is used to store large amount of datasets
*
* @param path location of the JSON file
* @param version If version doesn't match with the dataset, remove all saved datas
*/
public JsonDB(String path, int version) {
this.path = path;
try {
String json = Utils.readFile(path, false);
if (json != null) {
databaseMain = new JSONObject(json);
if (databaseMain.getInt("version") == version)
databaseItems = databaseMain.getJSONArray("database");
}
} catch (JSONException ignored) {}
if (databaseItems == null) databaseItems = new JSONArray();
try {
databaseMain = new JSONObject();
databaseMain.put("version", version);
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Insert a dataset
*
* @param items the dataset will put into the JSONArray
*/
public void putItem(JSONObject items) {
databaseItems.put(items);
}
/**
* Read all sets
*
* @return all sets in a list
*/
public List < DBJsonItem > getAllItems() {
List < DBJsonItem > items = new ArrayList < > ();
try {
for (int i = 0; i < length(); i++)
items.add(getItem(databaseItems.getJSONObject(i)));
} catch (JSONException e) {
e.printStackTrace();
}
return items;
}
public abstract DBJsonItem getItem(JSONObject item);
public void delete(int position) {
JSONArray jsonArray = new JSONArray();
try {
for (int i = 0; i < length(); i++)
if (i != position) jsonArray.put(databaseItems.getJSONObject(i));
databaseItems = jsonArray;
} catch (JSONException e) {
e.printStackTrace();
}
}
public int length() {
return databaseItems.length();
}
/**
* Write the dataset as JSON file
*/
public void commit() {
try {
databaseMain.put("database", databaseItems);
Utils.writeFile(path, databaseMain.toString(), false, false);
} catch (JSONException e) {
e.printStackTrace();
}
}
public static class DBJsonItem {
protected JSONObject item;
public DBJsonItem() {
item = new JSONObject();
}
public JSONObject getItem() {
return item;
}
}
}
| apache-2.0 |
chrishumphreys/provocateur | provocateur-thirdparty/src/main/java/org/targettest/org/apache/lucene/search/WildcardQuery.java | 3826 | package org.targettest.org.apache.lucene.search;
/**
* 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 org.targettest.org.apache.lucene.index.IndexReader;
import org.targettest.org.apache.lucene.index.Term;
import org.targettest.org.apache.lucene.util.ToStringUtils;
import java.io.IOException;
/** Implements the wildcard search query. Supported wildcards are <code>*</code>, which
* matches any character sequence (including the empty one), and <code>?</code>,
* which matches any single character. Note this query can be slow, as it
* needs to iterate over many terms. In order to prevent extremely slow WildcardQueries,
* a Wildcard term should not start with one of the wildcards <code>*</code> or
* <code>?</code>.
*
* <p>This query uses the {@link
* MultiTermQuery#CONSTANT_SCORE_AUTO_REWRITE_DEFAULT}
* rewrite method.
*
* @see WildcardTermEnum */
public class WildcardQuery extends MultiTermQuery {
private boolean termContainsWildcard;
private boolean termIsPrefix;
protected Term term;
public WildcardQuery(Term term) {
this.term = term;
String text = term.text();
this.termContainsWildcard = (text.indexOf('*') != -1)
|| (text.indexOf('?') != -1);
this.termIsPrefix = termContainsWildcard
&& (text.indexOf('?') == -1)
&& (text.indexOf('*') == text.length() - 1);
}
@Override
protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {
if (termContainsWildcard)
return new WildcardTermEnum(reader, getTerm());
else
return new SingleTermEnum(reader, getTerm());
}
/**
* Returns the pattern term.
*/
public Term getTerm() {
return term;
}
@Override
public Query rewrite(IndexReader reader) throws IOException {
if (termIsPrefix) {
MultiTermQuery rewritten = new PrefixQuery(term.createTerm(term.text()
.substring(0, term.text().indexOf('*'))));
rewritten.setBoost(getBoost());
rewritten.setRewriteMethod(getRewriteMethod());
return rewritten;
} else {
return super.rewrite(reader);
}
}
/** Prints a user-readable version of this query. */
@Override
public String toString(String field) {
StringBuilder buffer = new StringBuilder();
if (!term.field().equals(field)) {
buffer.append(term.field());
buffer.append(":");
}
buffer.append(term.text());
buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((term == null) ? 0 : term.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
WildcardQuery other = (WildcardQuery) obj;
if (term == null) {
if (other.term != null)
return false;
} else if (!term.equals(other.term))
return false;
return true;
}
}
| apache-2.0 |
ramasinka/javers | javers-core/src/main/java/org/javers/core/diff/changetype/ValueChange.java | 914 | package org.javers.core.diff.changetype;
import org.javers.core.metamodel.object.GlobalId;
import org.javers.core.metamodel.property.Property;
import static org.javers.common.string.ToStringBuilder.addField;
/**
* @author bartosz walacik
*/
public final class ValueChange extends PropertyChange {
private final Atomic left;
private final Atomic right;
public ValueChange(GlobalId affectedCdoId, String propertyName, Object leftValue, Object rightValue) {
super(affectedCdoId, propertyName);
this.left = new Atomic(leftValue);
this.right = new Atomic(rightValue);
}
public Object getLeft() {
return left.unwrap();
}
public Object getRight() {
return right.unwrap();
}
@Override
protected String fieldsToString() {
return super.fieldsToString() + addField("oldVal", getLeft()) + addField("newVal", getRight());
}
}
| apache-2.0 |
joeyb/retry | src/test/java/org/joeyb/retry/StopsTests.java | 4766 | package org.joeyb.retry;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.joeyb.retry.TestHelpers.assertClassOnlyHasPrivateConstructor;
import org.assertj.core.util.Lists;
import org.junit.Test;
import java.util.concurrent.ThreadLocalRandom;
public class StopsTests {
@Test
public void stopsOnlyHasPrivateConstructor() {
assertClassOnlyHasPrivateConstructor(Stops.class);
}
@Test
public void andStopVararg0() {
Stop<Long> stop = Stops.and();
assertThat(stop).isInstanceOf(NeverStop.class);
}
@Test
public void andStopCollection0() {
Stop<Long> stop = Stops.and(Lists.newArrayList());
assertThat(stop).isInstanceOf(NeverStop.class);
}
@Test
public void andStopVararg1() {
Stop<Long> falseStop = a -> false;
Stop<Long> stop = Stops.and(falseStop);
assertThat(stop).isEqualTo(falseStop);
}
@Test
public void andStopCollection1() {
Stop<Long> falseStop = a -> false;
Stop<Long> stop = Stops.and(Lists.newArrayList(falseStop));
assertThat(stop).isEqualTo(falseStop);
}
@Test
@SuppressWarnings("unchecked")
public void andStopVararg2() {
Stop<Long> falseStop = a -> false;
Stop<Long> trueStop = a -> true;
Stop<Long> stop = Stops.and(falseStop, trueStop);
assertThat(stop).isInstanceOf(CompositeAndStop.class);
CompositeAndStop<Long> andStop = (CompositeAndStop<Long>) stop;
assertThat(andStop.stops()).containsExactlyInAnyOrder(falseStop, trueStop);
}
@Test
@SuppressWarnings("unchecked")
public void andStopCollection2() {
Stop<Long> falseStop = a -> false;
Stop<Long> trueStop = a -> true;
Stop<Long> stop = Stops.and(Lists.newArrayList(falseStop, trueStop));
assertThat(stop).isInstanceOf(CompositeAndStop.class);
CompositeAndStop<Long> andStop = (CompositeAndStop<Long>) stop;
assertThat(andStop.stops()).containsExactlyInAnyOrder(falseStop, trueStop);
}
@Test
public void maxAttemptsStop() {
long maxAttempts = ThreadLocalRandom.current().nextLong(10, Long.MAX_VALUE - 1);
Stop<Long> stop = Stops.maxAttempts(maxAttempts);
assertThat(stop).isInstanceOf(MaxAttemptsStop.class);
MaxAttemptsStop<Long> maxAttemptsStop = (MaxAttemptsStop<Long>) stop;
assertThat(maxAttemptsStop.maxAttempts()).isEqualTo(maxAttempts);
}
@Test
public void maxDelayAfterStartStop() {
long maxDelay = ThreadLocalRandom.current().nextLong(10, Long.MAX_VALUE - 1);
Stop<Long> stop = Stops.maxDelaySinceFirstAttempt(maxDelay);
assertThat(stop).isInstanceOf(MaxDelaySinceFirstAttemptStop.class);
MaxDelaySinceFirstAttemptStop<Long> maxDelayStop = (MaxDelaySinceFirstAttemptStop<Long>) stop;
assertThat(maxDelayStop.maxDelaySinceFirstAttempt()).isEqualTo(maxDelay);
}
@Test
public void neverStop() {
Stop<Long> stop = Stops.never();
assertThat(stop).isInstanceOf(NeverStop.class);
}
@Test
public void orStopVararg0() {
Stop<Long> stop = Stops.or();
assertThat(stop).isInstanceOf(NeverStop.class);
}
@Test
public void orStopCollection0() {
Stop<Long> stop = Stops.or(Lists.newArrayList());
assertThat(stop).isInstanceOf(NeverStop.class);
}
@Test
public void orStopVararg1() {
Stop<Long> falseStop = a -> false;
Stop<Long> stop = Stops.or(falseStop);
assertThat(stop).isEqualTo(falseStop);
}
@Test
public void orStopCollection1() {
Stop<Long> falseStop = a -> false;
Stop<Long> stop = Stops.or(Lists.newArrayList(falseStop));
assertThat(stop).isEqualTo(falseStop);
}
@Test
@SuppressWarnings("unchecked")
public void orStopVararg2() {
Stop<Long> falseStop = a -> false;
Stop<Long> trueStop = a -> true;
Stop<Long> stop = Stops.or(falseStop, trueStop);
assertThat(stop).isInstanceOf(CompositeOrStop.class);
CompositeOrStop<Long> orStop = (CompositeOrStop<Long>) stop;
assertThat(orStop.stops()).containsExactlyInAnyOrder(falseStop, trueStop);
}
@Test
@SuppressWarnings("unchecked")
public void orStopCollection2() {
Stop<Long> falseStop = a -> false;
Stop<Long> trueStop = a -> true;
Stop<Long> stop = Stops.or(Lists.newArrayList(falseStop, trueStop));
assertThat(stop).isInstanceOf(CompositeOrStop.class);
CompositeOrStop<Long> orStop = (CompositeOrStop<Long>) stop;
assertThat(orStop.stops()).containsExactlyInAnyOrder(falseStop, trueStop);
}
}
| apache-2.0 |
niroyb/bosh-bootloader | terraform/gcp/template_generator.go | 2597 | package gcp
import (
"fmt"
"strings"
"github.com/cloudfoundry/bosh-bootloader/storage"
)
type templates struct {
vars string
jumpbox string
boshDirector string
cfLB string
cfDNS string
concourseLB string
}
type TemplateGenerator struct{}
func NewTemplateGenerator() TemplateGenerator {
return TemplateGenerator{}
}
func (t TemplateGenerator) Generate(state storage.State) string {
tmpls := readTemplates()
template := strings.Join([]string{tmpls.vars, tmpls.boshDirector, tmpls.jumpbox}, "\n")
switch state.LB.Type {
case "concourse":
template = strings.Join([]string{template, tmpls.concourseLB}, "\n")
case "cf":
instanceGroups := t.GenerateInstanceGroups(state.GCP.Zones)
backendService := t.GenerateBackendService(state.GCP.Zones)
template = strings.Join([]string{template, tmpls.cfLB, instanceGroups, backendService}, "\n")
if state.LB.Domain != "" {
template = strings.Join([]string{template, tmpls.cfDNS}, "\n")
}
}
return template
}
func (t TemplateGenerator) GenerateBackendService(zoneList []string) string {
backendBase := `resource "google_compute_backend_service" "router-lb-backend-service" {
name = "${var.env_id}-router-lb"
port_name = "https"
protocol = "HTTPS"
timeout_sec = 900
enable_cdn = false
%s
health_checks = ["${google_compute_health_check.cf-public-health-check.self_link}"]
}
`
var backends string
for i := 0; i < len(zoneList); i++ {
backends = fmt.Sprintf(`%s
backend {
group = "${google_compute_instance_group.router-lb-%d.self_link}"
}
`, backends, i)
}
return fmt.Sprintf(backendBase, backends)
}
func (t TemplateGenerator) GenerateInstanceGroups(zoneList []string) string {
var groups []string
for i, zone := range zoneList {
groups = append(groups, fmt.Sprintf(`resource "google_compute_instance_group" "router-lb-%[1]d" {
name = "${var.env_id}-router-lb-%[1]d-%[2]s"
description = "terraform generated instance group that is multi-zone for https loadbalancing"
zone = "%[2]s"
named_port {
name = "https"
port = "443"
}
}
`, i, zone))
}
return strings.Join(groups, "\n")
}
func readTemplates() templates {
tmpls := templates{}
tmpls.vars = string(MustAsset("templates/vars.tf"))
tmpls.jumpbox = string(MustAsset("templates/jumpbox.tf"))
tmpls.boshDirector = string(MustAsset("templates/bosh_director.tf"))
tmpls.cfLB = string(MustAsset("templates/cf_lb.tf"))
tmpls.cfDNS = string(MustAsset("templates/cf_dns.tf"))
tmpls.concourseLB = string(MustAsset("templates/concourse_lb.tf"))
return tmpls
}
| apache-2.0 |
boadude/angularjs-es6-gulp-browserify-karma-mocha-chai-starter | gulp/config.js | 1018 | 'use strict';
export default {
browserPort: 3000,
UIPort: 3001,
sourceDir: './app/',
buildDir: './build/',
styles: {
src: 'app/styles/**/*.scss',
dest: 'build/css',
prodSourcemap: false,
sassIncludePaths: []
},
scripts: {
src: 'app/js/**/*.js',
dest: 'build/js'
},
images: {
src: 'app/images/**/*',
dest: 'build/images'
},
fonts: {
src: ['app/fonts/**/*'],
dest: 'build/fonts'
},
assetExtensions: [
'js',
'css',
'png',
'jpe?g',
'gif',
'svg',
'eot',
'otf',
'ttc',
'ttf',
'woff2?'
],
views: {
index: 'app/index.html',
src: 'app/views/**/*.html',
dest: 'app/js'
},
gzip: {
src: 'build/**/*.{html,xml,json,css,js,js.map,css.map}',
dest: 'build/',
options: {}
},
browserify: {
bundleName: 'main.js',
prodSourcemap: false
},
init: function() {
this.views.watch = [
this.views.index,
this.views.src
];
return this;
}
}.init();
| apache-2.0 |
onosfw/apis | onos/apis/dir_3e07eb83563bf7c562021a794e02da6d.js | 233 | var dir_3e07eb83563bf7c562021a794e02da6d =
[
[ "AppCommand.java", "src_2main_2resources_2archetype-resources_2src_2main_2java_2AppCommand_8java.html", [
[ "AppCommand", "classAppCommand.html", "classAppCommand" ]
] ]
]; | apache-2.0 |
gigya/microdot | Gigya.Microdot.Hosting/Validators/IValidator.cs | 262 | namespace Gigya.Microdot.Hosting.Validators
{
/// <summary>
/// When service is started, validates that the service is Ok to run, and throws an exception if not
/// </summary>
public interface IValidator
{
void Validate();
}
}
| apache-2.0 |
DiceHoldingsInc/orientdb | core/src/main/java/com/orientechnologies/common/io/OIOUtils.java | 8949 | /*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.common.io;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class OIOUtils {
public static final long SECOND = 1000;
public static final long MINUTE = SECOND * 60;
public static final long HOUR = MINUTE * 60;
public static final long DAY = HOUR * 24;
public static final long YEAR = DAY * 365;
public static final long WEEK = DAY * 7;
public static byte[] toStream(Externalizable iSource) throws IOException {
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
final ObjectOutputStream oos = new ObjectOutputStream(stream);
iSource.writeExternal(oos);
oos.flush();
stream.flush();
return stream.toByteArray();
}
public static long getTimeAsMillisecs(final Object iSize) {
if (iSize == null)
throw new IllegalArgumentException("Time is null");
if (iSize instanceof Number)
// MILLISECS
return ((Number) iSize).longValue();
String time = iSize.toString();
boolean number = true;
for (int i = time.length() - 1; i >= 0; --i) {
if (!Character.isDigit(time.charAt(i))) {
number = false;
break;
}
}
if (number)
// MILLISECS
return Long.parseLong(time);
else {
time = time.toUpperCase(Locale.ENGLISH);
int pos = time.indexOf("MS");
final String timeAsNumber = time.replaceAll("[^\\d]", "");
if (pos > -1)
return Long.parseLong(timeAsNumber);
pos = time.indexOf("S");
if (pos > -1)
return Long.parseLong(timeAsNumber) * SECOND;
pos = time.indexOf("M");
if (pos > -1)
return Long.parseLong(timeAsNumber) * MINUTE;
pos = time.indexOf("H");
if (pos > -1)
return Long.parseLong(timeAsNumber) * HOUR;
pos = time.indexOf("D");
if (pos > -1)
return Long.parseLong(timeAsNumber) * DAY;
pos = time.indexOf('W');
if (pos > -1)
return Long.parseLong(timeAsNumber) * WEEK;
pos = time.indexOf('Y');
if (pos > -1)
return Long.parseLong(timeAsNumber) * YEAR;
// RE-THROW THE EXCEPTION
throw new IllegalArgumentException("Time '" + time + "' has a unrecognizable format");
}
}
public static String getTimeAsString(final long iTime) {
if (iTime > YEAR && iTime % YEAR == 0)
return String.format("%dy", iTime / YEAR);
if (iTime > WEEK && iTime % WEEK == 0)
return String.format("%dw", iTime / WEEK);
if (iTime > DAY && iTime % DAY == 0)
return String.format("%dd", iTime / DAY);
if (iTime > HOUR && iTime % HOUR == 0)
return String.format("%dh", iTime / HOUR);
if (iTime > MINUTE && iTime % MINUTE == 0)
return String.format("%dm", iTime / MINUTE);
if (iTime > SECOND && iTime % SECOND == 0)
return String.format("%ds", iTime / SECOND);
// MILLISECONDS
return String.format("%dms", iTime);
}
public static Date getTodayWithTime(final String iTime) throws ParseException {
final SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
final long today = System.currentTimeMillis();
final Date rslt = new Date();
rslt.setTime(today - (today % DAY) + df.parse(iTime).getTime());
return rslt;
}
public static String readFileAsString(final File iFile) throws java.io.IOException {
return readStreamAsString(new FileInputStream(iFile));
}
public static String readStreamAsString(final InputStream iStream) throws java.io.IOException {
final StringBuffer fileData = new StringBuffer(1000);
final BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
try {
final char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
} finally {
reader.close();
}
return fileData.toString();
}
public static long copyStream(final InputStream in, final OutputStream out, long iMax) throws java.io.IOException {
if (iMax < 0)
iMax = Long.MAX_VALUE;
final byte[] buf = new byte[8192];
int byteRead = 0;
long byteTotal = 0;
while ((byteRead = in.read(buf, 0, (int) Math.min(buf.length, iMax - byteTotal))) > 0) {
out.write(buf, 0, byteRead);
byteTotal += byteRead;
}
return byteTotal;
}
/**
* Returns the Unix file name format converting backslashes (\) to slasles (/)
*/
public static String getUnixFileName(final String iFileName) {
return iFileName != null ? iFileName.replace('\\', '/') : null;
}
public static String getRelativePathIfAny(final String iDatabaseURL, final String iBasePath) {
if (iBasePath == null) {
final int pos = iDatabaseURL.lastIndexOf('/');
if (pos > -1)
return iDatabaseURL.substring(pos + 1);
} else {
final int pos = iDatabaseURL.indexOf(iBasePath);
if (pos > -1)
return iDatabaseURL.substring(pos + iBasePath.length() + 1);
}
return iDatabaseURL;
}
public static String getDatabaseNameFromPath(final String iPath) {
return iPath.replace('/', '$');
}
public static String getPathFromDatabaseName(final String iPath) {
return iPath.replace('$', '/');
}
public static String getStringMaxLength(final String iText, final int iMax) {
return getStringMaxLength(iText, iMax, "");
}
public static String getStringMaxLength(final String iText, final int iMax, final String iOther) {
if (iText == null)
return null;
if (iMax > iText.length())
return iText;
return iText.substring(0, iMax) + iOther;
}
public static Object encode(final Object iValue) {
if (iValue instanceof String) {
return java2unicode(((String) iValue).replace("\\", "\\\\").replace("\"", "\\\""));
} else
return iValue;
}
public static String java2unicode(final String iInput) {
final StringBuilder result = new StringBuilder(iInput.length()*2);
final int inputSize = iInput.length();
char ch;
String hex;
for (int i = 0; i < inputSize; i++) {
ch = iInput.charAt(i);
if (ch >= 0x0020 && ch <= 0x007e) // Does the char need to be converted to unicode?
result.append(ch); // No.
else // Yes.
{
result.append("\\u"); // standard unicode format.
hex = Integer.toHexString(ch & 0xFFFF); // Get hex value of the char.
for (int j = 0; j < 4 - hex.length(); j++)
// Prepend zeros because unicode requires 4 digits
result.append('0');
result.append(hex.toLowerCase()); // standard unicode format.
// ostr.append(hex.toLowerCase(Locale.ENGLISH));
}
}
return result.toString();
}
public static boolean isStringContent(final Object iValue) {
if (iValue == null)
return false;
final String s = iValue.toString();
if (s == null)
return false;
return s.length() > 1
&& (s.charAt(0) == '\'' && s.charAt(s.length() - 1) == '\'' || s.charAt(0) == '"' && s.charAt(s.length() - 1) == '"');
}
public static String getStringContent(final Object iValue) {
if (iValue == null)
return null;
final String s = iValue.toString();
if (s == null)
return null;
if (s.length() > 1
&& (s.charAt(0) == '\'' && s.charAt(s.length() - 1) == '\'' || s.charAt(0) == '"' && s.charAt(s.length() - 1) == '"'))
return s.substring(1, s.length() - 1);
return s;
}
public static boolean equals(final byte[] buffer, final byte[] buffer2) {
if (buffer == null || buffer2 == null || buffer.length != buffer2.length)
return false;
for (int i = 0; i < buffer.length; ++i)
if (buffer[i] != buffer2[i])
return false;
return true;
}
public static boolean isLong(final String iText) {
boolean isLong = true;
final int size = iText.length();
for (int i = 0; i < size && isLong; i++) {
final char c = iText.charAt(i);
isLong = isLong & ((c >= '0' && c <= '9'));
}
return isLong;
}
}
| apache-2.0 |
OakRaven/ltaf | src/LTAF.Infrastructure/Abstractions/IFileSystem.cs | 1170 | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace LTAF.Infrastructure.Abstractions
{
internal interface IFileSystem
{
bool DirectoryExists(string directoryPath);
string[] DirectoryGetSubDirs(string directoryPath, string searchPattern, SearchOption searchOption);
void DirectoryCreate(string path);
void DirectoryDelete(string directoryPath, bool recursive);
string[] DirectoryGetFiles(string directoryPath, string searchPattern, SearchOption searchOption);
void DirectoryCopy(string sourcePath, string destinationPath);
void DirectorySetAttribute(string dirpath, FileAttributes attributes);
bool FileExists(string filePath);
void FileCopy(string sourceFileName, string destFileName, bool overwrite);
string FileRead(string fileName);
void FileWrite(string filename, string content, Encoding encoding);
void FileWrite(string fileName, string content);
void FileDelete(string fileName);
void FileMove(string sourceFileName, string destFileName);
Version FileGetVersion(string fileName);
}
}
| apache-2.0 |
zjshen/hadoop-YARN-2928-POC | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/application/TestApplication.java | 23017 | /**
* 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.hadoop.yarn.server.nodemanager.containermanager.application;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.refEq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.records.ApplicationAccessType;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.event.DrainDispatcher;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.hadoop.yarn.security.ContainerTokenIdentifier;
import org.apache.hadoop.yarn.server.api.records.MasterKey;
import org.apache.hadoop.yarn.server.api.records.impl.pb.MasterKeyPBImpl;
import org.apache.hadoop.yarn.server.nodemanager.Context;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.AuxServicesEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.AuxServicesEventType;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerEventType;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerInitEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerKillEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainersLauncherEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainersLauncherEventType;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ApplicationLocalizationEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizationEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizationEventType;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerEventType;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.monitor.ContainersMonitorEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.monitor.ContainersMonitorEventType;
import org.apache.hadoop.yarn.server.nodemanager.security.NMContainerTokenSecretManager;
import org.apache.hadoop.yarn.server.nodemanager.security.NMTokenSecretManagerInNM;
import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
import org.apache.hadoop.yarn.server.utils.BuilderUtils;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
public class TestApplication {
/**
* All container start events before application running.
*/
@Test
public void testApplicationInit1() {
WrappedApplication wa = null;
try {
wa = new WrappedApplication(1, 314159265358979L, "yak", 3);
wa.initApplication();
wa.initContainer(1);
assertEquals(ApplicationState.INITING, wa.app.getApplicationState());
assertEquals(1, wa.app.getContainers().size());
wa.initContainer(0);
wa.initContainer(2);
assertEquals(ApplicationState.INITING, wa.app.getApplicationState());
assertEquals(3, wa.app.getContainers().size());
wa.applicationInited();
assertEquals(ApplicationState.RUNNING, wa.app.getApplicationState());
for (int i = 0; i < wa.containers.size(); i++) {
verify(wa.containerBus).handle(
argThat(new ContainerInitMatcher(wa.containers.get(i)
.getContainerId())));
}
} finally {
if (wa != null)
wa.finished();
}
}
/**
* Container start events after Application Running
*/
@Test
public void testApplicationInit2() {
WrappedApplication wa = null;
try {
wa = new WrappedApplication(2, 314159265358979L, "yak", 3);
wa.initApplication();
wa.initContainer(0);
assertEquals(ApplicationState.INITING, wa.app.getApplicationState());
assertEquals(1, wa.app.getContainers().size());
wa.applicationInited();
assertEquals(ApplicationState.RUNNING, wa.app.getApplicationState());
verify(wa.containerBus).handle(
argThat(new ContainerInitMatcher(wa.containers.get(0)
.getContainerId())));
wa.initContainer(1);
wa.initContainer(2);
assertEquals(ApplicationState.RUNNING, wa.app.getApplicationState());
assertEquals(3, wa.app.getContainers().size());
for (int i = 1; i < wa.containers.size(); i++) {
verify(wa.containerBus).handle(
argThat(new ContainerInitMatcher(wa.containers.get(i)
.getContainerId())));
}
} finally {
if (wa != null)
wa.finished();
}
}
/**
* App state RUNNING after all containers complete, before RM sends
* APP_FINISHED
*/
@Test
public void testAppRunningAfterContainersComplete() {
WrappedApplication wa = null;
try {
wa = new WrappedApplication(3, 314159265358979L, "yak", 3);
wa.initApplication();
wa.initContainer(-1);
assertEquals(ApplicationState.INITING, wa.app.getApplicationState());
wa.applicationInited();
assertEquals(ApplicationState.RUNNING, wa.app.getApplicationState());
wa.containerFinished(0);
assertEquals(ApplicationState.RUNNING, wa.app.getApplicationState());
assertEquals(2, wa.app.getContainers().size());
wa.containerFinished(1);
wa.containerFinished(2);
assertEquals(ApplicationState.RUNNING, wa.app.getApplicationState());
assertEquals(0, wa.app.getContainers().size());
} finally {
if (wa != null)
wa.finished();
}
}
/**
* Finished containers properly tracked when only container finishes in APP_INITING
*/
@Test
public void testContainersCompleteDuringAppInit1() {
WrappedApplication wa = null;
try {
wa = new WrappedApplication(3, 314159265358979L, "yak", 1);
wa.initApplication();
wa.initContainer(-1);
assertEquals(ApplicationState.INITING, wa.app.getApplicationState());
wa.containerFinished(0);
assertEquals(ApplicationState.INITING, wa.app.getApplicationState());
wa.applicationInited();
assertEquals(ApplicationState.RUNNING, wa.app.getApplicationState());
assertEquals(0, wa.app.getContainers().size());
} finally {
if (wa != null)
wa.finished();
}
}
/**
* Finished containers properly tracked when 1 of several containers finishes in APP_INITING
*/
@Test
public void testContainersCompleteDuringAppInit2() {
WrappedApplication wa = null;
try {
wa = new WrappedApplication(3, 314159265358979L, "yak", 3);
wa.initApplication();
wa.initContainer(-1);
assertEquals(ApplicationState.INITING, wa.app.getApplicationState());
wa.containerFinished(0);
assertEquals(ApplicationState.INITING, wa.app.getApplicationState());
wa.applicationInited();
assertEquals(ApplicationState.RUNNING, wa.app.getApplicationState());
assertEquals(2, wa.app.getContainers().size());
wa.containerFinished(1);
wa.containerFinished(2);
assertEquals(ApplicationState.RUNNING, wa.app.getApplicationState());
assertEquals(0, wa.app.getContainers().size());
} finally {
if (wa != null)
wa.finished();
}
}
@Test
@SuppressWarnings("unchecked")
public void testAppFinishedOnRunningContainers() {
WrappedApplication wa = null;
try {
wa = new WrappedApplication(4, 314159265358979L, "yak", 3);
wa.initApplication();
wa.initContainer(-1);
assertEquals(ApplicationState.INITING, wa.app.getApplicationState());
wa.applicationInited();
assertEquals(ApplicationState.RUNNING, wa.app.getApplicationState());
wa.containerFinished(0);
assertEquals(ApplicationState.RUNNING, wa.app.getApplicationState());
assertEquals(2, wa.app.getContainers().size());
wa.appFinished();
assertEquals(ApplicationState.FINISHING_CONTAINERS_WAIT,
wa.app.getApplicationState());
assertEquals(2, wa.app.getContainers().size());
for (int i = 1; i < wa.containers.size(); i++) {
verify(wa.containerBus).handle(
argThat(new ContainerKillMatcher(wa.containers.get(i)
.getContainerId())));
}
wa.containerFinished(1);
assertEquals(ApplicationState.FINISHING_CONTAINERS_WAIT,
wa.app.getApplicationState());
assertEquals(1, wa.app.getContainers().size());
reset(wa.localizerBus);
wa.containerFinished(2);
// All containers finished. Cleanup should be called.
assertEquals(ApplicationState.APPLICATION_RESOURCES_CLEANINGUP,
wa.app.getApplicationState());
assertEquals(0, wa.app.getContainers().size());
verify(wa.localizerBus).handle(
refEq(new ApplicationLocalizationEvent(
LocalizationEventType.DESTROY_APPLICATION_RESOURCES, wa.app)));
verify(wa.auxBus).handle(
refEq(new AuxServicesEvent(
AuxServicesEventType.APPLICATION_STOP, wa.appId)));
wa.appResourcesCleanedup();
for (Container container : wa.containers) {
ContainerTokenIdentifier identifier =
wa.getContainerTokenIdentifier(container.getContainerId());
waitForContainerTokenToExpire(identifier);
Assert.assertTrue(wa.context.getContainerTokenSecretManager()
.isValidStartContainerRequest(identifier));
}
assertEquals(ApplicationState.FINISHED, wa.app.getApplicationState());
} finally {
if (wa != null)
wa.finished();
}
}
protected ContainerTokenIdentifier waitForContainerTokenToExpire(
ContainerTokenIdentifier identifier) {
int attempts = 5;
while (System.currentTimeMillis() < identifier.getExpiryTimeStamp()
&& attempts-- > 0) {
try {
Thread.sleep(1000);
} catch (Exception e) {}
}
return identifier;
}
@Test
@SuppressWarnings("unchecked")
public void testAppFinishedOnCompletedContainers() {
WrappedApplication wa = null;
try {
wa = new WrappedApplication(5, 314159265358979L, "yak", 3);
wa.initApplication();
wa.initContainer(-1);
assertEquals(ApplicationState.INITING, wa.app.getApplicationState());
wa.applicationInited();
assertEquals(ApplicationState.RUNNING, wa.app.getApplicationState());
reset(wa.localizerBus);
wa.containerFinished(0);
wa.containerFinished(1);
wa.containerFinished(2);
assertEquals(ApplicationState.RUNNING, wa.app.getApplicationState());
assertEquals(0, wa.app.getContainers().size());
wa.appFinished();
assertEquals(ApplicationState.APPLICATION_RESOURCES_CLEANINGUP,
wa.app.getApplicationState());
verify(wa.localizerBus).handle(
refEq(new ApplicationLocalizationEvent(
LocalizationEventType.DESTROY_APPLICATION_RESOURCES, wa.app)));
wa.appResourcesCleanedup();
for ( Container container : wa.containers) {
ContainerTokenIdentifier identifier =
wa.getContainerTokenIdentifier(container.getContainerId());
waitForContainerTokenToExpire(identifier);
Assert.assertTrue(wa.context.getContainerTokenSecretManager()
.isValidStartContainerRequest(identifier));
}
assertEquals(ApplicationState.FINISHED, wa.app.getApplicationState());
} finally {
if (wa != null)
wa.finished();
}
}
//TODO Re-work after Application transitions are changed.
// @Test
@SuppressWarnings("unchecked")
public void testStartContainerAfterAppFinished() {
WrappedApplication wa = null;
try {
wa = new WrappedApplication(5, 314159265358979L, "yak", 3);
wa.initApplication();
wa.initContainer(-1);
assertEquals(ApplicationState.INITING, wa.app.getApplicationState());
wa.applicationInited();
assertEquals(ApplicationState.RUNNING, wa.app.getApplicationState());
reset(wa.localizerBus);
wa.containerFinished(0);
wa.containerFinished(1);
wa.containerFinished(2);
assertEquals(ApplicationState.RUNNING, wa.app.getApplicationState());
assertEquals(0, wa.app.getContainers().size());
wa.appFinished();
assertEquals(ApplicationState.APPLICATION_RESOURCES_CLEANINGUP,
wa.app.getApplicationState());
verify(wa.localizerBus).handle(
refEq(new ApplicationLocalizationEvent(
LocalizationEventType.DESTROY_APPLICATION_RESOURCES, wa.app)));
wa.appResourcesCleanedup();
assertEquals(ApplicationState.FINISHED, wa.app.getApplicationState());
} finally {
if (wa != null)
wa.finished();
}
}
//TODO Re-work after Application transitions are changed.
// @Test
@SuppressWarnings("unchecked")
public void testAppFinishedOnIniting() {
// AM may send a startContainer() - AM APP_FINIHSED processed after
// APP_FINISHED on another NM
WrappedApplication wa = null;
try {
wa = new WrappedApplication(1, 314159265358979L, "yak", 3);
wa.initApplication();
wa.initContainer(0);
assertEquals(ApplicationState.INITING, wa.app.getApplicationState());
assertEquals(1, wa.app.getContainers().size());
reset(wa.localizerBus);
wa.appFinished();
verify(wa.containerBus).handle(
argThat(new ContainerKillMatcher(wa.containers.get(0)
.getContainerId())));
assertEquals(ApplicationState.FINISHING_CONTAINERS_WAIT,
wa.app.getApplicationState());
wa.containerFinished(0);
assertEquals(ApplicationState.APPLICATION_RESOURCES_CLEANINGUP,
wa.app.getApplicationState());
verify(wa.localizerBus).handle(
refEq(new ApplicationLocalizationEvent(
LocalizationEventType.DESTROY_APPLICATION_RESOURCES, wa.app)));
wa.initContainer(1);
assertEquals(ApplicationState.APPLICATION_RESOURCES_CLEANINGUP,
wa.app.getApplicationState());
assertEquals(0, wa.app.getContainers().size());
wa.appResourcesCleanedup();
assertEquals(ApplicationState.FINISHED, wa.app.getApplicationState());
} finally {
if (wa != null)
wa.finished();
}
}
@Test
public void testNMTokenSecretManagerCleanup() {
WrappedApplication wa = null;
try {
wa = new WrappedApplication(1, 314159265358979L, "yak", 1);
wa.initApplication();
wa.initContainer(0);
assertEquals(ApplicationState.INITING, wa.app.getApplicationState());
assertEquals(1, wa.app.getContainers().size());
wa.appFinished();
wa.containerFinished(0);
wa.appResourcesCleanedup();
assertEquals(ApplicationState.FINISHED, wa.app.getApplicationState());
verify(wa.nmTokenSecretMgr).appFinished(eq(wa.appId));
} finally {
if (wa != null) {
wa.finished();
}
}
}
private class ContainerKillMatcher extends ArgumentMatcher<ContainerEvent> {
private ContainerId cId;
public ContainerKillMatcher(ContainerId cId) {
this.cId = cId;
}
@Override
public boolean matches(Object argument) {
if (argument instanceof ContainerKillEvent) {
ContainerKillEvent event = (ContainerKillEvent) argument;
return event.getContainerID().equals(cId);
}
return false;
}
}
private class ContainerInitMatcher extends ArgumentMatcher<ContainerEvent> {
private ContainerId cId;
public ContainerInitMatcher(ContainerId cId) {
this.cId = cId;
}
@Override
public boolean matches(Object argument) {
if (argument instanceof ContainerInitEvent) {
ContainerInitEvent event = (ContainerInitEvent) argument;
return event.getContainerID().equals(cId);
}
return false;
}
}
@SuppressWarnings("unchecked")
private class WrappedApplication {
final DrainDispatcher dispatcher;
final EventHandler<LocalizationEvent> localizerBus;
final EventHandler<ContainersLauncherEvent> launcherBus;
final EventHandler<ContainersMonitorEvent> monitorBus;
final EventHandler<AuxServicesEvent> auxBus;
final EventHandler<ContainerEvent> containerBus;
final EventHandler<LogHandlerEvent> logAggregationBus;
final String user;
final List<Container> containers;
final Context context;
final Map<ContainerId, ContainerTokenIdentifier> containerTokenIdentifierMap;
final NMTokenSecretManagerInNM nmTokenSecretMgr;
final ApplicationId appId;
final Application app;
WrappedApplication(int id, long timestamp, String user, int numContainers) {
Configuration conf = new Configuration();
dispatcher = new DrainDispatcher();
containerTokenIdentifierMap =
new HashMap<ContainerId, ContainerTokenIdentifier>();
dispatcher.init(conf);
localizerBus = mock(EventHandler.class);
launcherBus = mock(EventHandler.class);
monitorBus = mock(EventHandler.class);
auxBus = mock(EventHandler.class);
containerBus = mock(EventHandler.class);
logAggregationBus = mock(EventHandler.class);
dispatcher.register(LocalizationEventType.class, localizerBus);
dispatcher.register(ContainersLauncherEventType.class, launcherBus);
dispatcher.register(ContainersMonitorEventType.class, monitorBus);
dispatcher.register(AuxServicesEventType.class, auxBus);
dispatcher.register(ContainerEventType.class, containerBus);
dispatcher.register(LogHandlerEventType.class, logAggregationBus);
nmTokenSecretMgr = mock(NMTokenSecretManagerInNM.class);
context = mock(Context.class);
when(context.getContainerTokenSecretManager()).thenReturn(
new NMContainerTokenSecretManager(conf));
when(context.getApplicationACLsManager()).thenReturn(
new ApplicationACLsManager(conf));
when(context.getNMTokenSecretManager()).thenReturn(nmTokenSecretMgr);
when(context.getConf()).thenReturn(conf);
// Setting master key
MasterKey masterKey = new MasterKeyPBImpl();
masterKey.setKeyId(123);
masterKey.setBytes(ByteBuffer.wrap(new byte[] { (new Integer(123)
.byteValue()) }));
context.getContainerTokenSecretManager().setMasterKey(masterKey);
this.user = user;
this.appId = BuilderUtils.newApplicationId(timestamp, id);
app = new ApplicationImpl(
dispatcher, this.user, null, null, 0, appId, null, context);
containers = new ArrayList<Container>();
for (int i = 0; i < numContainers; i++) {
Container container = createMockedContainer(this.appId, i);
containers.add(container);
long currentTime = System.currentTimeMillis();
ContainerTokenIdentifier identifier =
new ContainerTokenIdentifier(container.getContainerId(), "", "",
null, currentTime + 2000, masterKey.getKeyId(), currentTime,
Priority.newInstance(0), 0);
containerTokenIdentifierMap
.put(identifier.getContainerID(), identifier);
context.getContainerTokenSecretManager().startContainerSuccessful(
identifier);
Assert.assertFalse(context.getContainerTokenSecretManager()
.isValidStartContainerRequest(identifier));
}
dispatcher.start();
}
private void drainDispatcherEvents() {
dispatcher.await();
}
public void finished() {
dispatcher.stop();
}
public void initApplication() {
app.handle(new ApplicationInitEvent(appId,
new HashMap<ApplicationAccessType, String>()));
}
public void initContainer(int containerNum) {
if (containerNum == -1) {
for (int i = 0; i < containers.size(); i++) {
app.handle(new ApplicationContainerInitEvent(containers.get(i)));
}
} else {
app.handle(new ApplicationContainerInitEvent(containers.get(containerNum)));
}
drainDispatcherEvents();
}
public void containerFinished(int containerNum) {
app.handle(new ApplicationContainerFinishedEvent(containers.get(
containerNum).getContainerId()));
drainDispatcherEvents();
}
public void applicationInited() {
app.handle(new ApplicationInitedEvent(appId));
drainDispatcherEvents();
}
public void appFinished() {
app.handle(new ApplicationFinishEvent(appId,
"Finish Application"));
drainDispatcherEvents();
}
public void appResourcesCleanedup() {
app.handle(new ApplicationEvent(appId,
ApplicationEventType.APPLICATION_RESOURCES_CLEANEDUP));
drainDispatcherEvents();
}
public ContainerTokenIdentifier getContainerTokenIdentifier(
ContainerId containerId) {
return this.containerTokenIdentifierMap.get(containerId);
}
}
private Container createMockedContainer(ApplicationId appId, int containerId) {
ApplicationAttemptId appAttemptId =
BuilderUtils.newApplicationAttemptId(appId, 1);
ContainerId cId = BuilderUtils.newContainerId(appAttemptId, containerId);
Container c = mock(Container.class);
when(c.getContainerId()).thenReturn(cId);
ContainerLaunchContext launchContext = mock(ContainerLaunchContext.class);
when(c.getLaunchContext()).thenReturn(launchContext);
when(launchContext.getApplicationACLs()).thenReturn(
new HashMap<ApplicationAccessType, String>());
return c;
}
}
| apache-2.0 |
felipemrvieira/NathaliaAmaral | pages/index.php | 3429 | <?php
date_default_timezone_set("Brazil/East");
include("DAO/conexao.php");
include("DAO/estoqueDAO.php");
include("DAO/operacoesDAO.php");
include('header.php');
validaUsuarioLogado();
?>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header"><img width="40%" src="img/Marca%20sem%20fundo.png"></h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<?php if(array_key_exists("vendaStatus", $_GET) && $_GET['vendaStatus']=='ok' && array_key_exists("id", $_GET) && $_GET['id']<>''){?>
<div class="alert alert-success fade in">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
Venda <?php echo $_GET['id'] ?> cadastrada com <strong>Successo!</strong>
</div>
<?php }if(array_key_exists("id", $_GET)&& $_GET['id']==''){ ?>
<div class="alert alert-danger fade in">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
Venda <strong>não registrada!</strong>
</div>
<?php }if(array_key_exists("vendaStatus", $_GET)&& $_GET['vendaStatus']=='cancelada'){ ?>
<div class="alert alert-success fade in">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
Venda <strong>cancelada!</strong>
</div>
<?php }if(array_key_exists("venda", $_GET)&& $_GET['venda']=='ok'){ ?>
<div class="alert alert-success fade in">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
Venda realizada com <strong>Sucesso!</strong>
</div>
<?php } $array_clientes = listaAniversariantesDiaNaoParabenizados($conexao);
if ( sizeof($array_clientes) > 0) {?>
<div class="alert alert-success fade in">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
Você tem <a href="aniversariantes.php">clientes</a> que completam ano hoje!
</div>
<?php } atualizaAniversariantes($conexao);?>
<?php
include('venda/listaCliente.php'); ?>
<!-- <div class="col-md-12">
<div class="col-md-6">
uma
</div>
<div class="col-md-6">
duas
</div>
</div> -->
</div>
<!-- <script>
function preenche(parametro){
document.formvenda.valor.value = parametro;
}
</script>-->
<!--/div>
<!-- /#wrapper -->
<!-- jQuery -->
<script src="../bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="../bower_components/metisMenu/dist/metisMenu.min.js"></script>
<!-- Custom Theme JavaScript -->
<script src="../dist/js/sb-admin-2.js"></script>
</body>
</html>
| apache-2.0 |
iVCE/RDFS | src/test/org/apache/hadoop/hdfs/TestNameNodeIdempotence.java | 6952 | package org.apache.hadoop.hdfs;
import junit.framework.TestCase;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.DFSInputStream;
import org.apache.hadoop.hdfs.DFSOutputStream;
import org.apache.hadoop.hdfs.MiniDFSCluster.DataNodeProperties;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.ClientProtocol;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlockWithMetaInfo;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.protocol.LocatedBlocksWithMetaInfo;
import org.apache.hadoop.hdfs.protocol.FSConstants.SafeModeAction;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.datanode.DataStorage;
import org.apache.hadoop.hdfs.server.datanode.FSDataset;
import org.apache.hadoop.hdfs.server.datanode.FSDatasetTestUtil;
import org.apache.hadoop.hdfs.server.datanode.NameSpaceSliceStorage;
import org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset;
import org.apache.hadoop.hdfs.server.namenode.FSNamesystem;
import org.apache.hadoop.hdfs.server.namenode.LeaseExpiredException;
import org.apache.hadoop.hdfs.server.namenode.LeaseManager;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.hdfs.server.namenode.FSEditLog;
import org.apache.hadoop.hdfs.server.namenode.FSImageAdapter;
import org.apache.hadoop.hdfs.server.namenode.NameNodeAdapter;
import org.apache.hadoop.ipc.ProtocolSignature;
import org.apache.hadoop.ipc.VersionedProtocol;
import static org.apache.hadoop.hdfs.AppendTestUtil.loseLeases;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.log4j.Level;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/* Test whether NameNode.close() and NmaeNode.addBlock() are idempotent
*/
public class TestNameNodeIdempotence extends TestCase {
{
((Log4JLogger) DataNode.LOG).getLogger().setLevel(Level.ALL);
((Log4JLogger) DFSClient.LOG).getLogger().setLevel(Level.ALL);
((Log4JLogger) FSNamesystem.LOG).getLogger().setLevel(Level.ALL);
((Log4JLogger) NameNode.LOG).getLogger().setLevel(Level.ALL);
}
MiniDFSCluster cluster;
@Override
protected void setUp() throws Exception {
Configuration conf = new Configuration();
conf.setLong("dfs.block.size", 512L);
cluster = new MiniDFSCluster(conf, 1, true, null);
}
@Override
protected void tearDown() throws Exception {
cluster.shutdown();
}
/**
* Test closeFile() name-node RPC is idempotent
*/
public void testIdepotentCloseCalls() throws IOException {
ClientProtocol nn = cluster.getNameNode();
FileSystem fs = cluster.getFileSystem();
DFSClient dfsclient = ((DistributedFileSystem) fs).dfs;
DFSClient mockDfs = spy(dfsclient);
ClientProtocol mockNameNode = spy(nn);
mockDfs.namenode = mockNameNode;
String src = "/testNameNodeFingerprintSent1.txt";
// Path f = new Path(src);
FSDataOutputStream a_out = new FSDataOutputStream(mockDfs.create(src, true)); // fs.create(f);
a_out.writeBytes("something");
doAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
try {
invocation.callRealMethod();
return (Void) invocation.callRealMethod();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}).when(mockDfs).closeFile(anyString(), anyLong(), (Block) anyObject());
a_out.close();
verify(mockNameNode, times(2)).complete(anyString(), anyString(),
anyLong(), (Block) anyObject());
boolean hasFail = false;
try {
nn.complete(src, "CC", 9, new Block(666));
} catch (IOException e) {
TestCase
.assertTrue(e
.getMessage()
.contains(
"Try close a closed file: last block from client side doesn't match name-node. client:"));
hasFail = true;
}
TestCase.assertTrue(hasFail);
hasFail = false;
try {
nn.complete(src, "CC", 9, null);
} catch (IOException e) {
TestCase
.assertTrue(
e.getMessage(),
e.getMessage()
.contains(
"No lease on /testNameNodeFingerprintSent1.txt File is not open for writing."));
hasFail = true;
}
TestCase.assertTrue(hasFail);
}
/**
* Test addBlock() name-node RPC is idempotent
*/
public void testIdepotentCallsAddBlock() throws IOException {
ClientProtocol nn = cluster.getNameNode();
FileSystem fs = cluster.getFileSystem();
DFSClient dfsclient = ((DistributedFileSystem) fs).dfs;
String src = "/testNameNodeFingerprintSent1.txt";
// Path f = new Path(src);
DFSOutputStream dos = (DFSOutputStream) dfsclient.create(src, true,
(short) 1, 512L);
FSDataOutputStream a_out = new FSDataOutputStream(dos); // fs.create(f);
for (int i = 0; i < 512; i++) {
a_out.writeBytes("bc");
}
a_out.flush();
LocatedBlocks lb = nn.getBlockLocations(src, 256, 257);
LocatedBlock lb1 = nn.addBlockAndFetchMetaInfo(src, dfsclient.clientName,
null, null, 512L, lb.getLocatedBlocks().get(lb.locatedBlockCount() - 1)
.getBlock());
LocatedBlock lb2 = nn.addBlockAndFetchMetaInfo(src, dfsclient.clientName,
null, null, 512L, lb.getLocatedBlocks().get(lb.locatedBlockCount() - 1)
.getBlock());
TestCase.assertTrue("blocks: " + lb1.getBlock() + " and " + lb2.getBlock(),
lb1.getBlock().equals(lb2.getBlock()));
}
}
| apache-2.0 |
interseroh/document-container-confluence | src/main/java/com/lofidewanto/demo/server/DemoGwtSpringbootApplication.java | 1721 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.lofidewanto.demo.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import com.google.gwt.logging.server.RemoteLoggingServiceImpl;
import com.lofidewanto.demo.shared.DemoGwtServiceEndpoint;
@SpringBootApplication
public class DemoGwtSpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(DemoGwtSpringbootApplication.class, args);
}
@Bean
public ServletRegistrationBean servletRegistrationBean() {
return new ServletRegistrationBean(new RemoteLoggingServiceImpl(),
DemoGwtServiceEndpoint.GWT_REMOTE_LOGGING + "/*");
}
@Bean
public RestTemplate restTemplateBean() {
return new RestTemplate();
}
}
| apache-2.0 |
gavin2lee/generic-support | auth-admin-api/src/main/java/com/generic/support/admin/service/PermissionService.java | 415 | package com.generic.support.admin.service;
import java.util.List;
import com.lachesis.support.objects.entity.auth.Permission;
public interface PermissionService {
Permission savePermission(Permission p);
Permission updatePermission(Permission p);
Permission removePermission(Permission p);
Permission findPermissionById(Long id);
Permission findPermissionByName(String name);
List<Permission> findAll();
}
| apache-2.0 |
CASPED/OpenGTS | src/org/opengts/util/Tuple.java | 2701 | // ----------------------------------------------------------------------------
// Copyright 2007-2011, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Description:
// This class provides Tuples
// ----------------------------------------------------------------------------
// Change History:
// 2009/06/01 Martin D. Flynn
// -Initial release
// ----------------------------------------------------------------------------
package org.opengts.util;
import java.util.*;
/**
*** <code>Tuple</code> a wrapper class for Tuples
**/
public class Tuple
{
// ------------------------------------------------------------------------
/**
*** A wrapper for a single item
**/
public static class Single<AA>
{
public AA a = null;
public Single(AA a) {
this.a = a;
}
public String toString() {
return (this.a != null)? this.a.toString() : "";
}
}
// ------------------------------------------------------------------------
/**
*** A wrapper for a pair of items
**/
public static class Pair<AA,BB>
{
public AA a = null;
public BB b = null;
public Pair(AA a, BB b) {
this.a = a;
this.b = b;
}
public String toString() {
return (this.a != null)? this.a.toString() : "";
}
}
// ------------------------------------------------------------------------
/**
*** A wrapper for a triple of items
**/
public static class Triple<AA,BB,CC>
{
public AA a = null;
public BB b = null;
public CC c = null;
public Triple(AA a, BB b, CC c) {
this.a = a;
this.b = b;
this.c = c;
}
public String toString() {
return (this.a != null)? this.a.toString() : "";
}
}
// ------------------------------------------------------------------------
}
| apache-2.0 |
thanple/tomcatsrc | java/org/apache/tomcat/util/net/JIoEndpoint.java | 22341 | /*
* 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.tomcat.util.net;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.RejectedExecutionException;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState;
import org.apache.tomcat.util.security.PrivilegedSetTccl;
/**
* Handle incoming TCP connections.
*
* This class implement a simple server model: one listener thread accepts on a socket and
* creates a new worker thread for each incoming connection.
*
* More advanced Endpoints will reuse the threads, use queues, etc.
*
* @author James Duncan Davidson
* @author Jason Hunter
* @author James Todd
* @author Costin Manolache
* @author Gal Shachor
* @author Yoav Shapira
* @author Remy Maucherat
*/
public class JIoEndpoint extends AbstractEndpoint<Socket> {
// -------------------------------------------------------------- Constants
private static final Log log = LogFactory.getLog(JIoEndpoint.class);
// ----------------------------------------------------------------- Fields
/**
* Associated server socket.
*/
protected ServerSocket serverSocket = null;
// ------------------------------------------------------------ Constructor
public JIoEndpoint() {
// Set maxConnections to zero so we can tell if the user has specified
// their own value on the connector when we reach bind()
setMaxConnections(0);
// Reduce the executor timeout for BIO as threads in keep-alive will not
// terminate when the executor interrupts them.
setExecutorTerminationTimeoutMillis(0);
}
// ------------------------------------------------------------- Properties
/**
* Handling of accepted sockets.
*/
protected Handler handler = null;
public void setHandler(Handler handler ) { this.handler = handler; }
public Handler getHandler() { return handler; }
/**
* Server socket factory.
*/
protected ServerSocketFactory serverSocketFactory = null;
public void setServerSocketFactory(ServerSocketFactory factory) { this.serverSocketFactory = factory; }
public ServerSocketFactory getServerSocketFactory() { return serverSocketFactory; }
/**
* Port in use.
*/
@Override
public int getLocalPort() {
ServerSocket s = serverSocket;
if (s == null) {
return -1;
} else {
return s.getLocalPort();
}
}
/*
* Optional feature support.
*/
@Override
public boolean getUseSendfile() { return false; } // Not supported
@Override
public boolean getUseComet() { return false; } // Not supported
@Override
public boolean getUseCometTimeout() { return false; } // Not supported
@Override
public boolean getDeferAccept() { return false; } // Not supported
@Override
public boolean getUsePolling() { return false; } // Not supported
// ------------------------------------------------ Handler Inner Interface
/**
* Bare bones interface used for socket processing. Per thread data is to be
* stored in the ThreadWithAttributes extra folders, or alternately in
* thread local fields.
*/
public interface Handler extends AbstractEndpoint.Handler {
public SocketState process(SocketWrapper<Socket> socket,
SocketStatus status);
public SSLImplementation getSslImplementation();
}
/**
* Async timeout thread
*/
protected class AsyncTimeout implements Runnable {
/**
* The background thread that checks async requests and fires the
* timeout if there has been no activity.
*/
@Override
public void run() {
// Loop until we receive a shutdown command
while (running) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
long now = System.currentTimeMillis();
Iterator<SocketWrapper<Socket>> sockets =
waitingRequests.iterator();
while (sockets.hasNext()) {
SocketWrapper<Socket> socket = sockets.next();
long access = socket.getLastAccess();
if (socket.getTimeout() > 0 &&
(now-access)>socket.getTimeout()) {
// Prevent multiple timeouts
socket.setTimeout(-1);
processSocketAsync(socket,SocketStatus.TIMEOUT);
}
}
// Loop if endpoint is paused
while (paused && running) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
}
}
}
}
// --------------------------------------------------- Acceptor Inner Class
/**
* The background thread that listens for incoming TCP/IP connections and
* hands them off to an appropriate processor.
*/
protected class Acceptor extends AbstractEndpoint.Acceptor {
@Override
public void run() {
int errorDelay = 0;
// Loop until we receive a shutdown command
while (running) {
// Loop if endpoint is paused
while (paused && running) {
state = AcceptorState.PAUSED;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore
}
}
if (!running) {
break;
}
state = AcceptorState.RUNNING;
try {
//if we have reached max connections, wait
countUpOrAwaitConnection();
Socket socket = null;
try {
// 此处用来接收 请求 监听客户端连接
// Accept the next incoming connection from the server
// socket
socket = serverSocketFactory.acceptSocket(serverSocket);
} catch (IOException ioe) {
countDownConnection();
// Introduce delay if necessary
errorDelay = handleExceptionWithDelay(errorDelay);
// re-throw
throw ioe;
}
// Successful accept, reset the error delay
errorDelay = 0;
// Configure the socket
if (running && !paused && setSocketOptions(socket)) {
// TODO 监听到连接后(即浏览器向服务器发起一次请求)
// Hand this socket off to an appropriate processor
if (!processSocket(socket)) {
countDownConnection();
// 关闭 socket 链接
// Close socket right away
closeSocket(socket);
}
} else {
countDownConnection();
// Close socket right away
closeSocket(socket);
}
} catch (IOException x) {
if (running) {
log.error(sm.getString("endpoint.accept.fail"), x);
}
} catch (NullPointerException npe) {
if (running) {
log.error(sm.getString("endpoint.accept.fail"), npe);
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString("endpoint.accept.fail"), t);
}
}
state = AcceptorState.ENDED;
}
}
private void closeSocket(Socket socket) {
try {
socket.close();
} catch (IOException e) {
// Ignore
}
}
// ------------------------------------------- SocketProcessor Inner Class
/**
* This class is the equivalent of the Worker, but will simply use in an
* external Executor thread pool.
*
* 该类就完成了一次 tcp 交互到 Http 的转化
* 最终会产生出 request、response 对象
*/
protected class SocketProcessor implements Runnable {
protected SocketWrapper<Socket> socket = null;
protected SocketStatus status = null;
public SocketProcessor(SocketWrapper<Socket> socket) {
if (socket==null) throw new NullPointerException();
this.socket = socket;
}
public SocketProcessor(SocketWrapper<Socket> socket, SocketStatus status) {
this(socket);
this.status = status;
}
@Override
public void run() {
boolean launch = false;
synchronized (socket) {
try {
SocketState state = SocketState.OPEN;
try {
// SSL handshake
serverSocketFactory.handshake(socket.getSocket());
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (log.isDebugEnabled()) {
log.debug(sm.getString("endpoint.err.handshake"), t);
}
// Tell to close the socket
state = SocketState.CLOSED;
}
if ((state != SocketState.CLOSED)) {// 非关闭状态
if (status == null) {
// 调用handler对象的process方法,
// 这里handler对象实际上是Http11ConnectionHandler类的实例,
// 该对象的初始化过程是在org.apache.coyote.http11.Http11Protocol对象的构造方法中:
state = handler.process(socket, SocketStatus.OPEN_READ);
} else {
state = handler.process(socket,status);
}
}
if (state == SocketState.CLOSED) {
// Close socket
if (log.isTraceEnabled()) {
log.trace("Closing socket:"+socket);
}
countDownConnection();
try {
socket.getSocket().close();
} catch (IOException e) {
// Ignore
}
} else if (state == SocketState.OPEN ||
state == SocketState.UPGRADING ||
state == SocketState.UPGRADING_TOMCAT ||
state == SocketState.UPGRADED){
socket.setKeptAlive(true);
socket.access();
launch = true;
} else if (state == SocketState.LONG) {
socket.access();
waitingRequests.add(socket);
}
} finally {
if (launch) {
try {
getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN_READ));
} catch (RejectedExecutionException x) {
log.warn("Socket reprocessing request was rejected for:"+socket,x);
try {
//unable to handle connection at this time
handler.process(socket, SocketStatus.DISCONNECT);
} finally {
countDownConnection();
}
} catch (NullPointerException npe) {
if (running) {
log.error(sm.getString("endpoint.launch.fail"),
npe);
}
}
}
}
}
socket = null;
// Finish up this request
}
}
// -------------------- Public methods --------------------
@Override
public void bind() throws Exception {
// Initialize thread count defaults for acceptor
if (acceptorThreadCount == 0) {
acceptorThreadCount = 1;
}
// Initialize maxConnections
if (getMaxConnections() == 0) {
// User hasn't set a value - use the default
setMaxConnections(getMaxThreadsInternal());
}
if (serverSocketFactory == null) {
if (isSSLEnabled()) {
serverSocketFactory =
handler.getSslImplementation().getServerSocketFactory(this);
} else {
serverSocketFactory = new DefaultServerSocketFactory(this);
}
}
if (serverSocket == null) {
try {
if (getAddress() == null) {
serverSocket = serverSocketFactory.createSocket(getPort(),
getBacklog());
} else {
serverSocket = serverSocketFactory.createSocket(getPort(),
getBacklog(), getAddress());
}
} catch (BindException orig) {
String msg;
if (getAddress() == null)
msg = orig.getMessage() + " <null>:" + getPort();
else
msg = orig.getMessage() + " " +
getAddress().toString() + ":" + getPort();
BindException be = new BindException(msg);
be.initCause(orig);
throw be;
}
}
}
@Override
public void startInternal() throws Exception {
if (!running) {
running = true;
paused = false;
// Create worker collection
if (getExecutor() == null) {
createExecutor();
}
initializeConnectionLatch();
startAcceptorThreads();
// Start async timeout thread
Thread timeoutThread = new Thread(new AsyncTimeout(),
getName() + "-AsyncTimeout");
timeoutThread.setPriority(threadPriority);
timeoutThread.setDaemon(true);
timeoutThread.start();
}
}
@Override
public void stopInternal() {
releaseConnectionLatch();
if (!paused) {
pause();
}
if (running) {
running = false;
unlockAccept();
}
shutdownExecutor();
}
/**
* Deallocate APR memory pools, and close server socket.
*/
@Override
public void unbind() throws Exception {
if (running) {
stop();
}
if (serverSocket != null) {
try {
if (serverSocket != null)
serverSocket.close();
} catch (Exception e) {
log.error(sm.getString("endpoint.err.close"), e);
}
serverSocket = null;
}
handler.recycle();
}
@Override
protected AbstractEndpoint.Acceptor createAcceptor() {
return new Acceptor();
}
/**
* Configure the socket.
*/
protected boolean setSocketOptions(Socket socket) {
try {
// 1: Set socket options: timeout, linger, etc
socketProperties.setProperties(socket);
} catch (SocketException s) {
//error here is common if the client has reset the connection
if (log.isDebugEnabled()) {
log.debug(sm.getString("endpoint.err.unexpected"), s);
}
// Close the socket
return false;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString("endpoint.err.unexpected"), t);
// Close the socket
return false;
}
return true;
}
/**
* Process a new connection from a new client. Wraps the socket so
* keep-alive and other attributes can be tracked and then passes the socket
* to the executor for processing.
*
* @param socket The socket associated with the client.
*
* @return <code>true</code> if the socket is passed to the
* executor, <code>false</code> if something went wrong or
* if the endpoint is shutting down. Returning
* <code>false</code> is an indication to close the socket
* immediately.
*
* 处理服务器监听到的一次客户端链接,并处理相关请求
*/
protected boolean processSocket(Socket socket) {
// Process the request from this socket
try {
SocketWrapper<Socket> wrapper = new SocketWrapper<Socket>(socket);
wrapper.setKeepAliveLeft(getMaxKeepAliveRequests());
wrapper.setSecure(isSSLEnabled());
// During shutdown, executor may be null - avoid NPE
if (!running) {
return false;
}
getExecutor().execute(new SocketProcessor(wrapper));
} catch (RejectedExecutionException x) {
log.warn("Socket processing request was rejected for:"+socket,x);
return false;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
// This means we got an OOM or similar creating a thread, or that
// the pool and its queue are full
log.error(sm.getString("endpoint.process.fail"), t);
return false;
}
return true;
}
/**
* Process an existing async connection. If processing is required, passes
* the wrapped socket to an executor for processing.
*
* @param socket The socket associated with the client.
* @param status Only OPEN and TIMEOUT are used. The others are used for
* Comet requests that are not supported by the BIO (JIO)
* Connector.
*/
@Override
public void processSocketAsync(SocketWrapper<Socket> socket,
SocketStatus status) {
try {
synchronized (socket) {
if (waitingRequests.remove(socket)) {
SocketProcessor proc = new SocketProcessor(socket,status);
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try {
//threads should not be created by the webapp classloader
if (Constants.IS_SECURITY_ENABLED) {
PrivilegedAction<Void> pa = new PrivilegedSetTccl(
getClass().getClassLoader());
AccessController.doPrivileged(pa);
} else {
Thread.currentThread().setContextClassLoader(
getClass().getClassLoader());
}
// During shutdown, executor may be null - avoid NPE
if (!running) {
return;
}
getExecutor().execute(proc);
//TODO gotta catch RejectedExecutionException and properly handle it
} finally {
if (Constants.IS_SECURITY_ENABLED) {
PrivilegedAction<Void> pa = new PrivilegedSetTccl(loader);
AccessController.doPrivileged(pa);
} else {
Thread.currentThread().setContextClassLoader(loader);
}
}
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
// This means we got an OOM or similar creating a thread, or that
// the pool and its queue are full
log.error(sm.getString("endpoint.process.fail"), t);
}
}
protected ConcurrentLinkedQueue<SocketWrapper<Socket>> waitingRequests =
new ConcurrentLinkedQueue<SocketWrapper<Socket>>();
@Override
public void removeWaitingRequest(SocketWrapper<Socket> socketWrapper) {
waitingRequests.remove(socketWrapper);
}
@Override
protected Log getLog() {
return log;
}
}
| apache-2.0 |
krizzdewizz/hyperxml | src/main/java/hyperxml/Xml.java | 816 | package hyperxml;
/**
* Writes arbitrary xml with only the method {@link #$(String, Object...)}.
* <p>
* <code>$()</code> expects its parameters as follows:
* <p>
* Example:
*
* <pre>
* $("html");
* {
* $("body", "onload", "doThings()"); // attribute name-value pairs
* {
* $("h1", "class", "title", "hello world", $); // with text content, $ --> 'short close'
* }
* $(); // body // no parameters --> end element
* }
* $(); // html
*
* -->
*
* <html>
* <body onload="doThings()">
* <h1 class="title">hello world</h1>
* </body>
* </html>
* </pre>
*
* @author krizzdewizz
*/
public class Xml extends Base<Xml> {
} | apache-2.0 |
wolfdog007/aruzhev | chapter_001/src/main/java/ru/job4j/Point.java | 1024 | package ru.job4j;
/**
* Class Point.
*
* @author Ruzhev Alexander
* @since 16.02.2017
*/
public class Point {
/**
* @param x a point of coordinates
*/
private double x;
/**
* @param y a point of coordinates
*/
private double y;
/**
* Getter for x.
*
* @return x
*/
public double getX() {
return this.x;
}
/**
* Getter for y.
*
* @return y
*/
public double getY() {
return this.y;
}
/**
* Designer.
*
* @param x a point of coordinates
* @param y a point of coordinates
*/
public Point(double x, double y) {
this.x = x;
this.y = y;
}
/**
* Return the distance between two points.
*
* @param point an object of class Point
* @return the distance between two points
*/
public double distanceTo(Point point) {
return Math.sqrt(Math.pow(this.x - point.getX(), 2) + Math.pow(this.y - point.getY(), 2));
}
}
| apache-2.0 |
babble/babble | src/test/ed/db/index5.js | 505 | // index5.js - test reverse direction index
function validate() {
assert.eq( 2, t.find().count() );
f = t.find().sort( { a: 1 } );
assert.eq( 2, t.count() );
assert.eq( 1, f[ 0 ].a );
assert.eq( 2, f[ 1 ].a );
r = t.find().sort( { a: -1 } );
assert.eq( 2, r.count() );
assert.eq( 2, r[ 0 ].a );
assert.eq( 1, r[ 1 ].a );
}
db = connect( "test" );
t = db.index5;
t.drop();
t.save( { a: 1 } );
t.save( { a: 2 } );
validate();
t.ensureIndex( { a: -1 } );
validate();
| apache-2.0 |
dougwig/x-neutron-vpnaas | neutron_vpnaas/tests/unit/services/vpn/test_vpn_agent.py | 7190 | # Copyright 2013, Nachi Ueno, NTT I3, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
from oslo.config import cfg
from neutron.agent.common import config as agent_config
from neutron.agent import l3_agent
from neutron.agent import l3_ha_agent
from neutron.agent.linux import interface
from neutron.common import config as base_config
from neutron.openstack.common import uuidutils
from neutron_vpnaas.services.vpn import agent
from neutron_vpnaas.services.vpn import device_drivers
from neutron.tests import base
_uuid = uuidutils.generate_uuid
NOOP_DEVICE_CLASS = 'NoopDeviceDriver'
NOOP_DEVICE = ('neutron.tests.unit.services.'
'vpn.test_vpn_agent.%s' % NOOP_DEVICE_CLASS)
class NoopDeviceDriver(device_drivers.DeviceDriver):
def sync(self, context, processes):
pass
def create_router(self, process_id):
pass
def destroy_router(self, process_id):
pass
class TestVPNAgent(base.BaseTestCase):
def setUp(self):
super(TestVPNAgent, self).setUp()
self.conf = cfg.CONF
self.conf.register_opts(base_config.core_opts)
self.conf.register_opts(l3_agent.L3NATAgent.OPTS)
self.conf.register_opts(l3_ha_agent.OPTS)
self.conf.register_opts(interface.OPTS)
agent_config.register_interface_driver_opts_helper(self.conf)
agent_config.register_use_namespaces_opts_helper(self.conf)
agent_config.register_agent_state_opts_helper(self.conf)
agent_config.register_root_helper(self.conf)
self.conf.set_override('interface_driver',
'neutron.agent.linux.interface.NullDriver')
self.conf.set_override(
'vpn_device_driver',
[NOOP_DEVICE],
'vpnagent')
for clazz in [
'neutron.agent.linux.ip_lib.device_exists',
'neutron.agent.linux.ip_lib.IPWrapper',
'neutron.agent.linux.interface.NullDriver',
'neutron.agent.linux.utils.execute'
]:
mock.patch(clazz).start()
l3pluginApi_cls = mock.patch(
'neutron.agent.l3_agent.L3PluginApi').start()
self.plugin_api = mock.MagicMock()
l3pluginApi_cls.return_value = self.plugin_api
looping_call_p = mock.patch(
'neutron.openstack.common.loopingcall.FixedIntervalLoopingCall')
looping_call_p.start()
self.fake_host = 'fake_host'
self.agent = agent.VPNAgent(self.fake_host)
def test_setup_drivers(self):
self.assertEqual(1, len(self.agent.devices))
device = self.agent.devices[0]
self.assertEqual(
NOOP_DEVICE_CLASS,
device.__class__.__name__
)
def test_get_namespace(self):
router_id = _uuid()
ns = "ns-" + router_id
ri = l3_agent.RouterInfo(router_id, self.conf.root_helper,
{}, ns_name=ns)
self.agent.router_info = {router_id: ri}
namespace = self.agent.get_namespace(router_id)
self.assertTrue(namespace.endswith(router_id))
self.assertFalse(self.agent.get_namespace('fake_id'))
def test_add_nat_rule(self):
router_id = _uuid()
ri = l3_agent.RouterInfo(router_id, self.conf.root_helper, {})
iptables = mock.Mock()
ri.iptables_manager.ipv4['nat'] = iptables
self.agent.router_info = {router_id: ri}
self.agent.add_nat_rule(router_id, 'fake_chain', 'fake_rule', True)
iptables.add_rule.assert_called_once_with(
'fake_chain', 'fake_rule', top=True)
def test_add_nat_rule_with_no_router(self):
self.agent.router_info = {}
#Should do nothing
self.agent.add_nat_rule(
'fake_router_id',
'fake_chain',
'fake_rule',
True)
def test_remove_rule(self):
router_id = _uuid()
ri = l3_agent.RouterInfo(router_id, self.conf.root_helper, {})
iptables = mock.Mock()
ri.iptables_manager.ipv4['nat'] = iptables
self.agent.router_info = {router_id: ri}
self.agent.remove_nat_rule(router_id, 'fake_chain', 'fake_rule', True)
iptables.remove_rule.assert_called_once_with(
'fake_chain', 'fake_rule', top=True)
def test_remove_rule_with_no_router(self):
self.agent.router_info = {}
#Should do nothing
self.agent.remove_nat_rule(
'fake_router_id',
'fake_chain',
'fake_rule')
def test_iptables_apply(self):
router_id = _uuid()
ri = l3_agent.RouterInfo(router_id, self.conf.root_helper, {})
iptables = mock.Mock()
ri.iptables_manager = iptables
self.agent.router_info = {router_id: ri}
self.agent.iptables_apply(router_id)
iptables.apply.assert_called_once_with()
def test_iptables_apply_with_no_router(self):
#Should do nothing
self.agent.router_info = {}
self.agent.iptables_apply('fake_router_id')
def test_router_added(self):
mock.patch(
'neutron.agent.linux.iptables_manager.IptablesManager').start()
router_id = _uuid()
router = {'id': router_id}
device = mock.Mock()
self.agent.devices = [device]
self.agent._router_added(router_id, router)
device.create_router.assert_called_once_with(router_id)
def test_router_removed(self):
self.plugin_api.get_external_network_id.return_value = None
mock.patch(
'neutron.agent.linux.iptables_manager.IptablesManager').start()
router_id = _uuid()
ri = l3_agent.RouterInfo(router_id, self.conf.root_helper, {},
ns_name="qrouter-%s" % router_id)
ri.router = {
'id': router_id,
'admin_state_up': True,
'routes': [],
'external_gateway_info': {},
'distributed': False}
device = mock.Mock()
self.agent.router_info = {router_id: ri}
self.agent.devices = [device]
self.agent._router_removed(router_id)
device.destroy_router.assert_called_once_with(router_id)
def test_process_router_if_compatible(self):
self.plugin_api.get_external_network_id.return_value = None
router = {'id': _uuid(),
'admin_state_up': True,
'routes': [],
'external_gateway_info': {}}
device = mock.Mock()
self.agent.devices = [device]
self.agent._process_router_if_compatible(router)
device.sync.assert_called_once_with(mock.ANY, [router])
| apache-2.0 |
Kangmo/korbit-nodejs-sdk | main/src/main/scala/helper/Excp.scala | 209 | package org.kangmo.helper
object Excp {
def getStackTrace(e : Exception) = {
val sr = new java.io.StringWriter();
val writer = new java.io.PrintWriter(sr);
e.printStackTrace(writer)
sr.toString
}
}
| apache-2.0 |
desertbit/bulldozer | sessions/socket/dummysocket.go | 1324 | /*
* Bulldozer Framework
* Copyright (C) DesertBit
*/
package socket
import (
"sync"
)
//###########################//
//### Dummy Socket struct ###//
//###########################//
type DummySocket struct {
remoteAddr string
userAgent string
isClosed bool
mutex sync.Mutex
onClose func()
}
func NewSocketDummy(remoteAddr string, userAgent string) *DummySocket {
// Create a new dummy socket struct
return &DummySocket{
remoteAddr: remoteAddr,
userAgent: userAgent,
isClosed: false,
onClose: nil,
}
}
func (s *DummySocket) Type() SocketType {
return TypeDummySocket
}
func (s *DummySocket) RemoteAddr() string {
return s.remoteAddr
}
func (s *DummySocket) UserAgent() string {
return s.userAgent
}
func (s *DummySocket) IsClosed() bool {
return s.isClosed
}
func (s *DummySocket) Close() {
// Lock the mutex
s.mutex.Lock()
// Just return if the socket is already closed
if s.isClosed {
// Unlock the mutex again
s.mutex.Unlock()
return
}
// Update the flag
s.isClosed = true
// Unlock the mutex again
s.mutex.Unlock()
// Trigger the onClose function if defined
if s.onClose != nil {
s.onClose()
}
}
func (s *DummySocket) OnClose(f func()) {
s.onClose = f
}
func (s *DummySocket) Write(string) {}
func (s *DummySocket) OnRead(func(string)) {}
| apache-2.0 |
macanhhuy/dcp-api | src/test/java/org/jboss/dcp/api/rest/SecurityPreProcessInterceptorTest.java | 6801 | /*
* JBoss, Home of Professional Open Source
* Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
*/
package org.jboss.dcp.api.rest;
import java.security.Principal;
import java.util.logging.Logger;
import javax.ws.rs.core.SecurityContext;
import org.jboss.dcp.api.annotations.security.GuestAllowed;
import org.jboss.dcp.api.annotations.security.ProviderAllowed;
import org.jboss.resteasy.core.ResourceMethod;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.plugins.server.embedded.SimplePrincipal;
import org.jboss.resteasy.util.HttpResponseCodes;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
/**
* Unit test for {@link SecurityPreProcessInterceptor}
*
* @author Vlastimil Elias (velias at redhat dot com)
*/
public class SecurityPreProcessInterceptorTest {
Principal principal = new SimplePrincipal("uname");
private SecurityPreProcessInterceptor getTested() {
SecurityPreProcessInterceptor tested = new SecurityPreProcessInterceptor();
tested.securityContext = Mockito.mock(SecurityContext.class);
tested.log = Logger.getLogger("testlogger");
return tested;
}
@Test
public void notAuthenticatedTest() {
SecurityPreProcessInterceptor tested = getTested();
Mockito.when(tested.securityContext.getUserPrincipal()).thenReturn(null);
ServerResponse res = tested.preProcess(null, null);
Assert.assertNotNull(res);
Assert.assertEquals(HttpResponseCodes.SC_UNAUTHORIZED, res.getStatus());
Assert.assertEquals("Basic realm=\"Insert Provider's username and password\"",
res.getMetadata().get("WWW-Authenticate").get(0));
}
@SuppressWarnings("unchecked")
@Test
public void authenticatedTest() throws NoSuchMethodException, SecurityException {
SecurityPreProcessInterceptor tested = getTested();
Mockito.when(tested.securityContext.getUserPrincipal()).thenReturn(principal);
ResourceMethod methodMock = Mockito.mock(ResourceMethod.class);
Mockito.when((Class<MethodAnnotationsMock>) methodMock.getResourceClass()).thenReturn(MethodAnnotationsMock.class);
Mockito.when(methodMock.getMethod()).thenReturn(MethodAnnotationsMock.class.getMethod("methodProviderAllowed"));
ServerResponse res = tested.preProcess(null, methodMock);
Assert.assertNull(res);
}
@SuppressWarnings("unchecked")
@Test
public void superProviderTest() throws NoSuchMethodException, SecurityException {
SecurityPreProcessInterceptor tested = getTested();
ResourceMethod methodMock = Mockito.mock(ResourceMethod.class);
Mockito.when((Class<ClassSuperProviderAllowedMock>) methodMock.getResourceClass()).thenReturn(
ClassSuperProviderAllowedMock.class);
Mockito.when(methodMock.getMethod()).thenReturn(MethodAnnotationsMock.class.getMethod("methodNotAnnotated"));
// case - user is not super provider but annotation requires super provider
{
Mockito.when(tested.securityContext.getUserPrincipal()).thenReturn(principal);
Mockito.when(tested.securityContext.isUserInRole(CustomSecurityContext.SUPER_ADMIN_ROLE)).thenReturn(false);
ServerResponse res = tested.preProcess(null, methodMock);
Assert.assertNotNull(res);
Assert.assertEquals(HttpResponseCodes.SC_FORBIDDEN, res.getStatus());
}
// case - user is super provider and annotation requires super provider
{
Mockito.reset(tested.securityContext);
Mockito.when(tested.securityContext.getUserPrincipal()).thenReturn(principal);
Mockito.when(tested.securityContext.isUserInRole(CustomSecurityContext.SUPER_ADMIN_ROLE)).thenReturn(true);
ServerResponse res = tested.preProcess(null, methodMock);
Assert.assertNull(res);
}
}
@Test
public void getProviderAllowedAnnotationTest() throws SecurityException, NoSuchMethodException {
Assert.assertNull(SecurityPreProcessInterceptor.getProviderAllowedAnnotation(MethodAnnotationsMock.class,
MethodAnnotationsMock.class.getMethod("methodNotAnnotated")));
Assert.assertNull(SecurityPreProcessInterceptor.getProviderAllowedAnnotation(MethodAnnotationsMock.class,
MethodAnnotationsMock.class.getMethod("methodGuestAllowed")));
Assert.assertNotNull(SecurityPreProcessInterceptor.getProviderAllowedAnnotation(MethodAnnotationsMock.class,
MethodAnnotationsMock.class.getMethod("methodProviderAllowed")));
Assert.assertNotNull(SecurityPreProcessInterceptor.getProviderAllowedAnnotation(ClassProviderAllowedMock.class,
ClassProviderAllowedMock.class.getMethod("methodNotAnnotated")));
Assert.assertNotNull(SecurityPreProcessInterceptor.getProviderAllowedAnnotation(SubclassProviderAllowedMock.class,
SubclassProviderAllowedMock.class.getMethod("methodNotAnnotated")));
}
@Test
public void acceptTest() throws SecurityException, NoSuchMethodException {
SecurityPreProcessInterceptor tested = getTested();
Assert.assertFalse(tested.accept(MethodAnnotationsMock.class,
MethodAnnotationsMock.class.getMethod("methodNotAnnotated")));
Assert.assertFalse(tested.accept(MethodAnnotationsMock.class,
MethodAnnotationsMock.class.getMethod("methodGuestAllowed")));
Assert.assertTrue(tested.accept(MethodAnnotationsMock.class,
MethodAnnotationsMock.class.getMethod("methodProviderAllowed")));
Assert.assertTrue(tested.accept(ClassProviderAllowedMock.class,
ClassProviderAllowedMock.class.getMethod("methodNotAnnotated")));
Assert.assertTrue(tested.accept(SubclassProviderAllowedMock.class,
SubclassProviderAllowedMock.class.getMethod("methodNotAnnotated")));
Assert.assertTrue(tested.accept(ClassSuperProviderAllowedMock.class,
ClassSuperProviderAllowedMock.class.getMethod("methodNotAnnotated")));
}
@Test
public void isGuestAllowed() throws SecurityException, NoSuchMethodException {
Assert.assertFalse(SecurityPreProcessInterceptor.isGuestAllowed(MethodAnnotationsMock.class
.getMethod("methodNotAnnotated")));
Assert.assertFalse(SecurityPreProcessInterceptor.isGuestAllowed(MethodAnnotationsMock.class
.getMethod("methodProviderAllowed")));
Assert.assertTrue(SecurityPreProcessInterceptor.isGuestAllowed(MethodAnnotationsMock.class
.getMethod("methodGuestAllowed")));
}
public static class MethodAnnotationsMock {
@GuestAllowed
public void methodGuestAllowed() {
}
@ProviderAllowed
public void methodProviderAllowed() {
}
public void methodNotAnnotated() {
}
}
@ProviderAllowed
public static class ClassProviderAllowedMock {
public void methodNotAnnotated() {
}
}
@ProviderAllowed(superProviderOnly = true)
public static class ClassSuperProviderAllowedMock {
public void methodNotAnnotated() {
}
}
public static class SubclassProviderAllowedMock extends ClassProviderAllowedMock {
}
}
| apache-2.0 |
jaheme/oloba-security | src/main/java/com/oloba/verify/Quant.java | 14678 | package com.oloba.verify;
/**
* <p></p>
*
* @version:1.0
*/
public class Quant
{
protected static final int netsize = 256; /* number of colours used */
/* four primes near 500 - assume no image has a length so large */
/* that it is divisible by all four primes */
protected static final int prime1 = 499;
protected static final int prime2 = 491;
protected static final int prime3 = 487;
protected static final int prime4 = 503;
protected static final int minpicturebytes = (3 * prime4);
/* minimum size for input image */
/* Program Skeleton
----------------
[select samplefac in range 1..30]
[read image from input file]
pic = (unsigned char*) malloc(3*width*height);
initnet(pic,3*width*height,samplefac);
learn();
unbiasnet();
[write output image header, using writecolourmap(f)]
inxbuild();
write output image using inxsearch(b,g,r) */
/* Network Definitions
------------------- */
protected static final int maxnetpos = (netsize - 1);
protected static final int netbiasshift = 4; /* bias for colour values */
protected static final int ncycles = 100; /* no. of learning cycles */
/* defs for freq and bias */
protected static final int intbiasshift = 16; /* bias for fractions */
protected static final int intbias = (((int) 1) << intbiasshift);
protected static final int gammashift = 10; /* gamma = 1024 */
protected static final int gamma = (((int) 1) << gammashift);
protected static final int betashift = 10;
protected static final int beta = (intbias >> betashift); /* beta = 1/1024 */
protected static final int betagamma =
(intbias << (gammashift - betashift));
/* defs for decreasing radius factor */
protected static final int initrad = (netsize >> 3); /* for 256 cols, radius starts */
protected static final int radiusbiasshift = 6; /* at 32.0 biased by 6 bits */
protected static final int radiusbias = (((int) 1) << radiusbiasshift);
protected static final int initradius = (initrad * radiusbias); /* and decreases by a */
protected static final int radiusdec = 30; /* factor of 1/30 each cycle */
/* defs for decreasing alpha factor */
protected static final int alphabiasshift = 10; /* alpha starts at 1.0 */
protected static final int initalpha = (((int) 1) << alphabiasshift);
protected int alphadec; /* biased by 10 bits */
/* radbias and alpharadbias used for radpower calculation */
protected static final int radbiasshift = 8;
protected static final int radbias = (((int) 1) << radbiasshift);
protected static final int alpharadbshift = (alphabiasshift + radbiasshift);
protected static final int alpharadbias = (((int) 1) << alpharadbshift);
/* Types and Global Variables
-------------------------- */
protected byte[] thepicture; /* the input image itself */
protected int lengthcount; /* lengthcount = H*W*3 */
protected int samplefac; /* sampling factor 1..30 */
// typedef int pixel[4]; /* BGRc */
protected int[][] network; /* the network itself - [netsize][4] */
protected int[] netindex = new int[256];
/* for network lookup - really 256 */
protected int[] bias = new int[netsize];
/* bias and freq arrays for learning */
protected int[] freq = new int[netsize];
protected int[] radpower = new int[initrad];
/* radpower for precomputation */
/* Initialise network in range (0,0,0) to (255,255,255) and set parameters
----------------------------------------------------------------------- */
public Quant(byte[] thepic, int len, int sample) {
int i;
int[] p;
thepicture = thepic;
lengthcount = len;
samplefac = sample;
network = new int[netsize][];
for (i = 0; i < netsize; i++) {
network[i] = new int[4];
p = network[i];
p[0] = p[1] = p[2] = (i << (netbiasshift + 8)) / netsize;
freq[i] = intbias / netsize; /* 1/netsize */
bias[i] = 0;
}
}
public byte[] colorMap() {
byte[] map = new byte[3 * netsize];
int[] index = new int[netsize];
for (int i = 0; i < netsize; i++)
index[network[i][3]] = i;
int k = 0;
for (int i = 0; i < netsize; i++) {
int j = index[i];
map[k++] = (byte) (network[j][0]);
map[k++] = (byte) (network[j][1]);
map[k++] = (byte) (network[j][2]);
}
return map;
}
/* Insertion sort of network and building of netindex[0..255] (to do after unbias)
------------------------------------------------------------------------------- */
public void inxbuild() {
int i, j, smallpos, smallval;
int[] p;
int[] q;
int previouscol, startpos;
previouscol = 0;
startpos = 0;
for (i = 0; i < netsize; i++) {
p = network[i];
smallpos = i;
smallval = p[1]; /* index on g */
/* find smallest in i..netsize-1 */
for (j = i + 1; j < netsize; j++) {
q = network[j];
if (q[1] < smallval) { /* index on g */
smallpos = j;
smallval = q[1]; /* index on g */
}
}
q = network[smallpos];
/* swap p (i) and q (smallpos) entries */
if (i != smallpos) {
j = q[0];
q[0] = p[0];
p[0] = j;
j = q[1];
q[1] = p[1];
p[1] = j;
j = q[2];
q[2] = p[2];
p[2] = j;
j = q[3];
q[3] = p[3];
p[3] = j;
}
/* smallval entry is now in position i */
if (smallval != previouscol) {
netindex[previouscol] = (startpos + i) >> 1;
for (j = previouscol + 1; j < smallval; j++)
netindex[j] = i;
previouscol = smallval;
startpos = i;
}
}
netindex[previouscol] = (startpos + maxnetpos) >> 1;
for (j = previouscol + 1; j < 256; j++)
netindex[j] = maxnetpos; /* really 256 */
}
/* Main Learning Loop
------------------ */
public void learn() {
int i, j, b, g, r;
int radius, rad, alpha, step, delta, samplepixels;
byte[] p;
int pix, lim;
if (lengthcount < minpicturebytes)
samplefac = 1;
alphadec = 30 + ((samplefac - 1) / 3);
p = thepicture;
pix = 0;
lim = lengthcount;
samplepixels = lengthcount / (3 * samplefac);
delta = samplepixels / ncycles;
alpha = initalpha;
radius = initradius;
rad = radius >> radiusbiasshift;
if (rad <= 1)
rad = 0;
for (i = 0; i < rad; i++)
radpower[i] =
alpha * (((rad * rad - i * i) * radbias) / (rad * rad));
//fprintf(stderr,"beginning 1D learning: initial radius=%d\n", rad);
if (lengthcount < minpicturebytes)
step = 3;
else if ((lengthcount % prime1) != 0)
step = 3 * prime1;
else {
if ((lengthcount % prime2) != 0)
step = 3 * prime2;
else {
if ((lengthcount % prime3) != 0)
step = 3 * prime3;
else
step = 3 * prime4;
}
}
i = 0;
while (i < samplepixels) {
b = (p[pix + 0] & 0xff) << netbiasshift;
g = (p[pix + 1] & 0xff) << netbiasshift;
r = (p[pix + 2] & 0xff) << netbiasshift;
j = contest(b, g, r);
altersingle(alpha, j, b, g, r);
if (rad != 0)
alterneigh(rad, j, b, g, r); /* alter neighbours */
pix += step;
if (pix >= lim)
pix -= lengthcount;
i++;
if (delta == 0)
delta = 1;
if (i % delta == 0) {
alpha -= alpha / alphadec;
radius -= radius / radiusdec;
rad = radius >> radiusbiasshift;
if (rad <= 1)
rad = 0;
for (j = 0; j < rad; j++)
radpower[j] =
alpha * (((rad * rad - j * j) * radbias) / (rad * rad));
}
}
//fprintf(stderr,"finished 1D learning: final alpha=%f !\n",((float)alpha)/initalpha);
}
/* Search for BGR values 0..255 (after net is unbiased) and return colour index
---------------------------------------------------------------------------- */
public int map(int b, int g, int r) {
int i, j, dist, a, bestd;
int[] p;
int best;
bestd = 1000; /* biggest possible dist is 256*3 */
best = -1;
i = netindex[g]; /* index on g */
j = i - 1; /* start at netindex[g] and work outwards */
while ((i < netsize) || (j >= 0)) {
if (i < netsize) {
p = network[i];
dist = p[1] - g; /* inx key */
if (dist >= bestd)
i = netsize; /* stop iter */
else {
i++;
if (dist < 0)
dist = -dist;
a = p[0] - b;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
a = p[2] - r;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
best = p[3];
}
}
}
}
if (j >= 0) {
p = network[j];
dist = g - p[1]; /* inx key - reverse dif */
if (dist >= bestd)
j = -1; /* stop iter */
else {
j--;
if (dist < 0)
dist = -dist;
a = p[0] - b;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
a = p[2] - r;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
best = p[3];
}
}
}
}
}
return (best);
}
public byte[] process() {
learn();
unbiasnet();
inxbuild();
return colorMap();
}
/* Unbias network to give byte values 0..255 and record position i to prepare for sort
----------------------------------------------------------------------------------- */
public void unbiasnet() {
int i, j;
for (i = 0; i < netsize; i++) {
network[i][0] >>= netbiasshift;
network[i][1] >>= netbiasshift;
network[i][2] >>= netbiasshift;
network[i][3] = i; /* record colour no */
}
}
/* Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in radpower[|i-j|]
--------------------------------------------------------------------------------- */
protected void alterneigh(int rad, int i, int b, int g, int r) {
int j, k, lo, hi, a, m;
int[] p;
lo = i - rad;
if (lo < -1)
lo = -1;
hi = i + rad;
if (hi > netsize)
hi = netsize;
j = i + 1;
k = i - 1;
m = 1;
while ((j < hi) || (k > lo)) {
a = radpower[m++];
if (j < hi) {
p = network[j++];
try {
p[0] -= (a * (p[0] - b)) / alpharadbias;
p[1] -= (a * (p[1] - g)) / alpharadbias;
p[2] -= (a * (p[2] - r)) / alpharadbias;
} catch (Exception e) {
} // prevents 1.3 miscompilation
}
if (k > lo) {
p = network[k--];
try {
p[0] -= (a * (p[0] - b)) / alpharadbias;
p[1] -= (a * (p[1] - g)) / alpharadbias;
p[2] -= (a * (p[2] - r)) / alpharadbias;
} catch (Exception e) {
}
}
}
}
/* Move neuron i towards biased (b,g,r) by factor alpha
---------------------------------------------------- */
protected void altersingle(int alpha, int i, int b, int g, int r) {
/* alter hit neuron */
int[] n = network[i];
n[0] -= (alpha * (n[0] - b)) / initalpha;
n[1] -= (alpha * (n[1] - g)) / initalpha;
n[2] -= (alpha * (n[2] - r)) / initalpha;
}
/* Search for biased BGR values
---------------------------- */
protected int contest(int b, int g, int r) {
/* finds closest neuron (min dist) and updates freq */
/* finds best neuron (min dist-bias) and returns position */
/* for frequently chosen neurons, freq[i] is high and bias[i] is negative */
/* bias[i] = gamma*((1/netsize)-freq[i]) */
int i, dist, a, biasdist, betafreq;
int bestpos, bestbiaspos, bestd, bestbiasd;
int[] n;
bestd = ~(((int) 1) << 31);
bestbiasd = bestd;
bestpos = -1;
bestbiaspos = bestpos;
for (i = 0; i < netsize; i++) {
n = network[i];
dist = n[0] - b;
if (dist < 0)
dist = -dist;
a = n[1] - g;
if (a < 0)
a = -a;
dist += a;
a = n[2] - r;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
bestpos = i;
}
biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift));
if (biasdist < bestbiasd) {
bestbiasd = biasdist;
bestbiaspos = i;
}
betafreq = (freq[i] >> betashift);
freq[i] -= betafreq;
bias[i] += (betafreq << gammashift);
}
freq[bestpos] += beta;
bias[bestpos] -= betagamma;
return (bestbiaspos);
}
} | apache-2.0 |
Adrian-Turjak/openstack-interpreter | openstack_interpreter/v1/clients.py | 4442 | from ceilometerclient import client as ceilometerclient
from cinderclient import client as cinderclient
from glanceclient import client as glanceclient
from heatclient import client as heatclient
from keystoneclient import client as keystoneclient
from neutronclient.neutron import client as neutronclient
from novaclient import client as novaclient
from swiftclient import client as swiftclient
DEFAULT_SERVICE_VERSIONS = {
'compute': "2",
'identity': "3",
'image': "2",
'metering': "2",
'network': "2",
'orchestration': "1",
'volume': "2",
'object-store': "1",
}
# a wrapper to facilitate ease of use and avoid the inconsistency
# compared to other client constructors.
def swift_constructor(version, session, region_name):
return swiftclient.Connection(
os_options={'region_name': region_name},
session=session)
CLIENT_CONSTRUCTORS = {
'compute': novaclient.Client,
'identity': keystoneclient.Client,
'image': glanceclient.Client,
'metering': ceilometerclient.Client,
'network': neutronclient.Client,
'object-store': swift_constructor,
'orchestration': heatclient.Client,
'volume': cinderclient.Client,
}
class ServiceNotFound(Exception):
pass
class ClientManager(object):
"""
This class is a factory for the various per projects OpenStack clients.
It is a simple wrapper around all the various constructors in an
attempt to present them all to you in an easy way by hiding all the
normal setup, and in some case constructor differences.
To get a list of what services the ClientManager has been setup for:
In [1]: oi.clients.available_services
Default versions for services:
In [2]: oi.clients.available_services
To get a client (replace <service_type> with the service you want):
In [3]: oi.clients.<service_type>
Get novaclient in your configured region:
In [4]: novaclient = oi.clients.compute
Get novaclient in a specific region:
In [5]: novaclient = oi.clients.get_client(
'compute', region="RegionOne")
The python clients themselves have reasonably useful docstrings,
although the structure and fields of them may be a little unintuitive
at first. Using the autocomplete functionality of ipython as well as
<objects>? and <objects>?? should get you most of the way.
For additional help with the clients look at the offical OpenStack
client docs (although they are often incomplete or lacking). The
alternative and often more useful approach is looking at the code
itself on github.
"""
def __init__(self, session, default_region):
self._session = session
self._default_region = default_region
def get_client(self, service, version=None, region=None):
"""
Get an OpenStack client, in a given version, in a given region.
examples:
In [1]: novaclient = oi.clients.get_client('compute')
In [2]: novaclient = oi.clients.get_client(
'compute', region="RegionOne")
In [3]: novaclient = oi.clients.get_client(
'compute', version="1")
"""
try:
return CLIENT_CONSTRUCTORS[service](
version or DEFAULT_SERVICE_VERSIONS[service],
region_name=region or self._default_region,
session=self._session)
except KeyError:
raise ServiceNotFound(service)
@property
def available_services(self):
"""
List available services.
"""
return CLIENT_CONSTRUCTORS.keys()
@property
def default_service_version(self):
"""
List default service versions.
"""
return dict(DEFAULT_SERVICE_VERSIONS)
@property
def compute(self):
return self.get_client('compute')
@property
def identity(self):
return self.get_client('identity')
@property
def image(self):
return self.get_client('image')
@property
def metering(self):
return self.get_client('metering')
@property
def network(self):
return self.get_client('network')
@property
def object_store(self):
return self.get_client('object-store')
@property
def orchestration(self):
return self.get_client('orchestration')
@property
def volume(self):
return self.get_client('volume')
| apache-2.0 |
googleapis/google-api-ruby-client | generated/google-apis-connectors_v1/spec/generated_spec.rb | 919 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "rspec"
RSpec.describe "Google::Apis::ConnectorsV1" do
# Minimal test just to ensure no syntax errors in generated code
it "should load" do
expect do
require "google/apis/connectors_v1"
end.not_to raise_error
expect do
Google::Apis::ConnectorsV1::ConnectorsService.new
end.not_to raise_error
end
end
| apache-2.0 |
tensorics/tensorics-core | src/java/org/tensorics/core/tensorbacked/AbstractTensorbacked.java | 2796 | // @formatter:off
/*******************************************************************************
*
* This file is part of tensorics.
*
* Copyright (c) 2008-2011, CERN. 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.
*
******************************************************************************/
// @formatter:on
package org.tensorics.core.tensorbacked;
import java.io.Serializable;
import org.tensorics.core.tensor.Tensor;
import static java.util.Objects.requireNonNull;
/**
* An abstract class for classes that are backed by a tensor. The purpose of such classes is that they can be used for
* calculations just in the same way (or at least in a similar way) as tensors themselves.
*
* @param <E> the type of the elements of the tensor, which backs this class
* @author kfuchsbe
* @see Tensorbacked
*/
public abstract class AbstractTensorbacked<E> implements Tensorbacked<E>, Serializable {
private static final long serialVersionUID = 1L;
protected final Tensor<E> backingTensor;
@SuppressWarnings("unchecked")
public AbstractTensorbacked(Tensor<E> tensor) {
this.backingTensor = TensorbackedInternals.ensureExactTensorbackedDimensions(this.getClass(), tensor);
}
@Override
public Tensor<E> tensor() {
return this.backingTensor;
}
@Override
public final int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((backingTensor == null) ? 0 : backingTensor.hashCode());
return result;
}
@Override
public final boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
AbstractTensorbacked<?> other = (AbstractTensorbacked<?>) obj;
if (backingTensor == null) {
if (other.backingTensor != null) {
return false;
}
} else if (!backingTensor.equals(other.backingTensor)) {
return false;
}
return true;
}
@Override
public String toString() {
return getClass().getSimpleName() + " [backingTensor=" + backingTensor + "]";
}
} | apache-2.0 |
Maghoumi/GP-Tracker | lib/ecj/ec/app/sum/Sum.java | 1960 | /*
Copyright 2006 by Sean Luke
Licensed under the Academic Free License version 3.0
See the file "LICENSE" for more information
*/
package ec.app.sum;
import ec.vector.*;
import ec.*;
import ec.simple.*;
import ec.util.*;
/*
* Sum.java
*
* Created on Sat Jun 16 23:26:38 EDT 2001
* By Sean Luke
*/
/**
* Sum is a simple example of the ec.Vector package, implementing the
* very simple sum problem (fitness = sum over vector).
* This is a generalization of the common MaxOnes problem
* (fitness = number of 1's in vector).
*
* @author Sean Luke
* @version 1.0
*/
public class Sum extends Problem implements SimpleProblemForm
{
public static final String P_SUM = "sum";
public Parameter defaultBase()
{
return super.defaultBase().push(P_SUM);
}
public void evaluate(final EvolutionState state,
final Individual ind,
final int subpopulation,
final int threadnum)
{
if (ind.evaluated) return;
if (!(ind instanceof IntegerVectorIndividual))
state.output.fatal("Whoa! It's not an IntegerVectorIndividual!!!",null);
IntegerVectorIndividual ind2 = (IntegerVectorIndividual)ind;
IntegerVectorSpecies s = (IntegerVectorSpecies)ind2.species;
long sum=0;
long max=0;
for(int x=0; x<ind2.genome.length; x++)
{
sum += ind2.genome[x];
max += (int)(s.maxGene(x)); // perhaps this neededn't be computed over and over again
}
// Now we know that max is the maximum possible value, and sum is the fitness.
// assume we're using SimpleFitness
((SimpleFitness)ind2.fitness).setFitness(state,
/// ...the fitness...
(float)(((double)sum)),
///... our definition of the ideal individual
sum == max);
ind2.evaluated = true;
}
}
| apache-2.0 |
ColmexBDCV/sufia-oai | config/initializers/explain_partials.rb | 748 | # Start the app with EXPLAIN_PARTIALS=true to show locations of view partials
if Rails.env.development? && ENV['EXPLAIN_PARTIALS']
module ActionView
class PartialRenderer
def render_with_explanation(*args)
rendered = render_without_explanation(*args).to_s
# Note: We haven't figured out how to get a path when @template is nil.
start_explanation = "\n<!-- START PARTIAL #{@template.inspect} -->\n"
end_explanation = "\n<!-- END PARTIAL #{@template.inspect} -->\n"
# rubocop:disable Rails/OutputSafety
start_explanation.html_safe + rendered + end_explanation.html_safe
# rubocop:enable Rails/OutputSafety
end
alias_method_chain :render, :explanation
end
end
end
| apache-2.0 |
mmz-srf/puppet-rkhunter | spec/classes/init_spec.rb | 426 | require 'spec_helper'
describe 'rkhunter', :type => :class do
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts){facts}
it do
should contain_class('rkhunter::packages')
end
it do
should contain_file("/etc/rkhunter.conf").with(
'owner' => 'root',
'group' => 'root',
'mode' => '0644',
)
end
end
end
end
| apache-2.0 |
tophua/spark1.52 | mllib/src/test/scala/org/apache/spark/ml/feature/IDFSuite.scala | 5078 | /*
* 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.spark.ml.feature
import org.apache.spark.SparkFunSuite
import org.apache.spark.ml.param.ParamsSuite
import org.apache.spark.mllib.feature.{IDFModel => OldIDFModel}
import org.apache.spark.mllib.linalg.{DenseVector, SparseVector, Vector, Vectors}
import org.apache.spark.mllib.util.MLlibTestSparkContext
import org.apache.spark.mllib.util.TestingUtils._
import org.apache.spark.sql.Row
/**
* HashTF从一个文档中计算出给定大小的词频向量。为了将词和向量顺序对应起来,所以使用了哈希。
* HashingTF使用每个单词对所需向量的长度S取模得出的哈希值,把所有单词映射到一个0到S-1之间的数字上。
* 由此可以保证生成一个S维的向量。随后当构建好词频向量后,使用IDF来计算逆文档频率,然后将它们与词频相乘计算TF-IDF
*/
class IDFSuite extends SparkFunSuite with MLlibTestSparkContext {
def scaleDataWithIDF(dataSet: Array[Vector], model: Vector): Array[Vector] = {
dataSet.map {
case data: DenseVector =>
val res = data.toArray.zip(model.toArray).map { case (x, y) => x * y }
Vectors.dense(res)
case data: SparseVector =>
val res = data.indices.zip(data.values).map { case (id, value) =>
(id, value * model(id))
}
Vectors.sparse(data.size, res)
}
}
test("params") {
ParamsSuite.checkParams(new IDF)
val model = new IDFModel("idf", new OldIDFModel(Vectors.dense(1.0)))
ParamsSuite.checkParams(model)
}
test("compute IDF with default parameter") {//默认参数计算IDF
val numOfFeatures = 4
/**
* data= Array((4,[1,3],[1.0,2.0]),[0.0,1.0,2.0,3.0],(4,[1],[1.0]))
*/
val data = Array(
Vectors.sparse(numOfFeatures, Array(1, 3), Array(1.0, 2.0)),
Vectors.dense(0.0, 1.0, 2.0, 3.0),
Vectors.sparse(numOfFeatures, Array(1), Array(1.0))
)
val numOfData = data.size
/**
* idf= [1.3862943611198906,0.0,0.6931471805599453,0.28768207245178085]
*/
val idf = Vectors.dense(Array(0, 3, 1, 2).map { x =>
math.log((numOfData + 1.0) / (x + 1.0))
})
/**
expected = Array((4,[1,3],[0.0,0.5753641449035617]),
[0.0,0.0,1.3862943611198906,0.8630462173553426],
(4,[1],[0.0])
)
*
*/
val expected = scaleDataWithIDF(data, idf)
val df = sqlContext.createDataFrame(data.zip(expected)).toDF("features", "expected")
//计算逆词频 idf
//fit()方法将DataFrame转化为一个Transformer的算法
val idfModel = new IDF().setInputCol("features").setOutputCol("idfValue").fit(df)
//transform()方法将DataFrame转化为另外一个DataFrame的算法
idfModel.transform(df).select("idfValue", "expected").collect().foreach {
case Row(x: Vector, y: Vector) =>
//println(x+"|||"+y)
/**
(4,[1,3],[0.0,0.5753641449035617])|||(4,[1,3],[0.0,0.5753641449035617])
[0.0,0.0,1.3862943611198906,0.8630462173553426]|||[0.0,0.0,1.3862943611198906,0.8630462173553426]
(4,[1],[0.0])|||(4,[1],[0.0])
*/
assert(x ~== y absTol 1e-5, "Transformed vector is different with expected vector.")
}
}
test("compute IDF with setter") {//设置IDF计算
val numOfFeatures = 4
val data = Array(
Vectors.sparse(numOfFeatures, Array(1, 3), Array(1.0, 2.0)),
Vectors.dense(0.0, 1.0, 2.0, 3.0),
Vectors.sparse(numOfFeatures, Array(1), Array(1.0))
)
val numOfData = data.size
val idf = Vectors.dense(Array(0, 3, 1, 2).map { x =>
if (x > 0) math.log((numOfData + 1.0) / (x + 1.0)) else 0
})
val expected = scaleDataWithIDF(data, idf)
val df = sqlContext.createDataFrame(data.zip(expected)).toDF("features", "expected")
val idfModel = new IDF()
.setInputCol("features")
.setOutputCol("idfValue")
.setMinDocFreq(1)
.fit(df)//fit()方法将DataFrame转化为一个Transformer的算法
//transform()方法将DataFrame转化为另外一个DataFrame的算法
idfModel.transform(df).select("idfValue", "expected").collect().foreach {
case Row(x: Vector, y: Vector) =>
assert(x ~== y absTol 1e-5, "Transformed vector is different with expected vector.")
}
}
}
| apache-2.0 |
bnogent/ws | src/main/java/com/lammesoft/idea1/business/UserManagment.java | 8111 | package com.lammesoft.idea1.business;
import com.lammesoft.idea1.business.exceptions.InvalidParameter;
import com.lammesoft.idea1.business.exceptions.UserExistException;
import com.lammesoft.idea1.domain.User;
import com.lammesoft.idea1.services.UserService;
import com.lammesoft.idea1.utils.HibernateUtil;
import com.lammesoft.idea1.utils.Utils;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.UUID;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class UserManagment {
public static void validate(String userName, String idToValidateUser) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Query query = session.createQuery("FROM User U where U.idToValidateUser = :idToValidateUser and U.name=:name");
query.setParameter("idToValidateUser", idToValidateUser);
query.setParameter("name", userName);
List<User> users = query.list();
if (users.size() == 1) {
User user = users.get(0);
user.setIdToValidateUser(null);
user.setValidUser(true);
session.persist(user);
}
session.getTransaction().commit();
session.close();
}
public static void createUser(String name,String email, String password, String parameterCodePrefix,
String code, String result, HttpServletRequest req)
throws InvalidParameter, UserExistException {
if (!Utils.isValid(name))
throw new InvalidParameter("name",name);
if (!Utils.isValid(email))
throw new InvalidParameter("email",email);
if (!Utils.isValid(password))
throw new InvalidParameter("password",password);
// test code
String calcResult = UserService.calculResultCode(parameterCodePrefix, code);
if (!calcResult.equals(result)) {
throw new InvalidParameter("code",code);
}
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
} catch (AddressException ex) {
throw new InvalidParameter("email",email);
}
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Query queryUserExist = session.createQuery("FROM User U where U.name = :name or U.email= :email");
queryUserExist.setParameter("name", name);
queryUserExist.setParameter("email", email);
List<User> exisingUsers = queryUserExist.list();
User user=null;
if (exisingUsers.isEmpty())
{
user = new User();
user.setUserId(UUID.randomUUID().toString());
user.setName(name);
user.setEmail(email);
user.setPassword(password);
user.setValidUser(false);
user.setIdToValidateUser(createVerificationCode());
session.persist(user);
System.out.println("VALIDATION CODE : " + user.getIdToValidateUser());
}
session.getTransaction().commit();
session.close();
if (user==null ) {
throw new UserExistException("l'adresse mail ou le nom d'utilisateur existe deja !");
}
//sendMail(email, "bienvenue !", "<html><head></head><body><p>confirmation</p><a href=\""+validatePath+"\">confirm !</a><h3>"+createVerificationCode()+"</h3></body></html>");
}
private static String createVerificationCode() {
Random rand = new Random();
int n = 1;
NumberFormat x = new DecimalFormat("00");
String code = "";
for(int i=0; i<n; i++) {
if (i>0)
code+="-";
code += x.format(rand.nextInt(1000));
}
return code;
}
private static void sendMail(final String to, final String subject, final String html) throws RuntimeException {
final String username = "demo@lammesoft.com";
final String password = "";
final String from = "demo@lammesoft.com";
String host = "smtp.lammesoft.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
javax.mail.Session session = javax.mail.Session.getInstance(props,
new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
//message.setText(text);
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(html, "text/html");
mp.addBodyPart(htmlPart);
message.setContent(mp);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
public static User login(String name, String password) {
User user = null;
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Query query = session.createQuery("FROM User U where U.name = :name and U.password = :password and U.validUser=:validUser");
query.setParameter("name", name);
query.setParameter("password", password);
query.setParameter("validUser", true);
List<User> users = query.list();
if (users.size()==1) {
user = users.get(0);
user.setToken(UUID.randomUUID().toString());
//user.setValidUntil(getCurrentTime(20));
session.persist(user);
}
session.getTransaction().commit();
session.close();
return user;
}
//private static final String DATEFORMAT = "yyyy-MM-dd HH:mm:ss";
// public static String getCurrentTime(int offsetMinutes) {
// SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
// sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//
// Date date = new Date();
//
// Calendar cal = Calendar.getInstance();
// cal.setTime(date);
// cal.add(Calendar.MINUTE, Math.max(0, offsetMinutes) );
//
// final String utcTime = sdf.format(cal.getTime());
// return utcTime;
// }
}
| apache-2.0 |
knative/build | vendor/github.com/knative/pkg/codegen/cmd/injection-gen/generators/informer.go | 4135 | /*
Copyright 2019 The Knative Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package generators
import (
"io"
clientgentypes "k8s.io/code-generator/cmd/client-gen/types"
"k8s.io/gengo/generator"
"k8s.io/gengo/namer"
"k8s.io/gengo/types"
"k8s.io/klog"
)
// injectionTestGenerator produces a file of listers for a given GroupVersion and
// type.
type injectionGenerator struct {
generator.DefaultGen
outputPackage string
groupVersion clientgentypes.GroupVersion
groupGoName string
typeToGenerate *types.Type
imports namer.ImportTracker
typedInformerPackage string
groupInformerFactoryPackage string
}
var _ generator.Generator = (*injectionGenerator)(nil)
func (g *injectionGenerator) Filter(c *generator.Context, t *types.Type) bool {
// Only process the type for this informer generator.
return t == g.typeToGenerate
}
func (g *injectionGenerator) Namers(c *generator.Context) namer.NameSystems {
publicPluralNamer := &ExceptionNamer{
Exceptions: map[string]string{
// these exceptions are used to deconflict the generated code
// you can put your fully qualified package like
// to generate a name that doesn't conflict with your group.
// "k8s.io/apis/events/v1beta1.Event": "EventResource"
},
KeyFunc: func(t *types.Type) string {
return t.Name.Package + "." + t.Name.Name
},
Delegate: namer.NewPublicPluralNamer(map[string]string{
"Endpoints": "Endpoints",
}),
}
return namer.NameSystems{
"raw": namer.NewRawNamer(g.outputPackage, g.imports),
"publicPlural": publicPluralNamer,
}
}
func (g *injectionGenerator) Imports(c *generator.Context) (imports []string) {
imports = append(imports, g.imports.ImportLines()...)
return
}
func (g *injectionGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
sw := generator.NewSnippetWriter(w, c, "{{", "}}")
klog.V(5).Infof("processing type %v", t)
m := map[string]interface{}{
"group": namer.IC(g.groupGoName),
"type": t,
"version": namer.IC(g.groupVersion.Version.String()),
"injectionRegisterInformer": c.Universe.Type(types.Name{Package: "github.com/knative/pkg/injection", Name: "Default.RegisterInformer"}),
"controllerInformer": c.Universe.Type(types.Name{Package: "github.com/knative/pkg/controller", Name: "Informer"}),
"informersTypedInformer": c.Universe.Type(types.Name{Package: g.typedInformerPackage, Name: t.Name.Name + "Informer"}),
"factoryGet": c.Universe.Type(types.Name{Package: g.groupInformerFactoryPackage, Name: "Get"}),
"loggingFromContext": c.Universe.Function(types.Name{
Package: "github.com/knative/pkg/logging",
Name: "FromContext",
}),
}
sw.Do(injectionInformer, m)
return sw.Error()
}
var injectionInformer = `
func init() {
{{.injectionRegisterInformer|raw}}(withInformer)
}
// Key is used for associating the Informer inside the context.Context.
type Key struct{}
func withInformer(ctx context.Context) (context.Context, {{.controllerInformer|raw}}) {
f := {{.factoryGet|raw}}(ctx)
inf := f.{{.group}}().{{.version}}().{{.type|publicPlural}}()
return context.WithValue(ctx, Key{}, inf), inf.Informer()
}
// Get extracts the typed informer from the context.
func Get(ctx context.Context) {{.informersTypedInformer|raw}} {
untyped := ctx.Value(Key{})
if untyped == nil {
{{.loggingFromContext|raw}}(ctx).Fatalf(
"Unable to fetch %T from context.", ({{.informersTypedInformer|raw}})(nil))
}
return untyped.({{.informersTypedInformer|raw}})
}
`
| apache-2.0 |
AsuraTeam/asura | asura-conf/src/test/java/com/asura/test/T_ZkConfigContext.java | 2263 | /*
* Copyright (c) 2016. struggle.2036@163.com. All rights reserved.
*/
package com.asura.test;
import com.asura.framework.conf.subscribe.ConfigSubscriber;
import com.asura.test.pojo.TestNewEnum;
import com.asura.test.pojo.TestOldEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p></p>
*
* <PRE>
* <BR> 修改记录
* <BR>-----------------------------------------------
* <BR> 修改日期 修改人 修改内容
* </PRE>
*
* @author wurt2
* @since 1.0
* @version 1.0
*/
public class T_ZkConfigContext {
private static final Logger LOGGER = LoggerFactory.getLogger(T_ZkConfigContext.class);
/**
* 获取自如客根据Token获取URL的地址
* @return
*/
public static String getOldZrkInfoByTokenUrl() {
try {
String type = TestOldEnum.INFO_BY_TOKEN_URL.getType();
String code = TestOldEnum.INFO_BY_TOKEN_URL.getCode();
String value = ConfigSubscriber.getInstance().getConfigValue(type, code);
if (value == null) {
value = TestOldEnum.INFO_BY_TOKEN_URL.getDefaultValue();
}
return value;
} catch (Exception e) {
LOGGER.error("zk config INFO_BY_TOKEN_URL error:{}", e);
//出NumberFormatException异常了的话使用默认值
return TestOldEnum.INFO_BY_TOKEN_URL.getDefaultValue();
}
}
/**
* 获取自如客根据Token获取URL的地址
* @return
*/
public static Object getNewZrkInfoByTokenUrl() {
try {
String appName = TestNewEnum.INFO_BY_TOKEN_URL.getAppName();
String type = TestNewEnum.INFO_BY_TOKEN_URL.getType();
String code = TestNewEnum.INFO_BY_TOKEN_URL.getCode();
String value = ConfigSubscriber.getInstance().getConfigValue(appName, type, code);
if (value == null) {
value = TestOldEnum.INFO_BY_TOKEN_URL.getDefaultValue();
}
return value;
} catch (Exception e) {
LOGGER.error("zk config INFO_BY_TOKEN_URL error:{}", e);
//出NumberFormatException异常了的话使用默认值
return TestNewEnum.INFO_BY_TOKEN_URL.getDefaultValue();
}
}
}
| apache-2.0 |
blackcathacker/kc.preclean | coeus-code/src/main/java/org/kuali/coeus/common/committee/impl/meeting/AlternateForValuesFinder.java | 1845 | /*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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.kuali.coeus.common.committee.impl.meeting;
import org.kuali.rice.core.api.util.ConcreteKeyValue;
import org.kuali.rice.core.api.util.KeyValue;
import org.kuali.rice.krad.uif.control.UifKeyValuesFinderBase;
import java.util.ArrayList;
import java.util.List;
/**
*
* This class is to set up the 'Alternate For' drop down list for members who have 'Alternate' role.
*/
public class AlternateForValuesFinder extends UifKeyValuesFinderBase {
private static final String MEMBER_SEPARATOR = "#m#";
private static final String FIELD_SEPARATOR = "#f#";
private String absenteeList;
@Override
public List<KeyValue> getKeyValues() {
List<KeyValue> keyValues = new ArrayList<KeyValue>();
for (String idName : absenteeList.split(MEMBER_SEPARATOR)) {
String[] valuePair = idName.split(FIELD_SEPARATOR);
keyValues.add(new ConcreteKeyValue(valuePair[0], valuePair[1]));
}
keyValues.add(0, new ConcreteKeyValue("", "select"));
return keyValues;
}
public String getAbsenteeList() {
return absenteeList;
}
public void setAbsenteeList(String absenteeList) {
this.absenteeList = absenteeList;
}
}
| apache-2.0 |
Eric217/-OnSale | server/src/main/java/cn/omsfuk/discount/base/Result.java | 267 | package cn.omsfuk.discount.base;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* Created by omsfuk on 2017/7/17.
*/
@Data
@AllArgsConstructor
public class Result {
private Integer status;
private String message;
private Object data;
}
| apache-2.0 |
zagart/rent | src/main/rent/model/dao/impl/TariffDao.java | 233 | package rent.model.dao.impl;
import rent.model.dao.AbstractDao;
import rent.model.entities.Tariff;
/**
* DAO implementation for {@link Tariff}.
*
* @author zagart
*/
public class TariffDao extends AbstractDao<Tariff, Long> {
}
| apache-2.0 |
box/augmented_types | tests/values_can_be_modified_in_error_cb.phpt | 1158 | --TEST--
Ensure that the augmented types error callback can safely modify values with the same semantics as normal php functions
--INI--
augmented_types.enforce_by_default = 1
--FILE--
<?php
/**
* @param mixed|null $offending_value
* @param bool $is_void
* @param string $expected_type
* @param string $function_name
* @param string $file_path
* @param int $line_number
* @param int $arg_num
* @return void
*/
function error_cb($offending_value, $is_void, $expected_type, $function_name, $file_path, $line_number, $arg_num)
{
if ($arg_num === -1) {
echo "error in return type! value = $offending_value\n";
$offending_value += 1;
}
if (is_array($offending_value)) {
echo "got an array!\n";
$offending_value[] = "MODIFIED";
}
}
augmented_types_register_type_error_callback("error_cb");
/**
* @param int input
* @return uint output
*/
function negate($i) {
return $i;
}
$ret = negate(-1);
var_dump($ret);
/**
* @param int
* @return array
*/
function impossible($i) {
return $i;
}
$a = impossible(['hello']);
var_dump($a);
?>
--EXPECT--
error in return type! value = -1
int(-1)
got an array!
array(1) {
[0]=>
string(5) "hello"
}
| apache-2.0 |
awhitford/DependencyCheck | core/src/test/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzerTest.java | 3785 | /*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2015 The OWASP Foundatio. All Rights Reserved.
*/
package org.owasp.dependencycheck.analyzer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.owasp.dependencycheck.BaseDBTestCase;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.dependency.Dependency;
import java.io.File;
import org.apache.commons.lang3.ArrayUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
/**
* Unit tests for NodePackageAnalyzer.
*
* @author Dale Visser
*/
public class ComposerLockAnalyzerTest extends BaseDBTestCase {
/**
* The analyzer to test.
*/
private ComposerLockAnalyzer analyzer;
/**
* Correctly setup the analyzer for testing.
*
* @throws Exception thrown if there is a problem
*/
@Before
@Override
public void setUp() throws Exception {
super.setUp();
analyzer = new ComposerLockAnalyzer();
analyzer.initialize(getSettings());
analyzer.setFilesMatched(true);
analyzer.prepare(null);
}
/**
* Cleanup the analyzer's temp files, etc.
*
* @throws Exception thrown if there is a problem
*/
@After
@Override
public void tearDown() throws Exception {
analyzer.close();
super.tearDown();
}
/**
* Test of getName method, of class ComposerLockAnalyzer.
*/
@Test
public void testGetName() {
assertEquals("Composer.lock analyzer", analyzer.getName());
}
/**
* Test of supportsExtension method, of class ComposerLockAnalyzer.
*/
@Test
public void testSupportsFiles() {
assertTrue(analyzer.accept(new File("composer.lock")));
}
/**
* Test of inspect method, of class PythonDistributionAnalyzer.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@Test
public void testAnalyzePackageJson() throws Exception {
try (Engine engine = new Engine(getSettings())) {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this,
"composer.lock"));
//simulate normal operation when the composer.lock is already added to the engine as a dependency
engine.addDependency(result);
analyzer.analyze(result, engine);
//make sure the redundant composer.lock is removed
assertFalse(ArrayUtils.contains(engine.getDependencies(), result));
assertEquals(30, engine.getDependencies().length);
Dependency d = engine.getDependencies()[0];
assertEquals("classpreloader", d.getName());
assertEquals("2.0.0", d.getVersion());
assertThat(d.getDisplayFileName(), equalTo("classpreloader:2.0.0"));
assertEquals(ComposerLockAnalyzer.DEPENDENCY_ECOSYSTEM, d.getEcosystem());
}
}
}
| apache-2.0 |
pyj0918/study | dynamic-proxy/dynamic-proxy-01/src/com/test/MyMain.java | 763 | package com.test;
import java.io.FileOutputStream;
import sun.misc.ProxyGenerator;
public class MyMain {
public static void main(String[] args) {
Person person = new PersonImpl();
DynamicProxy prox = new DynamicProxy(person);
Person personProx = prox.getProxy();
System.out.println(personProx.getClass().getName());
personProx.say();
personProx.work();
createProxyClassFile();
}
//²é¿´Éú³ÉµÄ´úÀíÀ࣬ÓÃÓÚÀí½â¶¯Ì¬´úÀí
public static void createProxyClassFile() {
String name = "$Proxy0";
byte[] data = ProxyGenerator.generateProxyClass(name,new Class[] { Person.class });
try {
FileOutputStream out = new FileOutputStream(name + ".class");
out.write(data);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| apache-2.0 |
mtconnect/cppagent | test/relationship_test.cpp | 5484 | // Ensure that gtest is the first header otherwise Windows raises an error
#include <gtest/gtest.h>
// Keep this comment to keep gtest.h above. (clang-format off/on is not working here!)
#include "adapter/adapter.hpp"
#include "agent.hpp"
#include "agent_test_helper.hpp"
#include "json_helper.hpp"
#include "device_model/relationships.hpp"
#include <cstdio>
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
using json = nlohmann::json;
using namespace std;
using namespace mtconnect;
using namespace mtconnect::adapter;
class RelationshipTest : public testing::Test
{
protected:
void SetUp() override
{ // Create an agent with only 16 slots and 8 data items.
m_agentTestHelper = make_unique<AgentTestHelper>();
m_agentTestHelper->createAgent("/samples/configuration.xml",
8, 4, "1.7", 25);
m_agentId = to_string(getCurrentTimeInSec());
auto device = m_agentTestHelper->m_agent->getDeviceByName("LinuxCNC");
m_component = device->getComponentById("c");
}
void TearDown() override
{
m_agentTestHelper.reset();
}
adapter::Adapter *m_adapter{nullptr};
std::string m_agentId;
Component *m_component{nullptr};
std::unique_ptr<AgentTestHelper> m_agentTestHelper;
};
TEST_F(RelationshipTest, ParseDeviceAndComponentRelationships)
{
ASSERT_NE(nullptr, m_component);
ASSERT_EQ(2, m_component->getConfiguration().size());
const auto conf = m_component->getConfiguration().front().get();
ASSERT_EQ(typeid(Relationships), typeid(*conf));
const Relationships *rels = dynamic_cast<const Relationships*>(conf);
ASSERT_NE(nullptr, rels);
ASSERT_EQ(2, rels->getRelationships().size());
auto reli = rels->getRelationships().begin();
const auto rel1 = reli->get();
ASSERT_EQ(typeid(ComponentRelationship), typeid(*rel1));
const auto crel = dynamic_cast<ComponentRelationship*>(rel1);
EXPECT_EQ("ref1", crel->m_id);
EXPECT_EQ("Power", crel->m_name);
EXPECT_EQ("PEER", crel->m_type);
EXPECT_EQ("CRITICAL", crel->m_criticality);
EXPECT_EQ("power", crel->m_idRef);
reli++;
const auto rel2 = reli->get();
ASSERT_EQ(typeid(DeviceRelationship), typeid(*rel2));
const auto drel = dynamic_cast<DeviceRelationship*>(rel2);
EXPECT_EQ("ref2", drel->m_id);
EXPECT_EQ("coffee", drel->m_name);
EXPECT_EQ("PARENT", drel->m_type);
EXPECT_EQ("NON_CRITICAL", drel->m_criticality);
EXPECT_EQ("AUXILIARY", drel->m_role);
EXPECT_EQ("http://127.0.0.1:2000/coffee", drel->m_href);
EXPECT_EQ("bfccbfb0-5111-0138-6cd5-0c85909298d9", drel->m_deviceUuidRef);
}
#define CONFIGURATION_PATH "//m:Rotary[@id='c']/m:Configuration"
#define RELATIONSHIPS_PATH CONFIGURATION_PATH "/m:Relationships"
TEST_F(RelationshipTest, XmlPrinting)
{
{
PARSE_XML_RESPONSE("/probe");
ASSERT_XML_PATH_COUNT(doc, RELATIONSHIPS_PATH , 1);
ASSERT_XML_PATH_COUNT(doc, RELATIONSHIPS_PATH "/*" , 2);
ASSERT_XML_PATH_EQUAL(doc, RELATIONSHIPS_PATH "/m:ComponentRelationship@id" , "ref1");
ASSERT_XML_PATH_EQUAL(doc, RELATIONSHIPS_PATH "/m:ComponentRelationship@name" , "Power");
ASSERT_XML_PATH_EQUAL(doc, RELATIONSHIPS_PATH "/m:ComponentRelationship@type" , "PEER");
ASSERT_XML_PATH_EQUAL(doc, RELATIONSHIPS_PATH "/m:ComponentRelationship@criticality" , "CRITICAL");
ASSERT_XML_PATH_EQUAL(doc, RELATIONSHIPS_PATH "/m:ComponentRelationship@idRef" , "power");
ASSERT_XML_PATH_EQUAL(doc, RELATIONSHIPS_PATH "/m:DeviceRelationship@id" , "ref2");
ASSERT_XML_PATH_EQUAL(doc, RELATIONSHIPS_PATH "/m:DeviceRelationship@name" , "coffee");
ASSERT_XML_PATH_EQUAL(doc, RELATIONSHIPS_PATH "/m:DeviceRelationship@type" , "PARENT");
ASSERT_XML_PATH_EQUAL(doc, RELATIONSHIPS_PATH "/m:DeviceRelationship@criticality" , "NON_CRITICAL");
ASSERT_XML_PATH_EQUAL(doc, RELATIONSHIPS_PATH "/m:DeviceRelationship@role" , "AUXILIARY");
ASSERT_XML_PATH_EQUAL(doc, RELATIONSHIPS_PATH "/m:DeviceRelationship@href" , "http://127.0.0.1:2000/coffee");
ASSERT_XML_PATH_EQUAL(doc, RELATIONSHIPS_PATH "/m:DeviceRelationship@deviceUuidRef" , "bfccbfb0-5111-0138-6cd5-0c85909298d9");
}
}
TEST_F(RelationshipTest, JsonPrinting)
{
m_agentTestHelper->m_request.m_accepts = "Application/json";
{
PARSE_JSON_RESPONSE("/probe");
auto devices = doc.at("/MTConnectDevices/Devices"_json_pointer);
auto device = devices.at(1).at("/Device"_json_pointer);
auto rotary = device.at("/Components/0/Axes/Components/0/Rotary"_json_pointer);
auto relationships = rotary.at("/Configuration/Relationships"_json_pointer);
ASSERT_TRUE(relationships.is_array());
ASSERT_EQ(2_S, relationships.size());
auto crel = relationships.at(0);
auto cfields = crel.at("/ComponentRelationship"_json_pointer);
EXPECT_EQ("ref1", cfields["id"]);
EXPECT_EQ("Power", cfields["name"]);
EXPECT_EQ("PEER", cfields["type"]);
EXPECT_EQ("CRITICAL", cfields["criticality"]);
EXPECT_EQ("power", cfields["idRef"]);
auto drel = relationships.at(1);
auto dfields = drel.at("/DeviceRelationship"_json_pointer);
EXPECT_EQ("ref2", dfields["id"]);
EXPECT_EQ("coffee", dfields["name"]);
EXPECT_EQ("PARENT", dfields["type"]);
EXPECT_EQ("NON_CRITICAL", dfields["criticality"]);
EXPECT_EQ("AUXILIARY", dfields["role"]);
EXPECT_EQ("http://127.0.0.1:2000/coffee", dfields["href"]);
EXPECT_EQ("bfccbfb0-5111-0138-6cd5-0c85909298d9", dfields["deviceUuidRef"]);
}
}
| apache-2.0 |
ClusterHQ/libcloud | libcloud/compute/types.py | 7518 | # 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.
"""
Base types used by other parts of libcloud
"""
from libcloud.common.types import LibcloudError, MalformedResponseError
from libcloud.common.types import InvalidCredsError, InvalidCredsException
__all__ = [
"Provider",
"NodeState",
"DeploymentError",
"DeploymentException",
# @@TR: should the unused imports below be exported?
"LibcloudError",
"MalformedResponseError",
"InvalidCredsError",
"InvalidCredsException",
"DEPRECATED_RACKSPACE_PROVIDERS",
"OLD_CONSTANT_TO_NEW_MAPPING"
]
class Provider(object):
"""
Defines for each of the supported providers
:cvar DUMMY: Example provider
:cvar EC2_US_EAST: Amazon AWS US N. Virgina
:cvar EC2_US_WEST: Amazon AWS US N. California
:cvar EC2_EU_WEST: Amazon AWS EU Ireland
:cvar RACKSPACE: Rackspace next-gen OpenStack based Cloud Servers
:cvar RACKSPACE_FIRST_GEN: Rackspace First Gen Cloud Servers
:cvar GCE: Google Compute Engine
:cvar GOGRID: GoGrid
:cvar VPSNET: VPS.net
:cvar LINODE: Linode.com
:cvar VCLOUD: vmware vCloud
:cvar RIMUHOSTING: RimuHosting.com
:cvar ECP: Enomaly
:cvar IBM: IBM Developer Cloud
:cvar OPENNEBULA: OpenNebula.org
:cvar DREAMHOST: DreamHost Private Server
:cvar ELASTICHOSTS: ElasticHosts.com
:cvar CLOUDSIGMA: CloudSigma
:cvar NIMBUS: Nimbus
:cvar BLUEBOX: Bluebox
:cvar OPSOURCE: Opsource Cloud
:cvar NINEFOLD: Ninefold
:cvar TERREMARK: Terremark
:cvar EC2_US_WEST_OREGON: Amazon AWS US West 2 (Oregon)
:cvar CLOUDSTACK: CloudStack
:cvar CLOUDSIGMA_US: CloudSigma US Las Vegas
:cvar LIBVIRT: Libvirt driver
:cvar JOYENT: Joyent driver
:cvar VCL: VCL driver
:cvar KTUCLOUD: kt ucloud driver
:cvar GRIDSPOT: Gridspot driver
:cvar ABIQUO: Abiquo driver
:cvar NEPHOSCALE: NephoScale driver
:cvar EXOSCALE: Exoscale driver.
:cvar IKOULA: Ikoula driver.
"""
DUMMY = 'dummy'
EC2 = 'ec2_us_east'
RACKSPACE = 'rackspace'
GCE = 'gce'
GOGRID = 'gogrid'
VPSNET = 'vpsnet'
LINODE = 'linode'
VCLOUD = 'vcloud'
RIMUHOSTING = 'rimuhosting'
VOXEL = 'voxel'
SOFTLAYER = 'softlayer'
EUCALYPTUS = 'eucalyptus'
ECP = 'ecp'
IBM = 'ibm'
OPENNEBULA = 'opennebula'
DREAMHOST = 'dreamhost'
ELASTICHOSTS = 'elastichosts'
BRIGHTBOX = 'brightbox'
CLOUDSIGMA = 'cloudsigma'
NIMBUS = 'nimbus'
BLUEBOX = 'bluebox'
GANDI = 'gandi'
OPSOURCE = 'opsource'
OPENSTACK = 'openstack'
SKALICLOUD = 'skalicloud'
SERVERLOVE = 'serverlove'
NINEFOLD = 'ninefold'
TERREMARK = 'terremark'
CLOUDSTACK = 'cloudstack'
LIBVIRT = 'libvirt'
JOYENT = 'joyent'
VCL = 'vcl'
KTUCLOUD = 'ktucloud'
GRIDSPOT = 'gridspot'
RACKSPACE_FIRST_GEN = 'rackspace_first_gen'
HOSTVIRTUAL = 'hostvirtual'
ABIQUO = 'abiquo'
DIGITAL_OCEAN = 'digitalocean'
NEPHOSCALE = 'nephoscale'
CLOUDFRAMES = 'cloudframes'
EXOSCALE = 'exoscale'
IKOULA = 'ikoula'
# Deprecated constants which are still supported
EC2_US_EAST = 'ec2_us_east'
EC2_EU = 'ec2_eu_west' # deprecated name
EC2_EU_WEST = 'ec2_eu_west'
EC2_US_WEST = 'ec2_us_west'
EC2_AP_SOUTHEAST = 'ec2_ap_southeast'
EC2_AP_NORTHEAST = 'ec2_ap_northeast'
EC2_US_WEST_OREGON = 'ec2_us_west_oregon'
EC2_SA_EAST = 'ec2_sa_east'
EC2_AP_SOUTHEAST2 = 'ec2_ap_southeast_2'
ELASTICHOSTS_UK1 = 'elastichosts_uk1'
ELASTICHOSTS_UK2 = 'elastichosts_uk2'
ELASTICHOSTS_US1 = 'elastichosts_us1'
ELASTICHOSTS_US2 = 'elastichosts_us2'
ELASTICHOSTS_US3 = 'elastichosts_us3'
ELASTICHOSTS_CA1 = 'elastichosts_ca1'
ELASTICHOSTS_AU1 = 'elastichosts_au1'
ELASTICHOSTS_CN1 = 'elastichosts_cn1'
CLOUDSIGMA_US = 'cloudsigma_us'
# Deprecated constants which aren't supported anymore
RACKSPACE_UK = 'rackspace_uk'
RACKSPACE_NOVA_BETA = 'rackspace_nova_beta'
RACKSPACE_NOVA_DFW = 'rackspace_nova_dfw'
RACKSPACE_NOVA_LON = 'rackspace_nova_lon'
RACKSPACE_NOVA_ORD = 'rackspace_nova_ord'
# Removed
# SLICEHOST = 'slicehost'
DEPRECATED_RACKSPACE_PROVIDERS = [Provider.RACKSPACE_UK,
Provider.RACKSPACE_NOVA_BETA,
Provider.RACKSPACE_NOVA_DFW,
Provider.RACKSPACE_NOVA_LON,
Provider.RACKSPACE_NOVA_ORD]
OLD_CONSTANT_TO_NEW_MAPPING = {
Provider.RACKSPACE: Provider.RACKSPACE_FIRST_GEN,
Provider.RACKSPACE_UK: Provider.RACKSPACE_FIRST_GEN,
Provider.RACKSPACE_NOVA_BETA: Provider.RACKSPACE,
Provider.RACKSPACE_NOVA_DFW: Provider.RACKSPACE,
Provider.RACKSPACE_NOVA_LON: Provider.RACKSPACE,
Provider.RACKSPACE_NOVA_ORD: Provider.RACKSPACE
}
class NodeState(object):
"""
Standard states for a node
:cvar RUNNING: Node is running.
:cvar REBOOTING: Node is rebooting.
:cvar TERMINATED: Node is terminated. This node can't be started later on.
:cvar STOPPED: Node is stopped. This node can be started later on.
:cvar PENDING: Node is pending.
:cvar UNKNOWN: Node state is unknown.
"""
RUNNING = 0
REBOOTING = 1
TERMINATED = 2
PENDING = 3
UNKNOWN = 4
STOPPED = 5
class Architecture(object):
"""
Image and size architectures.
:cvar I386: i386 (32 bt)
:cvar X86_64: x86_64 (64 bit)
"""
I386 = 0
X86_X64 = 1
class DeploymentError(LibcloudError):
"""
Exception used when a Deployment Task failed.
:ivar node: :class:`Node` on which this exception happened, you might want
to call :func:`Node.destroy`
"""
def __init__(self, node, original_exception=None, driver=None):
self.node = node
self.value = original_exception
self.driver = driver
def __str__(self):
return self.__repr__()
def __repr__(self):
return (('<DeploymentError: node=%s, error=%s, driver=%s>'
% (self.node.id, str(self.value), str(self.driver))))
class KeyPairError(LibcloudError):
error_type = 'KeyPairError'
def __init__(self, name, driver):
self.name = name
self.value = 'Key pair with name %s does not exist' % (name)
super(KeyPairError, self).__init__(value=self.value, driver=driver)
def __str__(self):
return self.__repr__()
def __repr__(self):
return ('<%s name=%s, value=%s, driver=%s>' %
(self.error_type, self.name, self.value, self.driver.name))
class KeyPairDoesNotExistError(KeyPairError):
error_type = 'KeyPairDoesNotExistError'
"""Deprecated alias of :class:`DeploymentException`"""
DeploymentException = DeploymentError
| apache-2.0 |