code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
'use strict';
var test = require('tap').test;
var fs = require('fs');
var path = require('path');
var temp = require('temp');
var streamBuffers = require("stream-buffers");
var unzip = require('../');
var Stream = require('stream');
// Backwards compatibility for node 0.8
if (!Stream.Writable)
Stream = require('readable-stream');
test("pipe a single file entry out of a zip", function (t) {
var receiver = Stream.Transform({objectMode:true});
receiver._transform = function(entry,e,cb) {
if (entry.path === 'file.txt') {
var writableStream = new streamBuffers.WritableStreamBuffer();
writableStream.on('close', function () {
var str = writableStream.getContentsAsString('utf8');
var fileStr = fs.readFileSync(path.join(__dirname, '../testData/compressed-standard/inflated/file.txt'), 'utf8');
t.equal(str, fileStr);
t.end();
cb();
});
entry.pipe(writableStream);
} else {
entry.autodrain();
cb();
}
};
var archive = path.join(__dirname, '../testData/compressed-standard/archive.zip');
fs.createReadStream(archive)
.pipe(unzip.Parse())
.pipe(receiver);
}); | maddiraz/nodejs-demo | node_modules/unzipper/test/streamSingleEntry.js | JavaScript | apache-2.0 | 1,177 |
namespace FunctionalityLibrary
{
class TranslatePicture
{
}
}
| Manicca/Interiora | Interiora/FunctionalityLibrary/TranslatePicture.cs | C# | apache-2.0 | 77 |
<?php
class MylifeserviceAction extends CommonAction {
public function index() {
$Houseworksetting = D('Houseworksetting');//类目表
$Housework = D('Housework');//报名表
import('ORG.Util.Page'); // 导入分页类
$map = array('user_id' => $this->uid);
$count = $Housework->where($map)->count(); // 查询满足要求的总记录数
$Page = new Page($count, 10); // 实例化分页类 传入总记录数和每页显示的记录数
$show = $Page->show(); // 分页显示输出
$list = $Housework->where($map)->order(array('housework_id' => 'desc'))->limit($Page->firstRow . ',' . $Page->listRows)->select();
$houseworksetting_ids = array();
foreach ($list as $k => $val) {
$houseworksetting_ids[$val['id']] = $val['id'];
}
$this->assign('houseworksetting', $Houseworksetting->itemsByIds($houseworksetting_ids));
$this->assign('list', $list); // 赋值数据集
$this->assign('page', $show); // 赋值分页输出
$this->display(); // 输出模板
}
}
| ksyydream/api_llx | Baocms/Lib/Action/Member/MylifeserviceAction.class.php | PHP | apache-2.0 | 1,111 |
/**
* 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.storm.kafka;
import org.apache.storm.Config;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingServer;
import org.apache.curator.utils.ZKPaths;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.apache.storm.kafka.trident.GlobalPartitionInformation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Date: 16/05/2013
* Time: 20:35
*/
public class DynamicBrokersReaderTest {
private DynamicBrokersReader dynamicBrokersReader, wildCardBrokerReader;
private String masterPath = "/brokers";
private String topic = "testing1";
private String secondTopic = "testing2";
private String thirdTopic = "testing3";
private CuratorFramework zookeeper;
private TestingServer server;
@Before
public void setUp() throws Exception {
server = new TestingServer();
String connectionString = server.getConnectString();
Map conf = new HashMap();
conf.put(Config.STORM_ZOOKEEPER_SESSION_TIMEOUT, 1000);
conf.put(Config.STORM_ZOOKEEPER_CONNECTION_TIMEOUT, 1000);
conf.put(Config.STORM_ZOOKEEPER_RETRY_TIMES, 4);
conf.put(Config.STORM_ZOOKEEPER_RETRY_INTERVAL, 5);
ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3);
zookeeper = CuratorFrameworkFactory.newClient(connectionString, retryPolicy);
dynamicBrokersReader = new DynamicBrokersReader(conf, connectionString, masterPath, topic);
Map conf2 = new HashMap();
conf2.putAll(conf);
conf2.put("kafka.topic.wildcard.match",true);
wildCardBrokerReader = new DynamicBrokersReader(conf2, connectionString, masterPath, "^test.*$");
zookeeper.start();
}
@After
public void tearDown() throws Exception {
dynamicBrokersReader.close();
zookeeper.close();
server.close();
}
private void addPartition(int id, String host, int port, String topic) throws Exception {
writePartitionId(id, topic);
writeLeader(id, 0, topic);
writeLeaderDetails(0, host, port);
}
private void addPartition(int id, int leader, String host, int port, String topic) throws Exception {
writePartitionId(id, topic);
writeLeader(id, leader, topic);
writeLeaderDetails(leader, host, port);
}
private void writePartitionId(int id, String topic) throws Exception {
String path = dynamicBrokersReader.partitionPath(topic);
writeDataToPath(path, ("" + id));
}
private void writeDataToPath(String path, String data) throws Exception {
ZKPaths.mkdirs(zookeeper.getZookeeperClient().getZooKeeper(), path);
zookeeper.setData().forPath(path, data.getBytes());
}
private void writeLeader(int id, int leaderId, String topic) throws Exception {
String path = dynamicBrokersReader.partitionPath(topic) + "/" + id + "/state";
String value = " { \"controller_epoch\":4, \"isr\":[ 1, 0 ], \"leader\":" + leaderId + ", \"leader_epoch\":1, \"version\":1 }";
writeDataToPath(path, value);
}
private void writeLeaderDetails(int leaderId, String host, int port) throws Exception {
String path = dynamicBrokersReader.brokerPath() + "/" + leaderId;
String value = "{ \"host\":\"" + host + "\", \"jmx_port\":9999, \"port\":" + port + ", \"version\":1 }";
writeDataToPath(path, value);
}
private GlobalPartitionInformation getByTopic(List<GlobalPartitionInformation> partitions, String topic){
for(GlobalPartitionInformation partitionInformation : partitions) {
if (partitionInformation.topic.equals(topic)) return partitionInformation;
}
return null;
}
@Test
public void testGetBrokerInfo() throws Exception {
String host = "localhost";
int port = 9092;
int partition = 0;
addPartition(partition, host, port, topic);
List<GlobalPartitionInformation> partitions = dynamicBrokersReader.getBrokerInfo();
GlobalPartitionInformation brokerInfo = getByTopic(partitions, topic);
assertNotNull(brokerInfo);
assertEquals(1, brokerInfo.getOrderedPartitions().size());
assertEquals(port, brokerInfo.getBrokerFor(partition).port);
assertEquals(host, brokerInfo.getBrokerFor(partition).host);
}
@Test
public void testGetBrokerInfoWildcardMatch() throws Exception {
String host = "localhost";
int port = 9092;
int partition = 0;
addPartition(partition, host, port, topic);
addPartition(partition, host, port, secondTopic);
List<GlobalPartitionInformation> partitions = wildCardBrokerReader.getBrokerInfo();
GlobalPartitionInformation brokerInfo = getByTopic(partitions, topic);
assertNotNull(brokerInfo);
assertEquals(1, brokerInfo.getOrderedPartitions().size());
assertEquals(port, brokerInfo.getBrokerFor(partition).port);
assertEquals(host, brokerInfo.getBrokerFor(partition).host);
brokerInfo = getByTopic(partitions, secondTopic);
assertNotNull(brokerInfo);
assertEquals(1, brokerInfo.getOrderedPartitions().size());
assertEquals(port, brokerInfo.getBrokerFor(partition).port);
assertEquals(host, brokerInfo.getBrokerFor(partition).host);
addPartition(partition, host, port, thirdTopic);
//Discover newly added topic
partitions = wildCardBrokerReader.getBrokerInfo();
assertNotNull(getByTopic(partitions, topic));
assertNotNull(getByTopic(partitions, secondTopic));
assertNotNull(getByTopic(partitions, secondTopic));
}
@Test
public void testMultiplePartitionsOnDifferentHosts() throws Exception {
String host = "localhost";
int port = 9092;
int secondPort = 9093;
int partition = 0;
int secondPartition = partition + 1;
addPartition(partition, 0, host, port, topic);
addPartition(secondPartition, 1, host, secondPort, topic);
List<GlobalPartitionInformation> partitions = dynamicBrokersReader.getBrokerInfo();
GlobalPartitionInformation brokerInfo = getByTopic(partitions, topic);
assertNotNull(brokerInfo);
assertEquals(2, brokerInfo.getOrderedPartitions().size());
assertEquals(port, brokerInfo.getBrokerFor(partition).port);
assertEquals(host, brokerInfo.getBrokerFor(partition).host);
assertEquals(secondPort, brokerInfo.getBrokerFor(secondPartition).port);
assertEquals(host, brokerInfo.getBrokerFor(secondPartition).host);
}
@Test
public void testMultiplePartitionsOnSameHost() throws Exception {
String host = "localhost";
int port = 9092;
int partition = 0;
int secondPartition = partition + 1;
addPartition(partition, 0, host, port, topic);
addPartition(secondPartition, 0, host, port, topic);
List<GlobalPartitionInformation> partitions = dynamicBrokersReader.getBrokerInfo();
GlobalPartitionInformation brokerInfo = getByTopic(partitions, topic);
assertNotNull(brokerInfo);
assertEquals(2, brokerInfo.getOrderedPartitions().size());
assertEquals(port, brokerInfo.getBrokerFor(partition).port);
assertEquals(host, brokerInfo.getBrokerFor(partition).host);
assertEquals(port, brokerInfo.getBrokerFor(secondPartition).port);
assertEquals(host, brokerInfo.getBrokerFor(secondPartition).host);
}
@Test
public void testSwitchHostForPartition() throws Exception {
String host = "localhost";
int port = 9092;
int partition = 0;
addPartition(partition, host, port, topic);
List<GlobalPartitionInformation> partitions = dynamicBrokersReader.getBrokerInfo();
GlobalPartitionInformation brokerInfo = getByTopic(partitions, topic);
assertNotNull(brokerInfo);
assertEquals(port, brokerInfo.getBrokerFor(partition).port);
assertEquals(host, brokerInfo.getBrokerFor(partition).host);
String newHost = host + "switch";
int newPort = port + 1;
addPartition(partition, newHost, newPort, topic);
partitions = dynamicBrokersReader.getBrokerInfo();
brokerInfo = getByTopic(partitions, topic);
assertNotNull(brokerInfo);
assertEquals(newPort, brokerInfo.getBrokerFor(partition).port);
assertEquals(newHost, brokerInfo.getBrokerFor(partition).host);
}
@Test(expected = NullPointerException.class)
public void testErrorLogsWhenConfigIsMissing() throws Exception {
String connectionString = server.getConnectString();
Map conf = new HashMap();
conf.put(Config.STORM_ZOOKEEPER_SESSION_TIMEOUT, 1000);
// conf.put(Config.STORM_ZOOKEEPER_CONNECTION_TIMEOUT, 1000);
conf.put(Config.STORM_ZOOKEEPER_RETRY_TIMES, 4);
conf.put(Config.STORM_ZOOKEEPER_RETRY_INTERVAL, 5);
DynamicBrokersReader dynamicBrokersReader1 = new DynamicBrokersReader(conf, connectionString, masterPath, topic);
}
}
| anshuiisc/storm-Allbolts-wiring | external/storm-kafka/src/test/org/apache/storm/kafka/DynamicBrokersReaderTest.java | Java | apache-2.0 | 10,234 |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using AutoMapper;
using Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.Commands.Compute.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute
{
[Cmdlet("Remove", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VMSqlServerExtension")]
[OutputType(typeof(PSAzureOperationResponse))]
public class RemoveAzureVMSqlServerExtensionCommand : VirtualMachineExtensionBaseCmdlet
{
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource group name.")]
[ResourceGroupCompleter()]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
[Alias("ResourceName")]
[Parameter(
Mandatory = true,
Position = 1,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The virtual machine name.")]
[ResourceNameCompleter("Microsoft.Compute/virtualMachines", "ResourceGroupName")]
[ValidateNotNullOrEmpty]
public string VMName { get; set; }
[Alias("ExtensionName")]
[Parameter(
Mandatory = true,
Position = 2,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Name of the ARM resource that represents the extension. This is defaulted to 'Microsoft.SqlServer.Management.SqlIaaSAgent'.")]
[ResourceNameCompleter("Microsoft.Compute/virtualMachines/extensions", "ResourceGroupName", "VMName")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
ExecuteClientAction(() =>
{
if (string.IsNullOrEmpty(Name))
{
Name = VirtualMachineSqlServerExtensionContext.ExtensionPublishedNamespace + "." + VirtualMachineSqlServerExtensionContext.ExtensionPublishedName;
}
if (this.ShouldContinue(Properties.Resources.VirtualMachineExtensionRemovalConfirmation, Properties.Resources.VirtualMachineExtensionRemovalCaption))
{
var op = this.VirtualMachineExtensionClient.DeleteWithHttpMessagesAsync(
this.ResourceGroupName,
this.VMName,
this.Name).GetAwaiter().GetResult();
var result = ComputeAutoMapperProfile.Mapper.Map<PSAzureOperationResponse>(op);
WriteObject(result);
}
});
}
}
}
| ClogenyTechnologies/azure-powershell | src/ResourceManager/Compute/Commands.Compute/Extension/SqlServer/RemoveAzureVMSqlServerExtensionCommand.cs | C# | apache-2.0 | 3,476 |
/*
* 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.atlas.typesystem.builders
import org.apache.atlas.typesystem.{IReferenceableInstance, IStruct, Referenceable, Struct}
import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
import scala.collection.mutable.ArrayBuffer
import scala.language.{dynamics, implicitConversions}
import scala.util.DynamicVariable
class InstanceBuilder extends Dynamic {
private val references : ArrayBuffer[Referenceable] = new ArrayBuffer[Referenceable]()
val context = new DynamicVariable[DynamicStruct](null)
def struct(typeName : String) : DynamicStruct = {
context.value = new DynamicStruct(this, new Struct(typeName))
context.value
}
def instance(typeName: String, traitNames: String*)(f : => Unit) : DynamicReference = {
val r = new Referenceable(typeName, traitNames:_*)
references.append(r)
val dr = new DynamicReference(this, r)
context.withValue(dr){f}
dr
}
def create( f : => Unit ) : java.util.List[Referenceable] = {
f
references.asJava
}
def applyDynamic(name : String)(value : Any) : Any = {
context.value.updateDynamic(name)(value)
}
implicit def symbolToDynamicStruct(s : Symbol) : DynamicValue =
new DynamicValue(this, s.name, if (context.value == null) null else context.value.s)
}
object DynamicValue {
private[builders] def transformOut(s: IStruct, attr : String, v : Any)(implicit ib : InstanceBuilder) : DynamicValue =
v match {
case r : Referenceable => new DynamicReference(ib, r)
case s : Struct => new DynamicStruct(ib, s)
case jL : java.util.List[_] => {
if ( s != null ) {
new DynamicCollection(ib, attr, s)
} else {
new DynamicValue(ib, attr, s, jL.map{ e => transformOut(null, null, e)}.toSeq)
}
}
case jM : java.util.Map[_,_] => {
if ( s != null ) {
new DynamicMap(ib, attr, s)
} else {
new DynamicValue(ib, attr, s, jM.map {
case (k, v) => k -> transformOut(null, null, v)
}.toMap)
}
}
case x => {
if ( s != null ) {
new DynamicValue(ib, attr, s)
} else {
new DynamicValue(ib, attr, s, x)
}
}
}
private[builders] def transformIn(v : Any) : Any = v match {
case dr : DynamicReference => dr.r
case ds : DynamicStruct => ds.s
case dv : DynamicValue => dv.get
case l : Seq[_] => l.map{ e => transformIn(e)}.asJava
case m : Map[_,_] => m.map {
case (k,v) => k -> transformIn(v)
}.asJava
case x => x
}
}
class DynamicValue(val ib : InstanceBuilder, val attrName : String, val s: IStruct, var value : Any = null) extends Dynamic {
import DynamicValue._
implicit val iib : InstanceBuilder = ib
def ~(v : Any): Unit = {
if ( s != null ) {
s.set(attrName, transformIn(v))
} else {
value = v
}
}
def get : Any = if ( s != null ) s.get(attrName) else value
def selectDynamic(name: String) : DynamicValue = {
throw new UnsupportedOperationException()
}
def update(key : Any, value : Object): Unit = {
throw new UnsupportedOperationException()
}
def apply(key : Any): DynamicValue = {
if ( s != null && s.isInstanceOf[Referenceable] && key.isInstanceOf[String]) {
val r = s.asInstanceOf[Referenceable]
if ( r.getTraits contains attrName ) {
val traitAttr = key.asInstanceOf[String]
return new DynamicStruct(ib, r.getTrait(attrName)).selectDynamic(traitAttr)
}
}
throw new UnsupportedOperationException()
}
}
class DynamicCollection(ib : InstanceBuilder, attrName : String, s: IStruct) extends DynamicValue(ib, attrName ,s) {
import DynamicValue._
override def update(key : Any, value : Object): Unit = {
var jL = s.get(attrName)
val idx = key.asInstanceOf[Int]
if (jL == null ) {
val l = new java.util.ArrayList[Object]()
l.ensureCapacity(idx)
jL = l
}
val nJL = new java.util.ArrayList[Object](jL.asInstanceOf[java.util.List[Object]])
nJL.asInstanceOf[java.util.List[Object]].set(idx, transformIn(value).asInstanceOf[Object])
s.set(attrName, nJL)
}
override def apply(key : Any): DynamicValue = {
var jL = s.get(attrName)
val idx = key.asInstanceOf[Int]
if (jL == null ) {
null
} else {
transformOut(null, null, jL.asInstanceOf[java.util.List[Object]].get(idx))
}
}
}
class DynamicMap(ib : InstanceBuilder, attrName : String, s: IStruct) extends DynamicValue(ib, attrName ,s) {
import DynamicValue._
override def update(key : Any, value : Object): Unit = {
var jM = s.get(attrName)
if (jM == null ) {
jM = new java.util.HashMap[Object, Object]()
}
jM.asInstanceOf[java.util.Map[Object, Object]].put(key.asInstanceOf[AnyRef], value)
}
override def apply(key : Any): DynamicValue = {
var jM = s.get(attrName)
if (jM == null ) {
null
} else {
transformOut(null, null, jM.asInstanceOf[java.util.Map[Object, Object]].get(key))
}
}
}
class DynamicStruct(ib : InstanceBuilder, s: IStruct) extends DynamicValue(ib, null ,s) {
import DynamicValue._
override def selectDynamic(name: String) : DynamicValue = {
transformOut(s, name, s.get(name))
}
def updateDynamic(name: String)(value: Any) {
s.set(name, transformIn(value))
}
override def ~(v : Any): Unit = { throw new UnsupportedOperationException()}
override def get : Any = s
}
class DynamicReference(ib : InstanceBuilder, val r : IReferenceableInstance) extends DynamicStruct(ib, r) {
private def _trait(name : String) = new DynamicStruct(ib, r.getTrait(name))
override def selectDynamic(name: String) : DynamicValue = {
if ( r.getTraits contains name ) {
_trait(name)
} else {
super.selectDynamic(name)
}
}
}
| jnhagelberg/incubator-atlas | typesystem/src/main/scala/org/apache/atlas/typesystem/builders/InstanceBuilder.scala | Scala | apache-2.0 | 6,607 |
/*
* 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.sysds.runtime.controlprogram.paramserv.dp;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.sysds.hops.OptimizerUtils;
import org.apache.sysds.runtime.controlprogram.paramserv.ParamservUtils;
import org.apache.sysds.runtime.matrix.data.MatrixBlock;
import scala.Tuple2;
/**
* Spark data partitioner Disjoint_Random:
*
* For the current row block, find all the shifted place for each row (WorkerID {@literal =>} (row block ID, matrix)
*/
public class DRSparkScheme extends DataPartitionSparkScheme {
private static final long serialVersionUID = -7655310624144544544L;
protected DRSparkScheme() {
// No-args constructor used for deserialization
}
@Override
public Result doPartitioning(int numWorkers, int rblkID, MatrixBlock features, MatrixBlock labels) {
List<Tuple2<Integer, Tuple2<Long, MatrixBlock>>> pfs = partition(rblkID, features);
List<Tuple2<Integer, Tuple2<Long, MatrixBlock>>> pls = partition(rblkID, labels);
return new Result(pfs, pls);
}
private List<Tuple2<Integer, Tuple2<Long, MatrixBlock>>> partition(int rblkID, MatrixBlock mb) {
MatrixBlock partialPerm = _globalPerms.get(0).getBlock(rblkID, 1);
// For each row, find out the shifted place
return IntStream.range(0, mb.getNumRows()).mapToObj(r -> {
MatrixBlock rowMB = ParamservUtils.sliceMatrixBlock(mb, r + 1, r + 1);
long shiftedPosition = (long) partialPerm.getValue(r, 0);
// Get the shifted block and position
int shiftedBlkID = (int) (shiftedPosition / OptimizerUtils.DEFAULT_BLOCKSIZE + 1);
MatrixBlock indicator = _workerIndicator.getBlock(shiftedBlkID, 1);
int workerID = (int) indicator.getValue((int) shiftedPosition / OptimizerUtils.DEFAULT_BLOCKSIZE, 0);
return new Tuple2<>(workerID, new Tuple2<>(shiftedPosition, rowMB));
}).collect(Collectors.toList());
}
}
| apache/incubator-systemml | src/main/java/org/apache/sysds/runtime/controlprogram/paramserv/dp/DRSparkScheme.java | Java | apache-2.0 | 2,698 |
/**
* @copyright
* ====================================================================
* 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.
* ====================================================================
* @endcopyright
*/
#ifndef SVN_JAVAHL_JNIWRAPPER_EXCEPTION_HPP
#define SVN_JAVAHL_JNIWRAPPER_EXCEPTION_HPP
#include "jni_env.hpp"
#include "jni_object.hpp"
namespace Java {
/**
* Base class for all exception generators, and generator class for
* exceptions of type @c java.lang.Throwable.
*
* The associated JNI class reference is stored for the lifetime of
* the JVM in the global class cache.
*
* @since New in 1.9.
*/
class Exception
{
public:
/**
* Constructs a wrapper for the @c jthrowable object @a exc.
*/
explicit Exception(Env env, jthrowable exc)
: m_env(env),
m_jthis(exc),
m_class(env.GetObjectClass(exc))
{}
/**
* Raises a Java exception of the concrete class, and throws a
* native exception at the same time.
*
* It is an error to call this method if an existing @c jthrowable
* object was wrapped.
*/
void raise() const
{
throw_java_exception();
throw SignalExceptionThrown();
}
/**
* Raises a Java exception of the concrete class with the givem
* @a message, and throws a native exception at the same time.
*
* It is an error to call this method if an existing @c jthrowable
* object was wrapped.
*/
void raise(const char* message) const
{
throw_java_exception(message);
throw SignalExceptionThrown();
}
/**
* Raises a Java exception of the concrete class, but does not throw
* a native exception.
*
* It is an error to call this method if an existing @c jthrowable
* object was wrapped.
*/
void throw_java_exception() const;
/**
* Raises a Java exception of the concrete class with the given
* @a message, but does not throw a native exception.
*
* It is an error to call this method if an existing @c jthrowable
* object was wrapped.
*/
void throw_java_exception(const char* message) const;
/**
* Checks if an existing @c jthrowable object was wrapped.
*/
bool instantiated() const
{
return (m_jthis != NULL);
}
/**
* Returns the wrapped @c jthrowable object.
*/
jthrowable throwable() const
{
return m_jthis;
}
/**
* Wrapper for the Java method @c getMessage().
* Only valid if an existing @c jthrowable object was wrapped.
*/
jstring get_message() const;
/**
* Returns the wrapped exception instance.
*/
jobject get() const
{
return m_jthis;
}
/**
* Returns the wrapped exception class.
*/
jclass get_class() const
{
return m_class;
}
/**
* Returns the wrapped enviromnment reference.
*/
Env get_env() const
{
return m_env;
}
protected:
/**
* Constructs an exception generator with the concrete class
* @a class_name.
*/
explicit Exception(Env env, const char* class_name)
: m_env(env),
m_jthis(NULL),
m_class(env.FindClass(class_name))
{}
/**
* Constructs an exception generator with the concrete class @a cls.
*/
explicit Exception(Env env, const Object::ClassImpl* impl)
: m_env(env),
m_jthis(NULL),
m_class(impl->get_class())
{}
private:
/**
* This object's implementation details.
*/
class ClassImpl : public Object::ClassImpl
{
friend class ClassCacheImpl;
protected:
explicit ClassImpl(Env env, jclass cls)
: Object::ClassImpl(env, cls)
{}
public:
virtual ~ClassImpl();
};
const Env m_env;
jthrowable m_jthis;
jclass m_class;
friend class ClassCacheImpl;
static void static_init(Env env, jclass cls);
static const char* const m_class_name;
static MethodID m_mid_get_message;
};
/**
* Generator class for exceptions of type @c java.lang.RuntimeException.
*
* @since New in 1.9.
*/
class RuntimeException : public Exception
{
public:
/**
* Constructs an exception generator object.
*/
explicit RuntimeException(Env env)
: Exception(env, m_class_name)
{}
private:
static const char* const m_class_name;
};
/**
* Generator class for exceptions of type @c java.lang.NullPointerException.
*
* @since New in 1.9.
*/
class NullPointerException : public Exception
{
public:
/**
* Constructs an exception generator object.
*/
explicit NullPointerException(Env env)
: Exception(env, m_class_name)
{}
private:
static const char* const m_class_name;
};
/**
* Generator class for exceptions of type @c java.lang.OutOfMemoryError.
*
* @since New in 1.9.
*/
class OutOfMemoryError : public Exception
{
public:
/**
* Constructs an exception generator object.
*/
explicit OutOfMemoryError(Env env)
: Exception(env, m_class_name)
{}
private:
static const char* const m_class_name;
};
/**
* Generator class for exceptions of type
* @c java.lang.IndexOutOfBoundsException.
*
* @since New in 1.9.
*/
class IndexOutOfBoundsException : public Exception
{
public:
/**
* Constructs an exception generator object.
*/
explicit IndexOutOfBoundsException(Env env)
: Exception(env, m_class_name)
{}
private:
/**
* This object's implementation details.
*/
class ClassImpl : public Object::ClassImpl
{
friend class ClassCacheImpl;
protected:
explicit ClassImpl(Env env, jclass cls)
: Object::ClassImpl(env, cls)
{}
public:
virtual ~ClassImpl();
};
friend class ClassCacheImpl;
static const char* const m_class_name;
};
/**
* Generator class for exceptions of type @c java.io.IOException.
*
* @since New in 1.9.
*/
class IOException : public Exception
{
public:
/**
* Constructs an exception generator object.
*/
explicit IOException(Env env)
: Exception(env, m_class_name)
{}
private:
static const char* const m_class_name;
};
/**
* Generator class for exceptions of type @c java.lang.IllegalArgumentException.
*
* @since New in 1.9.
*/
class IllegalArgumentException : public Exception
{
public:
/**
* Constructs an exception generator object.
*/
explicit IllegalArgumentException(Env env)
: Exception(env, m_class_name)
{}
private:
static const char* const m_class_name;
};
/**
* Generator class for exceptions of type
* @c java.util.NoSuchElementException.
*
* @since New in 1.9.
*/
class NoSuchElementException : public Exception
{
public:
/**
* Constructs an exception generator object.
*/
explicit NoSuchElementException(Env env)
: Exception(env, m_class_name)
{}
private:
/**
* This object's implementation details.
*/
class ClassImpl : public Object::ClassImpl
{
friend class ClassCacheImpl;
protected:
explicit ClassImpl(Env env, jclass cls)
: Object::ClassImpl(env, cls)
{}
public:
virtual ~ClassImpl();
};
friend class ClassCacheImpl;
static const char* const m_class_name;
};
} // namespace Java
#endif // SVN_JAVAHL_JNIWRAPPER_EXCEPTION_HPP
| YueLinHo/Subversion | subversion/bindings/javahl/native/jniwrapper/jni_exception.hpp | C++ | apache-2.0 | 7,879 |
/*
* 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.jmeter.protocol.java.sampler;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.config.ConfigTestElement;
import org.apache.jmeter.protocol.java.test.JavaTest;
import org.apache.jmeter.samplers.AbstractSampler;
import org.apache.jmeter.samplers.Entry;
import org.apache.jmeter.samplers.Interruptible;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.TestStateListener;
import org.apache.jmeter.testelement.property.TestElementProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A sampler for executing custom Java code in each sample. See
* {@link JavaSamplerClient} and {@link AbstractJavaSamplerClient} for
* information on writing Java code to be executed by this sampler.
*
*/
public class JavaSampler extends AbstractSampler implements TestStateListener, Interruptible {
private static final Logger log = LoggerFactory.getLogger(JavaTest.class);
private static final long serialVersionUID = 233L; // Remember to change this when the class changes ...
private static final Set<String> APPLIABLE_CONFIG_CLASSES = new HashSet<>(
Arrays.asList(
"org.apache.jmeter.protocol.java.config.gui.JavaConfigGui",
"org.apache.jmeter.config.gui.SimpleConfigGui"
));
/**
* Set used to register instances which implement tearDownTest.
* This is used so that the JavaSamplerClient can be notified when the test ends.
*/
private static final Set<JavaSampler> TEAR_DOWN_SET =
Collections.newSetFromMap(new ConcurrentHashMap<JavaSampler,Boolean>());
/**
* Property key representing the classname of the JavaSamplerClient to user.
*/
public static final String CLASSNAME = "classname";
/**
* Property key representing the arguments for the JavaSamplerClient.
*/
public static final String ARGUMENTS = "arguments";
/**
* The JavaSamplerClient class used by this sampler.
* Created by testStarted; copied to cloned instances.
*/
private Class<?> javaClass;
/**
* If true, the JavaSamplerClient class implements tearDownTest.
* Created by testStarted; copied to cloned instances.
*/
private boolean isToBeRegistered;
/**
* The JavaSamplerClient instance used by this sampler to actually perform
* the sample.
*/
private transient JavaSamplerClient javaClient = null;
/**
* The JavaSamplerContext instance used by this sampler to hold information
* related to the test run, such as the parameters specified for the sampler
* client.
*/
private transient JavaSamplerContext context = null;
/**
* Create a JavaSampler.
*/
public JavaSampler() {
setArguments(new Arguments());
}
/*
* Ensure that the required class variables are cloned,
* as this is not currently done by the super-implementation.
*/
@Override
public Object clone() {
JavaSampler clone = (JavaSampler) super.clone();
clone.javaClass = this.javaClass;
clone.isToBeRegistered = this.isToBeRegistered;
return clone;
}
private void initClass() {
String name = getClassname().trim();
try {
javaClass = Class.forName(name, false, Thread.currentThread().getContextClassLoader());
Method method = javaClass.getMethod("teardownTest", JavaSamplerContext.class);
isToBeRegistered = !method.getDeclaringClass().equals(AbstractJavaSamplerClient.class);
log.info("Created class: {}. Uses tearDownTest: ", name, isToBeRegistered);
} catch (Exception e) {
log.error("{}\tException initialising: ", whoAmI(), name, e);
}
}
/**
* Set the arguments (parameters) for the JavaSamplerClient to be executed
* with.
*
* @param args
* the new arguments. These replace any existing arguments.
*/
public void setArguments(Arguments args) {
setProperty(new TestElementProperty(ARGUMENTS, args));
}
/**
* Get the arguments (parameters) for the JavaSamplerClient to be executed
* with.
*
* @return the arguments
*/
public Arguments getArguments() {
return (Arguments) getProperty(ARGUMENTS).getObjectValue();
}
/**
* Sets the Classname attribute of the JavaConfig object
*
* @param classname
* the new Classname value
*/
public void setClassname(String classname) {
setProperty(CLASSNAME, classname);
}
/**
* Gets the Classname attribute of the JavaConfig object
*
* @return the Classname value
*/
public String getClassname() {
return getPropertyAsString(CLASSNAME);
}
/**
* Performs a test sample.
*
* The <code>sample()</code> method retrieves the reference to the Java
* client and calls its <code>runTest()</code> method.
*
* @see JavaSamplerClient#runTest(JavaSamplerContext)
*
* @param entry
* the Entry for this sample
* @return test SampleResult
*/
@Override
public SampleResult sample(Entry entry) {
Arguments args = getArguments();
args.addArgument(TestElement.NAME, getName()); // Allow Sampler access
// to test element name
context = new JavaSamplerContext(args);
if (javaClient == null) {
if (log.isDebugEnabled()) {
log.debug("{}\tCreating Java Client", whoAmI());
}
javaClient = createJavaClient();
javaClient.setupTest(context);
}
SampleResult result = javaClient.runTest(context);
// Only set the default label if it has not been set
if (result != null && result.getSampleLabel().length() == 0) {
result.setSampleLabel(getName());
}
return result;
}
/**
* Returns reference to <code>JavaSamplerClient</code>.
*
* The <code>createJavaClient()</code> method uses reflection to create an
* instance of the specified Java protocol client. If the class can not be
* found, the method returns a reference to <code>this</code> object.
*
* @return JavaSamplerClient reference.
*/
private JavaSamplerClient createJavaClient() {
if (javaClass == null) { // failed to initialise the class
return new ErrorSamplerClient();
}
JavaSamplerClient client;
try {
client = (JavaSamplerClient) javaClass.getDeclaredConstructor().newInstance();
if (log.isDebugEnabled()) {
log.debug("{}\tCreated:\t{}@{}", whoAmI(), getClassname(), Integer.toHexString(client.hashCode()));
}
if(isToBeRegistered) {
TEAR_DOWN_SET.add(this);
}
} catch (Exception e) {
if (log.isErrorEnabled()) {
log.error("{}\tException creating: {}", whoAmI(), getClassname(), e);
}
client = new ErrorSamplerClient();
}
return client;
}
/**
* Retrieves reference to JavaSamplerClient.
*
* Convenience method used to check for null reference without actually
* creating a JavaSamplerClient
*
* @return reference to JavaSamplerClient NOTUSED private JavaSamplerClient
* retrieveJavaClient() { return javaClient; }
*/
/**
* Generate a String identifier of this instance for debugging purposes.
*
* @return a String identifier for this sampler instance
*/
private String whoAmI() {
StringBuilder sb = new StringBuilder();
sb.append(Thread.currentThread().getName());
sb.append("@");
sb.append(Integer.toHexString(hashCode()));
sb.append("-");
sb.append(getName());
return sb.toString();
}
// TestStateListener implementation
/* Implements TestStateListener.testStarted() */
@Override
public void testStarted() {
if (log.isDebugEnabled()) {
log.debug("{}\ttestStarted", whoAmI());
}
initClass();
}
/* Implements TestStateListener.testStarted(String) */
@Override
public void testStarted(String host) {
if (log.isDebugEnabled()) {
log.debug("{}\ttestStarted({})", whoAmI(), host);
}
initClass();
}
/**
* Method called at the end of the test. This is called only on one instance
* of JavaSampler. This method will loop through all of the other
* JavaSamplers which have been registered (automatically in the
* constructor) and notify them that the test has ended, allowing the
* JavaSamplerClients to cleanup.
*/
@Override
public void testEnded() {
if (log.isDebugEnabled()) {
log.debug("{}\ttestEnded", whoAmI());
}
synchronized (TEAR_DOWN_SET) {
for (JavaSampler javaSampler : TEAR_DOWN_SET) {
JavaSamplerClient client = javaSampler.javaClient;
if (client != null) {
client.teardownTest(javaSampler.context);
}
}
TEAR_DOWN_SET.clear();
}
}
/* Implements TestStateListener.testEnded(String) */
@Override
public void testEnded(String host) {
testEnded();
}
/**
* A {@link JavaSamplerClient} implementation used for error handling. If an
* error occurs while creating the real JavaSamplerClient object, it is
* replaced with an instance of this class. Each time a sample occurs with
* this class, the result is marked as a failure so the user can see that
* the test failed.
*/
class ErrorSamplerClient extends AbstractJavaSamplerClient {
/**
* Return SampleResult with data on error.
*
* @see JavaSamplerClient#runTest(JavaSamplerContext)
*/
@Override
public SampleResult runTest(JavaSamplerContext p_context) {
if (log.isDebugEnabled()) {
log.debug("{}\trunTest", whoAmI());
}
Thread.yield();
SampleResult results = new SampleResult();
results.setSuccessful(false);
results.setResponseData("Class not found: " + getClassname(), null);
results.setSampleLabel("ERROR: " + getClassname());
return results;
}
}
/**
* @see org.apache.jmeter.samplers.AbstractSampler#applies(org.apache.jmeter.config.ConfigTestElement)
*/
@Override
public boolean applies(ConfigTestElement configElement) {
String guiClass = configElement.getProperty(TestElement.GUI_CLASS).getStringValue();
return APPLIABLE_CONFIG_CLASSES.contains(guiClass);
}
@Override
public boolean interrupt() {
if (javaClient instanceof Interruptible) {
return ((Interruptible) javaClient).interrupt();
}
return false;
}
}
| ubikloadpack/jmeter | src/protocol/java/org/apache/jmeter/protocol/java/sampler/JavaSampler.java | Java | apache-2.0 | 12,241 |
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsRenderingContext.h"
#include "nsBoundingMetrics.h"
#include "nsRegion.h"
// XXXTodo: rename FORM_TWIPS to FROM_APPUNITS
#define FROM_TWIPS(_x) ((gfxFloat)((_x)/(mP2A)))
#define FROM_TWIPS_INT(_x) (NSToIntRound((gfxFloat)((_x)/(mP2A))))
#define TO_TWIPS(_x) ((nscoord)((_x)*(mP2A)))
#define GFX_RECT_FROM_TWIPS_RECT(_r) (gfxRect(FROM_TWIPS((_r).x), FROM_TWIPS((_r).y), FROM_TWIPS((_r).width), FROM_TWIPS((_r).height)))
// Hard limit substring lengths to 8000 characters ... this lets us statically
// size the cluster buffer array in FindSafeLength
#define MAX_GFX_TEXT_BUF_SIZE 8000
static int32_t FindSafeLength(const PRUnichar *aString, uint32_t aLength,
uint32_t aMaxChunkLength)
{
if (aLength <= aMaxChunkLength)
return aLength;
int32_t len = aMaxChunkLength;
// Ensure that we don't break inside a surrogate pair
while (len > 0 && NS_IS_LOW_SURROGATE(aString[len])) {
len--;
}
if (len == 0) {
// We don't want our caller to go into an infinite loop, so don't
// return zero. It's hard to imagine how we could actually get here
// unless there are languages that allow clusters of arbitrary size.
// If there are and someone feeds us a 500+ character cluster, too
// bad.
return aMaxChunkLength;
}
return len;
}
static int32_t FindSafeLength(const char *aString, uint32_t aLength,
uint32_t aMaxChunkLength)
{
// Since it's ASCII, we don't need to worry about clusters or RTL
return NS_MIN(aLength, aMaxChunkLength);
}
//////////////////////////////////////////////////////////////////////
//// nsRenderingContext
void
nsRenderingContext::Init(nsDeviceContext* aContext,
gfxASurface *aThebesSurface)
{
Init(aContext, new gfxContext(aThebesSurface));
}
void
nsRenderingContext::Init(nsDeviceContext* aContext,
gfxContext *aThebesContext)
{
mDeviceContext = aContext;
mThebes = aThebesContext;
mThebes->SetLineWidth(1.0);
mP2A = mDeviceContext->AppUnitsPerDevPixel();
}
//
// graphics state
//
void
nsRenderingContext::PushState()
{
mThebes->Save();
}
void
nsRenderingContext::PopState()
{
mThebes->Restore();
}
void
nsRenderingContext::IntersectClip(const nsRect& aRect)
{
mThebes->NewPath();
gfxRect clipRect(GFX_RECT_FROM_TWIPS_RECT(aRect));
if (mThebes->UserToDevicePixelSnapped(clipRect, true)) {
gfxMatrix mat(mThebes->CurrentMatrix());
mat.Invert();
clipRect = mat.Transform(clipRect);
mThebes->Rectangle(clipRect);
} else {
mThebes->Rectangle(clipRect);
}
mThebes->Clip();
}
void
nsRenderingContext::SetClip(const nsIntRegion& aRegion)
{
// Region is in device coords, no transformation. This should
// only be called when there is no transform in place, when we we
// just start painting a widget. The region is set by the platform
// paint routine. Therefore, there is no option to intersect with
// an existing clip.
gfxMatrix mat = mThebes->CurrentMatrix();
mThebes->IdentityMatrix();
mThebes->ResetClip();
mThebes->NewPath();
nsIntRegionRectIterator iter(aRegion);
const nsIntRect* rect;
while ((rect = iter.Next())) {
mThebes->Rectangle(gfxRect(rect->x, rect->y, rect->width, rect->height),
true);
}
mThebes->Clip();
mThebes->SetMatrix(mat);
}
void
nsRenderingContext::SetLineStyle(nsLineStyle aLineStyle)
{
switch (aLineStyle) {
case nsLineStyle_kSolid:
mThebes->SetDash(gfxContext::gfxLineSolid);
break;
case nsLineStyle_kDashed:
mThebes->SetDash(gfxContext::gfxLineDashed);
break;
case nsLineStyle_kDotted:
mThebes->SetDash(gfxContext::gfxLineDotted);
break;
case nsLineStyle_kNone:
default:
// nothing uses kNone
NS_ERROR("SetLineStyle: Invalid line style");
break;
}
}
void
nsRenderingContext::SetColor(nscolor aColor)
{
/* This sets the color assuming the sRGB color space, since that's
* what all CSS colors are defined to be in by the spec.
*/
mThebes->SetColor(gfxRGBA(aColor));
}
void
nsRenderingContext::Translate(const nsPoint& aPt)
{
mThebes->Translate(gfxPoint(FROM_TWIPS(aPt.x), FROM_TWIPS(aPt.y)));
}
void
nsRenderingContext::Scale(float aSx, float aSy)
{
mThebes->Scale(aSx, aSy);
}
//
// shapes
//
void
nsRenderingContext::DrawLine(const nsPoint& aStartPt, const nsPoint& aEndPt)
{
DrawLine(aStartPt.x, aStartPt.y, aEndPt.x, aEndPt.y);
}
void
nsRenderingContext::DrawLine(nscoord aX0, nscoord aY0,
nscoord aX1, nscoord aY1)
{
gfxPoint p0 = gfxPoint(FROM_TWIPS(aX0), FROM_TWIPS(aY0));
gfxPoint p1 = gfxPoint(FROM_TWIPS(aX1), FROM_TWIPS(aY1));
// we can't draw thick lines with gfx, so we always assume we want
// pixel-aligned lines if the rendering context is at 1.0 scale
gfxMatrix savedMatrix = mThebes->CurrentMatrix();
if (!savedMatrix.HasNonTranslation()) {
p0 = mThebes->UserToDevice(p0);
p1 = mThebes->UserToDevice(p1);
p0.Round();
p1.Round();
mThebes->IdentityMatrix();
mThebes->NewPath();
// snap straight lines
if (p0.x == p1.x) {
mThebes->Line(p0 + gfxPoint(0.5, 0),
p1 + gfxPoint(0.5, 0));
} else if (p0.y == p1.y) {
mThebes->Line(p0 + gfxPoint(0, 0.5),
p1 + gfxPoint(0, 0.5));
} else {
mThebes->Line(p0, p1);
}
mThebes->Stroke();
mThebes->SetMatrix(savedMatrix);
} else {
mThebes->NewPath();
mThebes->Line(p0, p1);
mThebes->Stroke();
}
}
void
nsRenderingContext::DrawRect(const nsRect& aRect)
{
mThebes->NewPath();
mThebes->Rectangle(GFX_RECT_FROM_TWIPS_RECT(aRect), true);
mThebes->Stroke();
}
void
nsRenderingContext::DrawRect(nscoord aX, nscoord aY,
nscoord aWidth, nscoord aHeight)
{
DrawRect(nsRect(aX, aY, aWidth, aHeight));
}
/* Clamp r to (0,0) (2^23,2^23)
* these are to be device coordinates.
*
* Returns false if the rectangle is completely out of bounds,
* true otherwise.
*
* This function assumes that it will be called with a rectangle being
* drawn into a surface with an identity transformation matrix; that
* is, anything above or to the left of (0,0) will be offscreen.
*
* First it checks if the rectangle is entirely beyond
* CAIRO_COORD_MAX; if so, it can't ever appear on the screen --
* false is returned.
*
* Then it shifts any rectangles with x/y < 0 so that x and y are = 0,
* and adjusts the width and height appropriately. For example, a
* rectangle from (0,-5) with dimensions (5,10) will become a
* rectangle from (0,0) with dimensions (5,5).
*
* If after negative x/y adjustment to 0, either the width or height
* is negative, then the rectangle is completely offscreen, and
* nothing is drawn -- false is returned.
*
* Finally, if x+width or y+height are greater than CAIRO_COORD_MAX,
* the width and height are clamped such x+width or y+height are equal
* to CAIRO_COORD_MAX, and true is returned.
*/
#define CAIRO_COORD_MAX (double(0x7fffff))
static bool
ConditionRect(gfxRect& r) {
// if either x or y is way out of bounds;
// note that we don't handle negative w/h here
if (r.X() > CAIRO_COORD_MAX || r.Y() > CAIRO_COORD_MAX)
return false;
if (r.X() < 0.0) {
r.width += r.X();
if (r.width < 0.0)
return false;
r.x = 0.0;
}
if (r.XMost() > CAIRO_COORD_MAX) {
r.width = CAIRO_COORD_MAX - r.X();
}
if (r.Y() < 0.0) {
r.height += r.Y();
if (r.Height() < 0.0)
return false;
r.y = 0.0;
}
if (r.YMost() > CAIRO_COORD_MAX) {
r.height = CAIRO_COORD_MAX - r.Y();
}
return true;
}
void
nsRenderingContext::FillRect(const nsRect& aRect)
{
gfxRect r(GFX_RECT_FROM_TWIPS_RECT(aRect));
/* Clamp coordinates to work around a design bug in cairo */
nscoord bigval = (nscoord)(CAIRO_COORD_MAX*mP2A);
if (aRect.width > bigval ||
aRect.height > bigval ||
aRect.x < -bigval ||
aRect.x > bigval ||
aRect.y < -bigval ||
aRect.y > bigval)
{
gfxMatrix mat = mThebes->CurrentMatrix();
r = mat.Transform(r);
if (!ConditionRect(r))
return;
mThebes->IdentityMatrix();
mThebes->NewPath();
mThebes->Rectangle(r, true);
mThebes->Fill();
mThebes->SetMatrix(mat);
}
mThebes->NewPath();
mThebes->Rectangle(r, true);
mThebes->Fill();
}
void
nsRenderingContext::FillRect(nscoord aX, nscoord aY,
nscoord aWidth, nscoord aHeight)
{
FillRect(nsRect(aX, aY, aWidth, aHeight));
}
void
nsRenderingContext::InvertRect(const nsRect& aRect)
{
gfxContext::GraphicsOperator lastOp = mThebes->CurrentOperator();
mThebes->SetOperator(gfxContext::OPERATOR_XOR);
FillRect(aRect);
mThebes->SetOperator(lastOp);
}
void
nsRenderingContext::DrawEllipse(nscoord aX, nscoord aY,
nscoord aWidth, nscoord aHeight)
{
mThebes->NewPath();
mThebes->Ellipse(gfxPoint(FROM_TWIPS(aX) + FROM_TWIPS(aWidth)/2.0,
FROM_TWIPS(aY) + FROM_TWIPS(aHeight)/2.0),
gfxSize(FROM_TWIPS(aWidth),
FROM_TWIPS(aHeight)));
mThebes->Stroke();
}
void
nsRenderingContext::FillEllipse(const nsRect& aRect)
{
FillEllipse(aRect.x, aRect.y, aRect.width, aRect.height);
}
void
nsRenderingContext::FillEllipse(nscoord aX, nscoord aY,
nscoord aWidth, nscoord aHeight)
{
mThebes->NewPath();
mThebes->Ellipse(gfxPoint(FROM_TWIPS(aX) + FROM_TWIPS(aWidth)/2.0,
FROM_TWIPS(aY) + FROM_TWIPS(aHeight)/2.0),
gfxSize(FROM_TWIPS(aWidth),
FROM_TWIPS(aHeight)));
mThebes->Fill();
}
void
nsRenderingContext::FillPolygon(const nsPoint twPoints[], int32_t aNumPoints)
{
if (aNumPoints == 0)
return;
nsAutoArrayPtr<gfxPoint> pxPoints(new gfxPoint[aNumPoints]);
for (int i = 0; i < aNumPoints; i++) {
pxPoints[i].x = FROM_TWIPS(twPoints[i].x);
pxPoints[i].y = FROM_TWIPS(twPoints[i].y);
}
mThebes->NewPath();
mThebes->Polygon(pxPoints, aNumPoints);
mThebes->Fill();
}
//
// text
//
void
nsRenderingContext::SetTextRunRTL(bool aIsRTL)
{
mFontMetrics->SetTextRunRTL(aIsRTL);
}
void
nsRenderingContext::SetFont(nsFontMetrics *aFontMetrics)
{
mFontMetrics = aFontMetrics;
}
int32_t
nsRenderingContext::GetMaxChunkLength()
{
if (!mFontMetrics)
return 1;
return NS_MIN(mFontMetrics->GetMaxStringLength(), MAX_GFX_TEXT_BUF_SIZE);
}
nscoord
nsRenderingContext::GetWidth(char aC)
{
if (aC == ' ' && mFontMetrics) {
return mFontMetrics->SpaceWidth();
}
return GetWidth(&aC, 1);
}
nscoord
nsRenderingContext::GetWidth(PRUnichar aC)
{
return GetWidth(&aC, 1);
}
nscoord
nsRenderingContext::GetWidth(const nsString& aString)
{
return GetWidth(aString.get(), aString.Length());
}
nscoord
nsRenderingContext::GetWidth(const char* aString)
{
return GetWidth(aString, strlen(aString));
}
nscoord
nsRenderingContext::GetWidth(const char* aString, uint32_t aLength)
{
uint32_t maxChunkLength = GetMaxChunkLength();
nscoord width = 0;
while (aLength > 0) {
int32_t len = FindSafeLength(aString, aLength, maxChunkLength);
width += mFontMetrics->GetWidth(aString, len, this);
aLength -= len;
aString += len;
}
return width;
}
nscoord
nsRenderingContext::GetWidth(const PRUnichar *aString, uint32_t aLength)
{
uint32_t maxChunkLength = GetMaxChunkLength();
nscoord width = 0;
while (aLength > 0) {
int32_t len = FindSafeLength(aString, aLength, maxChunkLength);
width += mFontMetrics->GetWidth(aString, len, this);
aLength -= len;
aString += len;
}
return width;
}
nsBoundingMetrics
nsRenderingContext::GetBoundingMetrics(const PRUnichar* aString,
uint32_t aLength)
{
uint32_t maxChunkLength = GetMaxChunkLength();
int32_t len = FindSafeLength(aString, aLength, maxChunkLength);
// Assign directly in the first iteration. This ensures that
// negative ascent/descent can be returned and the left bearing
// is properly initialized.
nsBoundingMetrics totalMetrics
= mFontMetrics->GetBoundingMetrics(aString, len, this);
aLength -= len;
aString += len;
while (aLength > 0) {
len = FindSafeLength(aString, aLength, maxChunkLength);
nsBoundingMetrics metrics
= mFontMetrics->GetBoundingMetrics(aString, len, this);
totalMetrics += metrics;
aLength -= len;
aString += len;
}
return totalMetrics;
}
void
nsRenderingContext::DrawString(const char *aString, uint32_t aLength,
nscoord aX, nscoord aY)
{
uint32_t maxChunkLength = GetMaxChunkLength();
while (aLength > 0) {
int32_t len = FindSafeLength(aString, aLength, maxChunkLength);
mFontMetrics->DrawString(aString, len, aX, aY, this);
aLength -= len;
if (aLength > 0) {
nscoord width = mFontMetrics->GetWidth(aString, len, this);
aX += width;
aString += len;
}
}
}
void
nsRenderingContext::DrawString(const nsString& aString, nscoord aX, nscoord aY)
{
DrawString(aString.get(), aString.Length(), aX, aY);
}
void
nsRenderingContext::DrawString(const PRUnichar *aString, uint32_t aLength,
nscoord aX, nscoord aY)
{
uint32_t maxChunkLength = GetMaxChunkLength();
if (aLength <= maxChunkLength) {
mFontMetrics->DrawString(aString, aLength, aX, aY, this, this);
return;
}
bool isRTL = mFontMetrics->GetTextRunRTL();
// If we're drawing right to left, we must start at the end.
if (isRTL) {
aX += GetWidth(aString, aLength);
}
while (aLength > 0) {
int32_t len = FindSafeLength(aString, aLength, maxChunkLength);
nscoord width = mFontMetrics->GetWidth(aString, len, this);
if (isRTL) {
aX -= width;
}
mFontMetrics->DrawString(aString, len, aX, aY, this, this);
if (!isRTL) {
aX += width;
}
aLength -= len;
aString += len;
}
}
| sergecodd/FireFox-OS | B2G/gecko/gfx/src/nsRenderingContext.cpp | C++ | apache-2.0 | 15,100 |
/*
* Copyright 2021 Scheer PAS Schweiz AG
*
* 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 io.apiman.common.es.util.builder.index;
import static io.apiman.common.es.util.EsConstants.ES_MAPPING_TYPE_KEYWORD;
import static io.apiman.common.es.util.EsConstants.ES_MAPPING_TYPE_TEXT;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import java.util.Objects;
/**
* An Elasticsearch type entry
*
* @author Marc Savy {@literal <marc@blackparrotlabs.io>}
*/
public class EsTypeEntry implements AllowableFieldEntry {
private final String type;
private EsTypeEntry(EsPropertyBuilder builder) {
this.type = builder.type;
}
public String getType() {
return type;
}
public EsPropertyBuilder builder() {
return new EsPropertyBuilder();
}
@Override
public String getEntryType() {
return this.getClass().getSimpleName();
}
@Override
public boolean isKeyword() {
return ES_MAPPING_TYPE_KEYWORD.equalsIgnoreCase(type);
}
@Override
public boolean isKeywordMultiField() {
return false;
}
@JsonPOJOBuilder(withPrefix = "set")
public static final class EsPropertyBuilder {
private String type;
public EsPropertyBuilder() {
}
public EsPropertyBuilder setType(String type) {
this.type = type;
return this;
}
public EsTypeEntry build() {
Objects.requireNonNull(type, "Type must not be null");
return new EsTypeEntry(this);
}
}
}
| msavy/apiman | common/es/src/main/java/io/apiman/common/es/util/builder/index/EsTypeEntry.java | Java | apache-2.0 | 2,090 |
package io.cattle.platform.inator.unit;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.model.Account;
import io.cattle.platform.core.model.Service;
import io.cattle.platform.core.util.PortSpec;
import io.cattle.platform.inator.Inator;
import io.cattle.platform.inator.InatorContext;
import io.cattle.platform.inator.InstanceBindable;
import io.cattle.platform.inator.Result;
import io.cattle.platform.inator.Unit;
import io.cattle.platform.inator.UnitRef;
import io.cattle.platform.inator.deploy.DeploymentUnitInator;
import io.cattle.platform.inator.factory.InatorServices;
import io.cattle.platform.inator.lock.PortUnitLock;
import io.cattle.platform.inator.wrapper.DeploymentUnitWrapper;
import io.cattle.platform.object.util.ObjectUtils;
import io.cattle.platform.resource.pool.PooledResource;
import io.cattle.platform.resource.pool.PooledResourceOptions;
import io.cattle.platform.resource.pool.util.ResourcePoolConstants;
import io.cattle.platform.util.exception.ResourceExhaustionException;
import io.cattle.platform.util.type.CollectionUtils;
import io.github.ibuildthecloud.gdapi.exception.ClientVisibleException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PortUnit implements Unit, InstanceBindable {
String name;
String portNum;
InatorServices svc;
UnitRef ref;
public PortUnit(String name, int portNum, InatorServices svc) {
this.name = name;
this.portNum = Integer.toString(portNum);
this.svc = svc;
this.ref = new UnitRef("port/" + getSubOwner());
}
@Override
public Result scheduleActions(InatorContext context) {
return Result.good();
}
@Override
public Result define(InatorContext context, boolean desired) {
return Result.good();
}
@Override
public Collection<UnitRef> dependencies(InatorContext context) {
return Collections.emptyList();
}
@Override
public UnitRef getRef() {
return ref;
}
protected DeploymentUnitWrapper getDeploymentUnit(InatorContext context) {
Inator inator = context.getInator();
if (inator instanceof DeploymentUnitInator) {
return ((DeploymentUnitInator) inator).getUnit();
}
return null;
}
@Override
public Result remove(InatorContext context) {
Object owner = getOwner(getDeploymentUnit(context));
Account account = getAccount(new HashMap<>(), owner);
if (account == null) {
return Result.good();
}
svc.poolManager.releaseResource(account, owner, new PooledResourceOptions()
.withSubOwner(getSubOwner())
.withQualifier(ResourcePoolConstants.ENVIRONMENT_PORT));
return Result.good();
}
protected String getSubOwner() {
return name + "/" + portNum;
}
protected Account getAccount(Map<Long, Account> accounts, Object owner) {
Object accountId = ObjectUtils.getAccountId(owner);
if (accountId == null) {
return null;
}
if (!accounts.containsKey(accountId)) {
accounts.put(Long.valueOf(accountId.toString()), svc.objectManager.loadResource(Account.class, accountId.toString()));
}
return accounts.get(accountId);
}
protected Object getOwner(DeploymentUnitWrapper unit) {
Service service = svc.objectManager.loadResource(Service.class, unit.getServiceId());
if (service != null) {
return service;
}
return unit.getInternal();
}
@Override
public String getDisplayName() {
return String.format("randomport(%d)", getSubOwner());
}
public Account getClusterAccount(Account account, Map<Long, Account> clusterAccounts, Long clusterId) {
if (!clusterAccounts.containsKey(clusterId)) {
Account clusterAccount = svc.clusterDao.getOwnerAcccountForCluster(account.getClusterId());
if (clusterAccount != null) {
clusterAccounts.put(account.getClusterId(), clusterAccount);
}
}
return clusterAccounts.get(account.getClusterId());
}
@Override
public void bind(InatorContext context, Map<String, Object> instanceData) {
@SuppressWarnings("unchecked")
List<String> ports = (List<String>)CollectionUtils.toList(instanceData.get(InstanceConstants.FIELD_PORTS));
boolean changed = false;
int port = Integer.parseInt(portNum);
Map<Long, Account> clusterAccounts = new HashMap<>();
Map<Long, Account> accounts = new HashMap<>();
for (int i = 0 ; i < ports.size() ; i++) {
try {
PortSpec spec = new PortSpec(ports.get(i));
if (spec.getPublicPort() == null && spec.getPrivatePort() == port) {
Object owner = getOwner(getDeploymentUnit(context));
Account account = getAccount(accounts, owner);
Account clusterAccount = getClusterAccount(account, clusterAccounts, account.getClusterId());
PooledResource resource = svc.lockManager.lock(new PortUnitLock(account.getClusterId(), this), () -> {
return svc.poolManager.allocateOneResource(clusterAccount, owner,
new PooledResourceOptions()
.withSubOwner(getSubOwner())
.withQualifier(ResourcePoolConstants.ENVIRONMENT_PORT));
});
if (resource == null) {
throw new ResourceExhaustionException("Not enough environment ports");
}
spec.setPublicPort(Integer.parseInt(resource.getName()));
ports.set(i, spec.toSpec());
changed = true;
break;
}
} catch (ClientVisibleException e) {
}
}
if (changed) {
instanceData.put(InstanceConstants.FIELD_PORTS, ports);
}
}
}
| rancherio/cattle | modules/caas/backend/src/main/java/io/cattle/platform/inator/unit/PortUnit.java | Java | apache-2.0 | 6,187 |
package com.ctrip.zeus.auth.impl;
import com.ctrip.zeus.auth.util.AuthUserUtil;
import com.ctrip.zeus.auth.util.AuthUtil;
import com.ctrip.zeus.util.MessageUtil;
import com.netflix.config.DynamicPropertyFactory;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.AssertionImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Authenticate with ip.
* <p>
* User: mag
* Date: 4/21/2015
* Time: 3:00 PM
*/
public class IPAuthenticationFilter implements Filter {
private static final String IP_AUTHENTICATION_PREFIX = "ip.authentication";
private static final Logger logger = LoggerFactory.getLogger(IPAuthenticationFilter.class);
private DynamicPropertyFactory factory = DynamicPropertyFactory.getInstance();
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
final HttpServletResponse response = (HttpServletResponse) servletResponse;
//1. ip auth flag
if (!factory.getBooleanProperty("ip.authentication.filter.enable", true).get()) {
filterChain.doFilter(request, response);
return;
} else if (request.getAttribute(AuthUtil.AUTH_USER) != null) {
//2.already assert
filterChain.doFilter(request, response);
return;
}
//3. if the request is from in ip white list, then authenticate it using the ip white list.
String clientIP = MessageUtil.getClientIP(request);
String ipUser = getIpUser(IP_AUTHENTICATION_PREFIX, AuthUserUtil.getAuthUsers(), clientIP);
if (ipUser != null) {
logger.info("Authenticated by IP: " + clientIP + " Assigned userName:" + ipUser);
setAssertion(request, ipUser);
}
filterChain.doFilter(request, response);
}
private void setAssertion(HttpServletRequest request, String userName) {
Assertion assertion = new AssertionImpl(userName);
request.setAttribute(AuthUtil.AUTH_USER, userName);
request.setAttribute(AbstractCasFilter.CONST_CAS_ASSERTION, assertion);
final HttpSession session = request.getSession(false);
if (session != null) {
session.setAttribute(AbstractCasFilter.CONST_CAS_ASSERTION, assertion);
}
}
@Override
public void destroy() {
// nothing to do
}
private Map<String, String> parseIpUserStr(String ipConfig) {
Map<String, String> result = new HashMap<>();
if (ipConfig == null || ipConfig.isEmpty()) {
return result;
}
int subLen = 2;
String[] configs = ipConfig.split("#");
for (String config : configs) {
String[] parts = config.split("=", -1);
if (parts.length != subLen) {
logger.error("fail to parse {}", config);
continue;
}
String[] ips = parts[0].split(",");
String userName = parts[1];
for (String ip : ips) {
result.put(ip, userName);
}
}
return result;
}
private String getIpUser(String prefix, Set<String> types, String value) {
if (prefix == null || types == null || types.size() == 0 || value == null)
return null;
String typeValue;
for (String typeName : types) {
typeValue = factory.getStringProperty(prefix + "." + typeName, null).get();
if (typeValue != null && Arrays.asList(typeValue.split(",")).contains(value)) {
return typeName;
}
}
String defaultValue = factory.getStringProperty(prefix + ".default", null).get();
Map<String, String> valueKeyMap = parseIpUserStr(defaultValue);
for (Map.Entry entry : valueKeyMap.entrySet()) {
if (entry.getKey().equals(value))
return entry.getValue().toString();
}
return null;
}
}
| sdgdsffdsfff/zeus | slb/src/main/java/com/ctrip/zeus/auth/impl/IPAuthenticationFilter.java | Java | apache-2.0 | 4,654 |
/*
Copyright (C) 2012 Anthony Foster, https://github.com/aantthony/contextmenu (v0.1)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
(function (d, window) { "use strict";
var nativeSupport = false, //((d.createElement('body').contextMenu === null) && window.HTMLMenuItemElement !== undefined),
cmKey = nativeSupport ? 'contextMenu' : '_contextMenu', // Which attribute to use
menuNodeName = 'CMENU',
lastX, // Last position where root context menu was launched
lastY, // ''
mousedown_timeout, // The timer which in timeout ms, will set the overlay with display: false
overlay, // A div that covers the screen while contextmenus are visible
menustack, // Stack of menu nodes open. menustack[0] is root. Does not include preview
preview, // A menu node which is visible (due to hovering on a expandable menu(item))
timeout, // The time (ms) taken to fade out.
t, // The time of mousedown. Used to determine if it is a hold and relase menu.
preview_show_timer, // Menu previews don't show instantly, but a few hundred ms later.
holding = false, // Is the user doing a hold an release menu selection?
doneEvents = [],
toAppend = [], // The menus which should be appended to the body as soon as the document.body is created
old_contextmenu = window.contextmenu; // See: contextmenu.noConflict()
function nextTick(callback) {
setTimeout(callback, 0);
}
// Calculate the position of a dom node
function offset(obj) {
var curleft = 0,
curtop = 0;
if (obj.getClientRects) {
return obj.getClientRects()[0];
}
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
obj = obj.offsetParent;
} while (obj);
return {
left: curleft,
top: curtop
};
}
function html(n){
if(n.get) {
return n.get(0);
}
return n;
}
function hideMenu(menu, fade) {
if (fade) {
throw ("no need to fade");
}
menu.style.display = "none";
var launcher = menu.launcher;
if (launcher) {
launcher.removeAttribute("open");
}
}
// Remove the topmost context menu from the stack
function popmenu() {
var top = menustack.pop();
hideMenu(top);
return top;
}
// Context menu operation complete. Triggered by multiple things.
function mouseend() {
overlay.style.opacity = "0.0";
mousedown_timeout = setTimeout(function () {
while (menustack.length) {
popmenu(false);
}
overlay.style.display = "none";
overlay.style.opacity = "1.0";
triggerDoneEvents();
}, timeout);
}
function showMenu(menu) {
menu.style.display = "inline-block";
}
// Don't allow right clicking a context menu.
function menuoncontextmenu(e) {
// TODO: Right clicking an item should trigger a click event.
e.stopPropagation();
e.preventDefault();
}
// Search up the dom tree for the first ancestor with a given name.
function ancestor(name, node) {
if (node.nodeName === name) {
return node;
}
return ancestor(name, node.parentNode || {nodeName: name});
}
// menu.onmouseover
function onmouseover(e) {
//This event is also triggered after mouseover on submenu menuitems
var menu = ancestor(menuNodeName, e.target),
msl,
a,
i;
if (preview) {
if (preview === menu) {
// It is no longer a preview anymore. Push it onto the stack
menustack.push(menu);
preview = undefined;
return;
}
// This shouldn't be triggered because while previews will be hidden instantly.
console.error("SHOULD NOT BE A PREVIEW");
}
msl = menustack.length;
//Pop contextmenus until the focused menu is at the top.
a = menustack.indexOf(menu);
for (i = msl - 1; i > a; i--) {
popmenu();
}
}
// menu.onmousedown
function onmousedown(e) {
if (e.target.nodeName === menuNodeName) {
if (e.offsetX === 0) {
//Left 1px border shouldn't be included.
//Close the menu: (bubble event)
return;
}
}
e.stopPropagation();
e.preventDefault();
return false;
}
function onsubcontextmenuout(e) {
// Cancel any other previews
preview_show_timer = clearTimeout(preview_show_timer);
var menu = ancestor(menuNodeName, e.toElement);
// The user has deselected an expandable menu item.
// If the mouse has moved to the new menu, then we don't hide it:
if (menu === preview) {
return false;
}
// Othewise, we do.
if (preview) {
hideMenu(preview);
preview = undefined;
}
}
// menu.onmouseover: Open an expandable menu.
function onsubcontextmenu(e) {
//Create a preview
preview_show_timer = clearTimeout(preview_show_timer);
preview_show_timer = setTimeout(function () {
var menuitem = e.target,
menu = menuitem[cmKey],
pos;
// For later removing the [open] attribute (for styling)
menu.launcher = menuitem;
menuitem.setAttribute("open", true);
if (preview && preview !== menu) {
hideMenu(preview);
}
preview = menu;
pos = offset(menuitem);
menu.style.top = Math.max(pos.top - 5, 0) + "px";
menu.style.left = (pos.left + pos.width - 1) + "px";
showMenu(menu);
}, 200);
// Don't stop propagation, the event bubbles to the <menu /> mouseover handler,
// which will hide any dead contextmenus
}
function appendToOverlay(menu) {
if (overlay) {
overlay.appendChild(menu);
} else {
toAppend.push(menu);
}
}
// Adds javascript code, so it works without native html5 contextmenu support
function prepareMenu(menu) {
var p = menu.parentNode,
clone;
menu.addEventListener("mouseover", onmouseover, false);
menu.addEventListener("mousedown", onmousedown);
menu.addEventListener("contextmenu", menuoncontextmenu);
if (p.nodeName === menuNodeName) {
// If it is a menu within a menu, instead make it a menu which points to another menu.
// It would be better to keep it as menu > menu ...,
// but styling became too difficult so menu > menu s are replaced with menuitem.submenu
// And the menu > menu is moved to overlay > menu, and is set as the contextMenu property
clone = d.createElement("menuitem");
menu.classList.add("submenu");
clone.className = menu.className;
clone.setAttribute("label", menu.getAttribute("label"));
clone[cmKey] = menu;
clone.addEventListener("mouseover", onsubcontextmenu);
clone.addEventListener("mouseout", onsubcontextmenuout);
p.replaceChild(clone, menu);
appendToOverlay(menu);
} else {
p.removeChild(menu);
appendToOverlay(menu);
}
}
function initContextMenu(menu, x, y) {
t = new Date();
menustack.push(menu);
menu.style.top = Math.max(y - 5, 0) + "px";
menu.style.left = x + "px";
showMenu(menu);
overlay.style.display = "block";
holding = false;
// Make sure contextmenu stays within window bounds.
var right = x + menu.offsetWidth;
var bottom = y + menu.offsetHeight;
var bodyHeight = document.body.offsetHeight;
var bodyWidth = document.body.offsetWidth;
if (bottom > bodyHeight) {
menu.style.top = (y - (bottom - bodyHeight)) + "px";
}
if (right > bodyWidth) {
menu.style.left = (x - (right - bodyWidth)) + "px";
}
}
// Context menu sheets are activated through buttons instead of right clicks.
function oncontextsheet(e, menu, button) {
var pos;
if (button === undefined) {
button = e.target;
}
pos = offset(button);
if (menu === undefined) {
menu = contextMenufor(button);
}
//initContextMenu(menu, pos.left, pos.top + pos.height + 8);
initContextMenu(menu, pos.left, pos.top + 28);
if (e) {
e.preventDefault();
e.stopPropagation();
}
holding = true;
return false;
}
function oncontextsheetbtnup(e){
oncontextsheet(e);
holding = false;
}
// Finds the menu element associated with an element. (Searchs up the dom tree)
function contextMenufor(node) {
if (!node || !node.hasAttribute) {
return;
}
if (node[cmKey]) {
return node[cmKey];
}
if (node.hasAttribute("contextmenu")) {
var node = d.getElementById(node.getAttribute("contextmenu"));
node[cmKey] = node;
return node;
}
return contextMenufor(node.parentNode);
}
function simulateClickEvent(elm, e) {
var evt;
if (document.createEvent) {
evt = document.createEvent("MouseEvents");
}
if (elm && elm.dispatchEvent && evt && evt.initMouseEvent) {
//Disgusing API:
evt.initMouseEvent(
"click",
true, // Click events bubble
true, // And they can be cancelled
document.defaultView,
1, //Single click
e.screenX,
e.screenY,
e.clientX,
e.clientY,
false, // Don't apply any key modifiers
false,
false,
false,
0, // 0 - left, 1 - middle, 2 - right
null //Single target
);
elm.dispatchEvent(evt);
}
}
// ([contextmenu]).oncontextmenu
function oncontextmenu(e) {
var menu = contextMenufor(e.target),
x = e.clientX,
y = e.clientY;
initContextMenu(menu, e.clientX, e.clientY);
holding = true;
lastX = x;
lastY = y;
e.preventDefault();
e.stopPropagation();
return false;
}
function triggerDoneEvents() {
doneEvents.forEach(function (f) {
try{
f();
} catch(ex) {
setTimeout(function (){
throw ex;
}, 0);
}
});
doneEvents = [];
}
function inititalize() {
menustack = [];
overlay = d.createElement("div");
// Style:
var os_code = "osx10_7",
mouseup_wait_for_me = 0;
if (/Mac/.test(navigator.userAgent)) {
os_code = "osx10_7";
} else if (/Win/.test(navigator.userAgent)) {
os_code = "win7";
}
d.body.classList.add(os_code);
overlay.className = "_contextmenu_screen_";
timeout = 150;
t = 0;
d.body.appendChild(overlay);
overlay.addEventListener("mousedown", function (e) {
mouseend(e);
});
overlay.addEventListener("mouseup", function (e) {
if (mouseup_wait_for_me) {
return;
}
var menuitem = e.target;
if (menuitem.nodeName === "MENUITEM") {
if (menuitem[cmKey]) {
return false;
}
if (holding) {
// When doing a hold down and release style selection, a click event isn't
// automatticaly triggered by the browser
simulateClickEvent(menuitem, e);
}
}
if (new Date() - t < 300) {
holding = false;
return;
}
if (menuitem.nodeName === "MENUITEM") {
//Click animation.
setTimeout(function () {
menuitem.style.background = "white";
setTimeout(function () {
menuitem.style.background = "";
setTimeout(function () {
mouseend(e);
}, 30);
}, 80);
}, 10);
}
});
// Prevent scrolling while context menus are active
overlay.addEventListener("mousewheel", function (e) {
e.preventDefault();
e.stopPropagation();
return false;
}, true);
// Attempt to begin another context menu while already in a context menu.
overlay.addEventListener("contextmenu", function (e) {
// Rememeber that the overlay covers up all other elements which
// may have a contextmenu associate with them.
overlay.style.display = "none";
var node = d.elementFromPoint(e.clientX, e.clientY),
menu = contextMenufor(node),
x,
y,
dx,
dy;
if (menu) {
overlay.style.display = "block";
clearTimeout(mousedown_timeout);
e.preventDefault();
if (menustack[0] === menu) {
//Same menu:
x = e.clientX;
y = e.clientY;
dx = x - lastX;
dy = y - lastY;
lastX = x;
lastY = y;
// If the mouse hasn't moved much, then ignore it.
// This was probably an attempt to hide the context menu,
// rather than initate another of exactly the same type.
if (dx * dx + dy * dy < 50) {
overlay.style.opacity = "1.0";
overlay.style.display = "block";
clearTimeout(mousedown_timeout);
nextTick(mouseend);
return;
}
}
// The mouseup event will attempt to hide all context menus.
// Temporarily disable it:
mouseup_wait_for_me++;
setTimeout(function () {
while (menustack.length) {
var m = menustack.pop();
hideMenu(m);
}
overlay.style.display = "none";
overlay.style.opacity = "1.0";
overlay.style.display = "block";
nextTick(function () {
mouseup_wait_for_me--;
initContextMenu(menu, e.clientX, e.clientY);
});
}, timeout);
return false;
}
overlay.style.opacity = "1.0";
overlay.style.display = "block";
clearTimeout(mousedown_timeout);
nextTick(mouseend);
});
overlay.addEventListener("mouseover", function (e) {
if (e.target !== overlay) {
return;
}
//Hide preview menu.
preview_show_timer = clearTimeout(preview_show_timer);
if (preview) {
hideMenu(preview);
preview = undefined;
}
});
}
function attachEventsToAllMenus() {
var menus_dom = d.getElementsByTagName(menuNodeName),
i,
l,
menus = [];
// Build an array, since 'NodeListPrototype's update themselves while iterating.
for (i = 0, l = menus_dom.length; i < l; i++) {
menus[i] = menus_dom[i];
}
for (i = 0, l = menus.length; i < l; i++) {
prepareMenu(menus[i]);
}
}
function hookUpContextMenus() {
var linkers = d.querySelectorAll("[contextmenu]"),
element,
i,
l;
for (i = 0, l = linkers.length; i < l; i++) {
element = linkers[i];
element[cmKey] = d.getElementById(element.getAttribute("contextmenu"))
if (element.nodeName === "INPUT") {
element.addEventListener("mouseup", oncontextsheetbtnup);
element.addEventListener("contextmenu", oncontextsheet);
} else {
element.addEventListener("contextmenu", oncontextmenu);
}
}
}
function buildMenu(x) {
var menu = d.createElement(menuNodeName),
i,
l,
xi,
submenu,
menuitem;
menu.setAttribute("type", "context");
for (i = 0, l = x.length; i < l; i++) {
xi = x[i];
if (xi.children) {
submenu = buildMenu(xi.children);
submenu.setAttribute("label", xi.label);
menu.appendChild(submenu);
} else {
if (xi.hr) {
menuitem = d.createElement("hr");
} else {
menuitem = d.createElement("menuitem");
menuitem.setAttribute("label", xi.label);
if (xi.onclick) {
menuitem.onclick = xi.onclick;
}
if (xi.icon) {
menuitem.icon = xi.icon;
}
if(xi.checked) {
menuitem.setAttribute("checked", xi.checked ? "checked" : "");
}
var key;
for(key in xi) {
if(xi.hasOwnProperty(key)) {
if(['label', 'icon', 'hr','onclick', 'checked'].indexOf(key) === -1) {
menuitem.dataset[key] = xi[key];
}
}
}
}
menu.appendChild(menuitem);
}
}
return menu;
}
// Main API:
function contextmenu(x) {
var menu = buildMenu(x),
submenus,
menus,
i,
l;
d.body.appendChild(menu);
if (nativeSupport) {
return menu;
}
submenus = menu.getElementsByTagName(menuNodeName);
menus = [menu];
for (i = 0, l = submenus.length; i < l; i++) {
menus.push(submenus[i]);
}
for (i = 0, l = menus.length; i < l; i++) {
prepareMenu(menus[i]);
}
return menu;
}
contextmenu.show = function (menu, x, y) {
if (nativeSupport) {
throw ("Not supported!");
}
if (typeof menu === "string") {
menu = d.getElementById(menu);
} else {
menu = html(menu);
}
if (typeof x === "number") {
initContextMenu(menu, x, y);
} else {
oncontextsheet(null, menu, html(x));
holding = false;
}
return this;
};
contextmenu.then = function (f) {
if(nativeSupport) {
f();
return;
}
doneEvents.push(f);
};
contextmenu.attach = function (element, menu) {
element = html(element);
menu = html(menu);
if(nativeSupport) {
menu.id = menu.id || (0 | 10000 * Math.random()).toString(30);
element.setAttribute("contextmenu", menu.id);
return;
}
element[cmKey] = menu;
if (element.nodeName === "INPUT" || element.nodeName === "BUTTON") {
element.addEventListener("mouseup", oncontextsheetbtnup);
// element.addEventListener("mousedown", oncontextsheet); css :hover doesn't work
element.addEventListener("contextmenu", oncontextsheet);
} else {
element.addEventListener("contextmenu", oncontextmenu);
}
};
contextmenu.noConflict = function () {
window.contextmenu = old_contextmenu;
return contextmenu;
};
if (!nativeSupport) {
window.addEventListener('load', function (e) {
inititalize();
attachEventsToAllMenus();
hookUpContextMenus();
var i;
for (i = 0; i < toAppend.length; i++) {
overlay.appendChild(toAppend[i]);
}
})
}
if (typeof define === "function" && define.amd) {
define( "contextMenu", [], function () { return contextmenu; } );
} else if (typeof module !== 'undefined') {
module.exports = contextmenu;
} else {
window.contextmenu = contextmenu;
}
})(document, window);
| ms123s/simpl4-src | surface2/js/libs/contextmenu.js | JavaScript | apache-2.0 | 22,574 |
/*
* sxg's debug macro
*
* @2007-2008, China
* @song.xian-guang@hotmail.com (MSN Accounts)
*
* This code is licenced under the GPL
* Feel free to contact me if any questions
*
*/
#ifndef _SXG_DEBUG_H_
#define _SXG_DEBUG_H_
/* debug macro*/
#ifdef _sxg_debug_
# define sxg_debug(fmt, args...) printk("ksocket : %s, %s, %d, "fmt, __FILE__, __FUNCTION__, __LINE__, ##args)
#else
# define sxg_debug(fmt, args...)
#endif
#endif /* !_SXG_DEBUG_H_ */
| Seitran/ksocket | src/sxgdebug.h | C | apache-2.0 | 469 |
/**
* FreeRDP: A Remote Desktop Protocol Implementation
* Transport Layer Security
*
* Copyright 2011-2012 Marc-Andre Moreau <marcandre.moreau@gmail.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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <winpr/crt.h>
#include <winpr/string.h>
#include <winpr/sspi.h>
#include <winpr/ssl.h>
#include <winpr/stream.h>
#include <freerdp/utils/ringbuffer.h>
#include <freerdp/log.h>
#include <freerdp/crypto/tls.h>
#include "../core/tcp.h"
#include "opensslcompat.h"
#ifdef HAVE_POLL_H
#include <poll.h>
#endif
#ifdef HAVE_VALGRIND_MEMCHECK_H
#include <valgrind/memcheck.h>
#endif
#define TAG FREERDP_TAG("crypto")
/**
* Earlier Microsoft iOS RDP clients have sent a null or even double null
* terminated hostname in the SNI TLS extension.
* If the length indicator does not equal the hostname strlen OpenSSL
* will abort (see openssl:ssl/t1_lib.c).
* Here is a tcpdump segment of Microsoft Remote Desktop Client Version
* 8.1.7 running on an iPhone 4 with iOS 7.1.2 showing the transmitted
* SNI hostname TLV blob when connection to server "abcd":
* 00 name_type 0x00 (host_name)
* 00 06 length_in_bytes 0x0006
* 61 62 63 64 00 00 host_name "abcd\0\0"
*
* Currently the only (runtime) workaround is setting an openssl tls
* extension debug callback that sets the SSL context's servername_done
* to 1 which effectively disables the parsing of that extension type.
*
* Nowadays this workaround is not required anymore but still can be
* activated by adding the following define:
*
* #define MICROSOFT_IOS_SNI_BUG
*/
struct _BIO_RDP_TLS
{
SSL* ssl;
CRITICAL_SECTION lock;
};
typedef struct _BIO_RDP_TLS BIO_RDP_TLS;
static int bio_rdp_tls_write(BIO* bio, const char* buf, int size)
{
int error;
int status;
BIO_RDP_TLS* tls = (BIO_RDP_TLS*) BIO_get_data(bio);
if (!buf || !tls)
return 0;
BIO_clear_flags(bio, BIO_FLAGS_WRITE | BIO_FLAGS_READ | BIO_FLAGS_IO_SPECIAL);
EnterCriticalSection(&tls->lock);
status = SSL_write(tls->ssl, buf, size);
error = SSL_get_error(tls->ssl, status);
LeaveCriticalSection(&tls->lock);
if (status <= 0)
{
switch (error)
{
case SSL_ERROR_NONE:
BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
break;
case SSL_ERROR_WANT_WRITE:
BIO_set_flags(bio, BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY);
break;
case SSL_ERROR_WANT_READ:
BIO_set_flags(bio, BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY);
break;
case SSL_ERROR_WANT_X509_LOOKUP:
BIO_set_flags(bio, BIO_FLAGS_IO_SPECIAL);
BIO_set_retry_reason(bio, BIO_RR_SSL_X509_LOOKUP);
break;
case SSL_ERROR_WANT_CONNECT:
BIO_set_flags(bio, BIO_FLAGS_IO_SPECIAL);
BIO_set_retry_reason(bio, BIO_RR_CONNECT);
break;
case SSL_ERROR_SYSCALL:
BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
break;
case SSL_ERROR_SSL:
BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
break;
}
}
return status;
}
static int bio_rdp_tls_read(BIO* bio, char* buf, int size)
{
int error;
int status;
BIO_RDP_TLS* tls = (BIO_RDP_TLS*) BIO_get_data(bio);
if (!buf || !tls)
return 0;
BIO_clear_flags(bio, BIO_FLAGS_WRITE | BIO_FLAGS_READ | BIO_FLAGS_IO_SPECIAL);
EnterCriticalSection(&tls->lock);
status = SSL_read(tls->ssl, buf, size);
error = SSL_get_error(tls->ssl, status);
LeaveCriticalSection(&tls->lock);
if (status <= 0)
{
switch (error)
{
case SSL_ERROR_NONE:
BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
break;
case SSL_ERROR_WANT_READ:
BIO_set_flags(bio, BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY);
break;
case SSL_ERROR_WANT_WRITE:
BIO_set_flags(bio, BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY);
break;
case SSL_ERROR_WANT_X509_LOOKUP:
BIO_set_flags(bio, BIO_FLAGS_IO_SPECIAL);
BIO_set_retry_reason(bio, BIO_RR_SSL_X509_LOOKUP);
break;
case SSL_ERROR_WANT_ACCEPT:
BIO_set_flags(bio, BIO_FLAGS_IO_SPECIAL);
BIO_set_retry_reason(bio, BIO_RR_ACCEPT);
break;
case SSL_ERROR_WANT_CONNECT:
BIO_set_flags(bio, BIO_FLAGS_IO_SPECIAL);
BIO_set_retry_reason(bio, BIO_RR_CONNECT);
break;
case SSL_ERROR_SSL:
BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
break;
case SSL_ERROR_ZERO_RETURN:
BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
break;
case SSL_ERROR_SYSCALL:
BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
break;
}
}
#ifdef HAVE_VALGRIND_MEMCHECK_H
if (status > 0)
{
VALGRIND_MAKE_MEM_DEFINED(buf, status);
}
#endif
return status;
}
static int bio_rdp_tls_puts(BIO* bio, const char* str)
{
int size;
int status;
if (!str)
return 0;
size = strlen(str);
status = BIO_write(bio, str, size);
return status;
}
static int bio_rdp_tls_gets(BIO* bio, char* str, int size)
{
return 1;
}
static long bio_rdp_tls_ctrl(BIO* bio, int cmd, long num, void* ptr)
{
BIO* ssl_rbio;
BIO* ssl_wbio;
BIO* next_bio;
int status = -1;
BIO_RDP_TLS* tls = (BIO_RDP_TLS*) BIO_get_data(bio);
if (!tls)
return 0;
if (!tls->ssl && (cmd != BIO_C_SET_SSL))
return 0;
next_bio = BIO_next(bio);
ssl_rbio = tls->ssl ? SSL_get_rbio(tls->ssl) : NULL;
ssl_wbio = tls->ssl ? SSL_get_wbio(tls->ssl) : NULL;
switch (cmd)
{
case BIO_CTRL_RESET:
SSL_shutdown(tls->ssl);
if (SSL_in_connect_init(tls->ssl))
SSL_set_connect_state(tls->ssl);
else if (SSL_in_accept_init(tls->ssl))
SSL_set_accept_state(tls->ssl);
SSL_clear(tls->ssl);
if (next_bio)
status = BIO_ctrl(next_bio, cmd, num, ptr);
else if (ssl_rbio)
status = BIO_ctrl(ssl_rbio, cmd, num, ptr);
else
status = 1;
break;
case BIO_C_GET_FD:
status = BIO_ctrl(ssl_rbio, cmd, num, ptr);
break;
case BIO_CTRL_INFO:
status = 0;
break;
case BIO_CTRL_SET_CALLBACK:
status = 0;
break;
case BIO_CTRL_GET_CALLBACK:
*((ULONG_PTR*) ptr) = (ULONG_PTR) SSL_get_info_callback(tls->ssl);
status = 1;
break;
case BIO_C_SSL_MODE:
if (num)
SSL_set_connect_state(tls->ssl);
else
SSL_set_accept_state(tls->ssl);
status = 1;
break;
case BIO_CTRL_GET_CLOSE:
status = BIO_get_shutdown(bio);
break;
case BIO_CTRL_SET_CLOSE:
BIO_set_shutdown(bio, (int) num);
status = 1;
break;
case BIO_CTRL_WPENDING:
status = BIO_ctrl(ssl_wbio, cmd, num, ptr);
break;
case BIO_CTRL_PENDING:
status = SSL_pending(tls->ssl);
if (status == 0)
status = BIO_pending(ssl_rbio);
break;
case BIO_CTRL_FLUSH:
BIO_clear_retry_flags(bio);
status = BIO_ctrl(ssl_wbio, cmd, num, ptr);
BIO_copy_next_retry(bio);
status = 1;
break;
case BIO_CTRL_PUSH:
if (next_bio && (next_bio != ssl_rbio))
{
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
SSL_set_bio(tls->ssl, next_bio, next_bio);
CRYPTO_add(&(bio->next_bio->references), 1, CRYPTO_LOCK_BIO);
#else
/*
* We are going to pass ownership of next to the SSL object...but
* we don't own a reference to pass yet - so up ref
*/
BIO_up_ref(next_bio);
SSL_set_bio(tls->ssl, next_bio, next_bio);
#endif
}
status = 1;
break;
case BIO_CTRL_POP:
/* Only detach if we are the BIO explicitly being popped */
if (bio == ptr)
{
if (ssl_rbio != ssl_wbio)
BIO_free_all(ssl_wbio);
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
if (next_bio)
CRYPTO_add(&(bio->next_bio->references), -1, CRYPTO_LOCK_BIO);
tls->ssl->wbio = tls->ssl->rbio = NULL;
#else
/* OpenSSL 1.1: This will also clear the reference we obtained during push */
SSL_set_bio(tls->ssl, NULL, NULL);
#endif
}
status = 1;
break;
case BIO_C_GET_SSL:
if (ptr)
{
*((SSL**) ptr) = tls->ssl;
status = 1;
}
break;
case BIO_C_SET_SSL:
BIO_set_shutdown(bio, (int) num);
if (ptr)
{
tls->ssl = (SSL*) ptr;
ssl_rbio = SSL_get_rbio(tls->ssl);
ssl_wbio = SSL_get_wbio(tls->ssl);
}
if (ssl_rbio)
{
if (next_bio)
BIO_push(ssl_rbio, next_bio);
BIO_set_next(bio, ssl_rbio);
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
CRYPTO_add(&(ssl_rbio->references), 1, CRYPTO_LOCK_BIO);
#else
BIO_up_ref(ssl_rbio);
#endif
}
BIO_set_init(bio, 1);
status = 1;
break;
case BIO_C_DO_STATE_MACHINE:
BIO_clear_flags(bio, BIO_FLAGS_READ | BIO_FLAGS_WRITE | BIO_FLAGS_IO_SPECIAL);
BIO_set_retry_reason(bio, 0);
status = SSL_do_handshake(tls->ssl);
if (status <= 0)
{
switch (SSL_get_error(tls->ssl, status))
{
case SSL_ERROR_WANT_READ:
BIO_set_flags(bio, BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY);
break;
case SSL_ERROR_WANT_WRITE:
BIO_set_flags(bio, BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY);
break;
case SSL_ERROR_WANT_CONNECT:
BIO_set_flags(bio, BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY);
BIO_set_retry_reason(bio, BIO_get_retry_reason(next_bio));
break;
default:
BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
break;
}
}
break;
default:
status = BIO_ctrl(ssl_rbio, cmd, num, ptr);
break;
}
return status;
}
static int bio_rdp_tls_new(BIO* bio)
{
BIO_RDP_TLS* tls;
BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
if (!(tls = calloc(1, sizeof(BIO_RDP_TLS))))
return 0;
InitializeCriticalSectionAndSpinCount(&tls->lock, 4000);
BIO_set_data(bio, (void*) tls);
return 1;
}
static int bio_rdp_tls_free(BIO* bio)
{
BIO_RDP_TLS* tls;
if (!bio)
return 0;
tls = (BIO_RDP_TLS*) BIO_get_data(bio);
if (!tls)
return 0;
if (BIO_get_shutdown(bio))
{
if (BIO_get_init(bio) && tls->ssl)
{
SSL_shutdown(tls->ssl);
SSL_free(tls->ssl);
}
BIO_set_init(bio, 0);
BIO_set_flags(bio, 0);
}
DeleteCriticalSection(&tls->lock);
free(tls);
return 1;
}
static long bio_rdp_tls_callback_ctrl(BIO* bio, int cmd, bio_info_cb* fp)
{
int status = 0;
BIO_RDP_TLS* tls;
if (!bio)
return 0;
tls = (BIO_RDP_TLS*) BIO_get_data(bio);
if (!tls)
return 0;
switch (cmd)
{
case BIO_CTRL_SET_CALLBACK:
SSL_set_info_callback(tls->ssl, (void (*)(const SSL*, int, int)) fp);
status = 1;
break;
default:
status = BIO_callback_ctrl(SSL_get_rbio(tls->ssl), cmd, fp);
break;
}
return status;
}
#define BIO_TYPE_RDP_TLS 68
static BIO_METHOD* BIO_s_rdp_tls(void)
{
static BIO_METHOD* bio_methods = NULL;
if (bio_methods == NULL)
{
if (!(bio_methods = BIO_meth_new(BIO_TYPE_RDP_TLS, "RdpTls")))
return NULL;
BIO_meth_set_write(bio_methods, bio_rdp_tls_write);
BIO_meth_set_read(bio_methods, bio_rdp_tls_read);
BIO_meth_set_puts(bio_methods, bio_rdp_tls_puts);
BIO_meth_set_gets(bio_methods, bio_rdp_tls_gets);
BIO_meth_set_ctrl(bio_methods, bio_rdp_tls_ctrl);
BIO_meth_set_create(bio_methods, bio_rdp_tls_new);
BIO_meth_set_destroy(bio_methods, bio_rdp_tls_free);
BIO_meth_set_callback_ctrl(bio_methods, bio_rdp_tls_callback_ctrl);
}
return bio_methods;
}
static BIO* BIO_new_rdp_tls(SSL_CTX* ctx, int client)
{
BIO* bio;
SSL* ssl;
bio = BIO_new(BIO_s_rdp_tls());
if (!bio)
return NULL;
ssl = SSL_new(ctx);
if (!ssl)
{
BIO_free(bio);
return NULL;
}
if (client)
SSL_set_connect_state(ssl);
else
SSL_set_accept_state(ssl);
BIO_set_ssl(bio, ssl, BIO_CLOSE);
return bio;
}
static CryptoCert tls_get_certificate(rdpTls* tls, BOOL peer)
{
CryptoCert cert;
X509* remote_cert;
STACK_OF(X509) *chain;
if (peer)
remote_cert = SSL_get_peer_certificate(tls->ssl);
else
remote_cert = X509_dup(SSL_get_certificate(tls->ssl));
if (!remote_cert)
{
WLog_ERR(TAG, "failed to get the server TLS certificate");
return NULL;
}
cert = malloc(sizeof(*cert));
if (!cert)
{
X509_free(remote_cert);
return NULL;
}
cert->px509 = remote_cert;
/* Get the peer's chain. If it does not exist, we're setting NULL (clean data either way) */
chain = SSL_get_peer_cert_chain(tls->ssl);
cert->px509chain = chain;
return cert;
}
static void tls_free_certificate(CryptoCert cert)
{
X509_free(cert->px509);
free(cert);
}
#define TLS_SERVER_END_POINT "tls-server-end-point:"
static SecPkgContext_Bindings* tls_get_channel_bindings(X509* cert)
{
UINT32 CertificateHashLength;
BYTE* ChannelBindingToken;
UINT32 ChannelBindingTokenLength;
SEC_CHANNEL_BINDINGS* ChannelBindings;
SecPkgContext_Bindings* ContextBindings;
const size_t PrefixLength = strnlen(TLS_SERVER_END_POINT, ARRAYSIZE(TLS_SERVER_END_POINT));
BYTE CertificateHash[32] = { 0 };
X509_digest(cert, EVP_sha256(), CertificateHash, &CertificateHashLength);
ChannelBindingTokenLength = PrefixLength + CertificateHashLength;
ContextBindings = (SecPkgContext_Bindings*) calloc(1,
sizeof(SecPkgContext_Bindings));
if (!ContextBindings)
return NULL;
ContextBindings->BindingsLength = sizeof(SEC_CHANNEL_BINDINGS) +
ChannelBindingTokenLength;
ChannelBindings = (SEC_CHANNEL_BINDINGS*) calloc(1,
ContextBindings->BindingsLength);
if (!ChannelBindings)
goto out_free;
ContextBindings->Bindings = ChannelBindings;
ChannelBindings->cbApplicationDataLength = ChannelBindingTokenLength;
ChannelBindings->dwApplicationDataOffset = sizeof(SEC_CHANNEL_BINDINGS);
ChannelBindingToken = &((BYTE*)
ChannelBindings)[ChannelBindings->dwApplicationDataOffset];
memcpy(ChannelBindingToken, TLS_SERVER_END_POINT, PrefixLength);
memcpy(ChannelBindingToken + PrefixLength, CertificateHash, CertificateHashLength);
return ContextBindings;
out_free:
free(ContextBindings);
return NULL;
}
#if OPENSSL_VERSION_NUMBER >= 0x010000000L
static BOOL tls_prepare(rdpTls* tls, BIO* underlying, const SSL_METHOD* method,
int options, BOOL clientMode)
#else
static BOOL tls_prepare(rdpTls* tls, BIO* underlying, SSL_METHOD* method,
int options, BOOL clientMode)
#endif
{
rdpSettings* settings = tls->settings;
tls->ctx = SSL_CTX_new(method);
if (!tls->ctx)
{
WLog_ERR(TAG, "SSL_CTX_new failed");
return FALSE;
}
SSL_CTX_set_mode(tls->ctx,
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE);
SSL_CTX_set_options(tls->ctx, options);
SSL_CTX_set_read_ahead(tls->ctx, 1);
if (settings->AllowedTlsCiphers)
{
if (!SSL_CTX_set_cipher_list(tls->ctx, settings->AllowedTlsCiphers))
{
WLog_ERR(TAG, "SSL_CTX_set_cipher_list %s failed", settings->AllowedTlsCiphers);
return FALSE;
}
}
tls->bio = BIO_new_rdp_tls(tls->ctx, clientMode);
if (BIO_get_ssl(tls->bio, &tls->ssl) < 0)
{
WLog_ERR(TAG, "unable to retrieve the SSL of the connection");
return FALSE;
}
BIO_push(tls->bio, underlying);
tls->underlying = underlying;
return TRUE;
}
static int tls_do_handshake(rdpTls* tls, BOOL clientMode)
{
CryptoCert cert;
int verify_status;
do
{
#ifdef HAVE_POLL_H
int fd;
int status;
struct pollfd pollfds;
#elif !defined(_WIN32)
SOCKET fd;
int status;
fd_set rset;
struct timeval tv;
#else
HANDLE event;
DWORD status;
#endif
status = BIO_do_handshake(tls->bio);
if (status == 1)
break;
if (!BIO_should_retry(tls->bio))
return -1;
#ifndef _WIN32
/* we select() only for read even if we should test both read and write
* depending of what have blocked */
fd = BIO_get_fd(tls->bio, NULL);
if (fd < 0)
{
WLog_ERR(TAG, "unable to retrieve BIO fd");
return -1;
}
#else
BIO_get_event(tls->bio, &event);
if (!event)
{
WLog_ERR(TAG, "unable to retrieve BIO event");
return -1;
}
#endif
#ifdef HAVE_POLL_H
pollfds.fd = fd;
pollfds.events = POLLIN;
pollfds.revents = 0;
do
{
status = poll(&pollfds, 1, 10);
}
while ((status < 0) && (errno == EINTR));
#elif !defined(_WIN32)
FD_ZERO(&rset);
FD_SET(fd, &rset);
tv.tv_sec = 0;
tv.tv_usec = 10 * 1000; /* 10ms */
status = _select(fd + 1, &rset, NULL, NULL, &tv);
#else
status = WaitForSingleObject(event, 10);
#endif
#ifndef _WIN32
if (status < 0)
{
WLog_ERR(TAG, "error during select()");
return -1;
}
#else
if ((status != WAIT_OBJECT_0) && (status != WAIT_TIMEOUT))
{
WLog_ERR(TAG, "error during WaitForSingleObject(): 0x%08"PRIX32"", status);
return -1;
}
#endif
}
while (TRUE);
cert = tls_get_certificate(tls, clientMode);
if (!cert)
{
WLog_ERR(TAG, "tls_get_certificate failed to return the server certificate.");
return -1;
}
tls->Bindings = tls_get_channel_bindings(cert->px509);
if (!tls->Bindings)
{
WLog_ERR(TAG, "unable to retrieve bindings");
verify_status = -1;
goto out;
}
if (!crypto_cert_get_public_key(cert, &tls->PublicKey, &tls->PublicKeyLength))
{
WLog_ERR(TAG,
"crypto_cert_get_public_key failed to return the server public key.");
verify_status = -1;
goto out;
}
/* server-side NLA needs public keys (keys from us, the server) but no certificate verify */
verify_status = 1;
if (clientMode)
{
verify_status = tls_verify_certificate(tls, cert, tls->hostname, tls->port);
if (verify_status < 1)
{
WLog_ERR(TAG, "certificate not trusted, aborting.");
tls_send_alert(tls);
verify_status = 0;
}
}
out:
tls_free_certificate(cert);
return verify_status;
}
int tls_connect(rdpTls* tls, BIO* underlying)
{
int options = 0;
/**
* SSL_OP_NO_COMPRESSION:
*
* The Microsoft RDP server does not advertise support
* for TLS compression, but alternative servers may support it.
* This was observed between early versions of the FreeRDP server
* and the FreeRDP client, and caused major performance issues,
* which is why we're disabling it.
*/
#ifdef SSL_OP_NO_COMPRESSION
options |= SSL_OP_NO_COMPRESSION;
#endif
/**
* SSL_OP_TLS_BLOCK_PADDING_BUG:
*
* The Microsoft RDP server does *not* support TLS padding.
* It absolutely needs to be disabled otherwise it won't work.
*/
options |= SSL_OP_TLS_BLOCK_PADDING_BUG;
/**
* SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:
*
* Just like TLS padding, the Microsoft RDP server does not
* support empty fragments. This needs to be disabled.
*/
options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
/**
* disable SSLv2 and SSLv3
*/
options |= SSL_OP_NO_SSLv2;
options |= SSL_OP_NO_SSLv3;
if (!tls_prepare(tls, underlying, SSLv23_client_method(), options, TRUE))
return FALSE;
#if !defined(OPENSSL_NO_TLSEXT) && !defined(LIBRESSL_VERSION_NUMBER)
SSL_set_tlsext_host_name(tls->ssl, tls->hostname);
#endif
return tls_do_handshake(tls, TRUE);
}
#if defined(MICROSOFT_IOS_SNI_BUG) && !defined(OPENSSL_NO_TLSEXT) && !defined(LIBRESSL_VERSION_NUMBER)
static void tls_openssl_tlsext_debug_callback(SSL* s, int client_server,
int type, unsigned char* data, int len, void* arg)
{
if (type == TLSEXT_TYPE_server_name)
{
WLog_DBG(TAG, "Client uses SNI (extension disabled)");
s->servername_done = 2;
}
}
#endif
BOOL tls_accept(rdpTls* tls, BIO* underlying, rdpSettings* settings)
{
long options = 0;
BIO* bio;
RSA* rsa;
X509* x509;
/**
* SSL_OP_NO_SSLv2:
*
* We only want SSLv3 and TLSv1, so disable SSLv2.
* SSLv3 is used by, eg. Microsoft RDC for Mac OS X.
*/
options |= SSL_OP_NO_SSLv2;
/**
* SSL_OP_NO_COMPRESSION:
*
* The Microsoft RDP server does not advertise support
* for TLS compression, but alternative servers may support it.
* This was observed between early versions of the FreeRDP server
* and the FreeRDP client, and caused major performance issues,
* which is why we're disabling it.
*/
#ifdef SSL_OP_NO_COMPRESSION
options |= SSL_OP_NO_COMPRESSION;
#endif
/**
* SSL_OP_TLS_BLOCK_PADDING_BUG:
*
* The Microsoft RDP server does *not* support TLS padding.
* It absolutely needs to be disabled otherwise it won't work.
*/
options |= SSL_OP_TLS_BLOCK_PADDING_BUG;
/**
* SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:
*
* Just like TLS padding, the Microsoft RDP server does not
* support empty fragments. This needs to be disabled.
*/
options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
if (!tls_prepare(tls, underlying, SSLv23_server_method(), options, FALSE))
return FALSE;
if (settings->PrivateKeyFile)
{
bio = BIO_new_file(settings->PrivateKeyFile, "rb");
if (!bio)
{
WLog_ERR(TAG, "BIO_new_file failed for private key %s",
settings->PrivateKeyFile);
return FALSE;
}
}
else if (settings->PrivateKeyContent)
{
bio = BIO_new_mem_buf(settings->PrivateKeyContent,
strlen(settings->PrivateKeyContent));
if (!bio)
{
WLog_ERR(TAG, "BIO_new_mem_buf failed for private key");
return FALSE;
}
}
else
{
WLog_ERR(TAG, "no private key defined");
return FALSE;
}
rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL);
BIO_free(bio);
if (!rsa)
{
WLog_ERR(TAG, "invalid private key");
return FALSE;
}
if (SSL_use_RSAPrivateKey(tls->ssl, rsa) <= 0)
{
WLog_ERR(TAG, "SSL_CTX_use_RSAPrivateKey_file failed");
RSA_free(rsa);
return FALSE;
}
if (settings->CertificateFile)
{
bio = BIO_new_file(settings->CertificateFile, "rb");
if (!bio)
{
WLog_ERR(TAG, "BIO_new_file failed for certificate %s",
settings->CertificateFile);
return FALSE;
}
}
else if (settings->CertificateContent)
{
bio = BIO_new_mem_buf(settings->CertificateContent,
strlen(settings->CertificateContent));
if (!bio)
{
WLog_ERR(TAG, "BIO_new_mem_buf failed for certificate");
return FALSE;
}
}
else
{
WLog_ERR(TAG, "no certificate defined");
return FALSE;
}
x509 = PEM_read_bio_X509(bio, NULL, NULL, 0);
BIO_free(bio);
if (!x509)
{
WLog_ERR(TAG, "invalid certificate");
return FALSE;
}
if (SSL_use_certificate(tls->ssl, x509) <= 0)
{
WLog_ERR(TAG, "SSL_use_certificate_file failed");
X509_free(x509);
return FALSE;
}
#if defined(MICROSOFT_IOS_SNI_BUG) && !defined(OPENSSL_NO_TLSEXT) && !defined(LIBRESSL_VERSION_NUMBER)
SSL_set_tlsext_debug_callback(tls->ssl, tls_openssl_tlsext_debug_callback);
#endif
return tls_do_handshake(tls, FALSE) > 0;
}
BOOL tls_send_alert(rdpTls* tls)
{
if (!tls)
return FALSE;
if (!tls->ssl)
return TRUE;
/**
* FIXME: The following code does not work on OpenSSL > 1.1.0 because the
* SSL struct is opaqe now
*/
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
if (tls->alertDescription != TLS_ALERT_DESCRIPTION_CLOSE_NOTIFY)
{
/**
* OpenSSL doesn't really expose an API for sending a TLS alert manually.
*
* The following code disables the sending of the default "close notify"
* and then proceeds to force sending a custom TLS alert before shutting down.
*
* Manually sending a TLS alert is necessary in certain cases,
* like when server-side NLA results in an authentication failure.
*/
SSL_SESSION* ssl_session = SSL_get_session(tls->ssl);
SSL_CTX* ssl_ctx = SSL_get_SSL_CTX(tls->ssl);
SSL_set_quiet_shutdown(tls->ssl, 1);
if ((tls->alertLevel == TLS_ALERT_LEVEL_FATAL) && (ssl_session))
SSL_CTX_remove_session(ssl_ctx, ssl_session);
tls->ssl->s3->alert_dispatch = 1;
tls->ssl->s3->send_alert[0] = tls->alertLevel;
tls->ssl->s3->send_alert[1] = tls->alertDescription;
if (tls->ssl->s3->wbuf.left == 0)
tls->ssl->method->ssl_dispatch_alert(tls->ssl);
}
#endif
return TRUE;
}
int tls_write_all(rdpTls* tls, const BYTE* data, int length)
{
int status;
int offset = 0;
BIO* bio = tls->bio;
while (offset < length)
{
status = BIO_write(bio, &data[offset], length - offset);
if (status > 0)
{
offset += status;
}
else
{
if (!BIO_should_retry(bio))
return -1;
if (BIO_write_blocked(bio))
status = BIO_wait_write(bio, 100);
else if (BIO_read_blocked(bio))
status = BIO_wait_read(bio, 100);
else
USleep(100);
if (status < 0)
return -1;
}
}
return length;
}
int tls_set_alert_code(rdpTls* tls, int level, int description)
{
tls->alertLevel = level;
tls->alertDescription = description;
return 0;
}
BOOL tls_match_hostname(char* pattern, int pattern_length, char* hostname)
{
if (strlen(hostname) == pattern_length)
{
if (_strnicmp(hostname, pattern, pattern_length) == 0)
return TRUE;
}
if ((pattern_length > 2) && (pattern[0] == '*') && (pattern[1] == '.')
&& (((int) strlen(hostname)) >= pattern_length))
{
char* check_hostname = &hostname[strlen(hostname) - pattern_length + 1];
if (_strnicmp(check_hostname, &pattern[1], pattern_length - 1) == 0)
{
return TRUE;
}
}
return FALSE;
}
static BOOL is_redirected(rdpTls* tls)
{
rdpSettings* settings = tls->settings;
if (LB_NOREDIRECT & settings->RedirectionFlags)
return FALSE;
return settings->RedirectionFlags != 0;
}
static BOOL is_accepted(rdpTls* tls, const BYTE* pem, size_t length)
{
rdpSettings* settings = tls->settings;
char* AccpetedKey;
UINT32 AcceptedKeyLength;
if (tls->isGatewayTransport)
{
AccpetedKey = settings->GatewayAcceptedCert;
AcceptedKeyLength = settings->GatewayAcceptedCertLength;
}
else if (is_redirected(tls))
{
AccpetedKey = settings->RedirectionAcceptedCert;
AcceptedKeyLength = settings->RedirectionAcceptedCertLength;
}
else
{
AccpetedKey = settings->AcceptedCert;
AcceptedKeyLength = settings->AcceptedCertLength;
}
if (AcceptedKeyLength > 0)
{
if (AcceptedKeyLength == length)
{
if (memcmp(AccpetedKey, pem, AcceptedKeyLength) == 0)
return TRUE;
}
}
if (tls->isGatewayTransport)
{
free(settings->GatewayAcceptedCert);
settings->GatewayAcceptedCert = NULL;
settings->GatewayAcceptedCertLength = 0;
}
else if (is_redirected(tls))
{
free(settings->RedirectionAcceptedCert);
settings->RedirectionAcceptedCert = NULL;
settings->RedirectionAcceptedCertLength = 0;
}
else
{
free(settings->AcceptedCert);
settings->AcceptedCert = NULL;
settings->AcceptedCertLength = 0;
}
return FALSE;
}
static BOOL accept_cert(rdpTls* tls, BYTE* pem, UINT32 length)
{
rdpSettings* settings = tls->settings;
if (tls->isGatewayTransport)
{
settings->GatewayAcceptedCert = (char*)pem;
settings->GatewayAcceptedCertLength = length;
}
else if (is_redirected(tls))
{
settings->RedirectionAcceptedCert = (char*)pem;
settings->RedirectionAcceptedCertLength = length;
}
else
{
settings->AcceptedCert = (char*)pem;
settings->AcceptedCertLength = length;
}
return TRUE;
}
static BOOL tls_extract_pem(CryptoCert cert, BYTE** PublicKey, DWORD* PublicKeyLength)
{
BIO* bio;
int status;
size_t offset;
int length = 0;
BOOL rc = FALSE;
BYTE* pemCert = NULL;
if (!PublicKey || !PublicKeyLength)
return FALSE;
*PublicKey = NULL;
*PublicKeyLength = 0;
/**
* Don't manage certificates internally, leave it up entirely to the external client implementation
*/
bio = BIO_new(BIO_s_mem());
if (!bio)
{
WLog_ERR(TAG, "BIO_new() failure");
return FALSE;
}
status = PEM_write_bio_X509(bio, cert->px509);
if (status < 0)
{
WLog_ERR(TAG, "PEM_write_bio_X509 failure: %d", status);
goto fail;
}
offset = 0;
length = 2048;
pemCert = (BYTE*) malloc(length + 1);
if (!pemCert)
{
WLog_ERR(TAG, "error allocating pemCert");
goto fail;
}
status = BIO_read(bio, pemCert, length);
if (status < 0)
{
WLog_ERR(TAG, "failed to read certificate");
goto fail;
}
offset += status;
while (offset >= length)
{
int new_len;
BYTE* new_cert;
new_len = length * 2;
new_cert = (BYTE*) realloc(pemCert, new_len + 1);
if (!new_cert)
goto fail;
length = new_len;
pemCert = new_cert;
status = BIO_read(bio, &pemCert[offset], length - offset);
if (status < 0)
break;
offset += status;
}
if (status < 0)
{
WLog_ERR(TAG, "failed to read certificate");
goto fail;
}
length = offset;
pemCert[length] = '\0';
*PublicKey = pemCert;
*PublicKeyLength = length;
rc = TRUE;
fail:
if (!rc)
free(pemCert);
BIO_free(bio);
return rc;
}
int tls_verify_certificate(rdpTls* tls, CryptoCert cert, char* hostname,
int port)
{
int match;
int index;
char* common_name = NULL;
int common_name_length = 0;
char** dns_names = 0;
int dns_names_count = 0;
int* dns_names_lengths = NULL;
BOOL certificate_status;
BOOL hostname_match = FALSE;
BOOL verification_status = FALSE;
rdpCertificateData* certificate_data;
freerdp* instance = (freerdp*) tls->settings->instance;
DWORD length;
BYTE* pemCert;
if (!tls_extract_pem(cert, &pemCert, &length))
return -1;
/* Check, if we already accepted this key. */
if (is_accepted(tls, pemCert, length))
{
free(pemCert);
return 1;
}
if (tls->settings->ExternalCertificateManagement)
{
int status = -1;
if (instance->VerifyX509Certificate)
status = instance->VerifyX509Certificate(instance, pemCert, length, hostname,
port, tls->isGatewayTransport | is_redirected(tls) ? 2 : 0);
else
WLog_ERR(TAG, "No VerifyX509Certificate callback registered!");
if (status > 0)
{
accept_cert(tls, pemCert, length);
}
else if (status < 0)
{
WLog_ERR(TAG, "VerifyX509Certificate failed: (length = %d) status: [%d] %s",
length, status, pemCert);
free(pemCert);
return -1;
}
else
free(pemCert);
return (status == 0) ? 0 : 1;
}
/* ignore certificate verification if user explicitly required it (discouraged) */
if (tls->settings->IgnoreCertificate)
{
free(pemCert);
return 1; /* success! */
}
if (!tls->isGatewayTransport && tls->settings->AuthenticationLevel == 0)
{
free(pemCert);
return 1; /* success! */
}
/* if user explicitly specified a certificate name, use it instead of the hostname */
if (!tls->isGatewayTransport && tls->settings->CertificateName)
hostname = tls->settings->CertificateName;
/* attempt verification using OpenSSL and the ~/.freerdp/certs certificate store */
certificate_status = x509_verify_certificate(cert,
tls->certificate_store->path);
/* verify certificate name match */
certificate_data = crypto_get_certificate_data(cert->px509, hostname, port);
/* extra common name and alternative names */
common_name = crypto_cert_subject_common_name(cert->px509, &common_name_length);
dns_names = crypto_cert_get_dns_names(cert->px509, &dns_names_count,
&dns_names_lengths);
/* compare against common name */
if (common_name)
{
if (tls_match_hostname(common_name, common_name_length, hostname))
hostname_match = TRUE;
}
/* compare against alternative names */
if (dns_names)
{
for (index = 0; index < dns_names_count; index++)
{
if (tls_match_hostname(dns_names[index], dns_names_lengths[index], hostname))
{
hostname_match = TRUE;
break;
}
}
}
/* if the certificate is valid and the certificate name matches, verification succeeds */
if (certificate_status && hostname_match)
verification_status = TRUE; /* success! */
/* verification could not succeed with OpenSSL, use known_hosts file and prompt user for manual verification */
if (!certificate_status || !hostname_match)
{
char* issuer;
char* subject;
char* fingerprint;
DWORD accept_certificate = 0;
issuer = crypto_cert_issuer(cert->px509);
subject = crypto_cert_subject(cert->px509);
fingerprint = crypto_cert_fingerprint(cert->px509);
/* search for matching entry in known_hosts file */
match = certificate_data_match(tls->certificate_store, certificate_data);
if (match == 1)
{
/* no entry was found in known_hosts file, prompt user for manual verification */
if (!hostname_match)
tls_print_certificate_name_mismatch_error(
hostname, port,
common_name, dns_names,
dns_names_count);
/* Automatically accept certificate on first use */
if (tls->settings->AutoAcceptCertificate)
{
WLog_INFO(TAG, "No certificate stored, automatically accepting.");
accept_certificate = 1;
}
else if (instance->VerifyCertificate)
{
accept_certificate = instance->VerifyCertificate(
instance, common_name,
subject, issuer,
fingerprint, !hostname_match);
}
switch (accept_certificate)
{
case 1:
/* user accepted certificate, add entry in known_hosts file */
verification_status = certificate_data_print(tls->certificate_store,
certificate_data);
break;
case 2:
/* user did accept temporaty, do not add to known hosts file */
verification_status = TRUE;
break;
default:
/* user did not accept, abort and do not add entry in known_hosts file */
verification_status = FALSE; /* failure! */
break;
}
}
else if (match == -1)
{
char* old_subject = NULL;
char* old_issuer = NULL;
char* old_fingerprint = NULL;
/* entry was found in known_hosts file, but fingerprint does not match. ask user to use it */
tls_print_certificate_error(hostname, port, fingerprint,
tls->certificate_store->file);
if (!certificate_get_stored_data(tls->certificate_store,
certificate_data, &old_subject,
&old_issuer, &old_fingerprint))
WLog_WARN(TAG, "Failed to get certificate entry for %s:%d",
hostname, port);
if (instance->VerifyChangedCertificate)
{
accept_certificate = instance->VerifyChangedCertificate(
instance, common_name, subject, issuer,
fingerprint, old_subject, old_issuer,
old_fingerprint);
}
free(old_subject);
free(old_issuer);
free(old_fingerprint);
switch (accept_certificate)
{
case 1:
/* user accepted certificate, add entry in known_hosts file */
verification_status = certificate_data_replace(tls->certificate_store,
certificate_data);
break;
case 2:
/* user did accept temporaty, do not add to known hosts file */
verification_status = TRUE;
break;
default:
/* user did not accept, abort and do not add entry in known_hosts file */
verification_status = FALSE; /* failure! */
break;
}
}
else if (match == 0)
verification_status = TRUE; /* success! */
free(issuer);
free(subject);
free(fingerprint);
}
certificate_data_free(certificate_data);
free(common_name);
if (dns_names)
crypto_cert_dns_names_free(dns_names_count, dns_names_lengths,
dns_names);
if (verification_status > 0)
{
accept_cert(tls, pemCert, length);
}
else
{
free(pemCert);
}
return (verification_status == 0) ? 0 : 1;
}
void tls_print_certificate_error(char* hostname, UINT16 port, char* fingerprint,
char* hosts_file)
{
WLog_ERR(TAG, "The host key for %s:%"PRIu16" has changed", hostname, port);
WLog_ERR(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
WLog_ERR(TAG, "@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @");
WLog_ERR(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
WLog_ERR(TAG, "IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
WLog_ERR(TAG,
"Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
WLog_ERR(TAG, "It is also possible that a host key has just been changed.");
WLog_ERR(TAG, "The fingerprint for the host key sent by the remote host is%s",
fingerprint);
WLog_ERR(TAG, "Please contact your system administrator.");
WLog_ERR(TAG, "Add correct host key in %s to get rid of this message.",
hosts_file);
WLog_ERR(TAG,
"Host key for %s has changed and you have requested strict checking.",
hostname);
WLog_ERR(TAG, "Host key verification failed.");
}
void tls_print_certificate_name_mismatch_error(char* hostname, UINT16 port,
char* common_name, char** alt_names,
int alt_names_count)
{
int index;
assert(NULL != hostname);
WLog_ERR(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
WLog_ERR(TAG, "@ WARNING: CERTIFICATE NAME MISMATCH! @");
WLog_ERR(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
WLog_ERR(TAG, "The hostname used for this connection (%s:%"PRIu16") ",
hostname, port);
WLog_ERR(TAG, "does not match %s given in the certificate:",
alt_names_count < 1 ? "the name" : "any of the names");
WLog_ERR(TAG, "Common Name (CN):");
WLog_ERR(TAG, "\t%s", common_name ? common_name : "no CN found in certificate");
if (alt_names_count > 0)
{
assert(NULL != alt_names);
WLog_ERR(TAG, "Alternative names:");
for (index = 0; index < alt_names_count; index++)
{
assert(alt_names[index]);
WLog_ERR(TAG, "\t %s", alt_names[index]);
}
}
WLog_ERR(TAG, "A valid certificate for the wrong name should NOT be trusted!");
}
rdpTls* tls_new(rdpSettings* settings)
{
rdpTls* tls;
tls = (rdpTls*) calloc(1, sizeof(rdpTls));
if (!tls)
return NULL;
tls->settings = settings;
if (!settings->ServerMode)
{
tls->certificate_store = certificate_store_new(settings);
if (!tls->certificate_store)
goto out_free;
}
tls->alertLevel = TLS_ALERT_LEVEL_WARNING;
tls->alertDescription = TLS_ALERT_DESCRIPTION_CLOSE_NOTIFY;
return tls;
out_free:
free(tls);
return NULL;
}
void tls_free(rdpTls* tls)
{
if (!tls)
return;
if (tls->ctx)
{
SSL_CTX_free(tls->ctx);
tls->ctx = NULL;
}
if (tls->bio)
{
BIO_free(tls->bio);
tls->bio = NULL;
}
if (tls->underlying)
{
BIO_free(tls->underlying);
tls->underlying = NULL;
}
if (tls->PublicKey)
{
free(tls->PublicKey);
tls->PublicKey = NULL;
}
if (tls->Bindings)
{
free(tls->Bindings->Bindings);
free(tls->Bindings);
tls->Bindings = NULL;
}
if (tls->certificate_store)
{
certificate_store_free(tls->certificate_store);
tls->certificate_store = NULL;
}
free(tls);
}
| eledoux/FreeRDP | libfreerdp/crypto/tls.c | C | apache-2.0 | 38,471 |
package com.clarkparsia.pellet.datatypes.types.real;
import edu.javax.xml.bind.DatatypeConverter;
import org.mindswap.pellet.utils.ATermUtils;
import org.mindswap.pellet.utils.Namespaces;
import com.clarkparsia.pellet.datatypes.exceptions.InvalidLiteralException;
/**
* <p>
* Title: <code>xsd:short</code>
* </p>
* <p>
* Description: Singleton implementation of <code>xsd:short</code> datatype
* </p>
* <p>
* Copyright: Copyright (c) 2009
* </p>
* <p>
* Company: Clark & Parsia, LLC. <http://www.clarkparsia.com>
* </p>
*
* @author Mike Smith
*/
public class XSDShort extends AbstractDerivedIntegerType {
private static final XSDShort instance;
static {
instance = new XSDShort();
}
public static XSDShort getInstance() {
return instance;
}
private XSDShort() {
super( ATermUtils.makeTermAppl( Namespaces.XSD + "short" ), Short.MIN_VALUE,
Short.MAX_VALUE );
}
@Override
protected Number fromLexicalForm(String lexicalForm) throws InvalidLiteralException {
try {
int n = DatatypeConverter.parseInt( lexicalForm );
if( n < Short.MIN_VALUE || n > Short.MAX_VALUE )
throw new InvalidLiteralException( getName(), lexicalForm );
return Short.valueOf( (short) n );
} catch( NumberFormatException e ) {
throw new InvalidLiteralException( getName(), lexicalForm );
}
}
}
| edlectrico/Pellet4Android | src/com/clarkparsia/pellet/datatypes/types/real/XSDShort.java | Java | apache-2.0 | 1,329 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2016 by Contributors
* \file c_api_ndarray.cc
* \brief C API of mxnet
*/
#include <mxnet/base.h>
#include <mxnet/c_api.h>
#include <mxnet/operator.h>
#include <mxnet/operator_util.h>
#include <mxnet/op_attr_types.h>
#include <mxnet/imperative.h>
#include <nnvm/node.h>
#include <nnvm/op_attr_types.h>
#include <string>
#include "./c_api_common.h"
#include "../common/utils.h"
#include "../common/exec_utils.h"
#include "../imperative/imperative_utils.h"
#include "../imperative/cached_op.h"
#include "../imperative/cached_op_threadsafe.h"
using namespace mxnet;
void SetNDInputsOutputs(const nnvm::Op* op,
std::vector<NDArray*>* ndinputs,
std::vector<NDArray*>* ndoutputs,
int num_inputs,
const NDArrayHandle *inputs,
int *num_outputs,
int infered_num_outputs,
int num_visible_outputs,
NDArrayHandle **outputs) {
NDArray** out_array = *reinterpret_cast<NDArray***>(outputs);
ndinputs->clear();
ndinputs->reserve(num_inputs);
for (int i = 0; i < num_inputs; ++i) {
NDArray* inp = reinterpret_cast<NDArray*>(inputs[i]);
if (!features::is_enabled(features::INT64_TENSOR_SIZE)) {
CHECK_LT(inp->shape().Size(), (int64_t{1} << 31) - 1) <<
"[SetNDInputsOutputs] Size of tensor you are trying to allocate is larger than "
"2^31 elements. Please build with flag USE_INT64_TENSOR_SIZE=1";
}
ndinputs->emplace_back(inp);
}
ndoutputs->clear();
ndoutputs->reserve(infered_num_outputs);
if (out_array == nullptr) {
for (int i = 0; i < infered_num_outputs; ++i) {
ndoutputs->emplace_back(new NDArray());
}
*num_outputs = num_visible_outputs;
} else {
CHECK(*num_outputs == infered_num_outputs || *num_outputs == num_visible_outputs)
<< "Operator expects " << infered_num_outputs << " (all) or "
<< num_visible_outputs << " (visible only) outputs, but got "
<< *num_outputs << " instead.";
for (int i = 0; i < *num_outputs; ++i) {
ndoutputs->emplace_back(out_array[i]);
}
for (int i = *num_outputs; i < infered_num_outputs; ++i) {
ndoutputs->emplace_back(new NDArray());
}
}
}
void MXImperativeInvokeImpl(AtomicSymbolCreator creator,
int num_inputs,
NDArrayHandle *inputs,
int *num_outputs,
NDArrayHandle **outputs,
int num_params,
const char **param_keys,
const char **param_vals) {
const nnvm::Op* op = static_cast<nnvm::Op*>(creator);
MXAPIThreadLocalEntry<> *ret = MXAPIThreadLocalStore<>::Get();
nnvm::NodeAttrs attrs = imperative::ParseAttrs(op, num_inputs, num_params,
param_keys, param_vals);
int infered_num_outputs;
int num_visible_outputs;
imperative::SetNumOutputs(op, attrs, num_inputs, &infered_num_outputs, &num_visible_outputs);
std::vector<NDArray*> ndinputs, ndoutputs;
SetNDInputsOutputs(op, &ndinputs, &ndoutputs, num_inputs, inputs,
num_outputs, infered_num_outputs, num_visible_outputs, outputs);
auto state = Imperative::Get()->Invoke(Context::CPU(), attrs, ndinputs, ndoutputs);
if (Imperative::Get()->is_recording()) {
Imperative::Get()->RecordOp(std::move(attrs), ndinputs, ndoutputs, state);
}
for (int i = *num_outputs; i < infered_num_outputs; ++i) delete ndoutputs[i];
if (*outputs == nullptr) {
ret->ret_handles.clear();
ret->ret_handles.reserve(*num_outputs);
for (int i = 0; i < *num_outputs; ++i) ret->ret_handles.push_back(ndoutputs[i]);
*outputs = reinterpret_cast<NDArrayHandle*>(dmlc::BeginPtr(ret->ret_handles));
}
}
int MXImperativeInvoke(AtomicSymbolCreator creator,
int num_inputs,
NDArrayHandle *inputs,
int *num_outputs,
NDArrayHandle **outputs,
int num_params,
const char **param_keys,
const char **param_vals) {
API_BEGIN();
MXImperativeInvokeImpl(creator, num_inputs, inputs, num_outputs, outputs,
num_params, param_keys, param_vals);
API_END();
}
int MXImperativeInvokeEx(AtomicSymbolCreator creator,
int num_inputs,
NDArrayHandle *inputs,
int *num_outputs,
NDArrayHandle **outputs,
int num_params,
const char **param_keys,
const char **param_vals,
const int **out_stypes) { // outputs storage types
MXAPIThreadLocalEntry<> *ret = MXAPIThreadLocalStore<>::Get();
API_BEGIN();
MXImperativeInvokeImpl(creator, num_inputs, inputs, num_outputs, outputs,
num_params, param_keys, param_vals);
NDArray** out_array = *reinterpret_cast<NDArray***>(outputs);
ret->out_types.clear();
ret->out_types.reserve(*num_outputs);
for (int i = 0; i < *num_outputs; ++i) {
ret->out_types.emplace_back(out_array[i]->storage_type());
}
*out_stypes = dmlc::BeginPtr(ret->out_types);
API_END();
}
int MXCreateCachedOp(SymbolHandle handle,
CachedOpHandle *out) {
nnvm::Symbol* sym = static_cast<nnvm::Symbol*>(handle);
API_BEGIN();
auto inputs = sym->ListInputs(nnvm::Symbol::kAll);
std::vector<std::string> input_names;
input_names.reserve(inputs.size());
for (const auto& i : inputs) input_names.push_back(i->attrs.name);
*out = new CachedOpPtr(new CachedOp(
*sym, std::vector<std::pair<std::string, std::string> >()));
API_END();
}
int MXCreateCachedOpEx(SymbolHandle handle,
int num_flags,
const char** keys,
const char** vals,
CachedOpHandle *out) {
nnvm::Symbol* sym = static_cast<nnvm::Symbol*>(handle);
API_BEGIN();
std::vector<std::pair<std::string, std::string> > flags;
for (int i = 0; i < num_flags; ++i) {
flags.emplace_back(keys[i], vals[i]);
}
*out = new CachedOpPtr(new CachedOp(*sym, flags));
API_END();
}
int MXCreateCachedOpEX(SymbolHandle handle,
int num_flags,
const char** keys,
const char** vals,
CachedOpHandle *out,
bool thread_safe) {
nnvm::Symbol* sym = static_cast<nnvm::Symbol*>(handle);
API_BEGIN();
std::vector<std::pair<std::string, std::string> > flags;
for (int i = 0; i < num_flags; ++i) {
flags.emplace_back(keys[i], vals[i]);
}
if (!thread_safe) {
*out = new CachedOpPtr(new CachedOp(*sym, flags));
} else {
*out = new CachedOpPtr(new CachedOpThreadSafe(*sym, flags));
}
API_END();
}
int MXFreeCachedOp(CachedOpHandle handle) {
CachedOpPtr* g = static_cast<CachedOpPtr*>(handle);
API_BEGIN();
delete g;
API_END();
}
int MXInvokeCachedOp(CachedOpHandle handle,
int num_inputs,
NDArrayHandle *inputs,
int *num_outputs,
NDArrayHandle **outputs) {
MXAPIThreadLocalEntry<> *ret = MXAPIThreadLocalStore<>::Get();
API_BEGIN();
CachedOpPtr op_shared = *static_cast<CachedOpPtr*>(handle);
// CachedOp* points to CachedOpThreadSafe object if CreateCachedOpEX
// was called with thread_safe=true
CachedOp* op = dynamic_cast<CachedOp*>(op_shared.get());
std::vector<NDArray*> ndinputs;
ndinputs.reserve(num_inputs);
for (int i = 0; i < num_inputs; ++i) {
ndinputs.push_back(reinterpret_cast<NDArray*>(inputs[i]));
}
std::vector<NDArray*> ndoutputs;
ndoutputs.reserve(op->num_outputs());
if (*outputs == nullptr) {
*num_outputs = op->num_outputs();
for (int i = 0; i < *num_outputs; ++i) ndoutputs.push_back(new NDArray());
} else {
CHECK_EQ(*num_outputs, op->num_outputs())
<< "CachedOp expects " << op->num_outputs() << " outputs, but "
<< *num_outputs << " was given.";
for (int i = 0; i < *num_outputs; ++i) {
ndoutputs.push_back(reinterpret_cast<NDArray*>((*outputs)[i]));
}
}
op->Forward(op_shared, ndinputs, ndoutputs);
if (*outputs == nullptr) {
ret->ret_handles.clear();
ret->ret_handles.reserve(*num_outputs);
for (int i = 0; i < *num_outputs; ++i) {
ret->ret_handles.push_back(ndoutputs[i]);
}
*outputs = dmlc::BeginPtr(ret->ret_handles);
}
API_END();
}
int MXInvokeCachedOpEx(CachedOpHandle handle,
int num_inputs,
NDArrayHandle *inputs,
int *num_outputs,
NDArrayHandle **outputs,
const int **out_stypes) { // outputs storage types
MXAPIThreadLocalEntry<> *ret = MXAPIThreadLocalStore<>::Get();
int err = MXInvokeCachedOp(handle, num_inputs, inputs, num_outputs, outputs);
if (err != 0) return err;
API_BEGIN();
NDArray** out_array = reinterpret_cast<NDArray**>(*outputs);
ret->out_types.clear();
ret->out_types.reserve(*num_outputs);
for (int i = 0; i < *num_outputs; ++i) {
ret->out_types.emplace_back(out_array[i]->storage_type());
}
*out_stypes = dmlc::BeginPtr(ret->out_types);
API_END();
}
int MXAutogradIsTraining(bool* curr) {
API_BEGIN();
*curr = Imperative::Get()->is_training();
API_END();
}
int MXAutogradSetIsTraining(int is_training, int* prev) {
API_BEGIN();
*prev = Imperative::Get()->set_is_training(static_cast<bool>(is_training));
API_END();
}
int MXAutogradIsRecording(bool* curr) {
API_BEGIN();
*curr = Imperative::Get()->is_recording();
API_END();
}
int MXAutogradSetIsRecording(int is_recording, int* prev) {
API_BEGIN();
*prev = Imperative::Get()->set_is_recording(static_cast<bool>(is_recording));
API_END();
}
int MXIsNumpyShape(int* curr) {
API_BEGIN();
*curr = Imperative::Get()->is_np_shape();
API_END();
}
int MXSetIsNumpyShape(int is_np_shape, int* prev) {
API_BEGIN();
*prev = Imperative::Get()->set_is_np_shape(is_np_shape);
API_END();
}
int MXAutogradMarkVariables(uint32_t num_var,
NDArrayHandle *var_handles,
uint32_t *reqs_array,
NDArrayHandle *grad_handles) {
API_BEGIN();
std::vector<NDArray*> variables, gradients;
std::vector<uint32_t> grad_reqs;
variables.reserve(num_var);
gradients.reserve(num_var);
grad_reqs.reserve(num_var);
for (uint32_t i = 0; i < num_var; ++i) {
variables.emplace_back(static_cast<NDArray*>(var_handles[i]));
gradients.emplace_back(static_cast<NDArray*>(grad_handles[i]));
grad_reqs.emplace_back(reqs_array[i]);
}
Imperative::Get()->MarkVariables(variables, grad_reqs, gradients);
API_END();
}
int MXAutogradComputeGradient(uint32_t num_output,
NDArrayHandle *output_handles) {
return MXAutogradBackward(num_output, output_handles, nullptr, 0);
}
int MXAutogradBackward(uint32_t num_output,
NDArrayHandle *output_handles,
NDArrayHandle *ograd_handles,
int retain_graph) {
return MXAutogradBackwardEx(num_output, output_handles, ograd_handles,
0, nullptr, retain_graph, false, true,
nullptr, nullptr);
}
int MXAutogradBackwardEx(uint32_t num_output,
NDArrayHandle *output_handles,
NDArrayHandle *ograd_handles,
uint32_t num_variables,
NDArrayHandle *var_handles,
int retain_graph,
int create_graph,
int is_train,
NDArrayHandle **grad_handles,
int **grad_stypes) {
MXAPIThreadLocalEntry<> *ret = MXAPIThreadLocalStore<>::Get();
API_BEGIN();
std::vector<NDArray*> outputs, ograds, variables;
outputs.reserve(num_output);
for (uint32_t i = 0; i < num_output; ++i) {
outputs.emplace_back(reinterpret_cast<NDArray*>(output_handles[i]));
}
ograds.reserve(num_output);
for (uint32_t i = 0; i < num_output; ++i) {
if (ograd_handles != nullptr) {
ograds.emplace_back(reinterpret_cast<NDArray*>(ograd_handles[i]));
} else {
ograds.emplace_back(nullptr);
}
}
variables.reserve(num_variables);
for (uint32_t i = 0; i < num_variables; ++i) {
variables.emplace_back(reinterpret_cast<NDArray*>(var_handles[i]));
}
auto grads = Imperative::Get()->Backward(outputs, ograds, variables, is_train,
retain_graph, create_graph);
if (num_variables != 0) {
ret->ret_handles.clear();
ret->out_types.clear();
ret->ret_handles.reserve(grads.size());
ret->out_types.reserve(grads.size());
for (const auto& i : grads) {
ret->ret_handles.push_back(i);
ret->out_types.push_back(i->storage_type());
}
*grad_handles = dmlc::BeginPtr(ret->ret_handles);
*grad_stypes = dmlc::BeginPtr(ret->out_types);
}
API_END();
}
int MXAutogradGetSymbol(NDArrayHandle handle, SymbolHandle *out) {
API_BEGIN();
NDArray *head = reinterpret_cast<NDArray*>(handle);
auto sym = new nnvm::Symbol(head->get_autograd_symbol());
*out = reinterpret_cast<SymbolHandle>(sym);
API_END();
}
int MXCachedOpRegisterOpHook(NDArrayHandle handle,
CachedOpMonitorCallback callback,
bool monitor_all) {
API_BEGIN();
CachedOpMonitorCallback callback_temp = nullptr;
std::function<void(const char *, const char *, void*)> clbk;
if (callback) {
callback_temp = callback;
clbk = [callback_temp](const char *name, const char *opr_name,
void *handle) {
callback_temp(name, opr_name, handle);
};
} else {
clbk = nullptr;
}
CachedOpPtr op = *static_cast<CachedOpPtr *>(handle);
op->RegisterOpHook(clbk, monitor_all);
API_END();
}
| larroy/mxnet | src/c_api/c_api_ndarray.cc | C++ | apache-2.0 | 15,089 |
/*
* Copyright (c) 2016 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <zephyr.h>
#include <sys_clock.h>
#include <stdio.h>
#include <device.h>
#include <sensor.h>
#include <misc/util.h>
#include <gpio.h>
#include <ipm.h>
#include <ipm/ipm_quark_se.h>
QUARK_SE_IPM_DEFINE(bmi160_ipm, 0, QUARK_SE_IPM_OUTBOUND);
#define SLEEPTIME MSEC(1000)
#define BMI160_INTERRUPT_PIN 4
struct device *ipm;
struct gpio_callback cb;
static void aon_gpio_callback(struct device *port,
struct gpio_callback *cb, uint32_t pins)
{
ipm_send(ipm, 0, 0, NULL, 0);
}
void main(void)
{
uint32_t timer_data[2] = {0, 0};
struct device *aon_gpio;
struct nano_timer timer;
nano_timer_init(&timer, timer_data);
aon_gpio = device_get_binding("GPIO_AON_0");
if (!aon_gpio) {
printf("aon_gpio device not found.\n");
return;
}
ipm = device_get_binding("bmi160_ipm");
if (!ipm) {
printf("ipm device not found.\n");
return;
}
gpio_init_callback(&cb, aon_gpio_callback, BIT(BMI160_INTERRUPT_PIN));
gpio_add_callback(aon_gpio, &cb);
gpio_pin_configure(aon_gpio, BMI160_INTERRUPT_PIN,
GPIO_DIR_IN | GPIO_INT | GPIO_INT_EDGE |
GPIO_INT_ACTIVE_LOW | GPIO_INT_DEBOUNCE);
gpio_pin_enable_callback(aon_gpio, BMI160_INTERRUPT_PIN);
while (1) {
nano_task_timer_start(&timer, SLEEPTIME);
nano_task_timer_test(&timer, TICKS_UNLIMITED);
}
}
| mirzak/zephyr-os | samples/sensor/bmi160/x86/src/x86_bmi160.c | C | apache-2.0 | 1,901 |
/*
$Id: $
@file AjaxHelperMapImpl.java
@brief Contains the AjaxHelperMapImpl.java class
@author Rahul Singh [rsingh]
Copyright (c) 2013, Distelli Inc., All Rights Reserved.
*/
package com.distelli.europa.guice;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.distelli.europa.EuropaRequestContext;
import com.distelli.webserver.AjaxHelper;
import com.distelli.webserver.AjaxHelperMap;
import com.distelli.webserver.MatchedRoute;
import lombok.extern.log4j.Log4j;
@Log4j
@Singleton
public class AjaxHelperMapImpl implements AjaxHelperMap<EuropaRequestContext>
{
@Inject
private Map<String, AjaxHelper> _ajaxHelperMap;
@Inject
private Map<String, Set<String>> _pathRestrictions;
public AjaxHelperMapImpl()
{
}
public AjaxHelper get(String operationName, EuropaRequestContext requestContext)
{
MatchedRoute matchedRoute = requestContext.getMatchedRoute();
String path = matchedRoute.getPath();
Set<String> pathRestrictions = _pathRestrictions.get(operationName);
if(pathRestrictions != null)
{
if(!pathRestrictions.contains(path)) {
if(log.isDebugEnabled())
log.debug("Operation: "+operationName+". Path "+
path+" not found in Path Restriction Set: "+pathRestrictions+
" RequestContext: "+requestContext);
return null;
}
}
return _ajaxHelperMap.get(operationName);
}
}
| Distelli/europa | src/main/java/com/distelli/europa/guice/AjaxHelperMapImpl.java | Java | apache-2.0 | 1,582 |
# Usergrid Perl Client 
Usergrid::Client provides an easy to use Perl API for Apache Usergrid.
## Quickstart
Install Usergrid::Client from CPAN:
$ sudo cpan Usergrid::Client
Write a perl script that uses the Perl API to talk to Usergrid. Here's an example:
```perl
#!/usr/bin/perl
use Usergrid::Client;
# Create a client object for Usergrid that's used for subsequent activity
my $client = Usergrid::Client->new(
organization => 'test-organization',
application => 'test-app',
api_url => 'http://localhost:8080',
trace => 0
);
# Logs the user in. The security token is maintained by the library in memory
$client->login('johndoe', 'Johndoe123$');
# Add two entities to the "books" collection
$client->add_entity("books", { name => "Ulysses", author => "James Joyce" });
$client->add_entity("books", { name => "Neuromancer", author => "William Gibson" });
# Retrieve a handle to the collection
my $books = $client->get_collection("books");
# Add a new attribute for quantity in stock
while ($books->has_next_entity()) {
my $book = $books->get_next_entity();
print "Name: " . $book->get('name') . ", ";
print "Author: " . $book->get('author') . "\n";
# Create a new attribute and update the entity
$book->set("in-stock", 0);
$client->update_entity($book);
}
```
## What is Apache Usergrid
Usergrid is an open-source Backend-as-a-Service (“BaaS” or “mBaaS”) composed of
an integrated distributed NoSQL database, application layer and client tier with
SDKs for developers looking to rapidly build web and/or mobile applications.
It provides elementary services (user registration & management, data storage,
file storage, queues) and retrieval features (full text search, geolocation
search, joins) to power common app features.
It is a multi-tenant system designed for deployment to public cloud environments
(such as Amazon Web Services, Rackspace, etc.) or to run on traditional server
infrastructures so that anyone can run their own private BaaS deployment.
For architects and back-end teams, it aims to provide a distributed, easily
extendable, operationally predictable and highly scalable solution. For
front-end developers, it aims to simplify the development process by enabling
them to rapidly build and operate mobile and web applications without requiring
backend expertise.
Source: [Usergrid Documentation](https://usergrid.apache.org/docs/)
For more information, visit [http://www.usergrid.org](http://www.usergrid.org)
## Installation
### Prerequisites
Usergrid::Client depends on the following modules which can be installed
from CPAN as shown below:
$ sudo cpan install Moose
$ sudo cpan install JSON
$ sudo cpan install REST::Client
$ sudo cpan install URI::Template
$ sudo cpan install Log::Log4perl
$ sudo cpan install namespace::autoclean
### Build and install
$ perl Build.PL
$ ./Build
$ ./Build test
$ sudo ./Build install
### For legacy users on older versions of Perl
$ perl Makefile.PL
$ make
$ make test
$ sudo make install
## Usage
### Getting started
In order to login to Usergrid using the API, create a Usergrid::Client object
as shown below and invoke the login function.
```perl
# Create the client object that will be used for all subsequent requests
my $client = Usergrid::Client->new(
organization => $organization,
application => $application,
api_url => $api_url
);
$client->login($username, $password);
```
For troubleshooting the requests and responses, tracing can be enabled, which
will log all requests and responses to standard output.
```perl
# Create the client object that will be used for all subsequent requests
my $client = Usergrid::Client->new(
organization => $organization,
application => $application,
api_url => $api_url,
trace => 1
);
```
To get more details on the API, read the following perldocs:
Usergrid::Client
Usergrid::Collection
Usergrid::Entity
### Entities
Creating and updating an entity is easy. Here's how:
```perl
$book = $client->add_entity("books", { name => "Neuromancer", author => "William Gibson" });
$book->set('genre', 'Cyberpunk');
$client->update_entity($book);
```
Querying an entity can be done by UUID:
```perl
$book = $client->get_entity("books", $uuid);
```
or by name:
```perl
$book = $client->get_entity("books", "Neuromancer");
```
Similarly, an entity can be deleted by UUID or by name:
```perl
$client->delete_entity_by_id("books", $uuid_or_name);
# An entity can be also deleted by passing an entity object
$client->delete_entity($entity);
```
### Collections
A collection can be retrieved as shown below:
```perl
$collection = $client->get_collection("books");
# Outputs the number of records in the collection
print "$collection->count()\n";
```
To iterate over the collection:
```perl
while ($collection->has_next_entity()) {
$book = $collection->get_next_entity();
print "$book->get('name')\n";
}
```
Note that by default a collection returns a maximum of 10 records per page. This
can be overridden when retrieving the collection as shown below:
```perl
$collection = $client->get_collection("books", 30);
# Retrieve the first book in the collection's current page
$first_book = $collection->get_first_entity();
# Retrieve the last book in the collection's current page
$last_book = $collection->get_last_entity();
```
To navigate the pages in the collection:
```perl
$collection->get_next_page();
$collection->get_prev_page();
```
Both of the above return FALSE if the end or the beginning of the collection
is reached.
When iterating through a collection, the auto_page attribute can be set
to allow the collection to transparently fetch the next page when iterating.
```perl
$collection = $client->get_collection("books");
$collection->auto_page(1);
while ($collection->has_next_entity()) {
my $entity = $collection->get_next_entity();
# do something
}
```
### Querying & Batch Updates
Collections can be queried using a SQL-like query language for greater control
over the data set that is returned.
```perl
$collection = $client->query_collection("books", "select * where genre = 'Cyberpunk'", $limit );
```
Queries can also be used when deleting collections:
```perl
$collection = $client->delete_collection("books", "select * where genre = 'Cyberpunk'", $limit);
```
If the $limit is omitted in the above method calls, a default of 10 is assumed.
A collection can be batch updated as shown below:
```perl
$client->update_collection("books", { in_stock => 1 });
```
A query can be used to fine-tune the update:
```perl
$client->update_collection("books", { in_stock => 0 }, "select * where genre = 'Cyberpunk'", $limit);
```
Similarly, entities can be deleted in batch:
```perl
$client->delete_collection("books", "select * where genre = 'Novel'", $limit);
```
### Entity Connections
Connections can be created between entities through relationships as shown below:
```perl
$book1 = $client->add_entity("books", { name => "Neuromancer", author => "William Gibson" });
$book2 = $client->add_entity("books", { name => "Count Zero", author => "William Gibson" });
$book3 = $client->add_entity("books", { name => "Mona Lisa Overdrive", author => "William Gibson" });
$client->connect_entities($book1, "similar_to", $book2);
$client->connect_entities($book1, "similar_to", $book3);
```
They can also be queried just like any other collection:
```perl
$collection = $client->query_connections($book1, "similar_to");
# Queries and limits can also be passed in
$collection = $client->query_connections($book1, "similar_to", $query, $limit);
```
To delete a connection:
```perl
$client->disconnect_entities($book1, "similar_to", $book2);
```
### Code Coverage
Code coverage reporting requires Devel::Cover module which can be
installed from CPAN as shown:
$ sudo cpan install Devel::Cover
For generating reports on code coverage:
$ ./Build testcover
The generated report artifacts are located in cover_db/.
## Release notes
### 0.22
* Auto paging for collections
### 0.21
* Documentation updates
### 0.2
* Creating, querying and deleting entity connections
* Bi-directional collection pagination
### 0.11
* Added namespace::autoclean.pm as a dependency to fix build break on some
platforms
### 0.1
* Initial release
* Application and admin authentication
* Support for collections and entities (CRUD & queries)
## License
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.
| mdunker/usergrid | sdks/other/perl/README.md | Markdown | apache-2.0 | 9,335 |
/*
* Copyright 2010-2014 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.
*/
/*
* Do not modify this file. This file is generated from the autoscaling-2011-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.AutoScaling.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.AutoScaling.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for RecordLifecycleActionHeartbeat operation
/// </summary>
public class RecordLifecycleActionHeartbeatResponseUnmarshaller : XmlResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
RecordLifecycleActionHeartbeatResponse response = new RecordLifecycleActionHeartbeatResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.IsStartElement)
{
if(context.TestExpression("RecordLifecycleActionHeartbeatResult", 2))
{
UnmarshallResult(context, response);
continue;
}
if (context.TestExpression("ResponseMetadata", 2))
{
response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context);
}
}
}
return response;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId="response")]
private static void UnmarshallResult(XmlUnmarshallerContext context, RecordLifecycleActionHeartbeatResponse response)
{
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
}
}
return;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceContention"))
{
return new ResourceContentionException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonAutoScalingException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static RecordLifecycleActionHeartbeatResponseUnmarshaller _instance = new RecordLifecycleActionHeartbeatResponseUnmarshaller();
internal static RecordLifecycleActionHeartbeatResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static RecordLifecycleActionHeartbeatResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | rafd123/aws-sdk-net | sdk/src/Services/AutoScaling/Generated/Model/Internal/MarshallTransformations/RecordLifecycleActionHeartbeatResponseUnmarshaller.cs | C# | apache-2.0 | 4,804 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>inputEx - Autocomplete Usage</title>
<!-- YUI CSS -->
<link rel="stylesheet" type="text/css" href="../lib/yui/reset/reset-min.css">
<link rel="stylesheet" type="text/css" href="../lib/yui/fonts/fonts-min.css">
<link rel="stylesheet" type="text/css" href="../lib/yui/container/assets/container.css">
<link rel="stylesheet" type="text/css" href="../lib/yui/assets/skins/sam/skin.css">
<!-- InputEx CSS -->
<link type='text/css' rel='stylesheet' href='../css/inputEx.css' />
<!-- Demo CSS -->
<link rel="stylesheet" type="text/css" href="css/demo.css"/>
<link rel="stylesheet" type="text/css" href="css/dpSyntaxHighlighter.css">
</head>
<body class="yui-skin-sam">
<p class='demoTitle'>inputEx - Autocomplete Usage</p>
<!-- Example 1 -->
<div class='exampleDiv'>
<p class="title">Basic Autocomplete creation</p>
<p>Use the following code to create a basic inputEx Autocomplete.</p>
<div class='demoContainer' id='container1'></div>
<div class='codeContainer'>
<textarea name="code" class="JScript">
// Autocompleter
var field = inputEx({
type: "autocomplete",
inputParams: {
parentEl: 'container1',
label: 'Search US state',
datasource: new YAHOO.widget.DS_JSFunction( getStates), // see http://developer.yahoo.com/yui/examples/autocomplete/assets/js/states_jsfunction.js for getState function
// Format the hidden value (value returned by the form)
returnValue: function(oResultItem) {
return oResultItem[1];
},
autoComp: {
forceSelection: true,
minQueryLength: 2,
maxResultsDisplayed: 50,
formatResult: function(oResultItem, sQuery) {
var sMarkup = oResultItem[0] + " (" + oResultItem[1] + ")";
return sMarkup;
}
}
}
});
var button = inputEx.cn('button', null, null, 'GetValue');
YAHOO.util.Dom.get('container1').appendChild(button);
YAHOO.util.Event.addListener(button , 'click', function() {
alert( field.getValue() );
});
var logDiv = YAHOO.inputEx.cn('div', null, null, "");
YAHOO.util.Dom.get('container1').appendChild(logDiv);
field.updatedEvt.subscribe(function(e,params) {
var value = params[0];
logDiv.innerHTML += "Updated at "+(new Date())+" with value '"+value+"'<br />";
});
</textarea>
</div>
</div>
<!-- Example 2 -->
<div class='exampleDiv'>
<p class="title">Delicious Autocompleter</p>
<p>Uses the <a href="http://del.icio.us/help/json/posts">del.icio.us json API</a> to search within posts</p>
<div class='demoContainer' id='container2'></div>
<div class='codeContainer'>
<textarea name="code" class="JScript">
// Delicious DataSource using a JSFunction
// Delicious.posts is set by the http://feeds.delicious.com/feeds/json/neyric?count=100 script included in the page
var deliciousDS = new YAHOO.widget.DS_JSFunction(function (sQuery) {
if (!sQuery || sQuery.length == 0) return false;
var query = sQuery.toLowerCase();
var aResults = [];
for(var i = 0 ; i < Delicious.posts.length ; i++) {
var desc = Delicious.posts[i].d.toLowerCase();
if( desc.indexOf(query) != -1) {
aResults.push([Delicious.posts[i].d, Delicious.posts[i]]);
}
}
return aResults;
});
deliciousDS.maxCacheEntries = 100;
var deliciousAC = inputEx({
type: "autocomplete",
inputParams: {
label: 'Search my delicious bookmarks',
description: 'Try "javascript"',
parentEl: 'container2',
name: 'chosen_url',
datasource: deliciousDS,
// Format the hidden value (value returned by the form)
returnValue: function(oResultItem) {
var post = oResultItem[1];
return post.u;
},
// Autocompleter options
autoComp: {
forceSelection: true,
minQueryLength: 2,
maxResultsDisplayed: 50,
formatResult: function(oResultItem, sQuery) {
var post = oResultItem[1];
return '<a href="'+post.u+'">visit</a> <span target="_new">'+post.d+'</span>';
}
}
}
});
var button = inputEx.cn('button', null, null, 'GetValue');
YAHOO.util.Dom.get('container2').appendChild(button);
YAHOO.util.Event.addListener(button , 'click', function() {
alert( deliciousAC.getValue() );
});
</textarea>
</div>
</div>
<!-- YUI Library -->
<script type="text/javascript" src="../lib/yui/yahoo/yahoo-min.js"></script>
<script type="text/javascript" src="../lib/yui/dom/dom-min.js"></script>
<script type="text/javascript" src="../lib/yui/event/event-min.js"></script>
<script type="text/javascript" src="../lib/yui/datasource/datasource-min.js"></script>
<script type="text/javascript" src="../lib/yui/autocomplete/autocomplete-min.js"></script>
<!-- InputEx -->
<script src="../js/inputex.js" type='text/javascript'></script>
<script src="../js/Field.js" type='text/javascript'></script>
<script src="../js/Visus.js" type='text/javascript'></script>
<script src="../js/fields/StringField.js" type='text/javascript'></script>
<script src="../js/fields/AutoComplete.js" type='text/javascript'></script>
<!-- For the state autocompleter -->
<script src="http://developer.yahoo.com/yui/examples/autocomplete/assets/js/states_jsfunction.js" type='text/javascript'></script>
<!-- For the delicious autocompleter -->
<script src="http://feeds.delicious.com/feeds/json/neyric?count=100" type='text/javascript'></script>
<script>
YAHOO.util.Event.addListener(window, 'load', function() {
// Example 1
// Autocompleter
var field = inputEx({
type: "autocomplete",
inputParams: {
parentEl: 'container1',
label: 'Search US state',
typeInvite:'Enter US state',
datasource: new YAHOO.widget.DS_JSFunction( getStates), // see http://developer.yahoo.com/yui/examples/autocomplete/assets/js/states_jsfunction.js for getState function
// Format the hidden value (value returned by the form)
returnValue: function(oResultItem) {
return oResultItem[1];
},
autoComp: {
forceSelection: true,
minQueryLength: 2,
maxResultsDisplayed: 50,
formatResult: function(oResultItem, sQuery) {
var sMarkup = oResultItem[0] + " (" + oResultItem[1] + ")";
return sMarkup;
}
}
}
});
var button = inputEx.cn('button', null, null, 'GetValue');
YAHOO.util.Dom.get('container1').appendChild(button);
YAHOO.util.Event.addListener(button , 'click', function() {
alert( field.getValue() );
});
var logDiv = YAHOO.inputEx.cn('div', null, null, "");
YAHOO.util.Dom.get('container1').appendChild(logDiv);
field.updatedEvt.subscribe(function(e,params) {
var value = params[0];
logDiv.innerHTML += "Updated at "+(new Date())+" with value '"+value+"'<br />";
});
// Example 2: Delicious autocompleter
// Delicious DataSource using a JSFunction
// Delicious.posts is set by the http://feeds.delicious.com/feeds/json/neyric?count=100 script included in the page
var deliciousDS = new YAHOO.widget.DS_JSFunction(function (sQuery) {
if (!sQuery || sQuery.length == 0) return false;
var query = sQuery.toLowerCase();
var aResults = [];
for(var i = 0 ; i < Delicious.posts.length ; i++) {
var desc = Delicious.posts[i].d.toLowerCase();
if( desc.indexOf(query) != -1) {
aResults.push([Delicious.posts[i].d, Delicious.posts[i]]);
}
}
return aResults;
});
deliciousDS.maxCacheEntries = 100;
var deliciousAC = inputEx({
type: "autocomplete",
inputParams: {
label: 'Search my delicious bookmarks',
description: 'Try "javascript"',
parentEl: 'container2',
name: 'chosen_url',
datasource: deliciousDS,
// Format the hidden value (value returned by the form)
returnValue: function(oResultItem) {
var post = oResultItem[1];
return post.u;
},
// Autocompleter options
autoComp: {
forceSelection: true,
minQueryLength: 2,
maxResultsDisplayed: 50,
formatResult: function(oResultItem, sQuery) {
var post = oResultItem[1];
return '<a href="'+post.u+'">visit</a> <span target="_new">'+post.d+'</span>';
}
}
}
});
var button = inputEx.cn('button', null, null, 'GetValue');
YAHOO.util.Dom.get('container2').appendChild(button);
YAHOO.util.Event.addListener(button , 'click', function() {
alert( deliciousAC.getValue() );
});
});
</script>
<script src="js/dpSyntaxHighlighter.js"></script>
<script language="javascript">
dp.SyntaxHighlighter.HighlightAll('code');
</script>
</body>
</html> | festradasolano/mashment | mashment-frontend/WebContent/lib/inputex/examples/autocomplete.html | HTML | apache-2.0 | 8,612 |
---
title: filterNot -
---
//[Kotlin utilities](../../index.html)/[it.czerwinski.kotlin.util](../index.html)/[Failure](index.html)/[filterNot](filter-not.html)
# filterNot
[common]
Brief description
Returns the same [Success](../-success/index.html) if the predicate is not satisfied for the value. Otherwise returns a [Failure](index.html).
#### Return
The same [Success](../-success/index.html) if the predicate is not satisfied for the value. Otherwise returns a [Failure](index.html).
## Parameters
common
| Name| Summary|
|---|---|
| predicate| <br><br>Predicate function.<br><br>
Content
open override fun [filterNot](filter-not.html)(predicate: ([Nothing](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-nothing/index.html)) -> [Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)): [Try](../-try/index.html)<[Nothing](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-nothing/index.html)>
| sczerwinski/sczerwinski.github.io | projects/kotlin-util/1.4.20/docs/it.czerwinski.kotlin.util/-failure/filter-not.md | Markdown | apache-2.0 | 982 |
#!/usr/bin/env python
"""A module with functions for working with GRR packages."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import importlib
import inspect
import logging
import os
import sys
import pkg_resources
from typing import Text
from grr_response_core.lib.util import compatibility
def _GetPkgResources(package_name, filepath):
"""A wrapper for the `pkg_resource.resource_filename` function."""
requirement = pkg_resources.Requirement.parse(package_name)
try:
return pkg_resources.resource_filename(requirement, filepath)
except pkg_resources.DistributionNotFound:
# It may be that the working set is not in sync (e.g. if sys.path was
# manipulated). Try to reload it just in case.
pkg_resources.working_set = pkg_resources.WorkingSet()
try:
return pkg_resources.resource_filename(requirement, filepath)
except pkg_resources.DistributionNotFound:
logging.error("Distribution %s not found. Is it installed?", package_name)
return None
def ResourcePath(package_name, filepath):
"""Computes a path to the specified package resource.
Args:
package_name: A name of the package where the resource is located.
filepath: A path to the resource relative to the package location.
Returns:
A path to the resource or `None` if the resource cannot be found.
"""
# If we are running a pyinstaller-built binary we rely on the sys.prefix
# code below and avoid running this which will generate confusing error
# messages.
if not getattr(sys, "frozen", None):
target = _GetPkgResources(package_name, filepath)
if target and os.access(target, os.R_OK):
return target
# Installing from wheel places data_files relative to sys.prefix and not
# site-packages. If we can not find in site-packages, check sys.prefix
# instead.
# https://python-packaging-user-guide.readthedocs.io/en/latest/distributing/#data-files
target = os.path.join(sys.prefix, filepath)
if target and os.access(target, os.R_OK):
return target
return None
def ModulePath(module_name):
"""Computes a path to the specified module.
Args:
module_name: A name of the module to get the path for.
Returns:
A path to the specified module.
Raises:
ImportError: If specified module cannot be imported.
"""
module = importlib.import_module(module_name)
path = inspect.getfile(module)
# TODO: In Python 2 `inspect.getfile` returns a byte string, so
# we have to decode that in order to be consistent with Python 3.
if compatibility.PY2:
path = path.decode("utf-8")
# In case of modules with want a path to the directory rather than to the
# `__init__.py` file itself.
if os.path.basename(path).startswith("__init__."):
path = os.path.dirname(path)
# Sometimes __file__ points at a .pyc file, when we really mean the .py.
if path.endswith(".pyc"):
path = path[:-4] + ".py"
return path
| dunkhong/grr | grr/core/grr_response_core/lib/package.py | Python | apache-2.0 | 2,986 |
import { Component, HostListener, Inject } from '@angular/core';
import { MdlDialogReference } from '@angular-mdl/core';
import * as _ from 'lodash';
@Component({
selector: 'app-new-entity',
templateUrl: './new-entity.component.html',
styleUrls: ['./new-entity.component.scss']
})
export class NewEntityComponent {
actions: any;
pluginFormats = [
{ label: 'Javascript', value: 'JAVASCRIPT' },
{ label: 'XQuery', value: 'XQUERY' },
];
dataFormats = [
{ label: 'JSON', value: 'JSON' },
{ label: 'XML', value: 'XML' },
];
DEFAULTENTITY: any = {
info: {
title: null
}
};
entity: any = _.clone(this.DEFAULTENTITY);
constructor(
private dialog: MdlDialogReference,
@Inject('actions') actions: any
) {
this.entity = _.clone(this.DEFAULTENTITY);
this.actions = actions;
}
hide() {
this.dialog.hide();
}
create() {
if (this.entity.info.title && this.entity.info.title.length > 0) {
this.hide();
if (this.actions && this.actions.save) {
this.actions.save(this.entity);
}
}
}
cancel() {
this.hide();
}
}
| marklogic/data-hub-in-a-box | web/src/main/ui/app/components/new-entity/new-entity.component.ts | TypeScript | apache-2.0 | 1,131 |
// Copyright (c) 2001-2011 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(SPIRIT_STRICT_RELAXED_APR_22_2010_0959AM)
#define SPIRIT_STRICT_RELAXED_APR_22_2010_0959AM
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/spirit/home/support/common_terminals.hpp>
#include <boost/spirit/home/support/modify.hpp>
#include <boost/spirit/home/karma/domain.hpp>
#include <boost/spirit/home/karma/meta_compiler.hpp>
namespace boost { namespace spirit
{
///////////////////////////////////////////////////////////////////////////
// Enablers
///////////////////////////////////////////////////////////////////////////
template <>
struct use_directive<karma::domain, tag::strict> // enables strict[]
: mpl::true_ {};
template <>
struct use_directive<karma::domain, tag::relaxed> // enables relaxed[]
: mpl::true_ {};
///////////////////////////////////////////////////////////////////////////
template <>
struct is_modifier_directive<karma::domain, tag::strict>
: mpl::true_ {};
template <>
struct is_modifier_directive<karma::domain, tag::relaxed>
: mpl::true_ {};
///////////////////////////////////////////////////////////////////////////
// Don't add tag::strict or tag::relaxed if there is already one of those
// in the modifier list
template <typename Current>
struct compound_modifier<Current, tag::strict
, typename enable_if<has_modifier<Current, tag::relaxed> >::type>
: Current
{
compound_modifier()
: Current() {}
compound_modifier(Current const& current, tag::strict const&)
: Current(current) {}
};
template <typename Current>
struct compound_modifier<Current, tag::relaxed
, typename enable_if<has_modifier<Current, tag::strict> >::type>
: Current
{
compound_modifier()
: Current() {}
compound_modifier(Current const& current, tag::relaxed const&)
: Current(current) {}
};
namespace karma
{
using boost::spirit::strict;
using boost::spirit::strict_type;
using boost::spirit::relaxed;
using boost::spirit::relaxed_type;
}
}}
#endif
| pennwin2013/netsvr | include/boost/spirit/home/karma/directive/strict_relaxed.hpp | C++ | apache-2.0 | 2,438 |
<script type='text/javascript' src='{template_url}/js/jquery-1.10.2.js'></script>
<script type='text/javascript' src='{template_url}/js/bootstrap.min.js'></script>
<script type='text/javascript' src='{template_url}/js/tip-image.js'></script>
<script type='text/javascript' src='{template_url}/js/mytip.js'></script>
<script>
$(function() {
$('.tipsy-atas').tipsy
({
fade: true,
gravity: 's'
});
$('.tipsy-bawah').tipsy
({
fade: true,
gravity: 'n'
});
$('.tipsy-kiri').tipsy
({
fade: true,
gravity: 'e'
});
$('.tipsy-kanan').tipsy
({
fade: true,
gravity: 'w'
});
$('.tipsy-kanan-bawah').tipsy
({
fade: true,
gravity: 'nw'
});
$('.tipsy-kanan-atas').tipsy
({
fade: true,
gravity: 'sw'
});
$('.tipsy-kiri-bawah').tipsy
({
fade: true,
gravity: 'ne'
});
$('.tipsy-kiri-atas').tipsy
({
fade: true,
gravity: 'se'
});
});
</script>
| megablogging/megablogging | template/default/javascript.php | PHP | apache-2.0 | 947 |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# encoding: utf-8
# Copyright 2014 Orange
#
# 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 os.path
import sys
from logging import Logger
import logging.config
# import logging_tree
import traceback
from daemon import runner
import signal
from ConfigParser import SafeConfigParser, NoSectionError
from optparse import OptionParser
from bagpipe.bgp.common import utils
from bagpipe.bgp.common.looking_glass import LookingGlass, \
LookingGlassLogHandler
from bagpipe.bgp.engine.bgp_manager import Manager
from bagpipe.bgp.rest_api import RESTAPI
from bagpipe.bgp.vpn import VPNManager
def findDataplaneDrivers(dpConfigs, bgpConfig, isCleaningUp=False):
drivers = dict()
for vpnType in dpConfigs.iterkeys():
dpConfig = dpConfigs[vpnType]
if 'dataplane_driver' not in dpConfig:
logging.error(
"no dataplane_driver set for %s (%s)", vpnType, dpConfig)
driverName = dpConfig["dataplane_driver"]
logging.debug(
"Creating dataplane driver for %s, with %s", vpnType, driverName)
# FIXME: this is a hack, dataplane drivers should have a better way to
# access any item in the BGP dataplaneConfig
if 'dataplane_local_address' not in dpConfig:
dpConfig['dataplane_local_address'] = bgpConfig['local_address']
for tentativeClassName in (driverName,
'bagpipe.%s' % driverName,
'bagpipe.bgp.%s' % driverName,
'bagpipe.bgp.vpn.%s.%s' % (
vpnType, driverName),
):
try:
if '.' not in tentativeClassName:
logging.debug(
"Not trying to import '%s'", tentativeClassName)
continue
driverClass = utils.import_class(tentativeClassName)
try:
logging.info("Found driver for %s, initiating...", vpnType)
# skip the init step if called for cleanup
driver = driverClass(dpConfig, not isCleaningUp)
drivers[vpnType] = driver
logging.info(
"Successfully initiated dataplane driver for %s with"
" %s", vpnType, tentativeClassName)
except ImportError as e:
logging.debug(
"Could not initiate dataplane driver for %s with"
" %s: %s", vpnType, tentativeClassName, e)
except Exception as e:
logging.error(
"Found class, but error while instantiating dataplane"
" driver for %s with %s: %s", vpnType,
tentativeClassName, e)
logging.error(traceback.format_exc())
break
break
except SyntaxError as e:
logging.error(
"Found class, but syntax error while instantiating "
"dataplane driver for %s with %s: %s", vpnType,
tentativeClassName, e)
break
except Exception as e:
logging.debug(
"Could not initiate dataplane driver for %s with %s (%s)",
vpnType, tentativeClassName, e)
return drivers
class BgpDaemon(LookingGlass):
def __init__(self, catchAllLGLogHandler, **kwargs):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/null'
self.stderr_path = '/dev/null'
self.pidfile_path = '/var/run/bagpipe-bgp/bagpipe-bgp.pid'
self.pidfile_timeout = 5
logging.info("BGP manager configuration : %s", kwargs["bgpConfig"])
self.bgpConfig = kwargs["bgpConfig"]
logging.info("BGP dataplane dataplaneDriver configuration : %s",
kwargs["dataplaneConfig"])
self.dataplaneConfig = kwargs["dataplaneConfig"]
logging.info("BGP API configuration : %s", kwargs["apiConfig"])
self.apiConfig = kwargs["apiConfig"]
self.catchAllLGLogHandler = catchAllLGLogHandler
def run(self):
logging.info("Starting BGP component...")
logging.debug("Creating dataplane drivers")
drivers = findDataplaneDrivers(self.dataplaneConfig, self.bgpConfig)
for vpnType in self.dataplaneConfig.iterkeys():
if vpnType not in drivers:
logging.error(
"Could not initiate any dataplane driver for %s", vpnType)
return
logging.debug("Creating BGP manager")
self.bgpManager = Manager(self.bgpConfig)
logging.debug("Creating VPN manager")
self.vpnManager = VPNManager(self.bgpManager, drivers)
# BGP component REST API
logging.debug("Creating REST API")
bgpapi = RESTAPI(
self.apiConfig, self, self.vpnManager, self.catchAllLGLogHandler)
bgpapi.run()
def stop(self, signum, frame):
logging.info("Received signal %(signum)r, stopping...", vars())
self.vpnManager.stop()
self.bgpManager.stop()
# would need to stop main thread ?
logging.info("All threads now stopped...")
exception = SystemExit("Terminated on signal %(signum)r" % vars())
raise exception
def getLookingGlassLocalInfo(self, pathPrefix):
return {
"dataplane": self.dataplaneConfig,
"bgp": self.bgpConfig
}
def _loadConfig(configFile):
parser = SafeConfigParser()
if (len(parser.read(configFile)) == 0):
logging.error("Configuration file not found (%s)", configFile)
exit()
bgpConfig = parser.items("BGP")
dataplaneConfig = dict()
for vpnType in ['ipvpn', 'evpn']:
try:
dataplaneConfig[vpnType] = dict(
parser.items("DATAPLANE_DRIVER_%s" % vpnType.upper()))
except NoSectionError:
if vpnType == "ipvpn": # backward compat for ipvpn
dataplaneConfig['ipvpn'] = dict(
parser.items("DATAPLANE_DRIVER"))
logging.warning("Config file is obsolete, should have a "
"DATAPLANE_DRIVER_IPVPN section instead of"
" DATAPLANE_DRIVER")
else:
logging.error(
"Config file should have a DATAPLANE_DRIVER_EVPN section")
apiConfig = parser.items("API")
# TODO: add a default API config
config = {"bgpConfig": dict(bgpConfig),
"dataplaneConfig": dataplaneConfig,
"apiConfig": dict(apiConfig)
}
return config
def daemon_main():
usage = "usage: %prog [options] (see --help)"
parser = OptionParser(usage)
parser.add_option("--config-file", dest="configFile",
help="Set BGP component configuration file path",
default="/etc/bagpipe-bgp/bgp.conf")
parser.add_option("--log-file", dest="logFile",
help="Set logging configuration file path",
default="/etc/bagpipe-bgp/log.conf")
parser.add_option("--no-daemon", dest="daemon", action="store_false",
help="Do not daemonize", default=True)
(options, _) = parser.parse_args()
action = sys.argv[1]
assert(action == "start" or action == "stop")
if not os.path.isfile(options.logFile):
logging.basicConfig()
print "no logging configuration file at %s" % options.logFile
logging.warning("no logging configuration file at %s", options.logFile)
else:
logging.config.fileConfig(
options.logFile, disable_existing_loggers=False)
if action == "start":
logging.root.name = "Main"
logging.info("Starting...")
else: # stop
logging.root.name = "Stopper"
logging.info("Signal daemon to stop")
catchAllLogHandler = LookingGlassLogHandler()
# we inject this catch all log handler in all configured loggers
for (loggerName, logger) in Logger.manager.loggerDict.iteritems():
if isinstance(logger, Logger):
if (not logger.propagate and logger.parent is not None):
logging.debug("Adding looking glass log handler to logger: %s",
loggerName)
logger.addHandler(catchAllLogHandler)
logging.root.addHandler(catchAllLogHandler)
# logging_tree.printout()
config = _loadConfig(options.configFile)
bgpDaemon = BgpDaemon(catchAllLogHandler, **config)
try:
if options.daemon:
daemon_runner = runner.DaemonRunner(bgpDaemon)
# This ensures that the logger file handler does not get closed
# during daemonization
daemon_runner.daemon_context.files_preserve = [
logging.getLogger().handlers[0].stream]
daemon_runner.daemon_context.signal_map = {
signal.SIGTERM: bgpDaemon.stop
}
daemon_runner.do_action()
else:
signal.signal(signal.SIGTERM, bgpDaemon.stop)
signal.signal(signal.SIGINT, bgpDaemon.stop)
bgpDaemon.run()
except Exception as e:
logging.exception("Error while starting BGP daemon: %s", e)
logging.info("BGP component main thread stopped.")
def cleanup_main():
usage = "usage: %prog [options] (see --help)"
parser = OptionParser(usage)
parser.add_option("--config-file", dest="configFile",
help="Set BGP component configuration file path",
default="/etc/bagpipe-bgp/bgp.conf")
parser.add_option("--log-file", dest="logFile",
help="Set logging configuration file path",
default="/etc/bagpipe-bgp/log.conf")
(options, _) = parser.parse_args()
if not os.path.isfile(options.logFile):
print "no logging configuration file at %s" % options.logFile
logging.basicConfig()
else:
logging.config.fileConfig(
options.logFile, disable_existing_loggers=False)
logging.root.name = "[BgpDataplaneCleaner]"
logging.info("Cleaning BGP component dataplanes...")
config = _loadConfig(options.configFile)
drivers = findDataplaneDrivers(
config["dataplaneConfig"], config["bgpConfig"], isCleaningUp=True)
for (vpnType, dataplaneDriver) in drivers.iteritems():
logging.info("Cleaning BGP component dataplane for %s...", vpnType)
dataplaneDriver.resetState()
logging.info("BGP component dataplanes have been cleaned up.")
if __name__ == '__main__':
daemon_main()
| murat1985/bagpipe-bgp | bagpipe/bgp/bgp_daemon.py | Python | apache-2.0 | 11,381 |
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor
#
# 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.
"""Contains the logic for `aq update interface --machine`."""
from aquilon.exceptions_ import ArgumentError, AquilonError
from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611
from aquilon.worker.dbwrappers.interface import (verify_port_group,
choose_port_group,
assign_address,
rename_interface)
from aquilon.worker.locks import lock_queue
from aquilon.worker.templates.machine import PlenaryMachineInfo
from aquilon.worker.processes import DSDBRunner
from aquilon.aqdb.model import Machine, Interface, Model
from aquilon.utils import first_of
class CommandUpdateInterfaceMachine(BrokerCommand):
required_parameters = ["interface", "machine"]
def render(self, session, logger, interface, machine, mac, model, vendor,
boot, pg, autopg, comments, master, clear_master, default_route,
rename_to, **arguments):
"""This command expects to locate an interface based only on name
and machine - all other fields, if specified, are meant as updates.
If the machine has a host, dsdb may need to be updated.
The boot flag can *only* be set to true. This is mostly technical,
as at this point in the interface it is difficult to tell if the
flag was unset or set to false. However, it also vastly simplifies
the dsdb logic - we never have to worry about a user trying to
remove the boot flag from a host in dsdb.
"""
audit_results = []
dbhw_ent = Machine.get_unique(session, machine, compel=True)
dbinterface = Interface.get_unique(session, hardware_entity=dbhw_ent,
name=interface, compel=True)
oldinfo = DSDBRunner.snapshot_hw(dbhw_ent)
if arguments.get('hostname', None):
# Hack to set an intial interface for an aurora host...
dbhost = dbhw_ent.host
if dbhost.archetype.name == 'aurora' and \
dbhw_ent.primary_ip and not dbinterface.addresses:
assign_address(dbinterface, dbhw_ent.primary_ip,
dbhw_ent.primary_name.network)
# We may need extra IP verification (or an autoip option)...
# This may also throw spurious errors if attempting to set the
# port_group to a value it already has.
if pg is not None and dbinterface.port_group != pg.lower().strip():
dbinterface.port_group = verify_port_group(
dbinterface.hardware_entity, pg)
elif autopg:
dbinterface.port_group = choose_port_group(
session, logger, dbinterface.hardware_entity)
audit_results.append(('pg', dbinterface.port_group))
if master:
if dbinterface.addresses:
# FIXME: as a special case, if the only address is the
# primary IP, then we could just move it to the master
# interface. However this can be worked around by bonding
# the interface before calling "add host", so don't bother
# for now.
raise ArgumentError("Can not enslave {0:l} because it has "
"addresses.".format(dbinterface))
dbmaster = Interface.get_unique(session, hardware_entity=dbhw_ent,
name=master, compel=True)
if dbmaster in dbinterface.all_slaves():
raise ArgumentError("Enslaving {0:l} would create a circle, "
"which is not allowed.".format(dbinterface))
dbinterface.master = dbmaster
if clear_master:
if not dbinterface.master:
raise ArgumentError("{0} is not a slave.".format(dbinterface))
dbinterface.master = None
if comments:
dbinterface.comments = comments
if boot:
# Should we also transfer the primary IP to the new boot interface?
# That could get tricky if the new interface already has an IP
# address...
for i in dbhw_ent.interfaces:
if i == dbinterface:
i.bootable = True
i.default_route = True
else:
i.bootable = False
i.default_route = False
if default_route is not None:
dbinterface.default_route = default_route
if not first_of(dbhw_ent.interfaces, lambda x: x.default_route):
logger.client_info("Warning: {0:l} has no default route, hope "
"that's ok.".format(dbhw_ent))
#Set this mac address last so that you can update to a bootable
#interface *before* adding a mac address. This is so the validation
#that takes place in the interface class doesn't have to be worried
#about the order of update to bootable=True and mac address
if mac:
q = session.query(Interface).filter_by(mac=mac)
other = q.first()
if other and other != dbinterface:
raise ArgumentError("MAC address {0} is already in use by "
"{1:l}.".format(mac, other))
dbinterface.mac = mac
if model or vendor:
if not dbinterface.model_allowed:
raise ArgumentError("Model/vendor can not be set for a {0:lc}."
.format(dbinterface))
dbmodel = Model.get_unique(session, name=model, vendor=vendor,
machine_type='nic', compel=True)
dbinterface.model = dbmodel
if rename_to:
rename_interface(session, dbinterface, rename_to)
session.flush()
session.refresh(dbhw_ent)
plenary_info = PlenaryMachineInfo(dbhw_ent, logger=logger)
key = plenary_info.get_write_key()
try:
lock_queue.acquire(key)
plenary_info.write(locked=True)
if dbhw_ent.host and dbhw_ent.host.archetype.name != "aurora":
dsdb_runner = DSDBRunner(logger=logger)
dsdb_runner.update_host(dbhw_ent, oldinfo)
dsdb_runner.commit_or_rollback()
except AquilonError, err:
plenary_info.restore_stash()
raise ArgumentError(err)
except:
plenary_info.restore_stash()
raise
finally:
lock_queue.release(key)
for name, value in audit_results:
self.audit_result(session, name, value, **arguments)
return
| stdweird/aquilon | lib/python2.6/aquilon/worker/commands/update_interface_machine.py | Python | apache-2.0 | 7,493 |
<h3>
<!-- START Language list-->
<div class="pull-right">
<div class="btn-group" uib-dropdown="" is-open="language.listIsOpen">
<button class="btn btn-default" type="button" uib-dropdown-toggle="">{{language.selected}}
<span class="caret"></span>
</button>
<ul class="dropdown-menu dropdown-menu-right animated fadeInUpShort" role="menu">
<li ng-repeat="(localeId, langName) in language.available"><a ng-click="language.set(localeId, $event)" href="#">{{langName}}</a>
</li>
</ul>
</div>
</div>
<!-- END Language list -->Dashboard
<small>{{ 'dashboard.WELCOME' | translate:{ appName: app.name } }} !</small>
</h3>
<div class="row">
<div class="col-lg-4">
<!-- START List group-->
<ul class="list-group">
<li class="list-group-item">
<div class="row row-table pv-lg">
<div class="col-xs-6">
<p class="m0 lead">1204</p>
<p class="m0">
<small>Commits this month</small>
</p>
</div>
<div class="col-xs-6 text-center">
<div sparkline="" data-bar-color="{{colorByName('info')}}" data-height="60" data-bar-width="10" data-bar-spacing="6" data-chart-range-min="0" values="3,6,7,8,4,5"></div>
</div>
</div>
</li>
<li class="list-group-item">
<div class="row row-table pv-lg">
<div class="col-xs-6">
<p class="m0 lead">$ 3,200.00</p>
<p class="m0">
<small>Available budget</small>
</p>
</div>
<div class="col-xs-6 text-center">
<div sparkline="" data-type="line" data-height="60" data-width="80%" data-line-width="2" data-line-color="{{colorByName('purple')}}" data-chart-range-min="0" data-spot-color="#888" data-min-spot-color="{{colorByName('purple')}}" data-max-spot-color="{{colorByName('purple')}}"
data-fill-color="" data-highlight-line-color="#fff" data-spot-radius="3" values="7,3,4,7,5,9,4,4,7,5,9,6,4" data-resize="true"></div>
</div>
</div>
</li>
<li class="list-group-item">
<div class="row row-table pv-lg">
<div class="col-xs-6">
<p class="m0 lead">67</p>
<p class="m0">
<small>New followers</small>
</p>
</div>
<div class="col-xs-6">
<ul class="list-inline text-center">
<li>
<a href="#" uib-tooltip="Katie">
<img class="img-responsive img-circle thumb24" src="app/img/user/02.jpg" alt="Follower" />
</a>
</li>
<li>
<a href="#" uib-tooltip="Cody">
<img class="img-responsive img-circle thumb24" src="app/img/user/01.jpg" alt="Follower" />
</a>
</li>
<li>
<a href="#" uib-tooltip="Tamara">
<img class="img-responsive img-circle thumb24" src="app/img/user/03.jpg" alt="Follower" />
</a>
</li>
<li>
<a href="#" uib-tooltip="Gene">
<img class="img-responsive img-circle thumb24" src="app/img/user/04.jpg" alt="Follower" />
</a>
</li>
<li>
<a href="#" uib-tooltip="Marsha">
<img class="img-responsive img-circle thumb24" src="app/img/user/04.jpg" alt="Follower" />
</a>
</li>
<li>
<a href="#" uib-tooltip="Robin">
<img class="img-responsive img-circle thumb24" src="app/img/user/09.jpg" alt="Follower" />
</a>
</li>
</ul>
</div>
</div>
</li>
</ul>
<!-- END List group-->
</div>
<div class="col-lg-8">
<!-- START bar chart-->
<div class="panel" id="panelChart3">
<div class="panel-heading">
<!-- START button group-->
<div class="pull-right btn-group" uib-dropdown="dropdown2">
<button class="btn btn-default btn-sm" type="button" uib-dropdown-toggle="">Monthly</button>
<ul class="dropdown-menu fadeInLeft animated" role="menu">
<li><a href="#">Daily</a>
</li>
<li><a href="#">Monthly</a>
</li>
<li><a href="#">Yearly</a>
</li>
</ul>
</div>
<!-- END button group-->
<div class="panel-title">Projects Hours</div>
</div>
<div class="panel-wrapper" uib-collapse="panelChart3">
<div class="panel-body">
<flot src="'server/chart/barstackedv2.json'" options="dash2.barStackedOptions" height="250px"></flot>
</div>
</div>
</div>
<!-- END bar chart-->
</div>
</div>
<div class="unwrap mv-lg">
<!-- START chart-->
<div class="panel" id="panelChart9">
<div class="panel-heading">
<!-- START button group-->
<div class="pull-right btn-group" uib-dropdown="dropdown1">
<button class="btn btn-default btn-sm" type="button" uib-dropdown-toggle="">All time</button>
<ul class="dropdown-menu fadeInLeft animated" role="menu">
<li><a href="#">Daily</a>
</li>
<li><a href="#">Monthly</a>
</li>
<li class="divider"></li>
<li><a href="#">All time</a>
</li>
</ul>
</div>
<!-- END button group-->
<div class="panel-title">Overall progress</div>
</div>
<div class="panel-wrapper" uib-collapse="panelChart9">
<div class="panel-body">
<flot src="'server/chart/splinev2.json'" options="dash2.splineOptions" height="300px"></flot>
</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-3 col-xs-6 text-center">
<p>Projects</p>
<div class="h1">25</div>
</div>
<div class="col-sm-3 col-xs-6 text-center">
<p>Teammates</p>
<div class="h1">85</div>
</div>
<div class="col-sm-3 col-xs-6 text-center">
<p>Hours</p>
<div class="h1">380</div>
</div>
<div class="col-sm-3 col-xs-6 text-center">
<p>Budget</p>
<div class="h1">$ 10,000.00</div>
</div>
</div>
</div>
</div>
</div>
<!-- END chart-->
</div>
<!-- START radial charts-->
<div class="row mb-lg">
<div class="col-sm-3 col-xs-6 text-center">
<p>Current Project</p>
<canvas classyloader="" data-height="150px" data-diameter="60" data-font-size="25px" data-percentage="60" data-speed="30" data-line-color="{{colorByName('info')}}" data-remaining-line-color="#edf2f6" data-line-width="2"></canvas>
</div>
<div class="col-sm-3 col-xs-6 text-center">
<p>Current Progress</p>
<canvas classyloader="" data-height="150px" data-diameter="60" data-font-size="25px" data-percentage="30" data-speed="30" data-line-color="{{colorByName('pink')}}" data-remaining-line-color="#edf2f6" data-line-width="2"></canvas>
</div>
<div class="col-sm-3 col-xs-6 text-center">
<p>Space Usage</p>
<canvas classyloader="" data-height="150px" data-diameter="60" data-font-size="25px" data-percentage="50" data-speed="30" data-line-color="{{colorByName('purple')}}" data-remaining-line-color="#edf2f6" data-line-width="2"></canvas>
</div>
<div class="col-sm-3 col-xs-6 text-center">
<p>Interactions</p>
<canvas classyloader="" data-height="150px" data-diameter="60" data-font-size="25px" data-percentage="75" data-speed="30" data-line-color="{{colorByName('warning')}}" data-remaining-line-color="#edf2f6" data-line-width="2"></canvas>
</div>
</div>
<!-- START radial charts-->
<!-- START Multiple List group-->
<div class="list-group">
<a class="list-group-item" href="#">
<table class="wd-wide">
<tbody>
<tr>
<td class="wd-xs">
<div class="ph">
<img class="media-box-object img-responsive img-rounded thumb64" src="app/img/dummy.png" alt="" />
</div>
</td>
<td>
<div class="ph">
<h4 class="media-box-heading">Project A</h4>
<small class="text-muted">Vestibulum ante ipsum primis in faucibus orci</small>
</div>
</td>
<td class="wd-sm hidden-xs hidden-sm">
<div class="ph">
<p class="m0">Last change</p>
<small class="text-muted">4 weeks ago</small>
</div>
</td>
<td class="wd-xs hidden-xs hidden-sm">
<div class="ph">
<p class="m0 text-muted">
<em class="icon-user mr fa-lg"></em>26</p>
</div>
</td>
<td class="wd-xs hidden-xs hidden-sm">
<div class="ph">
<p class="m0 text-muted">
<em class="icon-doc mr fa-lg"></em>3500</p>
</div>
</td>
<td class="wd-sm">
<div class="ph">
<uib-progressbar class="m0 progress-xs" value="80" type="success">80%</uib-progressbar>
</div>
</td>
</tr>
</tbody>
</table>
</a>
</div>
<div class="list-group">
<a class="list-group-item" href="#">
<table class="wd-wide">
<tbody>
<tr>
<td class="wd-xs">
<div class="ph">
<img class="media-box-object img-responsive img-rounded thumb64" src="app/img/dummy.png" alt="" />
</div>
</td>
<td>
<div class="ph">
<h4 class="media-box-heading">Project X</h4>
<small class="text-muted">Vestibulum ante ipsum primis in faucibus orci</small>
</div>
</td>
<td class="wd-sm hidden-xs hidden-sm">
<div class="ph">
<p class="m0">Last change</p>
<small class="text-muted">Today at 06:23 am</small>
</div>
</td>
<td class="wd-xs hidden-xs hidden-sm">
<div class="ph">
<p class="m0 text-muted">
<em class="icon-user mr fa-lg"></em>3</p>
</div>
</td>
<td class="wd-xs hidden-xs hidden-sm">
<div class="ph">
<p class="m0 text-muted">
<em class="icon-doc mr fa-lg"></em>150</p>
</div>
</td>
<td class="wd-sm">
<div class="ph">
<uib-progressbar class="m0 progress-xs" value="50" type="purple">50%</uib-progressbar>
</div>
</td>
</tr>
</tbody>
</table>
</a>
</div>
<div class="list-group">
<a class="list-group-item" href="#">
<table class="wd-wide">
<tbody>
<tr>
<td class="wd-xs">
<div class="ph">
<img class="media-box-object img-responsive img-rounded thumb64" src="app/img/dummy.png" alt="" />
</div>
</td>
<td>
<div class="ph">
<h4 class="media-box-heading">Project Z</h4>
<small class="text-muted">Vestibulum ante ipsum primis in faucibus orci</small>
</div>
</td>
<td class="wd-sm hidden-xs hidden-sm">
<div class="ph">
<p class="m0">Last change</p>
<small class="text-muted">Yesterday at 10:20 pm</small>
</div>
</td>
<td class="wd-xs hidden-xs hidden-sm">
<div class="ph">
<p class="m0 text-muted">
<em class="icon-user mr fa-lg"></em>15</p>
</div>
</td>
<td class="wd-xs hidden-xs hidden-sm">
<div class="ph">
<p class="m0 text-muted">
<em class="icon-doc mr fa-lg"></em>480</p>
</div>
</td>
<td class="wd-sm">
<div class="ph">
<uib-progressbar class="m0 progress-xs" value="20" type="green">20%</uib-progressbar>
</div>
</td>
</tr>
</tbody>
</table>
</a>
<!-- END dashboard main content-->
</div>
<!-- END Multiple List group--> | gbhu/studynotes-projects | mybatispractice/target/MybatisPractice/app/views/dashboard_v2.html | HTML | apache-2.0 | 13,722 |
#!/usr/bin/env python2.7
# Copyright 2015 Cisco Systems, 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.
''' Sample usage of function 'inventory_not_connected' to show which devices are mounted, but not connected.
Print the function's documentation then invoke the function and print the output.
'''
from __future__ import print_function as _print_function
from basics.inventory import inventory_not_connected
from basics.render import print_table
from pydoc import render_doc as doc
from pydoc import plain
def main():
print(plain(doc(inventory_not_connected)))
print("inventory_not_connected()")
print_table(inventory_not_connected(), headers='device-name')
if __name__ == "__main__":
main() | tbarrongh/cosc-learning-labs | src/learning_lab/01_inventory_not_connected.py | Python | apache-2.0 | 1,219 |
---
layout: vakit_dashboard
title: KLØFTA, NORVEC için iftar, namaz vakitleri ve hava durumu - ilçe/eyalet seç
permalink: /NORVEC/KLØFTA/
---
<script type="text/javascript">
var GLOBAL_COUNTRY = 'NORVEC';
var GLOBAL_CITY = 'KLØFTA';
var GLOBAL_STATE = '';
var lat = 72;
var lon = 21;
</script>
| hakanu/iftar | _posts_/vakit/NORVEC/KLØFTA/2017-02-01-.markdown | Markdown | apache-2.0 | 311 |
/*
* 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.sql.execution.datasources.v2.orc
import scala.collection.JavaConverters._
import org.apache.hadoop.fs.FileStatus
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.connector.write.{LogicalWriteInfo, Write, WriteBuilder}
import org.apache.spark.sql.execution.datasources.FileFormat
import org.apache.spark.sql.execution.datasources.orc.OrcUtils
import org.apache.spark.sql.execution.datasources.v2.FileTable
import org.apache.spark.sql.types._
import org.apache.spark.sql.util.CaseInsensitiveStringMap
case class OrcTable(
name: String,
sparkSession: SparkSession,
options: CaseInsensitiveStringMap,
paths: Seq[String],
userSpecifiedSchema: Option[StructType],
fallbackFileFormat: Class[_ <: FileFormat])
extends FileTable(sparkSession, options, paths, userSpecifiedSchema) {
override def newScanBuilder(options: CaseInsensitiveStringMap): OrcScanBuilder =
new OrcScanBuilder(sparkSession, fileIndex, schema, dataSchema, options)
override def inferSchema(files: Seq[FileStatus]): Option[StructType] =
OrcUtils.inferSchema(sparkSession, files, options.asScala.toMap)
override def newWriteBuilder(info: LogicalWriteInfo): WriteBuilder =
new WriteBuilder {
override def build(): Write = OrcWrite(paths, formatName, supportsDataType, info)
}
override def supportsDataType(dataType: DataType): Boolean = dataType match {
case _: AnsiIntervalType => false
case _: AtomicType => true
case st: StructType => st.forall { f => supportsDataType(f.dataType) }
case ArrayType(elementType, _) => supportsDataType(elementType)
case MapType(keyType, valueType, _) =>
supportsDataType(keyType) && supportsDataType(valueType)
case udt: UserDefinedType[_] => supportsDataType(udt.sqlType)
case _ => false
}
override def formatName: String = "ORC"
}
| chuckchen/spark | sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/orc/OrcTable.scala | Scala | apache-2.0 | 2,682 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_43) on Fri Apr 19 11:40:07 CEST 2013 -->
<TITLE>
PuntosSecureAPI
</TITLE>
<META NAME="date" CONTENT="2013-04-19">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="PuntosSecureAPI";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/PuntosSecureAPI.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../org/tourgune/apptrack/controller/api/secure/DeveloperSecureAPI.html" title="class in org.tourgune.apptrack.controller.api.secure"><B>PREV CLASS</B></A>
<A HREF="../../../../../../org/tourgune/apptrack/controller/api/secure/VariableSecureAPI.html" title="class in org.tourgune.apptrack.controller.api.secure"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/tourgune/apptrack/controller/api/secure/PuntosSecureAPI.html" target="_top"><B>FRAMES</B></A>
<A HREF="PuntosSecureAPI.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.tourgune.apptrack.controller.api.secure</FONT>
<BR>
Class PuntosSecureAPI</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../../../resources/inherit.gif" ALT="extended by "><B>org.tourgune.apptrack.controller.api.secure.PuntosSecureAPI</B>
</PRE>
<HR>
<DL>
<DT><PRE><FONT SIZE="-1">@Controller
@RequestMapping(value="api/puntos")
</FONT>public class <B>PuntosSecureAPI</B><DT>extends java.lang.Object</DL>
</PRE>
<P>
Controlador privado encargado tratar peticiones HTTP relacionadas con la gestion de puntos.
<P>
<P>
<DL>
<DT><B>Author:</B></DT>
<DD>mariaperalta</DD>
</DL>
<HR>
<P>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../org/tourgune/apptrack/controller/api/secure/PuntosSecureAPI.html#PuntosSecureAPI()">PuntosSecureAPI</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.util.List<<A HREF="../../../../../../org/tourgune/apptrack/bean/Punto.html" title="class in org.tourgune.apptrack.bean">Punto</A>></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/tourgune/apptrack/controller/api/secure/PuntosSecureAPI.html#getListaPuntos(java.lang.String, int, java.lang.String, java.lang.String)">getListaPuntos</A></B>(java.lang.String jsonString,
int idaplicacion,
java.lang.String fecha_desde,
java.lang.String fecha_hasta)</CODE>
<BR>
Controlador encargado de consultar la lista de puntos entre fecha_desde y fecha_hasta, de una aplicación en concreto</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="PuntosSecureAPI()"><!-- --></A><H3>
PuntosSecureAPI</H3>
<PRE>
public <B>PuntosSecureAPI</B>()</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getListaPuntos(java.lang.String, int, java.lang.String, java.lang.String)"><!-- --></A><H3>
getListaPuntos</H3>
<PRE>
<FONT SIZE="-1">@RequestMapping(value="/puntos",
method=POST)
@ResponseBody
</FONT>public java.util.List<<A HREF="../../../../../../org/tourgune/apptrack/bean/Punto.html" title="class in org.tourgune.apptrack.bean">Punto</A>> <B>getListaPuntos</B>(<FONT SIZE="-1">@RequestBody</FONT>
java.lang.String jsonString,
<FONT SIZE="-1">@RequestParam(value="idaplicacion",required=false)</FONT>
int idaplicacion,
<FONT SIZE="-1">@RequestParam(value="fecha_desde",required=false)</FONT>
java.lang.String fecha_desde,
<FONT SIZE="-1">@RequestParam(value="fecha_hasta",required=false)</FONT>
java.lang.String fecha_hasta)</PRE>
<DL>
<DD>Controlador encargado de consultar la lista de puntos entre fecha_desde y fecha_hasta, de una aplicación en concreto
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>jsonString</CODE> - JSON de la lista de valores. Esta variable contiene los parametros de búsqueda<DD><CODE>idaplicacion</CODE> - Identificador de la aplicación que se quiere consultar<DD><CODE>fecha_desde</CODE> - Fecha desde la cual se quiere realizar la consulta<DD><CODE>fecha_hasta</CODE> - Desde hasta la cual se quiere realizar la consulta
<DT><B>Returns:</B><DD>Devuelve una lista de Punto que cumplen las condiciones de la busqueda</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/PuntosSecureAPI.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../org/tourgune/apptrack/controller/api/secure/DeveloperSecureAPI.html" title="class in org.tourgune.apptrack.controller.api.secure"><B>PREV CLASS</B></A>
<A HREF="../../../../../../org/tourgune/apptrack/controller/api/secure/VariableSecureAPI.html" title="class in org.tourgune.apptrack.controller.api.secure"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/tourgune/apptrack/controller/api/secure/PuntosSecureAPI.html" target="_top"><B>FRAMES</B></A>
<A HREF="PuntosSecureAPI.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| cictourgune/apptrack-web | doc/org/tourgune/apptrack/controller/api/secure/PuntosSecureAPI.html | HTML | apache-2.0 | 12,715 |
package org.marketcetera.photon.ui.databinding;
import java.util.Collections;
import org.apache.commons.lang.StringUtils;
import org.marketcetera.photon.commons.databinding.ITypedObservableValue;
import org.marketcetera.photon.commons.databinding.TypedObservableValueDecorator;
import org.marketcetera.trade.Equity;
import org.marketcetera.trade.Instrument;
import org.marketcetera.util.misc.ClassVersion;
/* $License$ */
/**
* Manages and {@link Equity} binding made up of a symbol string.
*
* @author <a href="mailto:will@marketcetera.com">Will Horn</a>
* @version $Id: EquityObservable.java 16154 2012-07-14 16:34:05Z colin $
* @since 2.0.0
*/
@ClassVersion("$Id: EquityObservable.java 16154 2012-07-14 16:34:05Z colin $")
public class EquityObservable extends
CompoundObservableManager<ITypedObservableValue<Instrument>> {
private final ITypedObservableValue<String> mSymbol;
public EquityObservable(ITypedObservableValue<Instrument> instrument) {
super(instrument);
mSymbol = TypedObservableValueDecorator.create(String.class);
init(Collections.singleton(mSymbol));
}
@Override
protected void updateChildren() {
Instrument instrument = getParent().getTypedValue();
if (instrument instanceof Equity) {
Equity equity = (Equity) instrument;
setIfChanged(mSymbol, equity.getSymbol());
} else {
setIfChanged(mSymbol, null);
}
}
@Override
protected void updateParent() {
String symbol = mSymbol.getTypedValue();
Equity newValue = null;
if (StringUtils.isNotBlank(symbol)) {
newValue = new Equity(symbol);
}
ITypedObservableValue<Instrument> instrument = getParent();
setIfChanged(instrument, newValue);
}
/**
* Returns an observable tied to the equity's symbol.
*
* @return an observable for the equity's symbol
*/
public ITypedObservableValue<String> observeSymbol() {
return mSymbol;
}
}
| nagyist/marketcetera | trunk/photon/plugins/org.marketcetera.photon/src/main/java/org/marketcetera/photon/ui/databinding/EquityObservable.java | Java | apache-2.0 | 2,105 |
package org.aksw.mlbenchmark.languages;
/**
* Framework values specific to owl
*/
public class OwlLanguageInfo extends LanguageInfoBase {
@Override
public String exampleExtension() {
return ".txt";
}
}
| AKSW/SML-Bench | src/main/java/org/aksw/mlbenchmark/languages/OwlLanguageInfo.java | Java | apache-2.0 | 210 |
/*
* Copyright (C) 2004-2006 Autodesk, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of version 2.1 of the GNU Lesser
* General Public License as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/// <library>GRFPOverrides.lib</library>
#ifndef FDOGRFPRASTERIMAGEDEFINITION_H
#define FDOGRFPRASTERIMAGEDEFINITION_H
#ifdef _WIN32
#pragma once
#endif //_WIN32
class FdoGrfpRasterExtents;
class FdoGrfpRasterGeoreferenceLocation;
/// <summary>
/// The FdoGrfpRasterImageDefinition class defines a raster image which contains a name
/// and the extents of the raster image.
/// </summary>
class FdoGrfpRasterImageDefinition : public FdoPhysicalElementMapping
{
typedef FdoPhysicalElementMapping BaseType;
friend class FdoGrfpRasterBandDefinition;
public:
/// <summary>Constructs a new Raster Image Definition.</summary>
/// <returns>Returns the newly created FdoGrfpRasterImageDefinition instance.</returns>
FDOGRFP_API static FdoGrfpRasterImageDefinition* Create();
/// <summary>Gets the frame number of the raster image.</summary>
/// <returns>Returns the frame number of the raster image.</returns>
FDOGRFP_API FdoInt32 GetFrameNumber();
/// <summary>Sets the frame number of the raster image.</summary>
/// <param name="extents">Input the frame number of the raster image.</param>
/// <returns>Returns nothing</returns>
FDOGRFP_API void SetFrameNumber(FdoInt32 frameNumber);
/// <summary>Gets the georeferenced location of the raster image.</summary>
/// <returns>Returns the georeferenced location of the raster image.</returns>
FDOGRFP_API FdoGrfpRasterGeoreferenceLocation * GetGeoreferencedLocation();
/// <summary>Sets the georeferenced location of the raster image.</summary>
/// <param name="location">Input the georeferenced location of the raster image.</param>
/// <returns>Returns nothing</returns>
FDOGRFP_API void SetGeoreferencedLocation (FdoGrfpRasterGeoreferenceLocation * location);
FDOGRFP_API bool GetBounds( double &minX, double &minY, double &maxX, double &maxY );
FDOGRFP_API void SetBounds( double minX, double minY, double maxX, double maxY );
//DOM-IGNORE-BEGIN
// XML Serialization functions, not part of supported API.
FDOGRFP_API virtual void InitFromXml(FdoXmlSaxContext* pContext, FdoXmlAttributeCollection* attrs);
FDOGRFP_API virtual FdoXmlSaxHandler* XmlStartElement(
FdoXmlSaxContext* context,
FdoString* uri,
FdoString* name,
FdoString* qname,
FdoXmlAttributeCollection* atts
);
FDOGRFP_API virtual FdoBoolean XmlEndElement(
FdoXmlSaxContext* context,
FdoString* uri,
FdoString* name,
FdoString* qname
);
FDOGRFP_API virtual void XmlCharacters(FdoXmlSaxContext*, FdoString*);
FDOGRFP_API void _writeXml( FdoXmlWriter* xmlWriter, const FdoXmlFlags* flags );
protected:
FDOGRFP_API FdoGrfpRasterImageDefinition(void);
FDOGRFP_API virtual ~FdoGrfpRasterImageDefinition(void);
void Dispose(void);
private:
FdoInt32 m_state;
FdoInt32 m_frameNumber;
FdoPtr<FdoGrfpRasterGeoreferenceLocation> m_geoReference;
bool m_haveBounds;
double m_minX;
double m_minY;
double m_maxX;
double m_maxY;
//DOM-IGNORE-END
};
/// <summary> FdoGrfpRasterImageDefinitionP is a FdoPtr on FdoGrfpRasterImageDefinition, provided for convenience. </summary>
typedef FdoPtr<FdoGrfpRasterImageDefinition> FdoGrfpRasterImageDefinitionP;
#endif
| SuperMap/Fdo_SuperMap | 源代码/Thirdparty/FDO/Inc/GdalFile/Override/FdoGrfpRasterImageDefinition.h | C | apache-2.0 | 4,029 |
/****************************************************************************
** Meta object code from reading C++ file 'finddialog.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../finddialog.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'finddialog.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.4.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_findDialog_t {
QByteArrayData data[7];
char stringdata[79];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_findDialog_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_findDialog_t qt_meta_stringdata_findDialog = {
{
QT_MOC_LITERAL(0, 0, 10), // "findDialog"
QT_MOC_LITERAL(1, 11, 8), // "findNext"
QT_MOC_LITERAL(2, 20, 0), // ""
QT_MOC_LITERAL(3, 21, 19), // "Qt::CaseSensitivity"
QT_MOC_LITERAL(4, 41, 8), // "findPrev"
QT_MOC_LITERAL(5, 50, 11), // "findClicked"
QT_MOC_LITERAL(6, 62, 16) // "enableFindButton"
},
"findDialog\0findNext\0\0Qt::CaseSensitivity\0"
"findPrev\0findClicked\0enableFindButton"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_findDialog[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
4, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
2, // signalCount
// signals: name, argc, parameters, tag, flags
1, 2, 34, 2, 0x06 /* Public */,
4, 2, 39, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
5, 0, 44, 2, 0x08 /* Private */,
6, 1, 45, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void, QMetaType::QString, 0x80000000 | 3, 2, 2,
QMetaType::Void, QMetaType::QString, 0x80000000 | 3, 2, 2,
// slots: parameters
QMetaType::Void,
QMetaType::Void, QMetaType::QString, 2,
0 // eod
};
void findDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
findDialog *_t = static_cast<findDialog *>(_o);
switch (_id) {
case 0: _t->findNext((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< Qt::CaseSensitivity(*)>(_a[2]))); break;
case 1: _t->findPrev((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< Qt::CaseSensitivity(*)>(_a[2]))); break;
case 2: _t->findClicked(); break;
case 3: _t->enableFindButton((*reinterpret_cast< const QString(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (findDialog::*_t)(const QString & , Qt::CaseSensitivity );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&findDialog::findNext)) {
*result = 0;
}
}
{
typedef void (findDialog::*_t)(const QString & , Qt::CaseSensitivity );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&findDialog::findPrev)) {
*result = 1;
}
}
}
}
const QMetaObject findDialog::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_findDialog.data,
qt_meta_data_findDialog, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *findDialog::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *findDialog::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_findDialog.stringdata))
return static_cast<void*>(const_cast< findDialog*>(this));
return QDialog::qt_metacast(_clname);
}
int findDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 4)
qt_static_metacall(this, _c, _id, _a);
_id -= 4;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 4)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 4;
}
return _id;
}
// SIGNAL 0
void findDialog::findNext(const QString & _t1, Qt::CaseSensitivity _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void findDialog::findPrev(const QString & _t1, Qt::CaseSensitivity _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 1, _a);
}
QT_END_MOC_NAMESPACE
| ChanJLee/ChanSpreadSheet | ChanSpreadsheet/GeneratedFiles/Release/moc_finddialog.cpp | C++ | apache-2.0 | 5,506 |
<!DOCTYPE html>
<!--
Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.2
Version: 3.7.0
Author: KeenThemes
Website: http://www.keenthemes.com/
Contact: support@keenthemes.com
Follow: www.twitter.com/keenthemes
Like: www.facebook.com/keenthemes
Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes
License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project.
-->
<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en" dir="rtl">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<meta charset="utf-8"/>
<title>Metronic | Form Stuff - Form Layouts</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta content="" name="description"/>
<meta content="" name="author"/>
<!-- BEGIN GLOBAL MANDATORY STYLES -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css">
<link href="../../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="../../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css">
<link href="../../assets/global/plugins/bootstrap/css/bootstrap-rtl.min.css" rel="stylesheet" type="text/css">
<link href="../../assets/global/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css">
<link href="../../assets/global/plugins/bootstrap-switch/css/bootstrap-switch-rtl.min.css" rel="stylesheet" type="text/css"/>
<!-- END GLOBAL MANDATORY STYLES -->
<!-- BEGIN PAGE LEVEL STYLES -->
<link rel="stylesheet" type="text/css" href="../../assets/global/plugins/select2/select2.css"/>
<!-- END PAGE LEVEL SCRIPTS -->
<!-- BEGIN THEME STYLES -->
<link href="../../assets/global/css/components-md-rtl.css" id="style_components" rel="stylesheet" type="text/css"/>
<link href="../../assets/global/css/plugins-md-rtl.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/admin/layout4/css/layout-rtl.css" rel="stylesheet" type="text/css"/>
<link id="style_color" href="../../assets/admin/layout4/css/themes/light-rtl.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/admin/layout4/css/custom-rtl.css" rel="stylesheet" type="text/css"/>
<!-- END THEME STYLES -->
<link rel="shortcut icon" href="favicon.ico"/>
</head>
<!-- END HEAD -->
<!-- BEGIN BODY -->
<!-- DOC: Apply "page-header-fixed-mobile" and "page-footer-fixed-mobile" class to body element to force fixed header or footer in mobile devices -->
<!-- DOC: Apply "page-sidebar-closed" class to the body and "page-sidebar-menu-closed" class to the sidebar menu element to hide the sidebar by default -->
<!-- DOC: Apply "page-sidebar-hide" class to the body to make the sidebar completely hidden on toggle -->
<!-- DOC: Apply "page-sidebar-closed-hide-logo" class to the body element to make the logo hidden on sidebar toggle -->
<!-- DOC: Apply "page-sidebar-hide" class to body element to completely hide the sidebar on sidebar toggle -->
<!-- DOC: Apply "page-sidebar-fixed" class to have fixed sidebar -->
<!-- DOC: Apply "page-footer-fixed" class to the body element to have fixed footer -->
<!-- DOC: Apply "page-sidebar-reversed" class to put the sidebar on the right side -->
<!-- DOC: Apply "page-full-width" class to the body element to have full width page without the sidebar menu -->
<body class="page-md page-header-fixed page-sidebar-closed-hide-logo ">
<!-- BEGIN HEADER -->
<div class="page-header md-shadow-z-1-i navbar navbar-fixed-top">
<!-- BEGIN HEADER INNER -->
<div class="page-header-inner">
<!-- BEGIN LOGO -->
<div class="page-logo">
<a href="index.html">
<img src="../../assets/admin/layout4/img/logo-light.png" alt="logo" class="logo-default"/>
</a>
<div class="menu-toggler sidebar-toggler">
<!-- DOC: Remove the above "hide" to enable the sidebar toggler button on header -->
</div>
</div>
<!-- END LOGO -->
<!-- BEGIN RESPONSIVE MENU TOGGLER -->
<a href="javascript:;" class="menu-toggler responsive-toggler" data-toggle="collapse" data-target=".navbar-collapse">
</a>
<!-- END RESPONSIVE MENU TOGGLER -->
<!-- BEGIN PAGE ACTIONS -->
<!-- DOC: Remove "hide" class to enable the page header actions -->
<div class="page-actions">
<div class="btn-group">
<button type="button" class="btn red-haze btn-sm dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<span class="hidden-sm hidden-xs">Actions </span><i class="fa fa-angle-down"></i>
</button>
<ul class="dropdown-menu" role="menu">
<li>
<a href="javascript:;">
<i class="icon-docs"></i> New Post </a>
</li>
<li>
<a href="javascript:;">
<i class="icon-tag"></i> New Comment </a>
</li>
<li>
<a href="javascript:;">
<i class="icon-share"></i> Share </a>
</li>
<li class="divider">
</li>
<li>
<a href="javascript:;">
<i class="icon-flag"></i> Comments <span class="badge badge-success">4</span>
</a>
</li>
<li>
<a href="javascript:;">
<i class="icon-users"></i> Feedbacks <span class="badge badge-danger">2</span>
</a>
</li>
</ul>
</div>
</div>
<!-- END PAGE ACTIONS -->
<!-- BEGIN PAGE TOP -->
<div class="page-top">
<!-- BEGIN HEADER SEARCH BOX -->
<!-- DOC: Apply "search-form-expanded" right after the "search-form" class to have half expanded search box -->
<form class="search-form" action="extra_search.html" method="GET">
<div class="input-group">
<input type="text" class="form-control input-sm" placeholder="Search..." name="query">
<span class="input-group-btn">
<a href="javascript:;" class="btn submit"><i class="icon-magnifier"></i></a>
</span>
</div>
</form>
<!-- END HEADER SEARCH BOX -->
<!-- BEGIN TOP NAVIGATION MENU -->
<div class="top-menu">
<ul class="nav navbar-nav pull-right">
<li class="separator hide">
</li>
<!-- BEGIN NOTIFICATION DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-extended dropdown-notification dropdown-dark" id="header_notification_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-bell"></i>
<span class="badge badge-success">
7 </span>
</a>
<ul class="dropdown-menu">
<li class="external">
<h3><span class="bold">12 pending</span> notifications</h3>
<a href="extra_profile.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283">
<li>
<a href="javascript:;">
<span class="time">just now</span>
<span class="details">
<span class="label label-sm label-icon label-success">
<i class="fa fa-plus"></i>
</span>
New user registered. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">3 mins</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span>
Server #12 overloaded. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">10 mins</span>
<span class="details">
<span class="label label-sm label-icon label-warning">
<i class="fa fa-bell-o"></i>
</span>
Server #2 not responding. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">14 hrs</span>
<span class="details">
<span class="label label-sm label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span>
Application error. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">2 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span>
Database overloaded 68%. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">3 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span>
A user IP blocked. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">4 days</span>
<span class="details">
<span class="label label-sm label-icon label-warning">
<i class="fa fa-bell-o"></i>
</span>
Storage Server #4 not responding dfdfdfd. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">5 days</span>
<span class="details">
<span class="label label-sm label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span>
System Error. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">9 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span>
Storage server failed. </span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END NOTIFICATION DROPDOWN -->
<li class="separator hide">
</li>
<!-- BEGIN INBOX DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-extended dropdown-inbox dropdown-dark" id="header_inbox_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-envelope-open"></i>
<span class="badge badge-danger">
4 </span>
</a>
<ul class="dropdown-menu">
<li class="external">
<h3>You have <span class="bold">7 New</span> Messages</h3>
<a href="inbox.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283">
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Lisa Wong </span>
<span class="time">Just Now </span>
</span>
<span class="message">
Vivamus sed auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar3.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Richard Doe </span>
<span class="time">16 mins </span>
</span>
<span class="message">
Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar1.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Bob Nilson </span>
<span class="time">2 hrs </span>
</span>
<span class="message">
Vivamus sed nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Lisa Wong </span>
<span class="time">40 mins </span>
</span>
<span class="message">
Vivamus sed auctor 40% nibh congue nibh... </span>
</a>
</li>
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar3.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Richard Doe </span>
<span class="time">46 mins </span>
</span>
<span class="message">
Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END INBOX DROPDOWN -->
<li class="separator hide">
</li>
<!-- BEGIN TODO DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-extended dropdown-tasks dropdown-dark" id="header_task_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-calendar"></i>
<span class="badge badge-primary">
3 </span>
</a>
<ul class="dropdown-menu extended tasks">
<li class="external">
<h3>You have <span class="bold">12 pending</span> tasks</h3>
<a href="page_todo.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283">
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">New release v1.2 </span>
<span class="percent">30%</span>
</span>
<span class="progress">
<span style="width: 40%;" class="progress-bar progress-bar-success" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">40% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Application deployment</span>
<span class="percent">65%</span>
</span>
<span class="progress">
<span style="width: 65%;" class="progress-bar progress-bar-danger" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">65% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Mobile app release</span>
<span class="percent">98%</span>
</span>
<span class="progress">
<span style="width: 98%;" class="progress-bar progress-bar-success" aria-valuenow="98" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">98% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Database migration</span>
<span class="percent">10%</span>
</span>
<span class="progress">
<span style="width: 10%;" class="progress-bar progress-bar-warning" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">10% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Web server upgrade</span>
<span class="percent">58%</span>
</span>
<span class="progress">
<span style="width: 58%;" class="progress-bar progress-bar-info" aria-valuenow="58" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">58% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Mobile development</span>
<span class="percent">85%</span>
</span>
<span class="progress">
<span style="width: 85%;" class="progress-bar progress-bar-success" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">85% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">New UI release</span>
<span class="percent">38%</span>
</span>
<span class="progress progress-striped">
<span style="width: 38%;" class="progress-bar progress-bar-important" aria-valuenow="18" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">38% Complete</span></span>
</span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END TODO DROPDOWN -->
<!-- BEGIN USER LOGIN DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-user dropdown-dark">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<span class="username username-hide-on-mobile">
Nick </span>
<!-- DOC: Do not remove below empty space( ) as its purposely used -->
<img alt="" class="img-circle" src="../../assets/admin/layout4/img/avatar9.jpg"/>
</a>
<ul class="dropdown-menu dropdown-menu-default">
<li>
<a href="extra_profile.html">
<i class="icon-user"></i> My Profile </a>
</li>
<li>
<a href="page_calendar.html">
<i class="icon-calendar"></i> My Calendar </a>
</li>
<li>
<a href="inbox.html">
<i class="icon-envelope-open"></i> My Inbox <span class="badge badge-danger">
3 </span>
</a>
</li>
<li>
<a href="page_todo.html">
<i class="icon-rocket"></i> My Tasks <span class="badge badge-success">
7 </span>
</a>
</li>
<li class="divider">
</li>
<li>
<a href="extra_lock.html">
<i class="icon-lock"></i> Lock Screen </a>
</li>
<li>
<a href="login.html">
<i class="icon-key"></i> Log Out </a>
</li>
</ul>
</li>
<!-- END USER LOGIN DROPDOWN -->
</ul>
</div>
<!-- END TOP NAVIGATION MENU -->
</div>
<!-- END PAGE TOP -->
</div>
<!-- END HEADER INNER -->
</div>
<!-- END HEADER -->
<div class="clearfix">
</div>
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN SIDEBAR -->
<div class="page-sidebar-wrapper">
<!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing -->
<!-- DOC: Change data-auto-speed="200" to adjust the sub menu slide up/down speed -->
<div class="page-sidebar md-shadow-z-2-i navbar-collapse collapse">
<!-- BEGIN SIDEBAR MENU -->
<!-- DOC: Apply "page-sidebar-menu-light" class right after "page-sidebar-menu" to enable light sidebar menu style(without borders) -->
<!-- DOC: Apply "page-sidebar-menu-hover-submenu" class right after "page-sidebar-menu" to enable hoverable(hover vs accordion) sub menu mode -->
<!-- DOC: Apply "page-sidebar-menu-closed" class right after "page-sidebar-menu" to collapse("page-sidebar-closed" class must be applied to the body element) the sidebar sub menu mode -->
<!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing -->
<!-- DOC: Set data-keep-expand="true" to keep the submenues expanded -->
<!-- DOC: Set data-auto-speed="200" to adjust the sub menu slide up/down speed -->
<ul class="page-sidebar-menu " data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200">
<li class="start ">
<a href="index.html">
<i class="icon-home"></i>
<span class="title">Dashboard</span>
</a>
</li>
<li>
<a href="javascript:;">
<i class="icon-basket"></i>
<span class="title">eCommerce</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="ecommerce_index.html">
<i class="icon-home"></i>
Dashboard</a>
</li>
<li>
<a href="ecommerce_orders.html">
<i class="icon-basket"></i>
Orders</a>
</li>
<li>
<a href="ecommerce_orders_view.html">
<i class="icon-tag"></i>
Order View</a>
</li>
<li>
<a href="ecommerce_products.html">
<i class="icon-handbag"></i>
Products</a>
</li>
<li>
<a href="ecommerce_products_edit.html">
<i class="icon-pencil"></i>
Product Edit</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-rocket"></i>
<span class="title">Page Layouts</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="layout_sidebar_reversed.html">
<span class="badge badge-warning">new</span>Right Sidebar Page</a>
</li>
<li>
<a href="layout_sidebar_fixed.html">
Sidebar Fixed Page</a>
</li>
<li>
<a href="layout_sidebar_closed.html">
Sidebar Closed Page</a>
</li>
<li>
<a href="layout_blank_page.html">
Blank Page</a>
</li>
<li>
<a href="layout_boxed_page.html">
Boxed Page</a>
</li>
<li>
<a href="layout_language_bar.html">
Language Switch Bar</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-diamond"></i>
<span class="title">UI Features</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="ui_general.html">
General Components</a>
</li>
<li>
<a href="ui_buttons.html">
Buttons</a>
</li>
<li>
<a href="ui_icons.html">
<span class="badge badge-danger">new</span>Font Icons</a>
</li>
<li>
<a href="ui_colors.html">
Flat UI Colors</a>
</li>
<li>
<a href="ui_typography.html">
Typography</a>
</li>
<li>
<a href="ui_tabs_accordions_navs.html">
Tabs, Accordions & Navs</a>
</li>
<li>
<a href="ui_tree.html">
<span class="badge badge-danger">new</span>Tree View</a>
</li>
<li>
<a href="ui_page_progress_style_1.html">
<span class="badge badge-warning">new</span>Page Progress Bar - Style 1</a>
</li>
<li>
<a href="ui_blockui.html">
Block UI</a>
</li>
<li>
<a href="ui_bootstrap_growl.html">
<span class="badge badge-roundless badge-warning">new</span>Bootstrap Growl Notifications</a>
</li>
<li>
<a href="ui_notific8.html">
Notific8 Notifications</a>
</li>
<li>
<a href="ui_toastr.html">
Toastr Notifications</a>
</li>
<li>
<a href="ui_alert_dialog_api.html">
<span class="badge badge-danger">new</span>Alerts & Dialogs API</a>
</li>
<li>
<a href="ui_session_timeout.html">
Session Timeout</a>
</li>
<li>
<a href="ui_idle_timeout.html">
User Idle Timeout</a>
</li>
<li>
<a href="ui_modals.html">
Modals</a>
</li>
<li>
<a href="ui_extended_modals.html">
Extended Modals</a>
</li>
<li>
<a href="ui_tiles.html">
Tiles</a>
</li>
<li>
<a href="ui_datepaginator.html">
<span class="badge badge-success">new</span>Date Paginator</a>
</li>
<li>
<a href="ui_nestable.html">
Nestable List</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-puzzle"></i>
<span class="title">UI Components</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="components_pickers.html">
Date & Time Pickers</a>
</li>
<li>
<a href="components_context_menu.html">
Context Menu</a>
</li>
<li>
<a href="components_dropdowns.html">
Custom Dropdowns</a>
</li>
<li>
<a href="components_form_tools.html">
Form Widgets & Tools</a>
</li>
<li>
<a href="components_form_tools2.html">
Form Widgets & Tools 2</a>
</li>
<li>
<a href="components_editors.html">
Markdown & WYSIWYG Editors</a>
</li>
<li>
<a href="components_ion_sliders.html">
Ion Range Sliders</a>
</li>
<li>
<a href="components_noui_sliders.html">
NoUI Range Sliders</a>
</li>
<li>
<a href="components_jqueryui_sliders.html">
jQuery UI Sliders</a>
</li>
<li>
<a href="components_knob_dials.html">
Knob Circle Dials</a>
</li>
</ul>
</li>
<!-- BEGIN ANGULARJS LINK -->
<li class="tooltips" data-container="body" data-placement="right" data-html="true" data-original-title="AngularJS version demo">
<a href="angularjs" target="_blank">
<i class="icon-paper-plane"></i>
<span class="title">
AngularJS Version </span>
</a>
</li>
<!-- END ANGULARJS LINK -->
<li class="active open">
<a href="javascript:;">
<i class="icon-settings"></i>
<span class="title">Form Stuff</span>
<span class="arrow open"></span>
</a>
<ul class="sub-menu">
<li>
<a href="form_controls_md.html">
<span class="badge badge-roundless badge-danger">new</span>Material Design<br>
Form Controls</a>
</li>
<li>
<a href="form_controls.html">
Bootstrap<br>
Form Controls</a>
</li>
<li class="active">
<a href="form_layouts.html">
Form Layouts</a>
</li>
<li>
<a href="form_editable.html">
<span class="badge badge-warning">new</span>Form X-editable</a>
</li>
<li>
<a href="form_wizard.html">
Form Wizard</a>
</li>
<li>
<a href="form_validation.html">
Form Validation</a>
</li>
<li>
<a href="form_image_crop.html">
<span class="badge badge-danger">new</span>Image Cropping</a>
</li>
<li>
<a href="form_fileupload.html">
Multiple File Upload</a>
</li>
<li>
<a href="form_dropzone.html">
Dropzone File Upload</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-briefcase"></i>
<span class="title">Data Tables</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="table_basic.html">
Basic Datatables</a>
</li>
<li>
<a href="table_tree.html">
Tree Datatables</a>
</li>
<li>
<a href="table_responsive.html">
Responsive Datatables</a>
</li>
<li>
<a href="table_managed.html">
Managed Datatables</a>
</li>
<li>
<a href="table_editable.html">
Editable Datatables</a>
</li>
<li>
<a href="table_advanced.html">
Advanced Datatables</a>
</li>
<li>
<a href="table_ajax.html">
Ajax Datatables</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-wallet"></i>
<span class="title">Portlets</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="portlet_general.html">
General Portlets</a>
</li>
<li>
<a href="portlet_general2.html">
<span class="badge badge-danger">new</span>New Portlets #1</a>
</li>
<li>
<a href="portlet_general3.html">
<span class="badge badge-danger">new</span>New Portlets #2</a>
</li>
<li>
<a href="portlet_ajax.html">
Ajax Portlets</a>
</li>
<li>
<a href="portlet_draggable.html">
Draggable Portlets</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-bar-chart"></i>
<span class="title">Charts</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="charts_amcharts.html">
Amchart</a>
</li>
<li>
<a href="charts_flotcharts.html">
Flotchart</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-docs"></i>
<span class="title">Pages</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="page_timeline.html">
<i class="icon-paper-plane"></i>
<span class="badge badge-warning">2</span>New Timeline</a>
</li>
<li>
<a href="extra_profile.html">
<i class="icon-user-following"></i>
<span class="badge badge-success badge-roundless">new</span>New User Profile</a>
</li>
<li>
<a href="page_todo.html">
<i class="icon-hourglass"></i>
<span class="badge badge-danger">4</span>Todo</a>
</li>
<li>
<a href="inbox.html">
<i class="icon-envelope"></i>
<span class="badge badge-danger">4</span>Inbox</a>
</li>
<li>
<a href="extra_faq.html">
<i class="icon-info"></i>
FAQ</a>
</li>
<li>
<a href="page_portfolio.html">
<i class="icon-feed"></i>
Portfolio</a>
</li>
<li>
<a href="page_timeline.html">
<i class="icon-clock"></i>
<span class="badge badge-info">4</span>Timeline</a>
</li>
<li>
<a href="page_coming_soon.html">
<i class="icon-flag"></i>
Coming Soon</a>
</li>
<li>
<a href="page_calendar.html">
<i class="icon-calendar"></i>
<span class="badge badge-danger">14</span>Calendar</a>
</li>
<li>
<a href="extra_invoice.html">
<i class="icon-flag"></i>
Invoice</a>
</li>
<li>
<a href="page_blog.html">
<i class="icon-speech"></i>
Blog</a>
</li>
<li>
<a href="page_blog_item.html">
<i class="icon-link"></i>
Blog Post</a>
</li>
<li>
<a href="page_news.html">
<i class="icon-eye"></i>
<span class="badge badge-success">9</span>News</a>
</li>
<li>
<a href="page_news_item.html">
<i class="icon-bell"></i>
News View</a>
</li>
<li>
<a href="page_timeline_old.html">
<i class="icon-paper-plane"></i>
<span class="badge badge-warning">2</span>Old Timeline</a>
</li>
<li>
<a href="extra_profile_old.html">
<i class="icon-user"></i>
Old User Profile</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-present"></i>
<span class="title">Extra</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="page_about.html">
About Us</a>
</li>
<li>
<a href="page_contact.html">
Contact Us</a>
</li>
<li>
<a href="extra_search.html">
Search Results</a>
</li>
<li>
<a href="extra_pricing_table.html">
Pricing Tables</a>
</li>
<li>
<a href="extra_404_option1.html">
404 Page Option 1</a>
</li>
<li>
<a href="extra_404_option2.html">
404 Page Option 2</a>
</li>
<li>
<a href="extra_404_option3.html">
404 Page Option 3</a>
</li>
<li>
<a href="extra_500_option1.html">
500 Page Option 1</a>
</li>
<li>
<a href="extra_500_option2.html">
500 Page Option 2</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-folder"></i>
<span class="title">Multi Level Menu</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="javascript:;">
<i class="icon-settings"></i> Item 1 <span class="arrow"></span>
</a>
<ul class="sub-menu">
<li>
<a href="javascript:;">
<i class="icon-user"></i>
Sample Link 1 <span class="arrow"></span>
</a>
<ul class="sub-menu">
<li>
<a href="#"><i class="icon-power"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-paper-plane"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-star"></i> Sample Link 1</a>
</li>
</ul>
</li>
<li>
<a href="#"><i class="icon-camera"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-link"></i> Sample Link 2</a>
</li>
<li>
<a href="#"><i class="icon-pointer"></i> Sample Link 3</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-globe"></i> Item 2 <span class="arrow"></span>
</a>
<ul class="sub-menu">
<li>
<a href="#"><i class="icon-tag"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-pencil"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-graph"></i> Sample Link 1</a>
</li>
</ul>
</li>
<li>
<a href="#">
<i class="icon-bar-chart"></i>
Item 3 </a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-user"></i>
<span class="title">Login Options</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="login.html">
Login Form 1</a>
</li>
<li>
<a href="login_2.html">
Login Form 2</a>
</li>
<li>
<a href="login_3.html">
Login Form 3</a>
</li>
<li>
<a href="login_soft.html">
Login Form 4</a>
</li>
<li>
<a href="extra_lock.html">
Lock Screen 1</a>
</li>
<li>
<a href="extra_lock2.html">
Lock Screen 2</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-envelope-open"></i>
<span class="title">Email Templates</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="email_template1.html">
New Email Template 1</a>
</li>
<li>
<a href="email_template2.html">
New Email Template 2</a>
</li>
<li>
<a href="email_template3.html">
New Email Template 3</a>
</li>
<li>
<a href="email_template4.html">
New Email Template 4</a>
</li>
<li>
<a href="email_newsletter.html">
Old Email Template 1</a>
</li>
<li>
<a href="email_system.html">
Old Email Template 2</a>
</li>
</ul>
</li>
<li class="last ">
<a href="javascript:;">
<i class="icon-pointer"></i>
<span class="title">Maps</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="maps_google.html">
Google Maps</a>
</li>
<li>
<a href="maps_vector.html">
Vector Maps</a>
</li>
</ul>
</li>
</ul>
<!-- END SIDEBAR MENU -->
</div>
</div>
<!-- END SIDEBAR -->
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<div class="page-content">
<!-- BEGIN SAMPLE PORTLET CONFIGURATION MODAL FORM-->
<div class="modal fade" id="portlet-config" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
Widget settings form goes here
</div>
<div class="modal-footer">
<button type="button" class="btn blue">Save changes</button>
<button type="button" class="btn default" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<!-- END SAMPLE PORTLET CONFIGURATION MODAL FORM-->
<!-- BEGIN PAGE HEADER-->
<!-- BEGIN PAGE HEAD -->
<div class="page-head">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Form Layouts <small>form layouts</small></h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<div class="page-toolbar">
<!-- BEGIN THEME PANEL -->
<div class="btn-group btn-theme-panel">
<a href="javascript:;" class="btn dropdown-toggle" data-toggle="dropdown">
<i class="icon-settings"></i>
</a>
<div class="dropdown-menu theme-panel pull-right dropdown-custom hold-on-click">
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<h3>THEME</h3>
<ul class="theme-colors">
<li class="theme-color theme-color-default active" data-theme="default">
<span class="theme-color-view"></span>
<span class="theme-color-name">Dark Header</span>
</li>
<li class="theme-color theme-color-light" data-theme="light">
<span class="theme-color-view"></span>
<span class="theme-color-name">Light Header</span>
</li>
</ul>
</div>
<div class="col-md-8 col-sm-8 col-xs-12 seperator">
<h3>LAYOUT</h3>
<ul class="theme-settings">
<li>
Theme Style
<select class="layout-style-option form-control input-small input-sm">
<option value="square" selected="selected">Square corners</option>
<option value="rounded">Rounded corners</option>
</select>
</li>
<li>
Layout
<select class="layout-option form-control input-small input-sm">
<option value="fluid" selected="selected">Fluid</option>
<option value="boxed">Boxed</option>
</select>
</li>
<li>
Header
<select class="page-header-option form-control input-small input-sm">
<option value="fixed" selected="selected">Fixed</option>
<option value="default">Default</option>
</select>
</li>
<li>
Top Dropdowns
<select class="page-header-top-dropdown-style-option form-control input-small input-sm">
<option value="light">Light</option>
<option value="dark" selected="selected">Dark</option>
</select>
</li>
<li>
Sidebar Mode
<select class="sidebar-option form-control input-small input-sm">
<option value="fixed">Fixed</option>
<option value="default" selected="selected">Default</option>
</select>
</li>
<li>
Sidebar Menu
<select class="sidebar-menu-option form-control input-small input-sm">
<option value="accordion" selected="selected">Accordion</option>
<option value="hover">Hover</option>
</select>
</li>
<li>
Sidebar Position
<select class="sidebar-pos-option form-control input-small input-sm">
<option value="left" selected="selected">Left</option>
<option value="right">Right</option>
</select>
</li>
<li>
Footer
<select class="page-footer-option form-control input-small input-sm">
<option value="fixed">Fixed</option>
<option value="default" selected="selected">Default</option>
</select>
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- END THEME PANEL -->
</div>
<!-- END PAGE TOOLBAR -->
</div>
<!-- END PAGE HEAD -->
<!-- BEGIN PAGE BREADCRUMB -->
<ul class="page-breadcrumb breadcrumb">
<li>
<a href="index.html">Home</a>
<i class="fa fa-circle"></i>
</li>
<li>
<a href="#">Form Stuff</a>
<i class="fa fa-circle"></i>
</li>
<li>
<a href="#">Form Layouts</a>
</li>
</ul>
<!-- END PAGE BREADCRUMB -->
<!-- END PAGE HEADER-->
<!-- BEGIN PAGE CONTENT-->
<div class="row">
<div class="col-md-12">
<div class="tabbable tabbable-custom tabbable-noborder tabbable-reversed">
<ul class="nav nav-tabs">
<li class="active">
<a href="#tab_0" data-toggle="tab">
Form Actions </a>
</li>
<li>
<a href="#tab_1" data-toggle="tab">
2 Cols </a>
</li>
<li>
<a href="#tab_2" data-toggle="tab">
2 Cols Horizontal </a>
</li>
<li>
<a href="#tab_3" data-toggle="tab">
2 Cols View Only </a>
</li>
<li>
<a href="#tab_4" data-toggle="tab">
Row Seperated </a>
</li>
<li>
<a href="#tab_5" data-toggle="tab">
Bordered </a>
</li>
<li>
<a href="#tab_6" data-toggle="tab">
Row Stripped </a>
</li>
<li>
<a href="#tab_7" data-toggle="tab">
Label Stripped </a>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab_0">
<div class="portlet box green">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Form Actions On Bottom
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="#portlet-config" data-toggle="modal" class="config">
</a>
<a href="javascript:;" class="reload">
</a>
<a href="javascript:;" class="remove">
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#" class="form-horizontal">
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Text</label>
<div class="col-md-4">
<input type="text" class="form-control input-circle" placeholder="Enter text">
<span class="help-block">
A block of help text. </span>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Email Address</label>
<div class="col-md-4">
<div class="input-group">
<span class="input-group-addon input-circle-left">
<i class="fa fa-envelope"></i>
</span>
<input type="email" class="form-control input-circle-right" placeholder="Email Address">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Password</label>
<div class="col-md-4">
<div class="input-group">
<input type="password" class="form-control input-circle-left" placeholder="Password">
<span class="input-group-addon input-circle-right">
<i class="fa fa-user"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Left Icon</label>
<div class="col-md-4">
<div class="input-icon">
<i class="fa fa-bell-o"></i>
<input type="text" class="form-control input-circle" placeholder="Left icon">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Right Icon</label>
<div class="col-md-4">
<div class="input-icon right">
<i class="fa fa-microphone"></i>
<input type="text" class="form-control input-circle" placeholder="Right icon">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Input With Spinner</label>
<div class="col-md-4">
<input type="password" class="form-control spinner input-circle" placeholder="Password">
</div>
</div>
<div class="form-group last">
<label class="col-md-3 control-label">Static Control</label>
<div class="col-md-4">
<span class="form-control-static">
email@example.com </span>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn btn-circle blue">Submit</button>
<button type="button" class="btn btn-circle default">Cancel</button>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<div class="portlet box blue-hoki">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Form Actions On Top
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="#portlet-config" data-toggle="modal" class="config">
</a>
<a href="javascript:;" class="reload">
</a>
<a href="javascript:;" class="remove">
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#" class="form-horizontal">
<div class="form-actions top">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Text</label>
<div class="col-md-4">
<input type="text" class="form-control" placeholder="Enter text">
<span class="help-block">
A block of help text. </span>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Email Address</label>
<div class="col-md-4">
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-envelope"></i>
</span>
<input type="email" class="form-control" placeholder="Email Address">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Password</label>
<div class="col-md-4">
<div class="input-group">
<input type="password" class="form-control" placeholder="Password">
<span class="input-group-addon">
<i class="fa fa-user"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Left Icon</label>
<div class="col-md-4">
<div class="input-icon">
<i class="fa fa-bell-o"></i>
<input type="text" class="form-control" placeholder="Left icon">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Right Icon</label>
<div class="col-md-4">
<div class="input-icon right">
<i class="fa fa-microphone"></i>
<input type="text" class="form-control" placeholder="Right icon">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Input With Spinner</label>
<div class="col-md-4">
<input type="password" class="form-control spinner" placeholder="Password">
</div>
</div>
<div class="form-group last">
<label class="col-md-3 control-label">Static Control</label>
<div class="col-md-4">
<p class="form-control-static">
email@example.com
</p>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<div class="portlet box yellow">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Form Actions On Top & Bottom
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="#portlet-config" data-toggle="modal" class="config">
</a>
<a href="javascript:;" class="reload">
</a>
<a href="javascript:;" class="remove">
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#" class="form-horizontal">
<div class="form-actions top">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Text</label>
<div class="col-md-4">
<input type="text" class="form-control" placeholder="Enter text">
<span class="help-block">
A block of help text. </span>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Email Address</label>
<div class="col-md-4">
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-envelope"></i>
</span>
<input type="email" class="form-control" placeholder="Email Address">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Password</label>
<div class="col-md-4">
<div class="input-group">
<input type="password" class="form-control" placeholder="Password">
<span class="input-group-addon">
<i class="fa fa-user"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Left Icon</label>
<div class="col-md-4">
<div class="input-icon">
<i class="fa fa-bell-o"></i>
<input type="text" class="form-control" placeholder="Left icon">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Right Icon</label>
<div class="col-md-4">
<div class="input-icon right">
<i class="fa fa-microphone"></i>
<input type="text" class="form-control" placeholder="Right icon">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Input With Spinner</label>
<div class="col-md-4">
<input type="password" class="form-control spinner" placeholder="Password">
</div>
</div>
<div class="form-group last">
<label class="col-md-3 control-label">Static Control</label>
<div class="col-md-4">
<p class="form-control-static">
email@example.com
</p>
</div>
</div>
</div>
<div class="form-actions fluid">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<i class="icon-equalizer font-red-sunglo"></i>
<span class="caption-subject font-red-sunglo bold uppercase">Form Sample</span>
<span class="caption-helper">form actions without bg color</span>
</div>
<div class="actions">
<div class="portlet-input input-inline input-small">
<div class="input-icon right">
<i class="icon-magnifier"></i>
<input type="text" class="form-control input-circle" placeholder="search...">
</div>
</div>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#" class="form-horizontal">
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Text</label>
<div class="col-md-4">
<input type="text" class="form-control" placeholder="Enter text">
<span class="help-block">
A block of help text. </span>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Email Address</label>
<div class="col-md-4">
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-envelope"></i>
</span>
<input type="email" class="form-control" placeholder="Email Address">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Password</label>
<div class="col-md-4">
<div class="input-group">
<input type="password" class="form-control" placeholder="Password">
<span class="input-group-addon">
<i class="fa fa-user"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Left Icon</label>
<div class="col-md-4">
<div class="input-icon">
<i class="fa fa-bell-o"></i>
<input type="text" class="form-control" placeholder="Left icon">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Right Icon</label>
<div class="col-md-4">
<div class="input-icon right">
<i class="fa fa-microphone"></i>
<input type="text" class="form-control" placeholder="Right icon">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Input With Spinner</label>
<div class="col-md-4">
<input type="password" class="form-control spinner" placeholder="Password">
</div>
</div>
<div class="form-group last">
<label class="col-md-3 control-label">Static Control</label>
<div class="col-md-4">
<p class="form-control-static">
email@example.com
</p>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="portlet box red">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Left Aligned
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="#portlet-config" data-toggle="modal" class="config">
</a>
<a href="javascript:;" class="reload">
</a>
<a href="javascript:;" class="remove">
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#">
<div class="form-actions top">
<button type="submit" class="btn green">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
<div class="form-body">
<div class="form-group">
<label class="control-label">Text</label>
<input type="text" class="form-control" placeholder="Enter text">
<span class="help-block">
A block of help text. </span>
</div>
<div class="form-group">
<label class="control-label">Email Address</label>
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-envelope"></i>
</span>
<input type="email" class="form-control" placeholder="Email Address">
</div>
</div>
<div class="form-group">
<label class="control-label">Password</label>
<div class="input-group">
<input type="password" class="form-control" placeholder="Password">
<span class="input-group-addon">
<i class="fa fa-user"></i>
</span>
</div>
</div>
<div class="form-group">
<label class="control-label">Left Icon</label>
<div class="input-icon">
<i class="fa fa-bell-o"></i>
<input type="text" class="form-control" placeholder="Left icon">
</div>
</div>
<div class="form-group">
<label class="control-label">Right Icon</label>
<div class="input-icon right">
<i class="fa fa-microphone"></i>
<input type="text" class="form-control" placeholder="Right icon">
</div>
</div>
<div class="form-group">
<label class="control-label">Input With Spinner</label>
<input type="password" class="form-control spinner" placeholder="Password">
</div>
<div class="form-group last">
<label class="control-label">Static Control</label>
<p class="form-control-static">
email@example.com
</p>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn green">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</form>
<!-- END FORM-->
</div>
</div>
</div>
<div class="col-md-6">
<div class="portlet box purple">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Right Aligned
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="#portlet-config" data-toggle="modal" class="config">
</a>
<a href="javascript:;" class="reload">
</a>
<a href="javascript:;" class="remove">
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#">
<div class="form-actions top right">
<button type="submit" class="btn green">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
<div class="form-body">
<div class="form-group">
<label class="control-label">Text</label>
<input type="text" class="form-control" placeholder="Enter text">
<span class="help-block">
A block of help text. </span>
</div>
<div class="form-group">
<label class="control-label">Email Address</label>
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-envelope"></i>
</span>
<input type="email" class="form-control" placeholder="Email Address">
</div>
</div>
<div class="form-group">
<label class="control-label">Password</label>
<div class="input-group">
<input type="password" class="form-control" placeholder="Password">
<span class="input-group-addon">
<i class="fa fa-user"></i>
</span>
</div>
</div>
<div class="form-group">
<label class="control-label">Left Icon</label>
<div class="input-icon">
<i class="fa fa-bell-o"></i>
<input type="text" class="form-control" placeholder="Left icon">
</div>
</div>
<div class="form-group">
<label class="control-label">Right Icon</label>
<div class="input-icon right">
<i class="fa fa-microphone"></i>
<input type="text" class="form-control" placeholder="Right icon">
</div>
</div>
<div class="form-group">
<label class="control-label">Input With Spinner</label>
<input type="password" class="form-control spinner" placeholder="Password">
</div>
<div class="form-group last">
<label class="control-label">Static Control</label>
<p class="form-control-static">
email@example.com
</p>
</div>
</div>
<div class="form-actions right">
<button type="submit" class="btn green">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</form>
<!-- END FORM-->
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="portlet box yellow">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Actions Buttons
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="#portlet-config" data-toggle="modal" class="config">
</a>
<a href="javascript:;" class="reload">
</a>
<a href="javascript:;" class="remove">
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#">
<div class="form-actions top">
<div class="btn-set pull-left">
<button type="submit" class="btn green">Submit</button>
<button type="button" class="btn blue">Other Action</button>
</div>
<div class="btn-set pull-right">
<button type="button" class="btn default">Action 1</button>
<button type="button" class="btn red">Action 2</button>
<button type="button" class="btn yellow">Action 3</button>
</div>
</div>
<div class="form-body">
<div class="form-group">
<label class="control-label">Text</label>
<input type="text" class="form-control" placeholder="Enter text">
<span class="help-block">
A block of help text. </span>
</div>
<div class="form-group">
<label class="control-label">Email Address</label>
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-envelope"></i>
</span>
<input type="email" class="form-control" placeholder="Email Address">
</div>
</div>
<div class="form-group">
<label class="control-label">Password</label>
<div class="input-group">
<input type="password" class="form-control" placeholder="Password">
<span class="input-group-addon">
<i class="fa fa-user"></i>
</span>
</div>
</div>
<div class="form-group">
<label class="control-label">Left Icon</label>
<div class="input-icon">
<i class="fa fa-bell-o"></i>
<input type="text" class="form-control" placeholder="Left icon">
</div>
</div>
<div class="form-group">
<label class="control-label">Right Icon</label>
<div class="input-icon right">
<i class="fa fa-microphone"></i>
<input type="text" class="form-control" placeholder="Right icon">
</div>
</div>
<div class="form-group">
<label class="control-label">Input With Spinner</label>
<input type="password" class="form-control spinner" placeholder="Password">
</div>
<div class="form-group last">
<label class="control-label">Static Control</label>
<p class="form-control-static">
email@example.com
</p>
</div>
</div>
<div class="form-actions">
<div class="btn-set pull-left">
<button type="submit" class="btn green">Submit</button>
<button type="button" class="btn blue">Other Action</button>
</div>
<div class="btn-set pull-right">
<button type="button" class="btn default">Action 1</button>
<button type="button" class="btn red">Action 2</button>
<button type="button" class="btn yellow">Action 3</button>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab_1">
<div class="portlet box blue">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Form Sample
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="#portlet-config" data-toggle="modal" class="config">
</a>
<a href="javascript:;" class="reload">
</a>
<a href="javascript:;" class="remove">
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#" class="horizontal-form">
<div class="form-body">
<h3 class="form-section">Person Info</h3>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">First Name</label>
<input type="text" id="firstName" class="form-control" placeholder="Chee Kin">
<span class="help-block">
This is inline help </span>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group has-error">
<label class="control-label">Last Name</label>
<input type="text" id="lastName" class="form-control" placeholder="Lim">
<span class="help-block">
This field has error. </span>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Gender</label>
<select class="form-control">
<option value="">Male</option>
<option value="">Female</option>
</select>
<span class="help-block">
Select your gender </span>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Date of Birth</label>
<input type="text" class="form-control" placeholder="dd/mm/yyyy">
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Category</label>
<select class="select2_category form-control" data-placeholder="Choose a Category" tabindex="1">
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 5</option>
<option value="Category 4">Category 4</option>
</select>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Membership</label>
<div class="radio-list">
<label class="radio-inline">
<input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked> Option 1 </label>
<label class="radio-inline">
<input type="radio" name="optionsRadios" id="optionsRadios2" value="option2"> Option 2 </label>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<h3 class="form-section">Address</h3>
<div class="row">
<div class="col-md-12 ">
<div class="form-group">
<label>Street</label>
<input type="text" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>City</label>
<input type="text" class="form-control">
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label>State</label>
<input type="text" class="form-control">
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Post Code</label>
<input type="text" class="form-control">
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label>Country</label>
<select class="form-control">
</select>
</div>
</div>
<!--/span-->
</div>
</div>
<div class="form-actions right">
<button type="button" class="btn default">Cancel</button>
<button type="submit" class="btn blue"><i class="fa fa-check"></i> Save</button>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<i class="icon-equalizer font-blue-hoki"></i>
<span class="caption-subject font-blue-hoki bold uppercase">Form Sample</span>
<span class="caption-helper">demo form...</span>
</div>
<div class="tools">
<a href="" class="collapse">
</a>
<a href="#portlet-config" data-toggle="modal" class="config">
</a>
<a href="" class="reload">
</a>
<a href="" class="remove">
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#" class="horizontal-form">
<div class="form-body">
<h3 class="form-section">Person Info</h3>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">First Name</label>
<input type="text" id="firstName" class="form-control" placeholder="Chee Kin">
<span class="help-block">
This is inline help </span>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group has-error">
<label class="control-label">Last Name</label>
<input type="text" id="lastName" class="form-control" placeholder="Lim">
<span class="help-block">
This field has error. </span>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Gender</label>
<select class="form-control">
<option value="">Male</option>
<option value="">Female</option>
</select>
<span class="help-block">
Select your gender </span>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Date of Birth</label>
<input type="text" class="form-control" placeholder="dd/mm/yyyy">
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Category</label>
<select class="select2_category form-control" data-placeholder="Choose a Category" tabindex="1">
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 5</option>
<option value="Category 4">Category 4</option>
</select>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Membership</label>
<div class="radio-list">
<label class="radio-inline">
<input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked> Option 1 </label>
<label class="radio-inline">
<input type="radio" name="optionsRadios" id="optionsRadios2" value="option2"> Option 2 </label>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<h3 class="form-section">Address</h3>
<div class="row">
<div class="col-md-12 ">
<div class="form-group">
<label>Street</label>
<input type="text" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>City</label>
<input type="text" class="form-control">
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label>State</label>
<input type="text" class="form-control">
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Post Code</label>
<input type="text" class="form-control">
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label>Country</label>
<select class="form-control">
</select>
</div>
</div>
<!--/span-->
</div>
</div>
<div class="form-actions right">
<button type="button" class="btn default">Cancel</button>
<button type="submit" class="btn blue"><i class="fa fa-check"></i> Save</button>
</div>
</form>
<!-- END FORM-->
</div>
</div>
</div>
<div class="tab-pane" id="tab_2">
<div class="portlet box green">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Form Sample
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="#portlet-config" data-toggle="modal" class="config">
</a>
<a href="javascript:;" class="reload">
</a>
<a href="javascript:;" class="remove">
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#" class="form-horizontal">
<div class="form-body">
<h3 class="form-section">Person Info</h3>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input type="text" class="form-control" placeholder="Chee Kin">
<span class="help-block">
This is inline help </span>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group has-error">
<label class="control-label col-md-3">Last Name</label>
<div class="col-md-9">
<select name="foo" class="select2me form-control">
<option value="1">Abc</option>
<option value="1">Abc</option>
<option value="1">This is a really long value that breaks the fluid design for a select2</option>
</select>
<span class="help-block">
This field has error. </span>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select class="form-control">
<option value="">Male</option>
<option value="">Female</option>
</select>
<span class="help-block">
Select your gender. </span>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input type="text" class="form-control" placeholder="dd/mm/yyyy">
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Category</label>
<div class="col-md-9">
<select class="select2_category form-control" data-placeholder="Choose a Category" tabindex="1">
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 5</option>
<option value="Category 4">Category 4</option>
</select>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Membership</label>
<div class="col-md-9">
<div class="radio-list">
<label class="radio-inline">
<input type="radio" name="optionsRadios2" value="option1"/>
Free </label>
<label class="radio-inline">
<input type="radio" name="optionsRadios2" value="option2" checked/>
Professional </label>
</div>
</div>
</div>
</div>
<!--/span-->
</div>
<h3 class="form-section">Address</h3>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Address 1</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Address 2</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">City</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">State</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Post Code</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Country</label>
<div class="col-md-9">
<select class="form-control">
<option>Country 1</option>
<option>Country 2</option>
</select>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
<div class="col-md-6">
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<i class="icon-equalizer font-red-sunglo"></i>
<span class="caption-subject font-red-sunglo bold uppercase">Form Sample</span>
<span class="caption-helper">some info...</span>
</div>
<div class="tools">
<a href="" class="collapse">
</a>
<a href="#portlet-config" data-toggle="modal" class="config">
</a>
<a href="" class="reload">
</a>
<a href="" class="remove">
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#" class="form-horizontal">
<div class="form-body">
<h3 class="form-section">Person Info</h3>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input type="text" class="form-control" placeholder="Chee Kin">
<span class="help-block">
This is inline help </span>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group has-error">
<label class="control-label col-md-3">Last Name</label>
<div class="col-md-9">
<select name="foo" class="select2me form-control">
<option value="1">Abc</option>
<option value="1">Abc</option>
<option value="1">This is a really long value that breaks the fluid design for a select2</option>
</select>
<span class="help-block">
This field has error. </span>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select class="form-control">
<option value="">Male</option>
<option value="">Female</option>
</select>
<span class="help-block">
Select your gender. </span>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input type="text" class="form-control" placeholder="dd/mm/yyyy">
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Category</label>
<div class="col-md-9">
<select class="select2_category form-control" data-placeholder="Choose a Category" tabindex="1">
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 5</option>
<option value="Category 4">Category 4</option>
</select>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Membership</label>
<div class="col-md-9">
<div class="radio-list">
<label class="radio-inline">
<input type="radio" name="optionsRadios2" value="option1"/>
Free </label>
<label class="radio-inline">
<input type="radio" name="optionsRadios2" value="option2" checked/>
Professional </label>
</div>
</div>
</div>
</div>
<!--/span-->
</div>
<h3 class="form-section">Address</h3>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Address 1</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Address 2</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">City</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">State</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Post Code</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Country</label>
<div class="col-md-9">
<select class="form-control">
<option>Country 1</option>
<option>Country 2</option>
</select>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
<div class="col-md-6">
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
</div>
<div class="tab-pane" id="tab_3">
<div class="portlet box blue">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Form Sample
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="#portlet-config" data-toggle="modal" class="config">
</a>
<a href="javascript:;" class="reload">
</a>
<a href="javascript:;" class="remove">
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form class="form-horizontal" role="form">
<div class="form-body">
<h2 class="margin-bottom-20"> View User Info - Bob Nilson </h2>
<h3 class="form-section">Person Info</h3>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">First Name:</label>
<div class="col-md-9">
<p class="form-control-static">
Bob
</p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Last Name:</label>
<div class="col-md-9">
<p class="form-control-static">
Nilson
</p>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Gender:</label>
<div class="col-md-9">
<p class="form-control-static">
Male
</p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Date of Birth:</label>
<div class="col-md-9">
<p class="form-control-static">
20.01.1984
</p>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Category:</label>
<div class="col-md-9">
<p class="form-control-static">
Category1
</p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Membership:</label>
<div class="col-md-9">
<p class="form-control-static">
Free
</p>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<h3 class="form-section">Address</h3>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Address:</label>
<div class="col-md-9">
<p class="form-control-static">
#24 Sun Park Avenue, Rolton Str
</p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">City:</label>
<div class="col-md-9">
<p class="form-control-static">
New York
</p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">State:</label>
<div class="col-md-9">
<p class="form-control-static">
New York
</p>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Post Code:</label>
<div class="col-md-9">
<p class="form-control-static">
457890
</p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Country:</label>
<div class="col-md-9">
<p class="form-control-static">
USA
</p>
</div>
</div>
</div>
<!--/span-->
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green"><i class="fa fa-pencil"></i> Edit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
<div class="col-md-6">
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<i class="icon-equalizer font-green-haze"></i>
<span class="caption-subject font-green-haze bold uppercase">Form Sample</span>
<span class="caption-helper">some info...</span>
</div>
<div class="tools">
<a href="" class="collapse">
</a>
<a href="#portlet-config" data-toggle="modal" class="config">
</a>
<a href="" class="reload">
</a>
<a href="" class="remove">
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form class="form-horizontal" role="form">
<div class="form-body">
<h2 class="margin-bottom-20"> View User Info - Bob Nilson </h2>
<h3 class="form-section">Person Info</h3>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">First Name:</label>
<div class="col-md-9">
<p class="form-control-static">
Bob
</p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Last Name:</label>
<div class="col-md-9">
<p class="form-control-static">
Nilson
</p>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Gender:</label>
<div class="col-md-9">
<p class="form-control-static">
Male
</p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Date of Birth:</label>
<div class="col-md-9">
<p class="form-control-static">
20.01.1984
</p>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Category:</label>
<div class="col-md-9">
<p class="form-control-static">
Category1
</p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Membership:</label>
<div class="col-md-9">
<p class="form-control-static">
Free
</p>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<h3 class="form-section">Address</h3>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Address:</label>
<div class="col-md-9">
<p class="form-control-static">
#24 Sun Park Avenue, Rolton Str
</p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">City:</label>
<div class="col-md-9">
<p class="form-control-static">
New York
</p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">State:</label>
<div class="col-md-9">
<p class="form-control-static">
New York
</p>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Post Code:</label>
<div class="col-md-9">
<p class="form-control-static">
457890
</p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Country:</label>
<div class="col-md-9">
<p class="form-control-static">
USA
</p>
</div>
</div>
</div>
<!--/span-->
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green"><i class="fa fa-pencil"></i> Edit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
<div class="col-md-6">
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
</div>
<div class="tab-pane" id="tab_4">
<div class="portlet box blue">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Form Sample
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="#portlet-config" data-toggle="modal" class="config">
</a>
<a href="javascript:;" class="reload">
</a>
<a href="javascript:;" class="remove">
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#" class="form-horizontal form-row-seperated">
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input type="text" placeholder="small" class="form-control"/>
<span class="help-block">
This is inline help </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Last Name</label>
<div class="col-md-9">
<input type="text" placeholder="medium" class="form-control"/>
<span class="help-block">
This is inline help </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select class="form-control">
<option value="">Male</option>
<option value="">Female</option>
</select>
<span class="help-block">
Select your gender. </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input type="text" class="form-control" placeholder="dd/mm/yyyy">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Category</label>
<div class="col-md-9">
<select class="form-control select2_category">
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 5</option>
<option value="Category 4">Category 4</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Multi-Value Select</label>
<div class="col-md-9">
<select class="form-control select2_sample1" multiple>
<optgroup label="NFC EAST">
<option>Dallas Cowboys</option>
<option>New York Giants</option>
<option>Philadelphia Eagles</option>
<option>Washington Redskins</option>
</optgroup>
<optgroup label="NFC NORTH">
<option>Chicago Bears</option>
<option>Detroit Lions</option>
<option>Green Bay Packers</option>
<option>Minnesota Vikings</option>
</optgroup>
<optgroup label="NFC SOUTH">
<option>Atlanta Falcons</option>
<option>Carolina Panthers</option>
<option>New Orleans Saints</option>
<option>Tampa Bay Buccaneers</option>
</optgroup>
<optgroup label="NFC WEST">
<option>Arizona Cardinals</option>
<option>St. Louis Rams</option>
<option>San Francisco 49ers</option>
<option>Seattle Seahawks</option>
</optgroup>
<optgroup label="AFC EAST">
<option>Buffalo Bills</option>
<option>Miami Dolphins</option>
<option>New England Patriots</option>
<option>New York Jets</option>
</optgroup>
<optgroup label="AFC NORTH">
<option>Baltimore Ravens</option>
<option>Cincinnati Bengals</option>
<option>Cleveland Browns</option>
<option>Pittsburgh Steelers</option>
</optgroup>
<optgroup label="AFC SOUTH">
<option>Houston Texans</option>
<option>Indianapolis Colts</option>
<option>Jacksonville Jaguars</option>
<option>Tennessee Titans</option>
</optgroup>
<optgroup label="AFC WEST">
<option>Denver Broncos</option>
<option>Kansas City Chiefs</option>
<option>Oakland Raiders</option>
<option>San Diego Chargers</option>
</optgroup>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Loading Data</label>
<div class="col-md-9">
<input type="hidden" class="form-control select2_sample2">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Tags Support List</label>
<div class="col-md-9">
<input type="hidden" class="form-control select2_sample3" value="red, blue">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Membership</label>
<div class="col-md-9">
<div class="radio-list">
<label>
<input type="radio" name="optionsRadios2" value="option1"/>
Free </label>
<label>
<input type="radio" name="optionsRadios2" value="option2" checked/>
Professional </label>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Street</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">City</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">State</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Post Code</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group last">
<label class="control-label col-md-3">Country</label>
<div class="col-md-9">
<select class="form-control">
</select>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green"><i class="fa fa-pencil"></i> 1Edit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<div class="portlet light bordered form-fit">
<div class="portlet-title">
<div class="caption">
<i class="icon-equalizer font-green-haze"></i>
<span class="caption-subject font-green-haze bold uppercase">Form Sample</span>
<span class="caption-helper">some info...</span>
</div>
<div class="actions">
<a href="javascript:;" class="btn btn-circle btn-default btn-sm">
<i class="fa fa-pencil"></i> Edit </a>
<a href="javascript:;" class="btn btn-circle btn-default btn-sm">
<i class="fa fa-plus"></i> Add </a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#" class="form-horizontal form-row-seperated">
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input type="text" placeholder="small" class="form-control"/>
<span class="help-block">
This is inline help </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Last Name</label>
<div class="col-md-9">
<input type="text" placeholder="medium" class="form-control"/>
<span class="help-block">
This is inline help </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select class="form-control">
<option value="">Male</option>
<option value="">Female</option>
</select>
<span class="help-block">
Select your gender. </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input type="text" class="form-control" placeholder="dd/mm/yyyy">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Category</label>
<div class="col-md-9">
<select class="form-control select2_category">
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 5</option>
<option value="Category 4">Category 4</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Multi-Value Select</label>
<div class="col-md-9">
<select class="form-control select2_sample1" multiple>
<optgroup label="NFC EAST">
<option>Dallas Cowboys</option>
<option>New York Giants</option>
<option>Philadelphia Eagles</option>
<option>Washington Redskins</option>
</optgroup>
<optgroup label="NFC NORTH">
<option>Chicago Bears</option>
<option>Detroit Lions</option>
<option>Green Bay Packers</option>
<option>Minnesota Vikings</option>
</optgroup>
<optgroup label="NFC SOUTH">
<option>Atlanta Falcons</option>
<option>Carolina Panthers</option>
<option>New Orleans Saints</option>
<option>Tampa Bay Buccaneers</option>
</optgroup>
<optgroup label="NFC WEST">
<option>Arizona Cardinals</option>
<option>St. Louis Rams</option>
<option>San Francisco 49ers</option>
<option>Seattle Seahawks</option>
</optgroup>
<optgroup label="AFC EAST">
<option>Buffalo Bills</option>
<option>Miami Dolphins</option>
<option>New England Patriots</option>
<option>New York Jets</option>
</optgroup>
<optgroup label="AFC NORTH">
<option>Baltimore Ravens</option>
<option>Cincinnati Bengals</option>
<option>Cleveland Browns</option>
<option>Pittsburgh Steelers</option>
</optgroup>
<optgroup label="AFC SOUTH">
<option>Houston Texans</option>
<option>Indianapolis Colts</option>
<option>Jacksonville Jaguars</option>
<option>Tennessee Titans</option>
</optgroup>
<optgroup label="AFC WEST">
<option>Denver Broncos</option>
<option>Kansas City Chiefs</option>
<option>Oakland Raiders</option>
<option>San Diego Chargers</option>
</optgroup>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Loading Data</label>
<div class="col-md-9">
<input type="hidden" class="form-control select2_sample2">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Tags Support List</label>
<div class="col-md-9">
<input type="hidden" class="form-control select2_sample3" value="red, blue">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Membership</label>
<div class="col-md-9">
<div class="radio-list">
<label>
<input type="radio" name="optionsRadios2" value="option1"/>
Free </label>
<label>
<input type="radio" name="optionsRadios2" value="option2" checked/>
Professional </label>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Street</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">City</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">State</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Post Code</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group last">
<label class="control-label col-md-3">Country</label>
<div class="col-md-9">
<select class="form-control">
</select>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green"><i class="fa fa-pencil"></i> 1Edit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
</div>
<div class="tab-pane" id="tab_5">
<div class="portlet box blue ">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Form Sample
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="#portlet-config" data-toggle="modal" class="config">
</a>
<a href="javascript:;" class="reload">
</a>
<a href="javascript:;" class="remove">
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#" class="form-horizontal form-bordered">
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input type="text" placeholder="small" class="form-control"/>
<span class="help-block">
This is inline help </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Last Name</label>
<div class="col-md-9">
<input type="text" placeholder="medium" class="form-control"/>
<span class="help-block">
This is inline help </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select class="form-control">
<option value="">Male</option>
<option value="">Female</option>
</select>
<span class="help-block">
Select your gender. </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input type="text" class="form-control" placeholder="dd/mm/yyyy">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Category</label>
<div class="col-md-9">
<select class="form-control select2_category">
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 5</option>
<option value="Category 4">Category 4</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Multi-Value Select</label>
<div class="col-md-9">
<select class="form-control select2_sample1" multiple>
<optgroup label="NFC EAST">
<option>Dallas Cowboys</option>
<option>New York Giants</option>
<option>Philadelphia Eagles</option>
<option>Washington Redskins</option>
</optgroup>
<optgroup label="NFC NORTH">
<option>Chicago Bears</option>
<option>Detroit Lions</option>
<option>Green Bay Packers</option>
<option>Minnesota Vikings</option>
</optgroup>
<optgroup label="NFC SOUTH">
<option>Atlanta Falcons</option>
<option>Carolina Panthers</option>
<option>New Orleans Saints</option>
<option>Tampa Bay Buccaneers</option>
</optgroup>
<optgroup label="NFC WEST">
<option>Arizona Cardinals</option>
<option>St. Louis Rams</option>
<option>San Francisco 49ers</option>
<option>Seattle Seahawks</option>
</optgroup>
<optgroup label="AFC EAST">
<option>Buffalo Bills</option>
<option>Miami Dolphins</option>
<option>New England Patriots</option>
<option>New York Jets</option>
</optgroup>
<optgroup label="AFC NORTH">
<option>Baltimore Ravens</option>
<option>Cincinnati Bengals</option>
<option>Cleveland Browns</option>
<option>Pittsburgh Steelers</option>
</optgroup>
<optgroup label="AFC SOUTH">
<option>Houston Texans</option>
<option>Indianapolis Colts</option>
<option>Jacksonville Jaguars</option>
<option>Tennessee Titans</option>
</optgroup>
<optgroup label="AFC WEST">
<option>Denver Broncos</option>
<option>Kansas City Chiefs</option>
<option>Oakland Raiders</option>
<option>San Diego Chargers</option>
</optgroup>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Loading Data</label>
<div class="col-md-9">
<input type="hidden" class="form-control select2_sample2">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Tags Support List</label>
<div class="col-md-9">
<input type="hidden" class="form-control select2_sample3" value="red, blue">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Membership</label>
<div class="col-md-9">
<div class="radio-list">
<label>
<input type="radio" name="optionsRadios2" value="option1"/>
Free </label>
<label>
<input type="radio" name="optionsRadios2" value="option2" checked/>
Professional </label>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Street</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">City</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">State</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Post Code</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group last">
<label class="control-label col-md-3">Country</label>
<div class="col-md-9">
<select class="form-control">
</select>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green"><i class="fa fa-check"></i> Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<div class="portlet light bordered form-fit">
<div class="portlet-title">
<div class="caption">
<i class="icon-equalizer font-blue-hoki"></i>
<span class="caption-subject font-blue-hoki bold uppercase">Form Sample</span>
<span class="caption-helper">demo form...</span>
</div>
<div class="actions">
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-cloud-upload"></i>
</a>
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-wrench"></i>
</a>
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-trash"></i>
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#" class="form-horizontal form-bordered">
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input type="text" placeholder="small" class="form-control"/>
<span class="help-block">
This is inline help </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Last Name</label>
<div class="col-md-9">
<input type="text" placeholder="medium" class="form-control"/>
<span class="help-block">
This is inline help </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select class="form-control">
<option value="">Male</option>
<option value="">Female</option>
</select>
<span class="help-block">
Select your gender. </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input type="text" class="form-control" placeholder="dd/mm/yyyy">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Category</label>
<div class="col-md-9">
<select class="form-control select2_category">
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 5</option>
<option value="Category 4">Category 4</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Multi-Value Select</label>
<div class="col-md-9">
<select class="form-control select2_sample1" multiple>
<optgroup label="NFC EAST">
<option>Dallas Cowboys</option>
<option>New York Giants</option>
<option>Philadelphia Eagles</option>
<option>Washington Redskins</option>
</optgroup>
<optgroup label="NFC NORTH">
<option>Chicago Bears</option>
<option>Detroit Lions</option>
<option>Green Bay Packers</option>
<option>Minnesota Vikings</option>
</optgroup>
<optgroup label="NFC SOUTH">
<option>Atlanta Falcons</option>
<option>Carolina Panthers</option>
<option>New Orleans Saints</option>
<option>Tampa Bay Buccaneers</option>
</optgroup>
<optgroup label="NFC WEST">
<option>Arizona Cardinals</option>
<option>St. Louis Rams</option>
<option>San Francisco 49ers</option>
<option>Seattle Seahawks</option>
</optgroup>
<optgroup label="AFC EAST">
<option>Buffalo Bills</option>
<option>Miami Dolphins</option>
<option>New England Patriots</option>
<option>New York Jets</option>
</optgroup>
<optgroup label="AFC NORTH">
<option>Baltimore Ravens</option>
<option>Cincinnati Bengals</option>
<option>Cleveland Browns</option>
<option>Pittsburgh Steelers</option>
</optgroup>
<optgroup label="AFC SOUTH">
<option>Houston Texans</option>
<option>Indianapolis Colts</option>
<option>Jacksonville Jaguars</option>
<option>Tennessee Titans</option>
</optgroup>
<optgroup label="AFC WEST">
<option>Denver Broncos</option>
<option>Kansas City Chiefs</option>
<option>Oakland Raiders</option>
<option>San Diego Chargers</option>
</optgroup>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Loading Data</label>
<div class="col-md-9">
<input type="hidden" class="form-control select2_sample2">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Tags Support List</label>
<div class="col-md-9">
<input type="hidden" class="form-control select2_sample3" value="red, blue">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Membership</label>
<div class="col-md-9">
<div class="radio-list">
<label>
<input type="radio" name="optionsRadios2" value="option1"/>
Free </label>
<label>
<input type="radio" name="optionsRadios2" value="option2" checked/>
Professional </label>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Street</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">City</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">State</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Post Code</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group last">
<label class="control-label col-md-3">Country</label>
<div class="col-md-9">
<select class="form-control">
</select>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green"><i class="fa fa-check"></i> Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
</div>
<div class="tab-pane" id="tab_6">
<div class="portlet box blue ">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Form Sample
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="#portlet-config" data-toggle="modal" class="config">
</a>
<a href="javascript:;" class="reload">
</a>
<a href="javascript:;" class="remove">
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#" class="form-horizontal form-bordered form-row-stripped">
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input type="text" placeholder="small" class="form-control"/>
<span class="help-block">
This is inline help </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Last Name</label>
<div class="col-md-9">
<input type="text" placeholder="medium" class="form-control"/>
<span class="help-block">
This is inline help </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select class="form-control">
<option value="">Male</option>
<option value="">Female</option>
</select>
<span class="help-block">
Select your gender. </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input type="text" class="form-control" placeholder="dd/mm/yyyy">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Category</label>
<div class="col-md-9">
<select class="form-control select2_category">
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 5</option>
<option value="Category 4">Category 4</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Multi-Value Select</label>
<div class="col-md-9">
<select class="form-control select2_sample1" multiple>
<optgroup label="NFC EAST">
<option>Dallas Cowboys</option>
<option>New York Giants</option>
<option>Philadelphia Eagles</option>
<option>Washington Redskins</option>
</optgroup>
<optgroup label="NFC NORTH">
<option>Chicago Bears</option>
<option>Detroit Lions</option>
<option>Green Bay Packers</option>
<option>Minnesota Vikings</option>
</optgroup>
<optgroup label="NFC SOUTH">
<option>Atlanta Falcons</option>
<option>Carolina Panthers</option>
<option>New Orleans Saints</option>
<option>Tampa Bay Buccaneers</option>
</optgroup>
<optgroup label="NFC WEST">
<option>Arizona Cardinals</option>
<option>St. Louis Rams</option>
<option>San Francisco 49ers</option>
<option>Seattle Seahawks</option>
</optgroup>
<optgroup label="AFC EAST">
<option>Buffalo Bills</option>
<option>Miami Dolphins</option>
<option>New England Patriots</option>
<option>New York Jets</option>
</optgroup>
<optgroup label="AFC NORTH">
<option>Baltimore Ravens</option>
<option>Cincinnati Bengals</option>
<option>Cleveland Browns</option>
<option>Pittsburgh Steelers</option>
</optgroup>
<optgroup label="AFC SOUTH">
<option>Houston Texans</option>
<option>Indianapolis Colts</option>
<option>Jacksonville Jaguars</option>
<option>Tennessee Titans</option>
</optgroup>
<optgroup label="AFC WEST">
<option>Denver Broncos</option>
<option>Kansas City Chiefs</option>
<option>Oakland Raiders</option>
<option>San Diego Chargers</option>
</optgroup>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Loading Data</label>
<div class="col-md-9">
<input type="hidden" class="form-control select2_sample2">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Tags Support List</label>
<div class="col-md-9">
<input type="hidden" class="form-control select2_sample3" value="red, blue">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Membership</label>
<div class="col-md-9">
<div class="radio-list">
<label>
<input type="radio" name="optionsRadios2" value="option1"/>
Free </label>
<label>
<input type="radio" name="optionsRadios2" value="option2" checked/>
Professional </label>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Street</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">City</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">State</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Post Code</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group last">
<label class="control-label col-md-3">Country</label>
<div class="col-md-9">
<select class="form-control">
</select>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green"><i class="fa fa-check"></i> Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<div class="portlet light bordered form-fit">
<div class="portlet-title">
<div class="caption">
<i class="icon-user font-blue-hoki"></i>
<span class="caption-subject font-blue-hoki bold uppercase">Form Sample</span>
<span class="caption-helper">demo form...</span>
</div>
<div class="actions">
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-cloud-upload"></i>
</a>
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-wrench"></i>
</a>
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-trash"></i>
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#" class="form-horizontal form-bordered form-row-stripped">
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input type="text" placeholder="small" class="form-control"/>
<span class="help-block">
This is inline help </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Last Name</label>
<div class="col-md-9">
<input type="text" placeholder="medium" class="form-control"/>
<span class="help-block">
This is inline help </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select class="form-control">
<option value="">Male</option>
<option value="">Female</option>
</select>
<span class="help-block">
Select your gender. </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input type="text" class="form-control" placeholder="dd/mm/yyyy">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Category</label>
<div class="col-md-9">
<select class="form-control select2_category">
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 5</option>
<option value="Category 4">Category 4</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Multi-Value Select</label>
<div class="col-md-9">
<select class="form-control select2_sample1" multiple>
<optgroup label="NFC EAST">
<option>Dallas Cowboys</option>
<option>New York Giants</option>
<option>Philadelphia Eagles</option>
<option>Washington Redskins</option>
</optgroup>
<optgroup label="NFC NORTH">
<option>Chicago Bears</option>
<option>Detroit Lions</option>
<option>Green Bay Packers</option>
<option>Minnesota Vikings</option>
</optgroup>
<optgroup label="NFC SOUTH">
<option>Atlanta Falcons</option>
<option>Carolina Panthers</option>
<option>New Orleans Saints</option>
<option>Tampa Bay Buccaneers</option>
</optgroup>
<optgroup label="NFC WEST">
<option>Arizona Cardinals</option>
<option>St. Louis Rams</option>
<option>San Francisco 49ers</option>
<option>Seattle Seahawks</option>
</optgroup>
<optgroup label="AFC EAST">
<option>Buffalo Bills</option>
<option>Miami Dolphins</option>
<option>New England Patriots</option>
<option>New York Jets</option>
</optgroup>
<optgroup label="AFC NORTH">
<option>Baltimore Ravens</option>
<option>Cincinnati Bengals</option>
<option>Cleveland Browns</option>
<option>Pittsburgh Steelers</option>
</optgroup>
<optgroup label="AFC SOUTH">
<option>Houston Texans</option>
<option>Indianapolis Colts</option>
<option>Jacksonville Jaguars</option>
<option>Tennessee Titans</option>
</optgroup>
<optgroup label="AFC WEST">
<option>Denver Broncos</option>
<option>Kansas City Chiefs</option>
<option>Oakland Raiders</option>
<option>San Diego Chargers</option>
</optgroup>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Loading Data</label>
<div class="col-md-9">
<input type="hidden" class="form-control select2_sample2">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Tags Support List</label>
<div class="col-md-9">
<input type="hidden" class="form-control select2_sample3" value="red, blue">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Membership</label>
<div class="col-md-9">
<div class="radio-list">
<label>
<input type="radio" name="optionsRadios2" value="option1"/>
Free </label>
<label>
<input type="radio" name="optionsRadios2" value="option2" checked/>
Professional </label>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Street</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">City</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">State</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Post Code</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group last">
<label class="control-label col-md-3">Country</label>
<div class="col-md-9">
<select class="form-control">
</select>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green"><i class="fa fa-check"></i> Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
</div>
<div class="tab-pane" id="tab_7">
<div class="portlet box blue ">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>Form Sample
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="#portlet-config" data-toggle="modal" class="config">
</a>
<a href="javascript:;" class="reload">
</a>
<a href="javascript:;" class="remove">
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#" class="form-horizontal form-bordered form-label-stripped">
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input type="text" placeholder="small" class="form-control"/>
<span class="help-block">
This is inline help </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Last Name</label>
<div class="col-md-9">
<input type="text" placeholder="medium" class="form-control"/>
<span class="help-block">
This is inline help </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select class="form-control">
<option value="">Male</option>
<option value="">Female</option>
</select>
<span class="help-block">
Select your gender. </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input type="text" class="form-control" placeholder="dd/mm/yyyy">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Category</label>
<div class="col-md-9">
<select class="form-control select2_category">
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 5</option>
<option value="Category 4">Category 4</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Multi-Value Select</label>
<div class="col-md-9">
<select class="form-control select2_sample1" multiple>
<optgroup label="NFC EAST">
<option>Dallas Cowboys</option>
<option>New York Giants</option>
<option>Philadelphia Eagles</option>
<option>Washington Redskins</option>
</optgroup>
<optgroup label="NFC NORTH">
<option>Chicago Bears</option>
<option>Detroit Lions</option>
<option>Green Bay Packers</option>
<option>Minnesota Vikings</option>
</optgroup>
<optgroup label="NFC SOUTH">
<option>Atlanta Falcons</option>
<option>Carolina Panthers</option>
<option>New Orleans Saints</option>
<option>Tampa Bay Buccaneers</option>
</optgroup>
<optgroup label="NFC WEST">
<option>Arizona Cardinals</option>
<option>St. Louis Rams</option>
<option>San Francisco 49ers</option>
<option>Seattle Seahawks</option>
</optgroup>
<optgroup label="AFC EAST">
<option>Buffalo Bills</option>
<option>Miami Dolphins</option>
<option>New England Patriots</option>
<option>New York Jets</option>
</optgroup>
<optgroup label="AFC NORTH">
<option>Baltimore Ravens</option>
<option>Cincinnati Bengals</option>
<option>Cleveland Browns</option>
<option>Pittsburgh Steelers</option>
</optgroup>
<optgroup label="AFC SOUTH">
<option>Houston Texans</option>
<option>Indianapolis Colts</option>
<option>Jacksonville Jaguars</option>
<option>Tennessee Titans</option>
</optgroup>
<optgroup label="AFC WEST">
<option>Denver Broncos</option>
<option>Kansas City Chiefs</option>
<option>Oakland Raiders</option>
<option>San Diego Chargers</option>
</optgroup>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Loading Data</label>
<div class="col-md-9">
<input type="hidden" class="form-control select2_sample2">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Tags Support List</label>
<div class="col-md-9">
<input type="hidden" class="form-control select2_sample3" value="red, blue">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Membership</label>
<div class="col-md-9">
<div class="radio-list">
<label>
<input type="radio" name="optionsRadios2" value="option1"/>
Free </label>
<label>
<input type="radio" name="optionsRadios2" value="option2" checked/>
Professional </label>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Street</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">City</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">State</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Post Code</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group last">
<label class="control-label col-md-3">Country</label>
<div class="col-md-9">
<select class="form-control">
</select>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green"><i class="fa fa-check"></i> Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<div class="portlet light bordered form-fit">
<div class="portlet-title">
<div class="caption">
<i class="icon-user font-blue-hoki"></i>
<span class="caption-subject font-blue-hoki bold uppercase">Form Sample</span>
<span class="caption-helper">demo form...</span>
</div>
<div class="actions">
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-cloud-upload"></i>
</a>
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-wrench"></i>
</a>
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-trash"></i>
</a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="#" class="form-horizontal form-bordered form-label-stripped">
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input type="text" placeholder="small" class="form-control"/>
<span class="help-block">
This is inline help </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Last Name</label>
<div class="col-md-9">
<input type="text" placeholder="medium" class="form-control"/>
<span class="help-block">
This is inline help </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select class="form-control">
<option value="">Male</option>
<option value="">Female</option>
</select>
<span class="help-block">
Select your gender. </span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input type="text" class="form-control" placeholder="dd/mm/yyyy">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Category</label>
<div class="col-md-9">
<select class="form-control select2_category">
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 5</option>
<option value="Category 4">Category 4</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Multi-Value Select</label>
<div class="col-md-9">
<select class="form-control select2_sample1" multiple>
<optgroup label="NFC EAST">
<option>Dallas Cowboys</option>
<option>New York Giants</option>
<option>Philadelphia Eagles</option>
<option>Washington Redskins</option>
</optgroup>
<optgroup label="NFC NORTH">
<option>Chicago Bears</option>
<option>Detroit Lions</option>
<option>Green Bay Packers</option>
<option>Minnesota Vikings</option>
</optgroup>
<optgroup label="NFC SOUTH">
<option>Atlanta Falcons</option>
<option>Carolina Panthers</option>
<option>New Orleans Saints</option>
<option>Tampa Bay Buccaneers</option>
</optgroup>
<optgroup label="NFC WEST">
<option>Arizona Cardinals</option>
<option>St. Louis Rams</option>
<option>San Francisco 49ers</option>
<option>Seattle Seahawks</option>
</optgroup>
<optgroup label="AFC EAST">
<option>Buffalo Bills</option>
<option>Miami Dolphins</option>
<option>New England Patriots</option>
<option>New York Jets</option>
</optgroup>
<optgroup label="AFC NORTH">
<option>Baltimore Ravens</option>
<option>Cincinnati Bengals</option>
<option>Cleveland Browns</option>
<option>Pittsburgh Steelers</option>
</optgroup>
<optgroup label="AFC SOUTH">
<option>Houston Texans</option>
<option>Indianapolis Colts</option>
<option>Jacksonville Jaguars</option>
<option>Tennessee Titans</option>
</optgroup>
<optgroup label="AFC WEST">
<option>Denver Broncos</option>
<option>Kansas City Chiefs</option>
<option>Oakland Raiders</option>
<option>San Diego Chargers</option>
</optgroup>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Loading Data</label>
<div class="col-md-9">
<input type="hidden" class="form-control select2_sample2">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Tags Support List</label>
<div class="col-md-9">
<input type="hidden" class="form-control select2_sample3" value="red, blue">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Membership</label>
<div class="col-md-9">
<div class="radio-list">
<label>
<input type="radio" name="optionsRadios2" value="option1"/>
Free </label>
<label>
<input type="radio" name="optionsRadios2" value="option2" checked/>
Professional </label>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Street</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">City</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">State</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Post Code</label>
<div class="col-md-9">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group last">
<label class="control-label col-md-3">Country</label>
<div class="col-md-9">
<select class="form-control">
</select>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green"><i class="fa fa-check"></i> Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END PAGE CONTENT-->
</div>
</div>
<!-- END CONTENT -->
</div>
<!-- END CONTAINER -->
<!-- BEGIN FOOTER -->
<div class="page-footer">
<div class="page-footer-inner">
2014 © Metronic by keenthemes.
</div>
<div class="scroll-to-top">
<i class="icon-arrow-up"></i>
</div>
</div>
<!-- END FOOTER -->
<!-- BEGIN JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) -->
<!-- BEGIN CORE PLUGINS -->
<!--[if lt IE 9]>
<script src="../../assets/global/plugins/respond.min.js"></script>
<script src="../../assets/global/plugins/excanvas.min.js"></script>
<![endif]-->
<script src="../../assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery-migrate.min.js" type="text/javascript"></script>
<!-- IMPORTANT! Load jquery-ui.min.js before bootstrap.min.js to fix bootstrap tooltip conflict with jquery ui tooltip -->
<script src="../../assets/global/plugins/jquery-ui/jquery-ui.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery.cokie.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/uniform/jquery.uniform.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
<!-- END CORE PLUGINS -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<script type="text/javascript" src="../../assets/global/plugins/select2/select2.min.js"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN PAGE LEVEL SCRIPTS -->
<script src="../../assets/global/scripts/metronic.js" type="text/javascript"></script>
<script src="../../assets/admin/layout4/scripts/layout.js" type="text/javascript"></script>
<script src="../../assets/admin/layout4/scripts/demo.js" type="text/javascript"></script>
<script src="../../assets/admin/pages/scripts/form-samples.js"></script>
<!-- END PAGE LEVEL SCRIPTS -->
<script>
jQuery(document).ready(function() {
// initiate layout and plugins
Metronic.init(); // init metronic core components
Layout.init(); // init current layout
Demo.init(); // init demo features
FormSamples.init();
});
</script>
<!-- END JAVASCRIPTS -->
</body>
<!-- END BODY -->
</html> | zzsoszz/metronicv37 | theme_rtl/templates/admin4_material_design/form_layouts.html | HTML | apache-2.0 | 171,674 |
/**
* Simple financial systemic risk simulator for Java
* http://code.google.com/p/systemic-risk/
*
* Copyright (c) 2011, CIMNE and Gilbert Peffer.
* All rights reserved
*
* This software is open-source under the BSD license; see
* http://code.google.com/p/systemic-risk/wiki/SoftwareLicense
*/
package info.financialecology.finance.utilities.datastruct;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
/**
* @author Gilbert Peffer
*
* TODO How shall we store values from multiple runs for the same result enum?
* TODO Use a logger to manage the output
*/
public class Datastore {
private static final Set<ResultEnum> availableResults = new HashSet<ResultEnum>();
private static final Map<Type, HashMap<ResultEnum, Object>> resultMap = new HashMap<Type, HashMap<ResultEnum, Object>>();
/**
* Create a data store with the parameters and their default values
*
* @param parameters: The model and simulator parameters and their default values. An Enum type
*/
public Datastore() { }
/**
* Set up the data store for all result fields in the {@code resultSet}
*
* @author Gilbert Peffer
*
*/
public static <T extends Enum<T> & ResultEnum> void logAllResults(Class<T> resultSet)
{
for (ResultEnum re : resultSet.getEnumConstants()) {
Class<?> c = (Class<?>) re.type();
if (c.equals(Double.class))
logResult(re, new Double(0.0));
else if (c.equals(Integer.class))
logResult(re, new Integer(0));
else if (c.equals(Long.class))
logResult(re, new Long(0));
else if (c.equals(Float.class))
logResult(re, new Float((float) 0));
else if (c.equals(Short.class))
logResult(re, new Short((short) 0));
else if (c.equals(Byte.class))
logResult(re, new Byte((byte) 0));
else if (c.equals(BigInteger.class))
logResult(re, new BigInteger ("0"));
else if (c.equals(BigDecimal.class))
logResult(re, new BigDecimal (0.0));
else if (c.equals(Boolean.class))
logResult(re, new Boolean(false));
else { // Infer the constructor without parameters from the class. Expects that for the given class such a constructor is defined
Constructor<?> con = null;
try {
con = c.getConstructor();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
logResult(re, con.newInstance());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* Set up data store for the result {@code re}
*
* @param re enum field representing the result to be stored in the data store
* @return the result
*
* @author Gilbert Peffer
*/
private static <T> T logResult(ResultEnum re, T result) {
availableResults.add(re);
Type t = re.type();
if (!t.equals(result.getClass()))
throw new IllegalArgumentException("Type of result is different to the type defined in the parent class");
if (!resultMap.containsKey(t))
resultMap.put(t, new HashMap<ResultEnum, Object>());
HashMap<ResultEnum, Object> resultsOfType = resultMap.get(t);
resultsOfType.put(re, result);
return result;
}
/**
*
* @param resultType the class of the retrieved result instance
* @param re the enum field representing the result
* @return the stored result
*
* @author Gilbert Peffer
*/
public static <T> T getResult(Class<T> resultType, ResultEnum re) {
if (!resultType.equals(re.type()))
throw new IllegalArgumentException("Type of result is different to type argument 'resultType'");
Map<ResultEnum, Object> resultsForType = resultMap.get(resultType);
T result = resultType.cast(resultsForType.get(re));
return result;
}
public static void clean() {
availableResults.clear();
resultMap.clear();
}
}
| gitwitcho/var-agent-model | simulator_utilities/src/info/financialecology/finance/utilities/datastruct/Datastore.java | Java | apache-2.0 | 5,290 |
package container
import (
"io"
"os"
"path/filepath"
"golang.org/x/net/context"
log "github.com/Sirupsen/logrus"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/strslice"
"github.com/docker/docker/pkg/archive"
"github.com/docker/docker/pkg/system"
"github.com/maliceio/malice/malice/docker/client"
er "github.com/maliceio/malice/malice/errors"
"github.com/maliceio/malice/malice/maldirs"
"github.com/maliceio/malice/malice/persist"
)
// CopyToVolume copies samples into Malice volume
func CopyToVolume(docker *client.Docker, file persist.File) {
name := "copy2volume"
image := "busybox"
cmd := strslice.StrSlice{"sh", "-c", "while true; do echo 'Waiting...'; sleep 1; done"}
binds := []string{"malice:/malice:rw"}
volSavePath := filepath.Join("/malice", file.SHA256)
if docker.Ping() {
cont, err := Start(docker, cmd, name, image, false, binds, nil, nil, nil)
er.CheckError(err)
defer func() {
er.CheckError(Remove(docker, cont.ID, true, false, true))
}()
// Get an absolute source path.
srcPath, err := resolveLocalPath(file.Path)
er.CheckError(err)
// Prepare destination copy info by stat-ing the container path.
dstInfo := archive.CopyInfo{Path: volSavePath}
dstStat, err := statContainerPath(docker, cont.Name, volSavePath)
log.WithFields(log.Fields{
"dstInfo": dstInfo,
"dstStat": dstStat,
"container.Name": cont.Name,
"file.Path": file.Path,
"volSavePath": volSavePath,
"SampledsDir": maldirs.GetSampledsDir(),
}).Debug("First statContainerPath call.")
// er.CheckError(err)
// Check if file already exists in volume
if dstStat.Size > 0 {
log.Debug("Sample ", file.Name, " already in malice volume.")
return
}
// If the destination is a symbolic link, we should evaluate it.
if err == nil && dstStat.Mode&os.ModeSymlink != 0 {
linkTarget := dstStat.LinkTarget
if !system.IsAbs(linkTarget) {
// Join with the parent directory.
dstParent, _ := archive.SplitPathDirEntry(volSavePath)
linkTarget = filepath.Join(dstParent, linkTarget)
}
dstInfo.Path = linkTarget
dstStat, err = statContainerPath(docker, cont.Name, linkTarget)
log.WithFields(log.Fields{
"dstInfo": dstInfo,
"dstStat": dstStat,
"container.Name": cont.Name,
"file.Path": file.Path,
"linkTarget": linkTarget,
"SampledsDir": maldirs.GetSampledsDir(),
}).Debug("Second statContainerPath call.")
er.CheckError(err)
}
if err == nil {
dstInfo.Exists = true
dstInfo.IsDir = dstStat.Mode.IsDir()
}
var (
content io.Reader
resolvedDstPath string
)
// Prepare source copy info.
srcInfo, err := archive.CopyInfoSourcePath(srcPath, false)
er.CheckError(err)
srcArchive, err := archive.TarResource(srcInfo)
er.CheckError(err)
defer srcArchive.Close()
dstDir, preparedArchive, err := archive.PrepareArchiveCopy(srcArchive, srcInfo, dstInfo)
er.CheckError(err)
defer preparedArchive.Close()
resolvedDstPath = dstDir
content = preparedArchive
copyOptions := types.CopyToContainerOptions{
AllowOverwriteDirWithFile: true,
}
// Copy sample to malice volume
er.CheckError(docker.Client.CopyToContainer(
context.Background(),
cont.ID,
resolvedDstPath,
content,
copyOptions,
))
}
}
func resolveLocalPath(localPath string) (absPath string, err error) {
if absPath, err = filepath.Abs(localPath); err != nil {
return
}
return archive.PreserveTrailingDotOrSeparator(absPath, localPath), nil
}
func statContainerPath(docker *client.Docker, containerName, path string) (types.ContainerPathStat, error) {
return docker.Client.ContainerStatPath(context.Background(), containerName, path)
}
| maliceio/malice | malice/docker/client/container/copy.go | GO | apache-2.0 | 3,759 |
<!-- Generated by pkgdown: do not edit by hand -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>25-Hydroxyvitamin D and Parathyroid Hormone Are Not Associated With Carotid Intima-Media Thickness or Plaque in the Multi-Ethnic Study of Atherosclerosis (2013) ARTERIOSCLEROSIS THROMBOSIS AND VASCULAR BIOLOGY — Blondon201325-Hydroxyvitamin • sachsmc</title>
<!-- favicons -->
<link rel="icon" type="image/png" sizes="16x16" href="../favicon-16x16.png">
<link rel="icon" type="image/png" sizes="32x32" href="../favicon-32x32.png">
<link rel="apple-touch-icon" type="image/png" sizes="180x180" href="../apple-touch-icon.png" />
<link rel="apple-touch-icon" type="image/png" sizes="120x120" href="../apple-touch-icon-120x120.png" />
<link rel="apple-touch-icon" type="image/png" sizes="76x76" href="../apple-touch-icon-76x76.png" />
<link rel="apple-touch-icon" type="image/png" sizes="60x60" href="../apple-touch-icon-60x60.png" />
<!-- jquery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.4.0/paper/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha256-nuL8/2cJ5NDSSwnKD8VqreErSWHtnEP9E7AySL+1ev4=" crossorigin="anonymous"></script>
<!-- bootstrap-toc -->
<link rel="stylesheet" href="../bootstrap-toc.css">
<script src="../bootstrap-toc.js"></script>
<!-- Font Awesome icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css" integrity="sha256-mmgLkCYLUQbXn0B1SRqzHar6dCnv9oZFPEC1g1cwlkk=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/v4-shims.min.css" integrity="sha256-wZjR52fzng1pJHwx4aV2AO3yyTOXrcDW7jBpJtTwVxw=" crossorigin="anonymous" />
<!-- clipboard.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.6/clipboard.min.js" integrity="sha256-inc5kl9MA1hkeYUt+EC3BhlIgyp/2jDIyBLS6k3UxPI=" crossorigin="anonymous"></script>
<!-- headroom.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/headroom/0.11.0/headroom.min.js" integrity="sha256-AsUX4SJE1+yuDu5+mAVzJbuYNPHj/WroHuZ8Ir/CkE0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/headroom/0.11.0/jQuery.headroom.min.js" integrity="sha256-ZX/yNShbjqsohH1k95liqY9Gd8uOiE1S4vZc+9KQ1K4=" crossorigin="anonymous"></script>
<!-- pkgdown -->
<link href="../pkgdown.css" rel="stylesheet">
<script src="../pkgdown.js"></script>
<meta property="og:title" content="25-Hydroxyvitamin D and Parathyroid Hormone Are Not Associated With Carotid Intima-Media Thickness or Plaque in the Multi-Ethnic Study of Atherosclerosis (2013) ARTERIOSCLEROSIS THROMBOSIS AND VASCULAR BIOLOGY — Blondon201325-Hydroxyvitamin" />
<meta property="og:description" content="Blondon, M; Sachs, M; Hoofnagle, AN; Ix, JH; Michos, ED; Korcarz, C; Gepner, AD; Siscovick, DS; Kaufman, JD; Stein, JH; Kestenbaum, B; deBoer, IH" />
<meta property="og:image" content="/logo.png" />
<!-- mathjax -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js" integrity="sha256-nvJJv9wWKEm88qvoQl9ekL2J+k/RWIsaSScxxlsrv8k=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/config/TeX-AMS-MML_HTMLorMML.js" integrity="sha256-84DKXVJXs0/F8OTMzX4UR909+jtl4G7SPypPavF+GfA=" crossorigin="anonymous"></script>
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body data-spy="scroll" data-target="#toc">
<div class="container template-reference-topic">
<header>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<span class="navbar-brand">
<a class="navbar-link" href="../index.html">sachsmc</a>
<span class="version label label-default" data-toggle="tooltip" data-placement="bottom" title="Released version">1983-09-07</span>
</span>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="../index.html">
<span class="fas fa-home fa-lg"></span>
</a>
</li>
<li>
<a href="../reference/index.html">Publications</a>
</li>
<li>
<a href="../articles/software.html">Software</a>
</li>
<li>
<a href="../articles/index.html">Articles</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
</header>
<div class="row">
<div class="col-md-9 contents">
<div class="page-header">
<h1>25-Hydroxyvitamin D and Parathyroid Hormone Are Not Associated With Carotid Intima-Media Thickness or Plaque in the Multi-Ethnic Study of Atherosclerosis (2013) <em>ARTERIOSCLEROSIS THROMBOSIS AND VASCULAR BIOLOGY</em></h1>
<div class="hidden name"><code>Blondon201325-Hydroxyvitamin.Rd</code></div>
</div>
<div class="ref-description">
<p>Blondon, M; Sachs, M; Hoofnagle, AN; Ix, JH; Michos, ED; Korcarz, C; Gepner, AD; Siscovick, DS; Kaufman, JD; Stein, JH; Kestenbaum, B; deBoer, IH</p>
</div>
<h2 class="hasAnchor" id="details"><a class="anchor" href="#details"></a>Details</h2>
<p>ARTERIOSCLEROSIS THROMBOSIS AND VASCULAR BIOLOGY (2013). 2639-45:33. <a href='http://www.ncbi.nlm.nih.gov/pubmed/23814117'>http://www.ncbi.nlm.nih.gov/pubmed/23814117</a></p>
</div>
<div class="col-md-3 hidden-xs hidden-sm" id="pkgdown-sidebar">
<nav id="toc" data-toggle="toc" class="sticky-top">
<h2 data-toc-skip>Contents</h2>
</nav>
</div>
</div>
<footer>
<div class="copyright">
<p>Developed by Michael Sachs.</p>
</div>
<div class="pkgdown">
<p>Site built with <a href="https://pkgdown.r-lib.org/">pkgdown</a> 1.6.1.</p>
</div>
</footer>
</div>
</body>
</html>
| sachsmc/sachsmc.github.io | reference/Blondon201325-Hydroxyvitamin.html | HTML | apache-2.0 | 6,753 |
# -*- coding: utf-8 -*-
#
# 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.
from airflow.hooks.oracle_hook import OracleHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class OracleOperator(BaseOperator):
"""
Executes sql code in a specific Oracle database
:param oracle_conn_id: reference to a specific Oracle database
:type oracle_conn_id: str
:param sql: the sql code to be executed. (templated)
:type sql: Can receive a str representing a sql statement,
a list of str (sql statements), or reference to a template file.
Template reference are recognized by str ending in '.sql'
"""
template_fields = ('sql',)
template_ext = ('.sql',)
ui_color = '#ededed'
@apply_defaults
def __init__(
self, sql, oracle_conn_id='oracle_default', parameters=None,
autocommit=False, *args, **kwargs):
super(OracleOperator, self).__init__(*args, **kwargs)
self.oracle_conn_id = oracle_conn_id
self.sql = sql
self.autocommit = autocommit
self.parameters = parameters
def execute(self, context):
self.log.info('Executing: %s', self.sql)
hook = OracleHook(oracle_conn_id=self.oracle_conn_id)
hook.run(
self.sql,
autocommit=self.autocommit,
parameters=self.parameters)
| akosel/incubator-airflow | airflow/operators/oracle_operator.py | Python | apache-2.0 | 2,130 |
package water.hive;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.hive.jdbc.HiveConnection;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class HiveTokenGenerator {
private static final String HIVE_DRIVER_CLASS = "org.apache.hive.jdbc.HiveDriver";
private static boolean isPresent(String value) {
return value != null && !value.isEmpty();
}
public static String makeHivePrincipalJdbcUrl(String hiveJdbcUrlPattern, String hiveHost, String hivePrincipal) {
if (isPresent(hiveJdbcUrlPattern) && isPresent(hivePrincipal)) {
String result = hiveJdbcUrlPattern;
if (hiveHost != null) result = result.replace("{{host}}", hiveHost);
result = result.replace("{{auth}}", "principal=" + hivePrincipal);
return result;
} else if (isPresent(hiveHost) && isPresent(hivePrincipal)) {
return "jdbc:hive2://" + hiveHost + "/" + ";principal=" + hivePrincipal;
} else {
return null;
}
}
public static String makeHiveDelegationTokenJdbcUrl(String hiveJdbcUrlPattern, String hiveHost) {
if (isPresent(hiveJdbcUrlPattern)) {
String result = hiveJdbcUrlPattern;
if (hiveHost != null) result = result.replace("{{host}}", hiveHost);
result = result.replace("{{auth}}", "auth=delegationToken");
return result;
} else if (isPresent(hiveHost)) {
return "jdbc:hive2://" + hiveHost + "/" + ";auth=delegationToken";
} else
return null;
}
public static String getHiveDelegationTokenIfHivePresent(
String hiveJdbcUrlPattern, String hiveHost, String hivePrincipal
) throws IOException, InterruptedException {
if (isHiveDriverPresent()) {
final String hiveJdbcUrl = makeHivePrincipalJdbcUrl(hiveJdbcUrlPattern, hiveHost, hivePrincipal);
return new HiveTokenGenerator().getHiveDelegationToken(hiveJdbcUrl, hivePrincipal);
} else {
log("Hive driver not present, not generating token.", null);
return null;
}
}
public static boolean addHiveDelegationTokenIfHivePresent(
Job job, String hiveJdbcUrlPattern, String hiveHost, String hivePrincipal
) throws IOException, InterruptedException {
if (isHiveDriverPresent()) {
final String hiveJdbcUrl = makeHivePrincipalJdbcUrl(hiveJdbcUrlPattern, hiveHost, hivePrincipal);
return new HiveTokenGenerator().addHiveDelegationToken(job, hiveJdbcUrl, hivePrincipal);
} else {
log("Hive driver not present, not generating token.", null);
return false;
}
}
public boolean addHiveDelegationToken(
Job job,
String hiveJdbcUrl,
String hivePrincipal
) throws IOException, InterruptedException {
if (!isPresent(hiveJdbcUrl) || !isPresent(hivePrincipal)) {
log("Hive JDBC URL or principal not set, no token generated.", null);
return false;
}
String token = getHiveDelegationToken(hiveJdbcUrl, hivePrincipal);
if (token != null) {
DelegationTokenPrinter.printToken(token);
addHiveDelegationToken(job, token);
return true;
} else {
log("Failed to get delegation token.", null);
return false;
}
}
public static void addHiveDelegationToken(Job job, String token) throws IOException {
Credentials creds = tokenToCredentials(token);
job.getCredentials().addAll(creds);
}
private String getHiveDelegationToken(String hiveJdbcUrl, String hivePrincipal) throws IOException, InterruptedException {
UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
UserGroupInformation realUser = currentUser;
if (realUser.getRealUser() != null) {
realUser = realUser.getRealUser();
}
return getHiveDelegationTokenAsUser(realUser, currentUser, hiveJdbcUrl, hivePrincipal);
}
public String getHiveDelegationTokenAsUser(
UserGroupInformation realUser, final UserGroupInformation user, final String hiveJdbcUrl, final String hivePrincipal
) throws IOException, InterruptedException {
return realUser.doAs(new PrivilegedExceptionAction<String>() {
@Override
public String run() {
return getHiveDelegationTokenIfPossible(user, hiveJdbcUrl, hivePrincipal);
}
});
}
private static void log(String s, Exception e) {
System.out.println(s);
if (e != null) {
e.printStackTrace(System.out);
}
}
private String getDelegationTokenFromConnection(String hiveJdbcUrl, String hivePrincipal, String userName) {
if (!isHiveDriverPresent()) {
throw new IllegalStateException("Hive Driver not found");
}
try (Connection connection = DriverManager.getConnection(hiveJdbcUrl)) {
return ((HiveConnection) connection).getDelegationToken(userName, hivePrincipal);
} catch (SQLException e) {
log("Failed to get connection.", e);
return null;
}
}
public String getHiveDelegationTokenIfPossible(UserGroupInformation tokenUser, String hiveJdbcUrl, String hivePrincipal) {
if (!isHiveDriverPresent()) {
return null;
}
String tokenUserName = tokenUser.getShortUserName();
log("Getting delegation token from " + hiveJdbcUrl + ", " + tokenUserName, null);
return getDelegationTokenFromConnection(hiveJdbcUrl, hivePrincipal, tokenUserName);
}
public static Credentials tokenToCredentials(String tokenStr) throws IOException {
if (tokenStr != null) {
Token<DelegationTokenIdentifier> hive2Token = new Token<>();
hive2Token.decodeFromUrlString(tokenStr);
hive2Token.setService(new Text("hiveserver2ClientToken"));
Credentials creds = new Credentials();
creds.addToken(new Text("hive.server2.delegation.token"), hive2Token);
creds.addToken(new Text("hiveserver2ClientToken"), hive2Token); //HiveAuthConstants.HS2_CLIENT_TOKEN
return creds;
} else {
return null;
}
}
public static boolean isHiveDriverPresent() {
try {
Class.forName(HIVE_DRIVER_CLASS);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
}
| michalkurka/h2o-3 | h2o-hive/src/main/java/water/hive/HiveTokenGenerator.java | Java | apache-2.0 | 6,399 |
// Copyright 2014 Serilog Contributors
//
// 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.
using System;
using Serilog.Sinks.NLog;
using Serilog.Configuration;
using Serilog.Events;
namespace Serilog
{
/// <summary>
/// Adds the WriteTo.NLog() extension method to <see cref="LoggerConfiguration"/>.
/// </summary>
public static class LoggerConfigurationsNLogExtensions
{
/// <summary>
/// Adds a sink that writes adapted log events to NLog.
/// </summary>
/// <param name="loggerConfiguration">The logger configuration.</param>
/// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
/// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
/// <returns>Logger configuration, allowing configuration to continue.</returns>
/// <exception cref="ArgumentNullException">A required parameter is null.</exception>
public static LoggerConfiguration NLog(
this LoggerSinkConfiguration loggerConfiguration,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
IFormatProvider formatProvider = null)
{
if (loggerConfiguration == null)
{
throw new ArgumentNullException("loggerConfiguration");
}
return loggerConfiguration.Sink(new NLogSink(formatProvider), restrictedToMinimumLevel);
}
}
}
| vossad01/serilog | src/Serilog.Sinks.NLog/LoggerConfigurationsNLogExtensions.cs | C# | apache-2.0 | 2,030 |
---
layout: vakit_dashboard
title: BOGOR, ENDONEZYA için iftar, namaz vakitleri ve hava durumu - ilçe/eyalet seç
permalink: /ENDONEZYA/BOGOR
---
## BOGOR (ENDONEZYA) için iftar, namaz vakitleri ve hava durumu görmek için bir ilçe/eyalet seç
Aşağıdaki listeden bir şehir ya da semt seçin
* [ (BOGOR, ENDONEZYA) için iftar ve namaz vakitleri](/ENDONEZYA/BOGOR/)
<script type="text/javascript">
var GLOBAL_COUNTRY = 'ENDONEZYA';
var GLOBAL_CITY = 'BOGOR';
var GLOBAL_STATE = 'BOGOR';
</script>
| hakanu/iftar | _posts_/vakit/ENDONEZYA/BOGOR/2017-02-01-BOGOR.markdown | Markdown | apache-2.0 | 516 |
<html dir="LTR">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
<title>IndexReader.Norms Method (String)</title>
<xml>
</xml>
<link rel="stylesheet" type="text/css" href="MSDN.css" />
</head>
<body id="bodyID" class="dtBODY">
<div id="nsbanner">
<div id="bannerrow1">
<table class="bannerparthead" cellspacing="0">
<tr id="hdr">
<td class="runninghead">Apache Lucene.Net 2.4.0 Class Library API</td>
<td class="product">
</td>
</tr>
</table>
</div>
<div id="TitleRow">
<h1 class="dtH1">IndexReader.Norms Method (String)</h1>
</div>
</div>
<div id="nstext">
<p>Returns the byte-encoded normalization factor for the named field of every document. This is used by the search code to score documents. </p>
<div class="syntax">public abstract <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemByteClassTopic.htm">byte[]</a> Norms(<br /> <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemStringClassTopic.htm">string</a> <i>field</i><br />);</div>
<h4 class="dtH4">See Also</h4>
<p>
<a href="Lucene.Net.Index.IndexReader.html">IndexReader Class</a> | <a href="Lucene.Net.Index.html">Lucene.Net.Index Namespace</a> | <a href="Lucene.Net.Index.IndexReader.Norms_overloads.html">IndexReader.Norms Overload List</a> | <b>SetBoost</b></p>
<object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
<param name="Keyword" value="Norms method">
</param>
<param name="Keyword" value="Norms method, IndexReader class">
</param>
<param name="Keyword" value="IndexReader.Norms method">
</param>
</object>
<hr />
<div id="footer">
<p>
</p>
<p>Generated from assembly Lucene.Net [2.4.0.2]</p>
</div>
</div>
</body>
</html> | Mpdreamz/lucene.net | doc/core/Lucene.Net.Index.IndexReader.Norms_overload_1.html | HTML | apache-2.0 | 2,164 |
/*
* 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.scheduler
import java.util.{Properties, Random}
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import org.mockito.Matchers.{any, anyInt, anyString}
import org.mockito.Mockito.{mock, never, spy, verify, when}
import org.mockito.invocation.InvocationOnMock
import org.mockito.stubbing.Answer
import org.apache.spark._
import org.apache.spark.internal.config
import org.apache.spark.internal.Logging
import org.apache.spark.serializer.SerializerInstance
import org.apache.spark.storage.BlockManagerId
import org.apache.spark.util.{AccumulatorV2, ManualClock}
class FakeDAGScheduler(sc: SparkContext, taskScheduler: FakeTaskScheduler)
extends DAGScheduler(sc) {
override def taskStarted(task: Task[_], taskInfo: TaskInfo) {
taskScheduler.startedTasks += taskInfo.index
}
override def taskEnded(
task: Task[_],
reason: TaskEndReason,
result: Any,
accumUpdates: Seq[AccumulatorV2[_, _]],
taskInfo: TaskInfo) {
taskScheduler.endedTasks(taskInfo.index) = reason
}
override def executorAdded(execId: String, host: String) {}
override def executorLost(execId: String, reason: ExecutorLossReason) {}
override def taskSetFailed(
taskSet: TaskSet,
reason: String,
exception: Option[Throwable]): Unit = {
taskScheduler.taskSetsFailed += taskSet.id
}
}
// Get the rack for a given host
object FakeRackUtil {
private val hostToRack = new mutable.HashMap[String, String]()
def cleanUp() {
hostToRack.clear()
}
def assignHostToRack(host: String, rack: String) {
hostToRack(host) = rack
}
def getRackForHost(host: String): Option[String] = {
hostToRack.get(host)
}
}
/**
* A mock TaskSchedulerImpl implementation that just remembers information about tasks started and
* feedback received from the TaskSetManagers. Note that it's important to initialize this with
* a list of "live" executors and their hostnames for isExecutorAlive and hasExecutorsAliveOnHost
* to work, and these are required for locality in TaskSetManager.
*/
class FakeTaskScheduler(sc: SparkContext, liveExecutors: (String, String)* /* execId, host */)
extends TaskSchedulerImpl(sc)
{
val startedTasks = new ArrayBuffer[Long]
val endedTasks = new mutable.HashMap[Long, TaskEndReason]
val finishedManagers = new ArrayBuffer[TaskSetManager]
val taskSetsFailed = new ArrayBuffer[String]
val executors = new mutable.HashMap[String, String]
for ((execId, host) <- liveExecutors) {
addExecutor(execId, host)
}
for ((execId, host) <- liveExecutors; rack <- getRackForHost(host)) {
hostsByRack.getOrElseUpdate(rack, new mutable.HashSet[String]()) += host
}
dagScheduler = new FakeDAGScheduler(sc, this)
def removeExecutor(execId: String) {
executors -= execId
val host = executorIdToHost.get(execId)
assert(host != None)
val hostId = host.get
val executorsOnHost = hostToExecutors(hostId)
executorsOnHost -= execId
for (rack <- getRackForHost(hostId); hosts <- hostsByRack.get(rack)) {
hosts -= hostId
if (hosts.isEmpty) {
hostsByRack -= rack
}
}
}
override def taskSetFinished(manager: TaskSetManager): Unit = finishedManagers += manager
override def isExecutorAlive(execId: String): Boolean = executors.contains(execId)
override def hasExecutorsAliveOnHost(host: String): Boolean = executors.values.exists(_ == host)
override def hasHostAliveOnRack(rack: String): Boolean = {
hostsByRack.get(rack) != None
}
def addExecutor(execId: String, host: String) {
executors.put(execId, host)
val executorsOnHost = hostToExecutors.getOrElseUpdate(host, new mutable.HashSet[String])
executorsOnHost += execId
executorIdToHost += execId -> host
for (rack <- getRackForHost(host)) {
hostsByRack.getOrElseUpdate(rack, new mutable.HashSet[String]()) += host
}
}
override def getRackForHost(value: String): Option[String] = FakeRackUtil.getRackForHost(value)
}
/**
* A Task implementation that results in a large serialized task.
*/
class LargeTask(stageId: Int) extends Task[Array[Byte]](stageId, 0, 0) {
val randomBuffer = new Array[Byte](TaskSetManager.TASK_SIZE_TO_WARN_KB * 1024)
val random = new Random(0)
random.nextBytes(randomBuffer)
override def runTask(context: TaskContext): Array[Byte] = randomBuffer
override def preferredLocations: Seq[TaskLocation] = Seq[TaskLocation]()
}
class TaskSetManagerSuite extends SparkFunSuite with LocalSparkContext with Logging {
import TaskLocality.{ANY, PROCESS_LOCAL, NO_PREF, NODE_LOCAL, RACK_LOCAL}
private val conf = new SparkConf
val LOCALITY_WAIT_MS = conf.getTimeAsMs("spark.locality.wait", "3s")
val MAX_TASK_FAILURES = 4
var sched: FakeTaskScheduler = null
override def beforeEach(): Unit = {
super.beforeEach()
FakeRackUtil.cleanUp()
sched = null
}
override def afterEach(): Unit = {
super.afterEach()
if (sched != null) {
sched.dagScheduler.stop()
sched.stop()
sched = null
}
}
test("TaskSet with no preferences") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
val taskSet = FakeTask.createTaskSet(1)
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
val accumUpdates = taskSet.tasks.head.metrics.internalAccums
// Offer a host with NO_PREF as the constraint,
// we should get a nopref task immediately since that's what we only have
val taskOption = manager.resourceOffer("exec1", "host1", NO_PREF)
assert(taskOption.isDefined)
clock.advance(1)
// Tell it the task has finished
manager.handleSuccessfulTask(0, createTaskResult(0, accumUpdates))
assert(sched.endedTasks(0) === Success)
assert(sched.finishedManagers.contains(manager))
}
test("multiple offers with no preferences") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
val taskSet = FakeTask.createTaskSet(3)
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES)
val accumUpdatesByTask: Array[Seq[AccumulatorV2[_, _]]] = taskSet.tasks.map { task =>
task.metrics.internalAccums
}
// First three offers should all find tasks
for (i <- 0 until 3) {
val taskOption = manager.resourceOffer("exec1", "host1", NO_PREF)
assert(taskOption.isDefined)
val task = taskOption.get
assert(task.executorId === "exec1")
}
assert(sched.startedTasks.toSet === Set(0, 1, 2))
// Re-offer the host -- now we should get no more tasks
assert(manager.resourceOffer("exec1", "host1", NO_PREF) === None)
// Finish the first two tasks
manager.handleSuccessfulTask(0, createTaskResult(0, accumUpdatesByTask(0)))
manager.handleSuccessfulTask(1, createTaskResult(1, accumUpdatesByTask(1)))
assert(sched.endedTasks(0) === Success)
assert(sched.endedTasks(1) === Success)
assert(!sched.finishedManagers.contains(manager))
// Finish the last task
manager.handleSuccessfulTask(2, createTaskResult(2, accumUpdatesByTask(2)))
assert(sched.endedTasks(2) === Success)
assert(sched.finishedManagers.contains(manager))
}
test("skip unsatisfiable locality levels") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("execA", "host1"), ("execC", "host2"))
val taskSet = FakeTask.createTaskSet(1, Seq(TaskLocation("host1", "execB")))
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// An executor that is not NODE_LOCAL should be rejected.
assert(manager.resourceOffer("execC", "host2", ANY) === None)
// Because there are no alive PROCESS_LOCAL executors, the base locality level should be
// NODE_LOCAL. So, we should schedule the task on this offered NODE_LOCAL executor before
// any of the locality wait timers expire.
assert(manager.resourceOffer("execA", "host1", ANY).get.index === 0)
}
test("basic delay scheduling") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"), ("exec2", "host2"))
val taskSet = FakeTask.createTaskSet(4,
Seq(TaskLocation("host1", "exec1")),
Seq(TaskLocation("host2", "exec2")),
Seq(TaskLocation("host1"), TaskLocation("host2", "exec2")),
Seq() // Last task has no locality prefs
)
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// First offer host1, exec1: first task should be chosen
assert(manager.resourceOffer("exec1", "host1", ANY).get.index === 0)
assert(manager.resourceOffer("exec1", "host1", PROCESS_LOCAL) == None)
clock.advance(LOCALITY_WAIT_MS)
// Offer host1, exec1 again, at NODE_LOCAL level: the node local (task 3) should
// get chosen before the noPref task
assert(manager.resourceOffer("exec1", "host1", NODE_LOCAL).get.index == 2)
// Offer host2, exec2, at NODE_LOCAL level: we should choose task 2
assert(manager.resourceOffer("exec2", "host2", NODE_LOCAL).get.index == 1)
// Offer host2, exec2 again, at NODE_LOCAL level: we should get noPref task
// after failing to find a node_Local task
assert(manager.resourceOffer("exec2", "host2", NODE_LOCAL) == None)
clock.advance(LOCALITY_WAIT_MS)
assert(manager.resourceOffer("exec2", "host2", NO_PREF).get.index == 3)
}
test("we do not need to delay scheduling when we only have noPref tasks in the queue") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"), ("exec3", "host2"))
val taskSet = FakeTask.createTaskSet(3,
Seq(TaskLocation("host1", "exec1")),
Seq(TaskLocation("host2", "exec3")),
Seq() // Last task has no locality prefs
)
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// First offer host1, exec1: first task should be chosen
assert(manager.resourceOffer("exec1", "host1", PROCESS_LOCAL).get.index === 0)
assert(manager.resourceOffer("exec3", "host2", PROCESS_LOCAL).get.index === 1)
assert(manager.resourceOffer("exec3", "host2", NODE_LOCAL) == None)
assert(manager.resourceOffer("exec3", "host2", NO_PREF).get.index === 2)
}
test("delay scheduling with fallback") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc,
("exec1", "host1"), ("exec2", "host2"), ("exec3", "host3"))
val taskSet = FakeTask.createTaskSet(5,
Seq(TaskLocation("host1")),
Seq(TaskLocation("host2")),
Seq(TaskLocation("host2")),
Seq(TaskLocation("host3")),
Seq(TaskLocation("host2"))
)
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// First offer host1: first task should be chosen
assert(manager.resourceOffer("exec1", "host1", ANY).get.index === 0)
// Offer host1 again: nothing should get chosen
assert(manager.resourceOffer("exec1", "host1", ANY) === None)
clock.advance(LOCALITY_WAIT_MS)
// Offer host1 again: second task (on host2) should get chosen
assert(manager.resourceOffer("exec1", "host1", ANY).get.index === 1)
// Offer host1 again: third task (on host2) should get chosen
assert(manager.resourceOffer("exec1", "host1", ANY).get.index === 2)
// Offer host2: fifth task (also on host2) should get chosen
assert(manager.resourceOffer("exec2", "host2", ANY).get.index === 4)
// Now that we've launched a local task, we should no longer launch the task for host3
assert(manager.resourceOffer("exec2", "host2", ANY) === None)
clock.advance(LOCALITY_WAIT_MS)
// After another delay, we can go ahead and launch that task non-locally
assert(manager.resourceOffer("exec2", "host2", ANY).get.index === 3)
}
test("delay scheduling with failed hosts") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"), ("exec2", "host2"),
("exec3", "host3"))
val taskSet = FakeTask.createTaskSet(3,
Seq(TaskLocation("host1")),
Seq(TaskLocation("host2")),
Seq(TaskLocation("host3"))
)
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// First offer host1: first task should be chosen
assert(manager.resourceOffer("exec1", "host1", ANY).get.index === 0)
// After this, nothing should get chosen, because we have separated tasks with unavailable
// preference from the noPrefPendingTasks
assert(manager.resourceOffer("exec1", "host1", ANY) === None)
// Now mark host2 as dead
sched.removeExecutor("exec2")
manager.executorLost("exec2", "host2", SlaveLost())
// nothing should be chosen
assert(manager.resourceOffer("exec1", "host1", ANY) === None)
clock.advance(LOCALITY_WAIT_MS * 2)
// task 1 and 2 would be scheduled as nonLocal task
assert(manager.resourceOffer("exec1", "host1", ANY).get.index === 1)
assert(manager.resourceOffer("exec1", "host1", ANY).get.index === 2)
// all finished
assert(manager.resourceOffer("exec1", "host1", ANY) === None)
assert(manager.resourceOffer("exec2", "host2", ANY) === None)
}
test("task result lost") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
val taskSet = FakeTask.createTaskSet(1)
val clock = new ManualClock
clock.advance(1)
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
assert(manager.resourceOffer("exec1", "host1", ANY).get.index === 0)
// Tell it the task has finished but the result was lost.
manager.handleFailedTask(0, TaskState.FINISHED, TaskResultLost)
assert(sched.endedTasks(0) === TaskResultLost)
// Re-offer the host -- now we should get task 0 again.
assert(manager.resourceOffer("exec1", "host1", ANY).get.index === 0)
}
test("repeated failures lead to task set abortion") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
val taskSet = FakeTask.createTaskSet(1)
val clock = new ManualClock
clock.advance(1)
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// Fail the task MAX_TASK_FAILURES times, and check that the task set is aborted
// after the last failure.
(1 to manager.maxTaskFailures).foreach { index =>
val offerResult = manager.resourceOffer("exec1", "host1", ANY)
assert(offerResult.isDefined,
"Expect resource offer on iteration %s to return a task".format(index))
assert(offerResult.get.index === 0)
manager.handleFailedTask(offerResult.get.taskId, TaskState.FINISHED, TaskResultLost)
if (index < MAX_TASK_FAILURES) {
assert(!sched.taskSetsFailed.contains(taskSet.id))
} else {
assert(sched.taskSetsFailed.contains(taskSet.id))
}
}
}
test("executors should be blacklisted after task failure, in spite of locality preferences") {
val rescheduleDelay = 300L
val conf = new SparkConf().
set(config.BLACKLIST_ENABLED, true).
set(config.BLACKLIST_TIMEOUT_CONF, rescheduleDelay).
// don't wait to jump locality levels in this test
set("spark.locality.wait", "0")
sc = new SparkContext("local", "test", conf)
// two executors on same host, one on different.
sched = new FakeTaskScheduler(sc, ("exec1", "host1"),
("exec1.1", "host1"), ("exec2", "host2"))
// affinity to exec1 on host1 - which we will fail.
val taskSet = FakeTask.createTaskSet(1, Seq(TaskLocation("host1", "exec1")))
val clock = new ManualClock
clock.advance(1)
// We don't directly use the application blacklist, but its presence triggers blacklisting
// within the taskset.
val mockListenerBus = mock(classOf[LiveListenerBus])
val blacklistTrackerOpt = Some(new BlacklistTracker(mockListenerBus, conf, None, clock))
val manager = new TaskSetManager(sched, taskSet, 4, blacklistTrackerOpt, clock)
{
val offerResult = manager.resourceOffer("exec1", "host1", PROCESS_LOCAL)
assert(offerResult.isDefined, "Expect resource offer to return a task")
assert(offerResult.get.index === 0)
assert(offerResult.get.executorId === "exec1")
// Cause exec1 to fail : failure 1
manager.handleFailedTask(offerResult.get.taskId, TaskState.FINISHED, TaskResultLost)
assert(!sched.taskSetsFailed.contains(taskSet.id))
// Ensure scheduling on exec1 fails after failure 1 due to blacklist
assert(manager.resourceOffer("exec1", "host1", PROCESS_LOCAL).isEmpty)
assert(manager.resourceOffer("exec1", "host1", NODE_LOCAL).isEmpty)
assert(manager.resourceOffer("exec1", "host1", RACK_LOCAL).isEmpty)
assert(manager.resourceOffer("exec1", "host1", ANY).isEmpty)
}
// Run the task on exec1.1 - should work, and then fail it on exec1.1
{
val offerResult = manager.resourceOffer("exec1.1", "host1", NODE_LOCAL)
assert(offerResult.isDefined,
"Expect resource offer to return a task for exec1.1, offerResult = " + offerResult)
assert(offerResult.get.index === 0)
assert(offerResult.get.executorId === "exec1.1")
// Cause exec1.1 to fail : failure 2
manager.handleFailedTask(offerResult.get.taskId, TaskState.FINISHED, TaskResultLost)
assert(!sched.taskSetsFailed.contains(taskSet.id))
// Ensure scheduling on exec1.1 fails after failure 2 due to blacklist
assert(manager.resourceOffer("exec1.1", "host1", NODE_LOCAL).isEmpty)
}
// Run the task on exec2 - should work, and then fail it on exec2
{
val offerResult = manager.resourceOffer("exec2", "host2", ANY)
assert(offerResult.isDefined, "Expect resource offer to return a task")
assert(offerResult.get.index === 0)
assert(offerResult.get.executorId === "exec2")
// Cause exec2 to fail : failure 3
manager.handleFailedTask(offerResult.get.taskId, TaskState.FINISHED, TaskResultLost)
assert(!sched.taskSetsFailed.contains(taskSet.id))
// Ensure scheduling on exec2 fails after failure 3 due to blacklist
assert(manager.resourceOffer("exec2", "host2", ANY).isEmpty)
}
// Despite advancing beyond the time for expiring executors from within the blacklist,
// we *never* expire from *within* the stage blacklist
clock.advance(rescheduleDelay)
{
val offerResult = manager.resourceOffer("exec1", "host1", PROCESS_LOCAL)
assert(offerResult.isEmpty)
}
{
val offerResult = manager.resourceOffer("exec3", "host3", ANY)
assert(offerResult.isDefined)
assert(offerResult.get.index === 0)
assert(offerResult.get.executorId === "exec3")
assert(manager.resourceOffer("exec3", "host3", ANY).isEmpty)
// Cause exec3 to fail : failure 4
manager.handleFailedTask(offerResult.get.taskId, TaskState.FINISHED, TaskResultLost)
}
// we have failed the same task 4 times now : task id should now be in taskSetsFailed
assert(sched.taskSetsFailed.contains(taskSet.id))
}
test("new executors get added and lost") {
// Assign host2 to rack2
FakeRackUtil.assignHostToRack("host2", "rack2")
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc)
val taskSet = FakeTask.createTaskSet(4,
Seq(TaskLocation("host1", "execA")),
Seq(TaskLocation("host1", "execB")),
Seq(TaskLocation("host2", "execC")),
Seq())
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// Only ANY is valid
assert(manager.myLocalityLevels.sameElements(Array(NO_PREF, ANY)))
// Add a new executor
sched.addExecutor("execD", "host1")
manager.executorAdded()
// Valid locality should contain NODE_LOCAL and ANY
assert(manager.myLocalityLevels.sameElements(Array(NODE_LOCAL, NO_PREF, ANY)))
// Add another executor
sched.addExecutor("execC", "host2")
manager.executorAdded()
// Valid locality should contain PROCESS_LOCAL, NODE_LOCAL, RACK_LOCAL and ANY
assert(manager.myLocalityLevels.sameElements(
Array(PROCESS_LOCAL, NODE_LOCAL, NO_PREF, RACK_LOCAL, ANY)))
// test if the valid locality is recomputed when the executor is lost
sched.removeExecutor("execC")
manager.executorLost("execC", "host2", SlaveLost())
assert(manager.myLocalityLevels.sameElements(Array(NODE_LOCAL, NO_PREF, ANY)))
sched.removeExecutor("execD")
manager.executorLost("execD", "host1", SlaveLost())
assert(manager.myLocalityLevels.sameElements(Array(NO_PREF, ANY)))
}
test("Executors exit for reason unrelated to currently running tasks") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc)
val taskSet = FakeTask.createTaskSet(4,
Seq(TaskLocation("host1", "execA")),
Seq(TaskLocation("host1", "execB")),
Seq(TaskLocation("host2", "execC")),
Seq())
val clock = new ManualClock()
clock.advance(1)
val manager = new TaskSetManager(sched, taskSet, 1, clock = clock)
sched.addExecutor("execA", "host1")
manager.executorAdded()
sched.addExecutor("execC", "host2")
manager.executorAdded()
assert(manager.resourceOffer("exec1", "host1", ANY).isDefined)
sched.removeExecutor("execA")
manager.executorLost(
"execA",
"host1",
ExecutorExited(143, false, "Terminated for reason unrelated to running tasks"))
assert(!sched.taskSetsFailed.contains(taskSet.id))
assert(manager.resourceOffer("execC", "host2", ANY).isDefined)
sched.removeExecutor("execC")
manager.executorLost(
"execC", "host2", ExecutorExited(1, true, "Terminated due to issue with running tasks"))
assert(sched.taskSetsFailed.contains(taskSet.id))
}
test("test RACK_LOCAL tasks") {
// Assign host1 to rack1
FakeRackUtil.assignHostToRack("host1", "rack1")
// Assign host2 to rack1
FakeRackUtil.assignHostToRack("host2", "rack1")
// Assign host3 to rack2
FakeRackUtil.assignHostToRack("host3", "rack2")
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc,
("execA", "host1"), ("execB", "host2"), ("execC", "host3"))
val taskSet = FakeTask.createTaskSet(2,
Seq(TaskLocation("host1", "execA")),
Seq(TaskLocation("host1", "execA")))
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
assert(manager.myLocalityLevels.sameElements(Array(PROCESS_LOCAL, NODE_LOCAL, RACK_LOCAL, ANY)))
// Set allowed locality to ANY
clock.advance(LOCALITY_WAIT_MS * 3)
// Offer host3
// No task is scheduled if we restrict locality to RACK_LOCAL
assert(manager.resourceOffer("execC", "host3", RACK_LOCAL) === None)
// Task 0 can be scheduled with ANY
assert(manager.resourceOffer("execC", "host3", ANY).get.index === 0)
// Offer host2
// Task 1 can be scheduled with RACK_LOCAL
assert(manager.resourceOffer("execB", "host2", RACK_LOCAL).get.index === 1)
}
test("do not emit warning when serialized task is small") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
val taskSet = FakeTask.createTaskSet(1)
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES)
assert(!manager.emittedTaskSizeWarning)
assert(manager.resourceOffer("exec1", "host1", ANY).get.index === 0)
assert(!manager.emittedTaskSizeWarning)
}
test("emit warning when serialized task is large") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
val taskSet = new TaskSet(Array(new LargeTask(0)), 0, 0, 0, null)
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES)
assert(!manager.emittedTaskSizeWarning)
assert(manager.resourceOffer("exec1", "host1", ANY).get.index === 0)
assert(manager.emittedTaskSizeWarning)
}
test("Not serializable exception thrown if the task cannot be serialized") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
val taskSet = new TaskSet(
Array(new NotSerializableFakeTask(1, 0), new NotSerializableFakeTask(0, 1)), 0, 0, 0, null)
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES)
intercept[TaskNotSerializableException] {
manager.resourceOffer("exec1", "host1", ANY)
}
assert(manager.isZombie)
}
test("abort the job if total size of results is too large") {
val conf = new SparkConf().set("spark.driver.maxResultSize", "2m")
sc = new SparkContext("local", "test", conf)
def genBytes(size: Int): (Int) => Array[Byte] = { (x: Int) =>
val bytes = Array.ofDim[Byte](size)
scala.util.Random.nextBytes(bytes)
bytes
}
// multiple 1k result
val r = sc.makeRDD(0 until 10, 10).map(genBytes(1024)).collect()
assert(10 === r.size)
// single 10M result
val thrown = intercept[SparkException] {sc.makeRDD(genBytes(10 << 20)(0), 1).collect()}
assert(thrown.getMessage().contains("bigger than spark.driver.maxResultSize"))
// multiple 1M results
val thrown2 = intercept[SparkException] {
sc.makeRDD(0 until 10, 10).map(genBytes(1 << 20)).collect()
}
assert(thrown2.getMessage().contains("bigger than spark.driver.maxResultSize"))
}
test("[SPARK-13931] taskSetManager should not send Resubmitted tasks after being a zombie") {
val conf = new SparkConf().set("spark.speculation", "true")
sc = new SparkContext("local", "test", conf)
val sched = new FakeTaskScheduler(sc, ("execA", "host1"), ("execB", "host2"))
sched.initialize(new FakeSchedulerBackend() {
override def killTask(
taskId: Long,
executorId: String,
interruptThread: Boolean,
reason: String): Unit = {}
})
// Keep track of the number of tasks that are resubmitted,
// so that the test can check that no tasks were resubmitted.
var resubmittedTasks = 0
val dagScheduler = new FakeDAGScheduler(sc, sched) {
override def taskEnded(
task: Task[_],
reason: TaskEndReason,
result: Any,
accumUpdates: Seq[AccumulatorV2[_, _]],
taskInfo: TaskInfo): Unit = {
super.taskEnded(task, reason, result, accumUpdates, taskInfo)
reason match {
case Resubmitted => resubmittedTasks += 1
case _ =>
}
}
}
sched.setDAGScheduler(dagScheduler)
val singleTask = new ShuffleMapTask(0, 0, null, new Partition {
override def index: Int = 0
}, Seq(TaskLocation("host1", "execA")), new Properties, null)
val taskSet = new TaskSet(Array(singleTask), 0, 0, 0, null)
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES)
// Offer host1, which should be accepted as a PROCESS_LOCAL location
// by the one task in the task set
val task1 = manager.resourceOffer("execA", "host1", TaskLocality.PROCESS_LOCAL).get
// Mark the task as available for speculation, and then offer another resource,
// which should be used to launch a speculative copy of the task.
manager.speculatableTasks += singleTask.partitionId
val task2 = manager.resourceOffer("execB", "host2", TaskLocality.ANY).get
assert(manager.runningTasks === 2)
assert(manager.isZombie === false)
val directTaskResult = new DirectTaskResult[String](null, Seq()) {
override def value(resultSer: SerializerInstance): String = ""
}
// Complete one copy of the task, which should result in the task set manager
// being marked as a zombie, because at least one copy of its only task has completed.
manager.handleSuccessfulTask(task1.taskId, directTaskResult)
assert(manager.isZombie === true)
assert(resubmittedTasks === 0)
assert(manager.runningTasks === 1)
manager.executorLost("execB", "host2", new SlaveLost())
assert(manager.runningTasks === 0)
assert(resubmittedTasks === 0)
}
test("speculative and noPref task should be scheduled after node-local") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(
sc, ("execA", "host1"), ("execB", "host2"), ("execC", "host3"))
val taskSet = FakeTask.createTaskSet(4,
Seq(TaskLocation("host1", "execA")),
Seq(TaskLocation("host2"), TaskLocation("host1")),
Seq(),
Seq(TaskLocation("host3", "execC")))
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
assert(manager.resourceOffer("execA", "host1", PROCESS_LOCAL).get.index === 0)
assert(manager.resourceOffer("execA", "host1", NODE_LOCAL) == None)
assert(manager.resourceOffer("execA", "host1", NO_PREF).get.index == 1)
manager.speculatableTasks += 1
clock.advance(LOCALITY_WAIT_MS)
// schedule the nonPref task
assert(manager.resourceOffer("execA", "host1", NO_PREF).get.index === 2)
// schedule the speculative task
assert(manager.resourceOffer("execB", "host2", NO_PREF).get.index === 1)
clock.advance(LOCALITY_WAIT_MS * 3)
// schedule non-local tasks
assert(manager.resourceOffer("execB", "host2", ANY).get.index === 3)
}
test("node-local tasks should be scheduled right away " +
"when there are only node-local and no-preference tasks") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(
sc, ("execA", "host1"), ("execB", "host2"), ("execC", "host3"))
val taskSet = FakeTask.createTaskSet(4,
Seq(TaskLocation("host1")),
Seq(TaskLocation("host2")),
Seq(),
Seq(TaskLocation("host3")))
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// node-local tasks are scheduled without delay
assert(manager.resourceOffer("execA", "host1", NODE_LOCAL).get.index === 0)
assert(manager.resourceOffer("execA", "host2", NODE_LOCAL).get.index === 1)
assert(manager.resourceOffer("execA", "host3", NODE_LOCAL).get.index === 3)
assert(manager.resourceOffer("execA", "host3", NODE_LOCAL) === None)
// schedule no-preference after node local ones
assert(manager.resourceOffer("execA", "host3", NO_PREF).get.index === 2)
}
test("SPARK-4939: node-local tasks should be scheduled right after process-local tasks finished")
{
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("execA", "host1"), ("execB", "host2"))
val taskSet = FakeTask.createTaskSet(4,
Seq(TaskLocation("host1")),
Seq(TaskLocation("host2")),
Seq(ExecutorCacheTaskLocation("host1", "execA")),
Seq(ExecutorCacheTaskLocation("host2", "execB")))
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// process-local tasks are scheduled first
assert(manager.resourceOffer("execA", "host1", NODE_LOCAL).get.index === 2)
assert(manager.resourceOffer("execB", "host2", NODE_LOCAL).get.index === 3)
// node-local tasks are scheduled without delay
assert(manager.resourceOffer("execA", "host1", NODE_LOCAL).get.index === 0)
assert(manager.resourceOffer("execB", "host2", NODE_LOCAL).get.index === 1)
assert(manager.resourceOffer("execA", "host1", NODE_LOCAL) == None)
assert(manager.resourceOffer("execB", "host2", NODE_LOCAL) == None)
}
test("SPARK-4939: no-pref tasks should be scheduled after process-local tasks finished") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("execA", "host1"), ("execB", "host2"))
val taskSet = FakeTask.createTaskSet(3,
Seq(),
Seq(ExecutorCacheTaskLocation("host1", "execA")),
Seq(ExecutorCacheTaskLocation("host2", "execB")))
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// process-local tasks are scheduled first
assert(manager.resourceOffer("execA", "host1", PROCESS_LOCAL).get.index === 1)
assert(manager.resourceOffer("execB", "host2", PROCESS_LOCAL).get.index === 2)
// no-pref tasks are scheduled without delay
assert(manager.resourceOffer("execA", "host1", PROCESS_LOCAL) == None)
assert(manager.resourceOffer("execA", "host1", NODE_LOCAL) == None)
assert(manager.resourceOffer("execA", "host1", NO_PREF).get.index === 0)
assert(manager.resourceOffer("execA", "host1", ANY) == None)
}
test("Ensure TaskSetManager is usable after addition of levels") {
// Regression test for SPARK-2931
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc)
val taskSet = FakeTask.createTaskSet(2,
Seq(TaskLocation("host1", "execA")),
Seq(TaskLocation("host2", "execB.1")))
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
// Only ANY is valid
assert(manager.myLocalityLevels.sameElements(Array(ANY)))
// Add a new executor
sched.addExecutor("execA", "host1")
sched.addExecutor("execB.2", "host2")
manager.executorAdded()
assert(manager.pendingTasksWithNoPrefs.size === 0)
// Valid locality should contain PROCESS_LOCAL, NODE_LOCAL and ANY
assert(manager.myLocalityLevels.sameElements(Array(PROCESS_LOCAL, NODE_LOCAL, ANY)))
assert(manager.resourceOffer("execA", "host1", ANY) !== None)
clock.advance(LOCALITY_WAIT_MS * 4)
assert(manager.resourceOffer("execB.2", "host2", ANY) !== None)
sched.removeExecutor("execA")
sched.removeExecutor("execB.2")
manager.executorLost("execA", "host1", SlaveLost())
manager.executorLost("execB.2", "host2", SlaveLost())
clock.advance(LOCALITY_WAIT_MS * 4)
sched.addExecutor("execC", "host3")
manager.executorAdded()
// Prior to the fix, this line resulted in an ArrayIndexOutOfBoundsException:
assert(manager.resourceOffer("execC", "host3", ANY) !== None)
}
test("Test that locations with HDFSCacheTaskLocation are treated as PROCESS_LOCAL.") {
// Regression test for SPARK-2931
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc,
("execA", "host1"), ("execB", "host2"), ("execC", "host3"))
val taskSet = FakeTask.createTaskSet(3,
Seq(TaskLocation("host1")),
Seq(TaskLocation("host2")),
Seq(TaskLocation("hdfs_cache_host3")))
val clock = new ManualClock
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
assert(manager.myLocalityLevels.sameElements(Array(PROCESS_LOCAL, NODE_LOCAL, ANY)))
sched.removeExecutor("execA")
manager.executorAdded()
assert(manager.myLocalityLevels.sameElements(Array(PROCESS_LOCAL, NODE_LOCAL, ANY)))
sched.removeExecutor("execB")
manager.executorAdded()
assert(manager.myLocalityLevels.sameElements(Array(PROCESS_LOCAL, NODE_LOCAL, ANY)))
sched.removeExecutor("execC")
manager.executorAdded()
assert(manager.myLocalityLevels.sameElements(Array(ANY)))
}
test("Test TaskLocation for different host type.") {
assert(TaskLocation("host1") === HostTaskLocation("host1"))
assert(TaskLocation("hdfs_cache_host1") === HDFSCacheTaskLocation("host1"))
assert(TaskLocation("executor_host1_3") === ExecutorCacheTaskLocation("host1", "3"))
assert(TaskLocation("executor_some.host1_executor_task_3") ===
ExecutorCacheTaskLocation("some.host1", "executor_task_3"))
}
test("Kill other task attempts when one attempt belonging to the same task succeeds") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"), ("exec2", "host2"))
val taskSet = FakeTask.createTaskSet(4)
// Set the speculation multiplier to be 0 so speculative tasks are launched immediately
sc.conf.set("spark.speculation.multiplier", "0.0")
sc.conf.set("spark.speculation", "true")
val clock = new ManualClock()
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
val accumUpdatesByTask: Array[Seq[AccumulatorV2[_, _]]] = taskSet.tasks.map { task =>
task.metrics.internalAccums
}
// Offer resources for 4 tasks to start
for ((k, v) <- List(
"exec1" -> "host1",
"exec1" -> "host1",
"exec2" -> "host2",
"exec2" -> "host2")) {
val taskOption = manager.resourceOffer(k, v, NO_PREF)
assert(taskOption.isDefined)
val task = taskOption.get
assert(task.executorId === k)
}
assert(sched.startedTasks.toSet === Set(0, 1, 2, 3))
clock.advance(1)
// Complete the 3 tasks and leave 1 task in running
for (id <- Set(0, 1, 2)) {
manager.handleSuccessfulTask(id, createTaskResult(id, accumUpdatesByTask(id)))
assert(sched.endedTasks(id) === Success)
}
// checkSpeculatableTasks checks that the task runtime is greater than the threshold for
// speculating. Since we use a threshold of 0 for speculation, tasks need to be running for
// > 0ms, so advance the clock by 1ms here.
clock.advance(1)
assert(manager.checkSpeculatableTasks(0))
// Offer resource to start the speculative attempt for the running task
val taskOption5 = manager.resourceOffer("exec1", "host1", NO_PREF)
assert(taskOption5.isDefined)
val task5 = taskOption5.get
assert(task5.index === 3)
assert(task5.taskId === 4)
assert(task5.executorId === "exec1")
assert(task5.attemptNumber === 1)
sched.backend = mock(classOf[SchedulerBackend])
// Complete the speculative attempt for the running task
manager.handleSuccessfulTask(4, createTaskResult(3, accumUpdatesByTask(3)))
// Verify that it kills other running attempt
verify(sched.backend).killTask(3, "exec2", true, "another attempt succeeded")
// Because the SchedulerBackend was a mock, the 2nd copy of the task won't actually be
// killed, so the FakeTaskScheduler is only told about the successful completion
// of the speculated task.
assert(sched.endedTasks(3) === Success)
}
test("Killing speculative tasks does not count towards aborting the taskset") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"), ("exec2", "host2"))
val taskSet = FakeTask.createTaskSet(5)
// Set the speculation multiplier to be 0 so speculative tasks are launched immediately
sc.conf.set("spark.speculation.multiplier", "0.0")
sc.conf.set("spark.speculation.quantile", "0.6")
sc.conf.set("spark.speculation", "true")
val clock = new ManualClock()
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = clock)
val accumUpdatesByTask: Array[Seq[AccumulatorV2[_, _]]] = taskSet.tasks.map { task =>
task.metrics.internalAccums
}
// Offer resources for 5 tasks to start
val tasks = new ArrayBuffer[TaskDescription]()
for ((k, v) <- List(
"exec1" -> "host1",
"exec1" -> "host1",
"exec1" -> "host1",
"exec2" -> "host2",
"exec2" -> "host2")) {
val taskOption = manager.resourceOffer(k, v, NO_PREF)
assert(taskOption.isDefined)
val task = taskOption.get
assert(task.executorId === k)
tasks += task
}
assert(sched.startedTasks.toSet === (0 until 5).toSet)
clock.advance(1)
// Complete 3 tasks and leave 2 tasks in running
for (id <- Set(0, 1, 2)) {
manager.handleSuccessfulTask(id, createTaskResult(id, accumUpdatesByTask(id)))
assert(sched.endedTasks(id) === Success)
}
def runningTaskForIndex(index: Int): TaskDescription = {
tasks.find { task =>
task.index == index && !sched.endedTasks.contains(task.taskId)
}.getOrElse {
throw new RuntimeException(s"couldn't find index $index in " +
s"tasks: ${tasks.map { t => t.index -> t.taskId }} with endedTasks:" +
s" ${sched.endedTasks.keys}")
}
}
// have each of the running tasks fail 3 times (not enough to abort the stage)
(0 until 3).foreach { attempt =>
Seq(3, 4).foreach { index =>
val task = runningTaskForIndex(index)
logInfo(s"failing task $task")
val endReason = ExceptionFailure("a", "b", Array(), "c", None)
manager.handleFailedTask(task.taskId, TaskState.FAILED, endReason)
sched.endedTasks(task.taskId) = endReason
assert(!manager.isZombie)
val nextTask = manager.resourceOffer(s"exec2", s"host2", NO_PREF)
assert(nextTask.isDefined, s"no offer for attempt $attempt of $index")
tasks += nextTask.get
}
}
// we can't be sure which one of our running tasks will get another speculative copy
val originalTasks = Seq(3, 4).map { index => index -> runningTaskForIndex(index) }.toMap
// checkSpeculatableTasks checks that the task runtime is greater than the threshold for
// speculating. Since we use a threshold of 0 for speculation, tasks need to be running for
// > 0ms, so advance the clock by 1ms here.
clock.advance(1)
assert(manager.checkSpeculatableTasks(0))
// Offer resource to start the speculative attempt for the running task
val taskOption5 = manager.resourceOffer("exec1", "host1", NO_PREF)
assert(taskOption5.isDefined)
val speculativeTask = taskOption5.get
assert(speculativeTask.index === 3 || speculativeTask.index === 4)
assert(speculativeTask.taskId === 11)
assert(speculativeTask.executorId === "exec1")
assert(speculativeTask.attemptNumber === 4)
sched.backend = mock(classOf[SchedulerBackend])
// Complete the speculative attempt for the running task
manager.handleSuccessfulTask(speculativeTask.taskId, createTaskResult(3, accumUpdatesByTask(3)))
// Verify that it kills other running attempt
val origTask = originalTasks(speculativeTask.index)
verify(sched.backend).killTask(origTask.taskId, "exec2", true, "another attempt succeeded")
// Because the SchedulerBackend was a mock, the 2nd copy of the task won't actually be
// killed, so the FakeTaskScheduler is only told about the successful completion
// of the speculated task.
assert(sched.endedTasks(3) === Success)
// also because the scheduler is a mock, our manager isn't notified about the task killed event,
// so we do that manually
manager.handleFailedTask(origTask.taskId, TaskState.KILLED, TaskKilled("test"))
// this task has "failed" 4 times, but one of them doesn't count, so keep running the stage
assert(manager.tasksSuccessful === 4)
assert(!manager.isZombie)
// now run another speculative task
val taskOpt6 = manager.resourceOffer("exec1", "host1", NO_PREF)
assert(taskOpt6.isDefined)
val speculativeTask2 = taskOpt6.get
assert(speculativeTask2.index === 3 || speculativeTask2.index === 4)
assert(speculativeTask2.index !== speculativeTask.index)
assert(speculativeTask2.attemptNumber === 4)
// Complete the speculative attempt for the running task
manager.handleSuccessfulTask(speculativeTask2.taskId,
createTaskResult(3, accumUpdatesByTask(3)))
// Verify that it kills other running attempt
val origTask2 = originalTasks(speculativeTask2.index)
verify(sched.backend).killTask(origTask2.taskId, "exec2", true, "another attempt succeeded")
assert(manager.tasksSuccessful === 5)
assert(manager.isZombie)
}
test("SPARK-19868: DagScheduler only notified of taskEnd when state is ready") {
// dagScheduler.taskEnded() is async, so it may *seem* ok to call it before we've set all
// appropriate state, eg. isZombie. However, this sets up a race that could go the wrong way.
// This is a super-focused regression test which checks the zombie state as soon as
// dagScheduler.taskEnded() is called, to ensure we haven't introduced a race.
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
val mockDAGScheduler = mock(classOf[DAGScheduler])
sched.dagScheduler = mockDAGScheduler
val taskSet = FakeTask.createTaskSet(numTasks = 1, stageId = 0, stageAttemptId = 0)
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = new ManualClock(1))
when(mockDAGScheduler.taskEnded(any(), any(), any(), any(), any())).thenAnswer(
new Answer[Unit] {
override def answer(invocationOnMock: InvocationOnMock): Unit = {
assert(manager.isZombie)
}
})
val taskOption = manager.resourceOffer("exec1", "host1", NO_PREF)
assert(taskOption.isDefined)
// this would fail, inside our mock dag scheduler, if it calls dagScheduler.taskEnded() too soon
manager.handleSuccessfulTask(0, createTaskResult(0))
}
test("SPARK-17894: Verify TaskSetManagers for different stage attempts have unique names") {
sc = new SparkContext("local", "test")
sched = new FakeTaskScheduler(sc, ("exec1", "host1"))
val taskSet = FakeTask.createTaskSet(numTasks = 1, stageId = 0, stageAttemptId = 0)
val manager = new TaskSetManager(sched, taskSet, MAX_TASK_FAILURES, clock = new ManualClock)
assert(manager.name === "TaskSet_0.0")
// Make sure a task set with the same stage ID but different attempt ID has a unique name
val taskSet2 = FakeTask.createTaskSet(numTasks = 1, stageId = 0, stageAttemptId = 1)
val manager2 = new TaskSetManager(sched, taskSet2, MAX_TASK_FAILURES, clock = new ManualClock)
assert(manager2.name === "TaskSet_0.1")
// Make sure a task set with the same attempt ID but different stage ID also has a unique name
val taskSet3 = FakeTask.createTaskSet(numTasks = 1, stageId = 1, stageAttemptId = 1)
val manager3 = new TaskSetManager(sched, taskSet3, MAX_TASK_FAILURES, clock = new ManualClock)
assert(manager3.name === "TaskSet_1.1")
}
test("don't update blacklist for shuffle-fetch failures, preemption, denied commits, " +
"or killed tasks") {
// Setup a taskset, and fail some tasks for a fetch failure, preemption, denied commit,
// and killed task.
val conf = new SparkConf().
set(config.BLACKLIST_ENABLED, true)
sc = new SparkContext("local", "test", conf)
sched = new FakeTaskScheduler(sc, ("exec1", "host1"), ("exec2", "host2"))
val taskSet = FakeTask.createTaskSet(4)
val tsm = new TaskSetManager(sched, taskSet, 4)
// we need a spy so we can attach our mock blacklist
val tsmSpy = spy(tsm)
val blacklist = mock(classOf[TaskSetBlacklist])
when(tsmSpy.taskSetBlacklistHelperOpt).thenReturn(Some(blacklist))
// make some offers to our taskset, to get tasks we will fail
val taskDescs = Seq(
"exec1" -> "host1",
"exec2" -> "host1"
).flatMap { case (exec, host) =>
// offer each executor twice (simulating 2 cores per executor)
(0 until 2).flatMap{ _ => tsmSpy.resourceOffer(exec, host, TaskLocality.ANY)}
}
assert(taskDescs.size === 4)
// now fail those tasks
tsmSpy.handleFailedTask(taskDescs(0).taskId, TaskState.FAILED,
FetchFailed(BlockManagerId(taskDescs(0).executorId, "host1", 12345), 0, 0, 0, "ignored"))
tsmSpy.handleFailedTask(taskDescs(1).taskId, TaskState.FAILED,
ExecutorLostFailure(taskDescs(1).executorId, exitCausedByApp = false, reason = None))
tsmSpy.handleFailedTask(taskDescs(2).taskId, TaskState.FAILED,
TaskCommitDenied(0, 2, 0))
tsmSpy.handleFailedTask(taskDescs(3).taskId, TaskState.KILLED, TaskKilled("test"))
// Make sure that the blacklist ignored all of the task failures above, since they aren't
// the fault of the executor where the task was running.
verify(blacklist, never())
.updateBlacklistForFailedTask(anyString(), anyString(), anyInt())
}
test("update application blacklist for shuffle-fetch") {
// Setup a taskset, and fail some one task for fetch failure.
val conf = new SparkConf()
.set(config.BLACKLIST_ENABLED, true)
.set(config.SHUFFLE_SERVICE_ENABLED, true)
.set(config.BLACKLIST_FETCH_FAILURE_ENABLED, true)
sc = new SparkContext("local", "test", conf)
sched = new FakeTaskScheduler(sc, ("exec1", "host1"), ("exec2", "host2"))
val taskSet = FakeTask.createTaskSet(4)
val blacklistTracker = new BlacklistTracker(sc, None)
val tsm = new TaskSetManager(sched, taskSet, 4, Some(blacklistTracker))
// make some offers to our taskset, to get tasks we will fail
val taskDescs = Seq(
"exec1" -> "host1",
"exec2" -> "host2"
).flatMap { case (exec, host) =>
// offer each executor twice (simulating 2 cores per executor)
(0 until 2).flatMap{ _ => tsm.resourceOffer(exec, host, TaskLocality.ANY)}
}
assert(taskDescs.size === 4)
assert(!blacklistTracker.isExecutorBlacklisted(taskDescs(0).executorId))
assert(!blacklistTracker.isNodeBlacklisted("host1"))
// Fail the task with fetch failure
tsm.handleFailedTask(taskDescs(0).taskId, TaskState.FAILED,
FetchFailed(BlockManagerId(taskDescs(0).executorId, "host1", 12345), 0, 0, 0, "ignored"))
assert(blacklistTracker.isNodeBlacklisted("host1"))
}
private def createTaskResult(
id: Int,
accumUpdates: Seq[AccumulatorV2[_, _]] = Seq.empty): DirectTaskResult[Int] = {
val valueSer = SparkEnv.get.serializer.newInstance()
new DirectTaskResult[Int](valueSer.serialize(id), accumUpdates)
}
}
| poffuomo/spark | core/src/test/scala/org/apache/spark/scheduler/TaskSetManagerSuite.scala | Scala | apache-2.0 | 50,570 |
package org.ray.api.test;
import org.ray.api.Ray;
import org.ray.api.RayPyActor;
import org.ray.api.TestUtils;
import org.ray.runtime.context.WorkerContext;
import org.ray.runtime.object.NativeRayObject;
import org.ray.runtime.object.ObjectSerializer;
import org.testng.Assert;
import org.testng.annotations.Test;
public class RaySerializerTest extends BaseMultiLanguageTest {
@Test
public void testSerializePyActor() {
RayPyActor pyActor = Ray.createPyActor("test", "RaySerializerTest");
WorkerContext workerContext = TestUtils.getRuntime().getWorkerContext();
NativeRayObject nativeRayObject = ObjectSerializer.serialize(pyActor);
RayPyActor result = (RayPyActor) ObjectSerializer
.deserialize(nativeRayObject, null, workerContext.getCurrentClassLoader());
Assert.assertEquals(result.getId(), pyActor.getId());
Assert.assertEquals(result.getModuleName(), "test");
Assert.assertEquals(result.getClassName(), "RaySerializerTest");
}
}
| ujvl/ray-ng | java/test/src/main/java/org/ray/api/test/RaySerializerTest.java | Java | apache-2.0 | 981 |
package test
import (
"io/ioutil"
"os"
"testing"
"github.com/coredns/coredns/plugin/test"
"github.com/miekg/dns"
)
func TestLookupBalanceRewriteCacheDnssec(t *testing.T) {
t.Parallel()
name, rm, err := test.TempFile(".", exampleOrg)
if err != nil {
t.Fatalf("Failed to create zone: %s", err)
}
defer rm()
rm1 := createKeyFile(t)
defer rm1()
corefile := `example.org:0 {
file ` + name + `
rewrite type ANY HINFO
dnssec {
key file ` + base + `
}
loadbalance
}`
ex, udp, _, err := CoreDNSServerAndPorts(corefile)
if err != nil {
t.Fatalf("Could not get CoreDNS serving instance: %s", err)
}
defer ex.Stop()
c := new(dns.Client)
m := new(dns.Msg)
m.SetQuestion("example.org.", dns.TypeA)
m.SetEdns0(4096, true)
res, _, err := c.Exchange(m, udp)
if err != nil {
t.Fatalf("Could not send query: %s", err)
}
sig := 0
for _, a := range res.Answer {
if a.Header().Rrtype == dns.TypeRRSIG {
sig++
}
}
if sig == 0 {
t.Errorf("Expected RRSIGs, got none")
t.Logf("%v\n", res)
}
}
func createKeyFile(t *testing.T) func() {
ioutil.WriteFile(base+".key",
[]byte(`example.org. IN DNSKEY 256 3 13 tDyI0uEIDO4SjhTJh1AVTFBLpKhY3He5BdAlKztewiZ7GecWj94DOodg ovpN73+oJs+UfZ+p9zOSN5usGAlHrw==`),
0644)
ioutil.WriteFile(base+".private",
[]byte(`Private-key-format: v1.3
Algorithm: 13 (ECDSAP256SHA256)
PrivateKey: HPmldSNfrkj/aDdUMFwuk/lgzaC5KIsVEG3uoYvF4pQ=
Created: 20160426083115
Publish: 20160426083115
Activate: 20160426083115`),
0644)
return func() {
os.Remove(base + ".key")
os.Remove(base + ".private")
}
}
const base = "Kexample.org.+013+44563"
| miekg/coredns | test/plugin_dnssec_test.go | GO | apache-2.0 | 1,614 |
var searchData=
[
['paikallaan',['PAIKALLAAN',['../namespace_julkinen.html#a81b50e3c6f21c0c1c46e186592107c3cafa60a1b03bc49af14fb90b7026f94957',1,'Julkinen']]]
];
| WhiteDeathFIN/Labyrinttipeli | html/search/enumvalues_7.js | JavaScript | apache-2.0 | 164 |
/* Copyright 2014-2016 Samsung Electronics Co., Ltd.
* Copyright 2015-2016 University of Szeged.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ecma-alloc.h"
#include "ecma-conversion.h"
#include "ecma-helpers.h"
#include "ecma-number-arithmetic.h"
#include "ecma-objects.h"
#include "ecma-try-catch-macro.h"
#include "opcodes.h"
#include "jrt-libc-includes.h"
/** \addtogroup vm Virtual machine
* @{
*
* \addtogroup vm_opcodes Opcodes
* @{
*/
/**
* Perform ECMA number arithmetic operation.
*
* The algorithm of the operation is following:
* leftNum = ToNumber (leftValue);
* rightNum = ToNumber (rightValue);
* result = leftNum ArithmeticOp rightNum;
*
* @return ecma value
* Returned value must be freed with ecma_free_value
*/
ecma_value_t
do_number_arithmetic (number_arithmetic_op op, /**< number arithmetic operation */
ecma_value_t left_value, /**< left value */
ecma_value_t right_value) /**< right value */
{
ecma_value_t ret_value = ecma_make_simple_value (ECMA_SIMPLE_VALUE_EMPTY);
ECMA_OP_TO_NUMBER_TRY_CATCH (num_left, left_value, ret_value);
ECMA_OP_TO_NUMBER_TRY_CATCH (num_right, right_value, ret_value);
ecma_number_t result = ECMA_NUMBER_ZERO;
switch (op)
{
case NUMBER_ARITHMETIC_SUBSTRACTION:
{
result = ecma_number_substract (num_left, num_right);
break;
}
case NUMBER_ARITHMETIC_MULTIPLICATION:
{
result = ecma_number_multiply (num_left, num_right);
break;
}
case NUMBER_ARITHMETIC_DIVISION:
{
result = ecma_number_divide (num_left, num_right);
break;
}
case NUMBER_ARITHMETIC_REMAINDER:
{
result = ecma_op_number_remainder (num_left, num_right);
break;
}
}
ret_value = ecma_make_number_value (result);
ECMA_OP_TO_NUMBER_FINALIZE (num_right);
ECMA_OP_TO_NUMBER_FINALIZE (num_left);
return ret_value;
} /* do_number_arithmetic */
/**
* 'Addition' opcode handler.
*
* See also: ECMA-262 v5, 11.6.1
*
* @return ecma value
* Returned value must be freed with ecma_free_value
*/
ecma_value_t
opfunc_addition (ecma_value_t left_value, /**< left value */
ecma_value_t right_value) /**< right value */
{
bool free_left_value = false;
bool free_right_value = false;
if (ecma_is_value_object (left_value))
{
ecma_object_t *obj_p = ecma_get_object_from_value (left_value);
left_value = ecma_op_object_default_value (obj_p, ECMA_PREFERRED_TYPE_NO);
free_left_value = true;
if (ECMA_IS_VALUE_ERROR (left_value))
{
return left_value;
}
}
if (ecma_is_value_object (right_value))
{
ecma_object_t *obj_p = ecma_get_object_from_value (right_value);
right_value = ecma_op_object_default_value (obj_p, ECMA_PREFERRED_TYPE_NO);
free_right_value = true;
if (ECMA_IS_VALUE_ERROR (right_value))
{
if (free_left_value)
{
ecma_free_value (left_value);
}
return right_value;
}
}
ecma_value_t ret_value = ecma_make_simple_value (ECMA_SIMPLE_VALUE_EMPTY);
if (ecma_is_value_string (left_value)
|| ecma_is_value_string (right_value))
{
ECMA_TRY_CATCH (str_left_value, ecma_op_to_string (left_value), ret_value);
ECMA_TRY_CATCH (str_right_value, ecma_op_to_string (right_value), ret_value);
ecma_string_t *string1_p = ecma_get_string_from_value (str_left_value);
ecma_string_t *string2_p = ecma_get_string_from_value (str_right_value);
ecma_string_t *concat_str_p = ecma_concat_ecma_strings (string1_p, string2_p);
ret_value = ecma_make_string_value (concat_str_p);
ECMA_FINALIZE (str_right_value);
ECMA_FINALIZE (str_left_value);
}
else
{
ECMA_OP_TO_NUMBER_TRY_CATCH (num_left, left_value, ret_value);
ECMA_OP_TO_NUMBER_TRY_CATCH (num_right, right_value, ret_value);
ret_value = ecma_make_number_value (ecma_number_add (num_left, num_right));
ECMA_OP_TO_NUMBER_FINALIZE (num_right);
ECMA_OP_TO_NUMBER_FINALIZE (num_left);
}
if (free_left_value)
{
ecma_free_value (left_value);
}
if (free_right_value)
{
ecma_free_value (right_value);
}
return ret_value;
} /* opfunc_addition */
/**
* 'Unary "+"' opcode handler.
*
* See also: ECMA-262 v5, 11.4, 11.4.6
*
* @return ecma value
* Returned value must be freed with ecma_free_value
*/
ecma_value_t
opfunc_unary_plus (ecma_value_t left_value) /**< left value */
{
ecma_value_t ret_value = ecma_make_simple_value (ECMA_SIMPLE_VALUE_EMPTY);
ECMA_OP_TO_NUMBER_TRY_CATCH (num_var_value,
left_value,
ret_value);
ret_value = ecma_make_number_value (num_var_value);
ECMA_OP_TO_NUMBER_FINALIZE (num_var_value);
return ret_value;
} /* opfunc_unary_plus */
/**
* 'Unary "-"' opcode handler.
*
* See also: ECMA-262 v5, 11.4, 11.4.7
*
* @return ecma value
* Returned value must be freed with ecma_free_value
*/
ecma_value_t
opfunc_unary_minus (ecma_value_t left_value) /**< left value */
{
ecma_value_t ret_value = ecma_make_simple_value (ECMA_SIMPLE_VALUE_EMPTY);
ECMA_OP_TO_NUMBER_TRY_CATCH (num_var_value,
left_value,
ret_value);
ret_value = ecma_make_number_value (ecma_number_negate (num_var_value));
ECMA_OP_TO_NUMBER_FINALIZE (num_var_value);
return ret_value;
} /* opfunc_unary_minus */
/**
* @}
* @}
*/
| tilmannOSG/jerryscript | jerry-core/vm/opcodes-ecma-arithmetics.c | C | apache-2.0 | 5,994 |
// Copyright 2015 CoreOS, 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 ec2
import (
"bufio"
"bytes"
"fmt"
"log"
"net"
"strings"
"github.com/rancher/os/netconf"
"github.com/rancher/os/config/cloudinit/datasource"
"github.com/rancher/os/config/cloudinit/datasource/metadata"
"github.com/rancher/os/config/cloudinit/pkg"
)
const (
DefaultAddress = "http://169.254.169.254/"
apiVersion = "latest/"
userdataPath = apiVersion + "user-data/"
metadataPath = apiVersion + "meta-data/"
)
type MetadataService struct {
metadata.Service
}
func NewDatasource(root string) *MetadataService {
if root == "" {
root = DefaultAddress
}
return &MetadataService{metadata.NewDatasource(root, apiVersion, userdataPath, metadataPath, nil)}
}
func (ms MetadataService) AvailabilityChanges() bool {
// TODO: if it can't find the network, maybe we can start it?
return false
}
func (ms MetadataService) FetchMetadata() (datasource.Metadata, error) {
// see http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html
metadata := datasource.Metadata{}
metadata.NetworkConfig = netconf.NetworkConfig{}
if keynames, err := ms.fetchAttributes("public-keys"); err == nil {
keyIDs := make(map[string]string)
for _, keyname := range keynames {
tokens := strings.SplitN(keyname, "=", 2)
if len(tokens) != 2 {
return metadata, fmt.Errorf("malformed public key: %q", keyname)
}
keyIDs[tokens[1]] = tokens[0]
}
metadata.SSHPublicKeys = map[string]string{}
for name, id := range keyIDs {
sshkey, err := ms.fetchAttribute(fmt.Sprintf("public-keys/%s/openssh-key", id))
if err != nil {
return metadata, err
}
metadata.SSHPublicKeys[name] = sshkey
log.Printf("Found SSH key for %q\n", name)
}
} else if _, ok := err.(pkg.ErrNotFound); !ok {
return metadata, err
}
if hostname, err := ms.fetchAttribute("hostname"); err == nil {
metadata.Hostname = strings.Split(hostname, " ")[0]
} else if _, ok := err.(pkg.ErrNotFound); !ok {
return metadata, err
}
// TODO: these are only on the first interface - it looks like you can have as many as you need...
if localAddr, err := ms.fetchAttribute("local-ipv4"); err == nil {
metadata.PrivateIPv4 = net.ParseIP(localAddr)
} else if _, ok := err.(pkg.ErrNotFound); !ok {
return metadata, err
}
if publicAddr, err := ms.fetchAttribute("public-ipv4"); err == nil {
metadata.PublicIPv4 = net.ParseIP(publicAddr)
} else if _, ok := err.(pkg.ErrNotFound); !ok {
return metadata, err
}
metadata.NetworkConfig.Interfaces = make(map[string]netconf.InterfaceConfig)
if macs, err := ms.fetchAttributes("network/interfaces/macs"); err != nil {
for _, mac := range macs {
if deviceNumber, err := ms.fetchAttribute(fmt.Sprintf("network/interfaces/macs/%s/device-number", mac)); err != nil {
network := netconf.InterfaceConfig{
DHCP: true,
}
/* Looks like we must use DHCP for aws
// private ipv4
if subnetCidrBlock, err := ms.fetchAttribute(fmt.Sprintf("network/interfaces/macs/%s/subnet-ipv4-cidr-block", mac)); err != nil {
cidr := strings.Split(subnetCidrBlock, "/")
if localAddr, err := ms.fetchAttributes(fmt.Sprintf("network/interfaces/macs/%s/local-ipv4s", mac)); err != nil {
for _, addr := range localAddr {
network.Addresses = append(network.Addresses, addr+"/"+cidr[1])
}
}
}
// ipv6
if localAddr, err := ms.fetchAttributes(fmt.Sprintf("network/interfaces/macs/%s/ipv6s", mac)); err != nil {
if subnetCidrBlock, err := ms.fetchAttributes(fmt.Sprintf("network/interfaces/macs/%s/subnet-ipv6-cidr-block", mac)); err != nil {
for i, addr := range localAddr {
cidr := strings.Split(subnetCidrBlock[i], "/")
network.Addresses = append(network.Addresses, addr+"/"+cidr[1])
}
}
}
*/
// disabled - it looks to me like you don't actually put the public IP on the eth device
/* if publicAddr, err := ms.fetchAttributes(fmt.Sprintf("network/interfaces/macs/%s/public-ipv4s", mac)); err != nil {
if vpcCidrBlock, err := ms.fetchAttribute(fmt.Sprintf("network/interfaces/macs/%s/vpc-ipv4-cidr-block", mac)); err != nil {
cidr := strings.Split(vpcCidrBlock, "/")
network.Addresses = append(network.Addresses, publicAddr+"/"+cidr[1])
}
}
*/
metadata.NetworkConfig.Interfaces["eth"+deviceNumber] = network
}
}
}
return metadata, nil
}
func (ms MetadataService) Type() string {
return "ec2-metadata-service"
}
func (ms MetadataService) fetchAttributes(key string) ([]string, error) {
url := ms.MetadataURL() + key
resp, err := ms.FetchData(url)
if err != nil {
return nil, err
}
scanner := bufio.NewScanner(bytes.NewBuffer(resp))
data := make([]string, 0)
for scanner.Scan() {
data = append(data, scanner.Text())
}
return data, scanner.Err()
}
func (ms MetadataService) fetchAttribute(key string) (string, error) {
attrs, err := ms.fetchAttributes(key)
if err == nil && len(attrs) > 0 {
return attrs[0], nil
}
return "", err
}
| juliengk/os | config/cloudinit/datasource/metadata/ec2/metadata.go | GO | apache-2.0 | 5,591 |
// Copyright 2022 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 code. DO NOT EDIT!
namespace Google.Cloud.VpcAccess.V1.Snippets
{
// [START vpcaccess_v1_generated_VpcAccessService_CreateConnector_sync_flattened_resourceNames]
using Google.Api.Gax.ResourceNames;
using Google.Cloud.VpcAccess.V1;
using Google.LongRunning;
public sealed partial class GeneratedVpcAccessServiceClientSnippets
{
/// <summary>Snippet for CreateConnector</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void CreateConnectorResourceNames()
{
// Create client
VpcAccessServiceClient vpcAccessServiceClient = VpcAccessServiceClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
string connectorId = "";
Connector connector = new Connector();
// Make the request
Operation<Connector, OperationMetadata> response = vpcAccessServiceClient.CreateConnector(parent, connectorId, connector);
// Poll until the returned long-running operation is complete
Operation<Connector, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Connector result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Connector, OperationMetadata> retrievedResponse = vpcAccessServiceClient.PollOnceCreateConnector(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Connector retrievedResult = retrievedResponse.Result;
}
}
}
// [END vpcaccess_v1_generated_VpcAccessService_CreateConnector_sync_flattened_resourceNames]
}
| jskeet/google-cloud-dotnet | apis/Google.Cloud.VpcAccess.V1/Google.Cloud.VpcAccess.V1.GeneratedSnippets/VpcAccessServiceClient.CreateConnectorResourceNamesSnippet.g.cs | C# | apache-2.0 | 2,807 |
/*
Copyright 2008-2013 CNR-ISTI, http://isti.cnr.it
Institute of Information Science and Technologies
of the Italian National Research Council
See the NOTICE file distributed with this work for additional
information regarding copyright ownership
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.persona.zigbee.tester.gui;
import it.cnr.isti.zigbee.ha.cluster.glue.Cluster;
import java.lang.reflect.Method;
/**
*
* @author <a href="mailto:stefano.lenzi@isti.cnr.it">Stefano "Kismet" Lenzi</a>
* @version $LastChangedRevision$ ($LastChangedDate$)
* @since 0.3.0
*/
public class Command {
public class CommandParsingException extends IllegalArgumentException {
/**
*
*/
private static final long serialVersionUID = 1396230279824610647L;
public String value;
public int index;
public CommandParsingException(String v, int i, String msg, Throwable ex){
super(msg,ex);
index = i;
value = v;
}
public CommandParsingException(String v, int i, String msg){
super(msg);
index = i;
value = v;
}
}
private Method method;
private Cluster cluster;
public Command(Cluster c, Method m){
cluster = c;
method = m;
}
public static String[] parametersTypeToString(final Method method){
Class<?>[] params = method.getParameterTypes();
String[] types = new String[params.length];
for (int i = 0; i < types.length; i++) {
if ( params[i].isArray() ) {
types[i] = "[]";
Class<?> cmp = params[i].getComponentType();
while(cmp.isArray()) {
types[i] = types[i] + "[]";
cmp = cmp.getComponentType();
}
types[i] = cmp.getName() + types[i];
} else {
types[i] = params[i].getName();
}
}
return types;
}
public String[] getInputParameters(){
return parametersTypeToString(method);
}
private boolean assignValueFromString(Class<?> clz, Object[] objs, int i, String value) {
objs[i] = null; //Emptying value
try {
if ( clz.isAssignableFrom( long.class ) ) objs[i] = Long.decode(value).longValue();
else if ( clz.isAssignableFrom( int.class ) )objs[i] = Integer.decode(value).intValue();
else if ( clz.isAssignableFrom( short.class ) ) objs[i] = Short.decode(value).shortValue();
else if ( clz.isAssignableFrom( byte.class ) ) objs[i] = Byte.decode(value).byteValue();
else if ( clz.isAssignableFrom( double.class ) ) objs[i] = Double.valueOf(value).doubleValue();
else if ( clz.isAssignableFrom( float.class ) ) objs[i] = Float.valueOf(value).floatValue();
}catch (NumberFormatException ex){
throw new CommandParsingException(value,i,"The parameter is a number and "+value+" does not reppresent a number", ex);
}
if ( objs[i] != null) return true; //Data already assigned
if ( clz.isAssignableFrom( boolean.class ) ) objs[i] = Boolean.valueOf(value).booleanValue() || "on".equalsIgnoreCase(value) || "1".equals(value);
else if ( clz.isAssignableFrom( String.class ) ) objs[i] = value;
return objs[i] != null;
}
private Object objectArrayToNativeArray(Class<?> nativeType,Object[] array, int length){
if ( nativeType == int.class ){
int[] result = new int[length];
for (int i = 0; i < result.length; i++) {
result[i] = (Integer) array[i];
}
return result;
}
if ( nativeType == long.class ){
long[] result = new long[length];
for (int i = 0; i < result.length; i++) {
result[i] = (Long) array[i];
}
return result;
}
if ( nativeType == short.class ){
short[] result = new short[length];
for (int i = 0; i < result.length; i++) {
result[i] = (Short) array[i];
}
return result;
}
if ( nativeType == byte.class ){
byte[] result = new byte[length];
for (int i = 0; i < result.length; i++) {
result[i] = (Byte) array[i];
}
return result;
}
if ( nativeType == boolean.class ){
boolean[] result = new boolean[length];
for (int i = 0; i < result.length; i++) {
result[i] = (Boolean) array[i];
}
return result;
}
if ( nativeType == float.class ){
float[] result = new float[length];
for (int i = 0; i < result.length; i++) {
result[i] = (Float) array[i];
}
return result;
}
if ( nativeType == double.class ){
double[] result = new double[length];
for (int i = 0; i < result.length; i++) {
result[i] = (Double) array[i];
}
return result;
}
throw new IllegalArgumentException("Unable to convert Object[] to "+nativeType+"[]");
}
private <T> boolean assignArrayFromString(Class<? extends T[]> clz, Object[] objs, int target, String value) {
objs[target] = null;
Class<?> type = clz.getComponentType();
String[] slices = value.split("[,;]");
Object[] array = new Object[slices.length];
int idx = 0;
for (int j = 0; j < slices.length; j++) {
slices[j] = slices[j].trim();
if ( "".equals( slices[j] ) ) continue;
assignValueFromString(type, array, idx, slices[j]);
idx++;
}
objs[target] = objectArrayToNativeArray(type,array,idx);
// objs[target] = Arrays.copyOfRange(array, 0, idx, clz); It's not working
return objs[target] != null;
}
public <T> String invoke(String[] values) throws Exception {
Class<?>[] params = method.getParameterTypes();
Object[] objs = new Object[params.length];
for (int i = 0; i < objs.length; i++) {
if ( params[i].isArray() ){
Class<? extends T[]> type = (Class<? extends T[]>) params[i];
assignArrayFromString(type, objs, i, values[i]);
} else {
assignValueFromString(params[i], objs, i, values[i]);
}
if ( objs[i] == null ){
throw new CommandParsingException(
values[i],
i,
"No convertion defined from "+String.class+" to argument of type "+params[i]
);
}
}
if( method.getReturnType() == void.class ) {
method.invoke(cluster, objs);
return null;
}else{
return method.invoke(cluster, objs).toString();
}
}
public String getName() {
return cluster.getName()+"."+method.getName();
}
public String toString() {
return method.getName();
}
}
| smulikHakipod/zb4osgi | zb4o-GUI-tester/src/main/java/org/persona/zigbee/tester/gui/Command.java | Java | apache-2.0 | 7,719 |
<?php
/**
* @file
* Definition of Drupal\taxonomy\Plugin\views\field\LinkEdit.
*/
namespace Drupal\taxonomy\Plugin\views\field;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;
use Drupal\Component\Annotation\PluginID;
/**
* Field handler to present a term edit link.
*
* @ingroup views_field_handlers
*
* @PluginID("term_link_edit")
*/
class LinkEdit extends FieldPluginBase {
/**
* Overrides Drupal\views\Plugin\views\field\FieldPluginBase::init().
*/
public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
parent::init($view, $display, $options);
$this->additional_fields['tid'] = 'tid';
$this->additional_fields['vid'] = 'vid';
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['text'] = array('default' => '', 'translatable' => TRUE);
return $options;
}
public function buildOptionsForm(&$form, &$form_state) {
$form['text'] = array(
'#type' => 'textfield',
'#title' => t('Text to display'),
'#default_value' => $this->options['text'],
);
parent::buildOptionsForm($form, $form_state);
}
public function query() {
$this->ensureMyTable();
$this->addAdditionalFields();
}
/**
* {@inheritdoc}
*/
public function render(ResultRow $values) {
// Check there is an actual value, as on a relationship there may not be.
if ($tid = $this->getValue($values, 'tid')) {
// Mock a term object for taxonomy_term_access(). Use machine name and
// vid to ensure compatibility with vid based and machine name based
// access checks. See http://drupal.org/node/995156
$term = entity_create('taxonomy_term', array(
'vid' => $values->{$this->aliases['vid']},
));
if ($term->access('update')) {
$text = !empty($this->options['text']) ? $this->options['text'] : t('edit');
return l($text, 'taxonomy/term/'. $tid . '/edit', array('query' => drupal_get_destination()));
}
}
}
}
| nickopris/musicapp | www/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/views/field/LinkEdit.php | PHP | apache-2.0 | 2,153 |
package net.bytebuddy.implementation.bind;
import net.bytebuddy.description.method.MethodDescription;
/**
* Implementation of an
* {@link net.bytebuddy.implementation.bind.MethodDelegationBinder.AmbiguityResolver}
* that resolves conflicting bindings by considering equality of a target method's internalName as an indicator for a dominant
* binding.
* <p> </p>
* For example, if method {@code source.foo} can be bound to methods {@code targetA.foo} and {@code targetB.bar},
* {@code targetA.foo} will be considered as dominant.
*/
public enum MethodNameEqualityResolver implements MethodDelegationBinder.AmbiguityResolver {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Resolution resolve(MethodDescription source,
MethodDelegationBinder.MethodBinding left,
MethodDelegationBinder.MethodBinding right) {
boolean leftEquals = left.getTarget().getName().equals(source.getName());
boolean rightEquals = right.getTarget().getName().equals(source.getName());
if (leftEquals ^ rightEquals) {
return leftEquals ? Resolution.LEFT : Resolution.RIGHT;
} else {
return Resolution.AMBIGUOUS;
}
}
}
| CodingFabian/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/implementation/bind/MethodNameEqualityResolver.java | Java | apache-2.0 | 1,272 |
---
description: expose, port, docker, bind publish
keywords: Examples, Usage, network, docker, documentation, user guide, multihost, cluster
title: Bind container ports to the host
---
The information in this section explains binding container ports within the Docker default bridge. This is a `bridge` network named `bridge` created automatically when you install Docker.
> **Note**: The [Docker networks feature](../index.md) allows you to
create user-defined networks in addition to the default bridge network.
By default Docker containers can make connections to the outside world, but the
outside world cannot connect to containers. Each outgoing connection will
appear to originate from one of the host machine's own IP addresses thanks to an
`iptables` masquerading rule on the host machine that the Docker server creates
when it starts:
```
$ sudo iptables -t nat -L -n
...
Chain POSTROUTING (policy ACCEPT)
target prot opt source destination
MASQUERADE all -- 172.17.0.0/16 0.0.0.0/0
...
```
The Docker server creates a masquerade rule that lets containers connect to IP
addresses in the outside world.
If you want containers to accept incoming connections, you will need to provide
special options when invoking `docker run`. There are two approaches.
First, you can supply `-P` or `--publish-all=true|false` to `docker run` which
is a blanket operation that identifies every port with an `EXPOSE` line in the
image's `Dockerfile` or `--expose <port>` commandline flag and maps it to a host
port somewhere within an _ephemeral port range_. The `docker port` command then
needs to be used to inspect created mapping. The _ephemeral port range_ is
configured by `/proc/sys/net/ipv4/ip_local_port_range` kernel parameter,
typically ranging from 32768 to 61000.
Mapping can be specified explicitly using `-p SPEC` or `--publish=SPEC` option.
It allows you to particularize which port on docker server - which can be any
port at all, not just one within the _ephemeral port range_ -- you want mapped
to which port in the container.
Either way, you should be able to peek at what Docker has accomplished in your
network stack by examining your NAT tables.
```
# What your NAT rules might look like when Docker
# is finished setting up a -P forward:
$ iptables -t nat -L -n
...
Chain DOCKER (2 references)
target prot opt source destination
DNAT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:49153 to:172.17.0.2:80
# What your NAT rules might look like when Docker
# is finished setting up a -p 80:80 forward:
Chain DOCKER (2 references)
target prot opt source destination
DNAT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 to:172.17.0.2:80
```
You can see that Docker has exposed these container ports on `0.0.0.0`, the
wildcard IP address that will match any possible incoming port on the host
machine. If you want to be more restrictive and only allow container services to
be contacted through a specific external interface on the host machine, you have
two choices. When you invoke `docker run` you can use either `-p
IP:host_port:container_port` or `-p IP::port` to specify the external interface
for one particular binding.
Or if you always want Docker port forwards to bind to one specific IP address,
you can edit your system-wide Docker server settings and add the option
`--ip=IP_ADDRESS`. Remember to restart your Docker server after editing this
setting.
> **Note**: With hairpin NAT enabled (`--userland-proxy=false`), containers port
exposure is achieved purely through iptables rules, and no attempt to bind the
exposed port is ever made. This means that nothing prevents shadowing a
previously listening service outside of Docker through exposing the same port
for a container. In such conflicting situation, Docker created iptables rules
will take precedence and route to the container.
The `--userland-proxy` parameter, true by default, provides a userland
implementation for inter-container and outside-to-container communication. When
disabled, Docker uses both an additional `MASQUERADE` iptable rule and the
`net.ipv4.route_localnet` kernel parameter which allow the host machine to
connect to a local container exposed port through the commonly used loopback
address: this alternative is preferred for performance reasons.
## Related information
- [Understand Docker container networks](../index.md)
- [Work with network commands](../work-with-networks.md)
- [Legacy container links](dockerlinks.md)
| shin-/docker.github.io | engine/userguide/networking/default_network/binding.md | Markdown | apache-2.0 | 4,552 |
/*
* Copyright 2013 The Closure Compiler 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 com.google.javascript.jscomp;
import com.google.common.base.Joiner;
import com.google.javascript.jscomp.newtypes.JSTypeCreatorFromJSDoc;
/**
* @author blickly@google.com (Ben Lickly)
* @author dimvar@google.com (Dimitris Vardoulakis)
*/
public final class NewTypeInferenceES5OrLowerTest extends NewTypeInferenceTestBase {
public void testExterns() {
typeCheck(
"/** @param {Array<string>} x */ function f(x) {}; f([5]);",
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testVarDefinitionsInExterns() {
typeCheckCustomExterns(
DEFAULT_EXTERNS + "var undecl = {};", "if (undecl) { undecl.x = 7 };");
typeCheckCustomExterns(
DEFAULT_EXTERNS + "var undecl = {};",
"function f() { if (undecl) { undecl.x = 7 }; }");
typeCheckCustomExterns(DEFAULT_EXTERNS + "var undecl;", "undecl(5);");
typeCheckCustomExterns(
DEFAULT_EXTERNS + "/** @type {number} */ var num;", "num - 5;");
typeCheckCustomExterns(
DEFAULT_EXTERNS + "var maybeStr; /** @type {string} */ var maybeStr;",
"maybeStr - 5;");
typeCheckCustomExterns(
DEFAULT_EXTERNS + "/** @type {string} */ var str;", "str - 5;",
NewTypeInference.INVALID_OPERAND_TYPE);
// TODO(blickly): Warn if function in externs has body
typeCheckCustomExterns(
DEFAULT_EXTERNS + "function f() {/** @type {string} */ var invisible;}",
"invisible - 5;");
// VarCheck.UNDEFINED_VAR_ERROR);
typeCheckCustomExterns(
DEFAULT_EXTERNS + "/** @type {number} */ var num;",
"/** @type {undefined} */ var x = num;",
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheckCustomExterns(
DEFAULT_EXTERNS + "var untypedNum;",
Joiner.on('\n').join(
"function f(x) {",
" x < untypedNum;",
" untypedNum - 5;",
"}",
"f('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testThisInAtTypeFunction() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){};",
"/** @type {number} */ Foo.prototype.n;",
"/** @type {function(this:Foo)} */ function f() { this.n = 'str' };"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(
"/** @type {function(this:gibberish)} */ function foo() {}",
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"var /** function(this:Foo) */ x = function() {};"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @param {function(this:Foo)} x */",
"function f(x) {}",
"f(/** @type {function(this:Foo)} */ (function() {}));"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() { /** @type {number} */ this.prop = 1; }",
"/** @type {function(this:Foo)} */",
"function f() { this.prop = 'asdf'; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @constructor */",
"function Bar() {}",
"/** @param {function(this:Foo)} x */",
"function f(x) {}",
"f(/** @type {function(this:Bar)} */ (function() {}));"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function High() {}",
"/** @constructor @extends {High} */",
"function Low() {}",
"function f(/** function(this:Low) */ low,",
" /** function(this:High) */ high) {",
" var fun = (1 < 2) ? low : high;",
" var /** function(this:High) */ f2 = fun;",
" var /** function(this:Low) */ f3 = fun;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function High() {}",
"/** @constructor @extends {High} */",
"function Low() {}",
"function f(/** function(function(this:Low)) */ low,",
" /** function(function(this:High)) */ high) {",
" var fun = (1 < 2) ? low : high;",
" var /** function(function(this:High)) */ f2 = fun;",
" var /** function(function(this:Low)) */ f3 = fun;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" * @param {T} x",
" */",
"function Foo(x) {}",
"/**",
" * @template T",
" * @param {function(this:Foo<T>)} fun",
" */",
"function f(fun) { return fun; }",
"var /** function(this:Foo<string>) */ x =",
" f(/** @type {function(this:Foo<number>)} */ (function() {}));"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testThisInFunctionJsdoc() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {};",
"/** @type {number} */ Foo.prototype.n;",
"/** @this {Foo} */",
"function f() { this.n = 'str'; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(
"/** @this {gibberish} */ function foo() {}",
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() { /** @type {number} */ this.prop = 1; }",
"/** @this {Foo} */",
"function f() { this.prop = 'asdf'; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
// TODO(dimvar): we must warn when a THIS fun isn't called as a method
public void testDontCallMethodAsFunction() {
typeCheck(Joiner.on('\n').join(
"/** @type{function(this: Object)} */",
"function f() {}",
"f();"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prototype.method = function() {};",
"var f = (new Foo).method;",
"f();"));
}
public void testNewInFunctionJsdoc() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"function h(/** function(new:Foo, ...number):number */ f) {",
" (new f()) - 5;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" * @param {T} x",
" */",
"function Foo(x) {}",
"/**",
" * @template T",
" * @param {function(new:Foo<T>)} fun",
" */",
"function f(fun) { return fun; }",
"/** @type {function(new:Foo<number>)} */",
"function f2() {}",
"var /** function(new:Foo<string>) */ x = f(f2);"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"function f(x) {",
" x();",
" var /** !Foo */ y = new x();",
" var /** function(new:Foo, number) */ z = x;",
"}"));
// TODO(dimvar): this is a bogus warning, x can be arbitrary and does not
// need to have the num property; see NominalType#getConstructorObject
// for what needs to change.
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @type {number} */",
"Foo.num = 123;",
"function f(/** function(new:Foo, string) */ x) {",
" var /** string */ s = x.num;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testAlhpaRenamingDoesntChangeType() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @param {U} x",
" * @param {U} y",
" * @template U",
" */",
"function f(x, y){}",
"/**",
" * @template T",
" * @param {function(T, T): boolean} comp",
" * @param {!Array<T>} arr",
" */",
"function g(comp, arr) {",
" var compare = comp || f;",
" compare(arr[0], arr[1]);",
"}"));
}
public void testInvalidThisReference() {
typeCheck("this.x = 5;", CheckGlobalThis.GLOBAL_THIS);
typeCheck("function f(x){}; f(this);");
typeCheck("function f(){ return this; }");
typeCheck("function f() { this.p = 1; }", CheckGlobalThis.GLOBAL_THIS);
typeCheck("function f() { return this.p; }", CheckGlobalThis.GLOBAL_THIS);
typeCheck("function f() { this['p']; }", CheckGlobalThis.GLOBAL_THIS);
typeCheck(Joiner.on('\n').join(
"function g(x) {}",
"g(function() { return this.p; })"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(x) {}",
"new Foo(function() { return this.p; })"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @this {T}",
" */",
"function f(x) {",
" this.p = 123;",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @this {Object} */",
"function f(pname) {",
" var x = this[pname];",
"}"));
}
public void testSuperClassWithUndeclaredProps() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Error() {};",
"Error.prototype.sourceURL;",
"/** @constructor @extends {Error} */ function SyntaxError() {}"));
}
public void testInheritMethodFromParent() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {};",
"/** @param {string} x */ Foo.prototype.method = function(x) {};",
"/** @constructor @extends {Foo} */ function Bar() {};",
"(new Bar).method(4)"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testSubClassWithUndeclaredProps() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Super() {};",
"/** @type {string} */ Super.prototype.str;",
"/** @constructor @extends {Super} */ function Sub() {};",
"Sub.prototype.str;"));
}
public void testUseBeforeDeclaration() {
// typeCheck("x; var x;", VariableReferenceCheck.EARLY_REFERENCE);
// typeCheck("x = 7; var x;", VariableReferenceCheck.EARLY_REFERENCE);
typeCheck(Joiner.on('\n').join(
"function f() { return 9; }",
"var x = f();",
"x - 7;"));
}
// public void testUseWithoutDeclaration() {
// typeCheck("x;", VarCheck.UNDEFINED_VAR_ERROR);
// typeCheck("x = 7;", VarCheck.UNDEFINED_VAR_ERROR);
// typeCheck("var y = x;", VarCheck.UNDEFINED_VAR_ERROR);
// }
// public void testVarRedeclaration() {
// typeCheck(
// "function f(x) { var x; }",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// typeCheck(
// "function f(x) { function x() {} }",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// typeCheck(
// "function f(x) { /** @typedef {number} */ var x; }",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// typeCheck(
// "var x; var x;",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// typeCheck(
// "var x; function x() {}",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// typeCheck(
// "var x; /** @typedef {number} */ var x;",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// typeCheck(
// "function x() {} function x() {}",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// typeCheck(
// "function x() {} var x;",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// typeCheck(
// "function x() {} /** @typedef {number} */ var x;",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// typeCheck(
// "/** @typedef {number} */ var x; /** @typedef {number} */ var x;",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// typeCheck(
// "/** @typedef {number} */ var x; var x;",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// typeCheck(
// "/** @typedef {number} */ var x; function x() {}",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// typeCheck("var f = function g() {}; function f() {};",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// typeCheck("var f = function g() {}; var f = function h() {};",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// typeCheck("var g = function f() {}; var h = function f() {};");
// typeCheck(
// "var x; /** @enum */ var x = { ONE: 1 };",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// typeCheck(
// "/** @enum */ var x = { ONE: 1 }; var x;",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// }
public void testDeclaredVariables() {
typeCheck("var /** null */ obj = 5;", NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(
"var /** ?number */ n = true;", NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testEmptyBlockPropagation() {
typeCheck(
"var x = 5; { }; var /** string */ s = x",
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testForLoopInference() {
typeCheck(Joiner.on('\n').join(
"var x = 5;",
"for (;true;) {",
" x = 'str';",
"}",
"var /** (string|number) */ y = x;",
"(function(/** string */ s){})(x);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"var x = 5;",
"while (true) {",
" x = 'str';",
"}",
"(function(/** string */ s){})(x);",
"var /** (string|number) */ y = x;"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"while (true) {",
" var x = 'str';",
"}",
"var /** (string|undefined) */ y = x;",
"(function(/** string */ s){})(x);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"for (var x = 5; x < 10; x++) {}",
"(function(/** string */ s){})(x);",
"var /** number */ y = x;"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testConditionalSpecialization() {
typeCheck(Joiner.on('\n').join(
"var x, y = 5;",
"if (true) {",
" x = 5;",
"} else {",
" x = 'str';",
"}",
"if (x === 5) {",
" y = x;",
"}",
"y - 5"));
typeCheck(Joiner.on('\n').join(
"var x, y = 5;",
"if (true) {",
" x = 5;",
"} else {",
" x = null;",
"}",
"if (x !== null) {",
" y = x;",
"}",
"y - 5"));
typeCheck(Joiner.on('\n').join(
"var x, y;",
"if (true) {",
" x = 5;",
"} else {",
" x = null;",
"}",
"if (x === null) {",
" y = 5;",
"} else {",
" y = x;",
"}",
"y - 5"));
typeCheck(Joiner.on('\n').join(
"var numOrNull = true ? null : 1",
"if (null === numOrNull) { var /** null */ n = numOrNull; }"));
}
public void testUnspecializedStrictComparisons() {
typeCheck(
"var /** number */ n = (1 === 2);",
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testAndOrConditionalSpecialization() {
typeCheck(Joiner.on('\n').join(
"var x, y = 5;",
"if (true) {",
" x = 5;",
"} else if (true) {",
" x = null;",
"}",
"if (x !== null && x !== undefined) {",
" y = x;",
"}",
"y - 5"));
typeCheck(Joiner.on('\n').join(
"var x, y;",
"if (true) {",
" x = 5;",
"} else if (true) {",
" x = null;",
"}",
"if (x === null || x === void 0) {",
" y = 5;",
"} else {",
" y = x;",
"}",
"y - 5"));
typeCheck(Joiner.on('\n').join(
"var x, y = 5;",
"if (true) {",
" x = 5;",
"} else if (true) {",
" x = null;",
"}",
"if (x === null || x === undefined) {",
" y = x;",
"}",
"var /** (number|null|undefined) **/ z = y;",
"(function(/** (number|null) */ x){})(y);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"var x, y;",
"if (true) {",
" x = 5;",
"} else if (true) {",
" x = null;",
"}",
"if (x !== null && x !== undefined) {",
" y = 5;",
"} else {",
" y = x;",
"}",
"var /** (number|null|undefined) **/ z = y;",
"(function(/** (number|null) */ x){})(y);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"var x, y = 5;",
"if (true) {",
" x = 5;",
"} else {",
" x = 'str';",
"}",
"if (x === 7 || x === 8) {",
" y = x;",
"}",
"y - 5"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function C(){}",
"var obj = new C;",
"if (obj || false) { 123, obj.asdf; }"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"function f(/** (number|string) */ x) {",
" (typeof x === 'number') && (x - 5);",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** (number|string|null) */ x) {",
" (x && (typeof x === 'number')) && (x - 5);",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** (number|string|null) */ x) {",
" (x && (typeof x === 'string')) && (x - 5);",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** (number|string|null) */ x) {",
" typeof x === 'string' && x;",
" x < 'asdf';",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testLoopConditionSpecialization() {
typeCheck(Joiner.on('\n').join(
"var x = true ? null : 'str';",
"while (x !== null) {}",
"var /** null */ y = x;"));
typeCheck(Joiner.on('\n').join(
"var x = true ? null : 'str';",
"for (;x !== null;) {}",
"var /** null */ y = x;"));
typeCheck(Joiner.on('\n').join(
"for (var x = true ? null : 'str'; x === null;) {}",
"var /** string */ y = x;"));
typeCheck(Joiner.on('\n').join(
"var x;",
"for (x = true ? null : 'str'; x === null;) {}",
"var /** string */ y = x;"));
typeCheck(Joiner.on('\n').join(
"var x = true ? null : 'str';",
"do {} while (x === null);",
"var /** string */ y = x;"));
}
public void testVarDecls() {
typeCheck("/** @type {number} */ var x, y;", TypeCheck.MULTIPLE_VAR_DEF);
typeCheck(
"var /** number */ x = 5, /** string */ y = 6;",
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(
"var /** number */ x = 'str', /** string */ y = 'str2';",
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testBadInitialization() {
typeCheck(
"/** @type {string} */ var s = 123;",
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testBadAssignment() {
typeCheck(
"/** @type {string} */ var s; s = 123;",
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testBadArithmetic() {
typeCheck("123 - 'str';", NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck("123 * 'str';", NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck("123 / 'str';", NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck("123 % 'str';", NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(
"var y = 123; var x = 'str'; var z = x - y;",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(
"var y = 123; var x; var z = x - y;",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck("+true;"); // This is considered an explicit coercion
typeCheck("true + 5;", NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck("5 + true;", NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testTypeAfterIF() {
typeCheck(
"var x = true ? 1 : 'str'; x - 1;",
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testSimpleBwdPropagation() {
typeCheck(Joiner.on('\n').join(
"function f(x) { x - 5; }",
"f(123);",
"f('asdf')"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) { x++; }",
"f(123);",
"f('asdf')"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(y) { var x = y; x - 5; }",
"f(123);",
"f('asdf')"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(y) { var x; x = y; x - 5; }",
"f(123);",
"f('asdf')"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) { x + 5; }",
"f(123);",
"f('asdf')"));
}
public void testSimpleReturn() {
typeCheck(Joiner.on('\n').join(
"function f(x) {}",
"var /** undefined */ x = f();",
"var /** number */ y = f();"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(x) { return; }",
"var /** undefined */ x = f();",
"var /** number */ y = f();"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(x) { return 123; }",
"var /** undefined */ x = f();",
"var /** number */ y = f();"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(x) { if (x) {return 123;} else {return 'asdf';} }",
"var /** (string|number) */ x = f();"));
typeCheck(Joiner.on('\n').join(
"function f(x) { if (x) {return 123;} }",
"var /** (undefined|number) */ x = f();"));
typeCheck(Joiner.on('\n').join(
"function f(x) { var y = x; y - 5; return x; }",
"var /** undefined */ x = f(1);",
"var /** number */ y = f(2);"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testComparisons() {
typeCheck(
"1 < 0; 'a' < 'b'; true < false; null < null; undefined < undefined;");
typeCheck(
"/** @param {{ p1: ?, p2: ? }} x */ function f(x) { x.p1 < x.p2; }");
typeCheck("function f(x, y) { x < y; }");
typeCheck(
"var x = 1; var y = true ? 1 : 'str'; x < y;",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(
"var x = 'str'; var y = 1; x < y;",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" var y = 1;",
" x < y;",
" return x;",
"}",
"var /** undefined */ x = f(1);",
"var /** number */ y = f(2);"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" var y = x, z = 7;",
" y < z;",
"}"));
}
public void testFunctionJsdoc() {
typeCheck(Joiner.on('\n').join(
"/** @param {number} n */",
"function f(n) { n < 5; }"));
typeCheck(Joiner.on('\n').join(
"/** @param {string} n */",
"function f(n) { n < 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @return {string} */",
"function f() { return 1; }"),
NewTypeInference.RETURN_NONDECLARED_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @return {string} */",
"function f() { return; }"),
NewTypeInference.RETURN_NONDECLARED_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @return {string} */",
"function f(s) { return s; }",
"f(123);",
"f('asdf')"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @return {number} */",
"function f() {}"),
CheckMissingReturn.MISSING_RETURN_STATEMENT);
typeCheck(Joiner.on('\n').join(
"/** @return {(undefined|number)} */",
"function f() { if (true) { return 'str'; } }"),
NewTypeInference.RETURN_NONDECLARED_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {function(number)} fun */",
"function f(fun) {}",
"f(function (/** string */ s) {});"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(
"/** @param {number} n */ function f(/** number */ n) {}",
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck("/** @constructor */ var Foo = function() {}; new Foo;");
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @param {number} x */ Foo.prototype.method = function(x) {};",
"(new Foo).method('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"Foo.prototype.method = /** @param {number} x */ function(x) {};",
"(new Foo).method('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"Foo.prototype.method = function(/** number */ x) {};",
"(new Foo).method('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(
"/** @type {function(number)} */ function f(x) {}; f('asdf');",
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(
"/** @type {number} */ function f() {}",
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"/** @type {function():number} */",
"function /** number */ f() { return 1; }"));
typeCheck(Joiner.on('\n').join(
"function f(/** function(number) */ fnum, floose, cond) {",
" var y;",
" if (cond) {",
" y = fnum;",
" } else {",
" floose();",
" y = floose;",
" }",
" return y;",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @param {function(): *} x */ function g(x) {}",
"/** @param {function(number): string} x */ function f(x) {",
" g(x);",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(
"var x = {}; x.a = function(/** string */ x) {}; x.a(123);",
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck("/** @param {function(...)} x */ function f(x) {}");
typeCheck(Joiner.on('\n').join(
"/**",
" * @interface",
" */",
"function A() {};",
"/** @return {number} */",
"A.prototype.foo = function() {};"));
typeCheck(
"/** @param {number} x */ function f(y) {}",
GlobalTypeInfo.INEXISTENT_PARAM);
}
public void testFunctionSubtyping() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @constructor */",
"function Bar() {}",
"function f(/** function(new:Foo) */ x) {}",
"f(Bar);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"function f(/** function(new:Foo) */ x) {}",
"f(function() {});"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @constructor @extends {Foo} */",
"function Bar() {}",
"function f(/** function(new:Foo) */ x) {}",
"f(Bar);"));
}
public void testFunctionJoin() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/**",
" * @param {function(new:Foo, (number|string))} x ",
" * @param {function(new:Foo, number)} y ",
" */",
"function f(x, y) {",
" var z = 1 < 2 ? x : y;",
" return new z(123);",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @constructor */",
"function Bar() {}",
"/**",
" * @param {function(new:Foo)} x ",
" * @param {function(new:Bar)} y ",
" */",
"function f(x, y) {",
" var z = 1 < 2 ? x : y;",
" return new z();",
"}"),
NewTypeInference.NOT_A_CONSTRUCTOR);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"function f(/** function(new:Foo) */ x, /** function() */ y) {",
" var z = 1 < 2 ? x : y;",
" return new z();",
"}"),
NewTypeInference.NOT_A_CONSTRUCTOR);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"function f(/** function(new:Foo) */ x, /** function() */ y) {",
" var z = 1 < 2 ? x : y;",
" return z();",
"}"));
}
public void testFunctionMeet() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/**",
" * @param {function(new:Foo, (number|string))} x ",
" * @param {function(new:Foo, number)} y ",
" */",
"function f(x, y) { if (x === y) { return x; } }"));
}
public void testRecordWithoutTypesJsdoc() {
typeCheck(Joiner.on('\n').join(
"function f(/** {a, b} */ x) {}",
"f({c: 123});"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testBackwardForwardPathologicalCase() {
typeCheck(Joiner.on('\n').join(
"function f(x) { var y = 5; y < x; }",
"f(123);",
"f('asdf')"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testTopInitialization() {
typeCheck("function f(x) { var y = x; y < 5; }");
typeCheck("function f(x) { x < 5; }");
typeCheck(
"function f(x) { x - 5; x < 'str'; }",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" var y = x; y - 5; y < 'str';",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
// public void testMultipleFunctions() {
// typeCheck("function g() {};\n function f(x) { var x; };",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// typeCheck("function f(x) { var x; };\n function g() {};",
// VariableReferenceCheck.REDECLARED_VARIABLE);
// }
public void testSimpleCalls() {
typeCheck("function f() {}; f(5);", TypeCheck.WRONG_ARGUMENT_COUNT);
typeCheck("function f(x) { x-5; }; f();", TypeCheck.WRONG_ARGUMENT_COUNT);
typeCheck(Joiner.on('\n').join(
"/** @return {number} */ function f() { return 1; }",
"var /** string */ s = f();"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(
"function f(/** number */ x) {}; f(true);",
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** boolean */ x) {}",
"function g() { f(123); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** void */ x) {}",
"function g() { f(123); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** boolean */ x) {}",
"function g(x) {",
" var /** string */ s = x;",
" f(x < 7);",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x) {}",
"function g(x, y) {",
" y < x;",
" f(x);",
" var /** string */ s = y;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testObjectType() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"function takesObj(/** Object */ x) {}",
"takesObj(new Foo);"));
typeCheck(Joiner.on('\n').join(
"function takesObj(/** Object */ x) {}",
"takesObj(null);"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"function /** Object */ returnsObj() { return {}; }",
"function takesFoo(/** Foo */ x) {}",
"takesFoo(returnsObj());"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck("Object.prototype.hasOwnProperty.call({}, 'asdf');");
}
public void testCallsWithComplexOperator() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @constructor */ function Bar() {}",
"function fun(cond, /** !Foo */ f, /** !Bar */ g) {",
" (cond ? f : g)();",
"}"),
TypeCheck.NOT_CALLABLE);
}
public void testDeferredChecks() {
typeCheck(Joiner.on('\n').join(
"function f() { return 'str'; }",
"function g() { f() - 5; }"),
NewTypeInference.INVALID_INFERRED_RETURN_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) { x - 5; }",
"f(5 < 6);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x, y) { x - y; }",
"f(5);"),
TypeCheck.WRONG_ARGUMENT_COUNT);
typeCheck(Joiner.on('\n').join(
"function f() { return 'str'; }",
"function g() { var x = f(); x - 7; }"),
NewTypeInference.INVALID_INFERRED_RETURN_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x, y) { return x-y; }",
"f(5, 'str');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @return {number} */ function f(x) { return x; }",
"f('str');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x) { return x; }",
"function g(x) {",
" var /** string */ s = f(x);",
"};"),
NewTypeInference.INVALID_INFERRED_RETURN_TYPE);
typeCheck(Joiner.on('\n').join(
"function f() { new Foo('asdf'); }",
"/** @constructor */ function Foo(x) { x - 5; }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Arr() {}",
"/**",
" * @template T",
" * @param {...T} var_args",
" */",
"Arr.prototype.push = function(var_args) {};",
"function f(x) {}",
"var renameByParts = function(parts) {",
" var mapped = new Arr();",
" mapped.push(f(parts));",
"};"));
// Here we don't want a deferred check and an INVALID_INFERRED_RETURN_TYPE
// warning b/c the return type is declared.
typeCheck(Joiner.on('\n').join(
"/** @return {string} */ function foo(){ return 'str'; }",
"function g() { foo() - 123; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f() {",
" function x() {};",
" function g() { x(1); }",
" g();",
"}"),
TypeCheck.WRONG_ARGUMENT_COUNT);
// We used to erroneously create a deferred check for the call to f
// (and crash as a result), because we had a bug where the top-level
// function was not being shadowed by the formal parameter.
typeCheck(Joiner.on('\n').join(
"function f() { return 123; }",
"var outer = 123;",
"function g(/** function(number) */ f) {",
" f(123) < 'str';",
" return outer;",
"}"));
// TODO(dimvar): Do deferred checks for known functions that are properties.
// typeCheck(Joiner.on('\n').join(
// "/** @const */ var ns = {};",
// "ns.f = function(x) { return x - 1; };",
// "function g() { ns.f('asdf'); }"),
// NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testShadowing() {
typeCheck(Joiner.on('\n').join(
"var /** number */ x = 5;",
"function f() {",
" var /** string */ x = 'str';",
" return x - 5;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"var /** number */ x = 5;",
"function f() {",
" /** @typedef {string} */ var x;",
" return x - 5;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"var /** number */ x = 5;",
"function f() {",
" /** @enum {string} */ var x = { FOO : 'str' };",
" return x - 5;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
// Types that are only present in types, and not in code do not cause shadowing in code
typeCheck(Joiner.on('\n').join(
"var /** number */ X = 5;",
"/** @template X */",
"function f() {",
" return X - 5;",
"}"));
typeCheck(Joiner.on('\n').join(
"var /** string */ X = 'str';",
"/** @template X */",
"function f() {",
" return X - 5;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testTypedefIsUndefined() {
typeCheck(Joiner.on('\n').join(
"function f() {",
" /** @typedef {string} */ var x;",
" /** @type {undefined} */ var y = x;",
"}"));
}
public void testFunctionsInsideFunctions() {
typeCheck(Joiner.on('\n').join(
"(function() {",
" function f() {}; f(5);",
"})();"),
TypeCheck.WRONG_ARGUMENT_COUNT);
typeCheck(Joiner.on('\n').join(
"(function() {",
" function f() { return 'str'; }",
" function g() { f() - 5; }",
"})();"),
NewTypeInference.INVALID_INFERRED_RETURN_TYPE);
typeCheck(Joiner.on('\n').join(
"var /** number */ x;",
"function f() { x = 'str'; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"var x;",
"function f() { x - 5; x < 'str'; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testCrossScopeWarnings() {
typeCheck(Joiner.on('\n').join(
"function f() {",
" x < 'str';",
"}",
"var x = 5;",
"f()"),
NewTypeInference.CROSS_SCOPE_GOTCHA);
// CROSS_SCOPE_GOTCHA is only for undeclared variables
typeCheck(Joiner.on('\n').join(
"/** @type {string} */ var s;",
"function f() {",
" s = 123;",
"}",
"f();"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function g(x) {",
" function f() { x < 'str'; z < 'str'; x = 5; }",
" var z = x;",
" f();",
" x - 5;",
" z < 'str';",
"}"));
// TODO(dimvar): we can't do this yet; requires more info in the summary
// typeCheck(Joiner.on('\n').join(
// "/** @constructor */",
// "function Foo() {",
// " /** @type{?Object} */ this.prop = null;",
// "}",
// "Foo.prototype.initProp = function() { this.prop = {}; };",
// "var obj = new Foo();",
// "if (obj.prop == null) {",
// " obj.initProp();",
// " obj.prop.a = 123;",
// "}"));
}
public void testTrickyUnknownBehavior() {
typeCheck(Joiner.on('\n').join(
"function f(/** function() */ x, cond) {",
" var y = cond ? x() : 5;",
" y < 'str';",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @param {function() : ?} x */ function f(x, cond) {",
" var y = cond ? x() : 5;",
" y < 'str';",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** function() */ x) {",
" x() < 'str';",
"}"));
typeCheck(Joiner.on('\n').join(
"function g() { return {}; }",
"function f() {",
" var /** ? */ x = g();",
" return x.y;",
"}"),
NewTypeInference.INVALID_INFERRED_RETURN_TYPE);
typeCheck(Joiner.on('\n').join(
"function g() { return {}; }",
"function f() {",
" var /** ? */ x = g()",
" x.y = 5;",
"}"));
typeCheck(Joiner.on('\n').join(
"function g(x) { return x; }",
"function f(z) {",
" var /** ? */ x = g(z);",
" x.y2 = 123;",
// specializing to a loose object here
" return x.y1 - 5;",
"}"));
}
public void testDeclaredFunctionTypesInFormals() {
typeCheck(Joiner.on('\n').join(
"function f(/** function():number */ x) {",
" var /** string */ s = x();",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(/** function(number) */ x) {",
" x(true);",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function g(x, y, /** function(number) */ f) {",
" y < x;",
" f(x);",
" var /** string */ s = y;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" var y = x(); y - 5; y < 'str';",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {function():?} x */ function f(x) {",
" var y = x(); y - 5; y < 'str';",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(
"function f(/** ? */ x) { x < 'asdf'; x - 5; }",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {function(number): string} x */ function g(x) {}",
"/** @param {function(number): string} x */ function f(x) {",
" g(x);",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @param {function(number): *} x */ function g(x) {}",
"/** @param {function(*): string} x */ function f(x) {",
" g(x);",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @param {function(*): string} x */ function g(x) {}",
"/** @param {function(number): string} x */ function f(x) {",
" g(x);",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {function(number): string} x */ function g(x) {}",
"/** @param {function(number): *} x */ function f(x) {",
" g(x);",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testSpecializedFunctions() {
typeCheck(Joiner.on('\n').join(
"function f(/** function(string) : number */ x) {",
" if (x('str') === 5) {",
" x(5);",
" }",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** function(string) : string */ x) {",
" if (x('str') === 5) {",
" x(5);",
" }",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** function(string) */ x, y) {",
" y(1);",
" if (x === y) {",
" x(5);",
" }",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (x === null) {",
" return 5;",
" } else {",
" return x - 43;",
" }",
"}",
"f('str');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var goog = {};",
"/** @type {!Function} */ goog.abstractMethod = function(){};",
"/** @constructor */ function Foo(){};",
"/** @return {!Foo} */ Foo.prototype.clone = goog.abstractMethod;",
"/** @constructor @extends {Foo} */",
"function Bar() {}",
"/** @return {!Bar} */ Bar.prototype.clone = goog.abstractMethod;"));
typeCheck(Joiner.on('\n').join(
"/** @const */ var goog = {};",
"/** @type {!Function} */ goog.abstractMethod = function(){};",
"/** @constructor */ function Foo(){};",
"/** @return {!Foo} */ Foo.prototype.clone = goog.abstractMethod;",
"/** @constructor @extends {Foo} */",
"function Bar() {}",
"/** @return {!Bar} */ Bar.prototype.clone = goog.abstractMethod;",
"var /** null */ n = (new Bar).clone();"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @constructor */",
"function Foo() {}",
"/** @type {function(number)} */",
"Foo.prototype.m = goog.nullFunction;",
"/** @enum {function(string)} */",
"var e = {",
" A: goog.nullFunction",
"};"));
typeCheck(Joiner.on('\n').join(
"function f() {}",
"/** @type {function(number)} */",
"var g = f;",
"/** @type {function(string)} */",
"var h = f;"));
}
public void testDifficultObjectSpecialization() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function X() { this.p = 1; }",
"/** @constructor */",
"function Y() { this.p = 2; }",
"/** @param {(!X|!Y)} a */",
"function fn(a) {",
" a.p;",
" /** @type {!X} */ (a);",
"}"));
// Currently, two types that have a common subtype specialize to bottom
// instead of to the common subtype. If we change that, then this test will
// have no warnings.
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function High1() {}",
"/** @interface */",
"function High2() {}",
"/**",
" * @constructor",
" * @implements {High1}",
" * @implements {High2}",
" */",
"function Low() {}",
"function f(x) {",
" var /** !High1 */ v1 = x;",
" var /** !High2 */ v2 = x;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
// Currently, two types that have a common subtype specialize to bottom
// instead of to the common subtype. If we change that, then this test will
// have no warnings, and the type of x will be !Low.
// (We must normalize the output of specialize to avoid getting (!Med|!Low))
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function High1() {}",
"/** @interface */",
"function High2() {}",
"/** @interface */",
"function High3() {}",
"/**",
" * @interface",
" * @extends {High1}",
" * @extends {High2}",
" */",
"function Mid() {}",
"/**",
" * @interface",
" * @extends {Mid}",
" * @extends {High3}",
" */",
"function Low() {}",
"function f(x) {",
" var /** !High1 */ v1 = x;",
" var /** (!High2|!High3) */ v2 = x;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testLooseConstructors() {
typeCheck(Joiner.on('\n').join(
"function f(ctor) {",
" new ctor(1);",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(ctor) {",
" new ctor(1);",
"}",
"/** @constructor */ function Foo(/** string */ y) {}",
"f(Foo);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testLooseFunctions() {
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" x(1);",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" x(1);",
"}",
"function g(/** string */ y) {}",
"f(g);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" x(1);",
"}",
"function g(/** number */ y) {}",
"f(g);"));
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" x(1);",
"}",
"function g(/** (number|string) */ y) {}",
"f(g);"));
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" 5 - x(1);",
"}",
"/** @return {string} */",
"function g(/** number */ y) { return ''; }",
"f(g);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" 5 - x(1);",
"}",
"/** @return {(number|string)} */",
"function g(/** number */ y) { return 5; }",
"f(g);"));
typeCheck(Joiner.on('\n').join(
"function f(x, y) {",
" x(5);",
" y(5);",
" return x(y);",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" x();",
" return x;",
"}",
"function g() {}",
"function h() { f(g) - 5; }"),
NewTypeInference.INVALID_INFERRED_RETURN_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x, cond) {",
" x();",
" return cond ? 5 : x;",
"}",
"function g() {}",
"function h() { f(g, true) - 5; }"),
NewTypeInference.INVALID_INFERRED_RETURN_TYPE);
// A loose function is a loose subtype of a non-loose function.
// Traditional function subtyping would warn here.
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" x(5);",
" return x;",
"}",
"function g(x) {}",
"function h() {",
" var /** function((number|string)) */ fun = f(g);",
"}"));
typeCheck(Joiner.on('\n').join(
"function g(/** string */ x) {}",
"function f(x, y) {",
" y - 5;",
" x(y);",
" y + y;",
"}",
"f(g, 5)"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @return {string} */",
"function g(/** number */ x) { return 'str'; }",
"/** @return {number} */",
"function f(x) {",
" var y = 5;",
" var z = x(y);",
" return z;",
"}",
"f(g)"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @return {number} */",
"function g(/** number */ y) { return 6; }",
"function f(x, cond) {",
" if (cond) {",
" 5 - x(1);",
" } else {",
" x('str') < 'str';",
" }",
"}",
"f(g, true)"));
typeCheck(Joiner.on('\n').join(
"function f(g, cond) {",
" if (cond) {",
" g(5, cond);",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @param {function (number)|Function} x",
" */",
"function f(x) {};",
"f(function () {});"));
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" x(true, 'asdf');",
" x(false);",
"}"));
}
public void testBackwardForwardPathologicalCase2() {
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x, /** string */ y, z) {",
" var w = z;",
" x < z;",
" w < y;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testNotCallable() {
typeCheck(Joiner.on('\n').join(
"/** @param {number} x */ function f(x) {",
" x(7);",
"}"),
TypeCheck.NOT_CALLABLE);
}
public void testSimpleLocallyDefinedFunction() {
typeCheck(Joiner.on('\n').join(
"function f() { return 'str'; }",
"var x = f();",
"x - 7;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f() { return 'str'; }",
"f() - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"(function() {",
" function f() { return 'str'; }",
" f() - 5;",
"})();"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"(function() {",
" function f() { return 'str'; }",
" f() - 5;",
"})();"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testIdentityFunction() {
typeCheck(Joiner.on('\n').join(
"function f(x) { return x; }",
"5 - f(1);"));
}
public void testReturnTypeInferred() {
typeCheck(Joiner.on('\n').join(
"function f() {",
" var x = g();",
" var /** string */ s = x;",
" x - 5;",
"};",
"function g() { return 'str'};"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testGetpropOnNonObjects() {
typeCheck("(null).foo;", NewTypeInference.PROPERTY_ACCESS_ON_NONOBJECT);
typeCheck(Joiner.on('\n').join(
"var /** undefined */ n;",
"n.foo;"),
NewTypeInference.PROPERTY_ACCESS_ON_NONOBJECT);
typeCheck("var x = {}; x.foo.bar = 1;", TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"var /** undefined */ n;",
"n.foo = 5;"),
NewTypeInference.PROPERTY_ACCESS_ON_NONOBJECT);
typeCheck(Joiner.on('\n').join(
"/** @param {*} x */",
"function f(x) {",
" if (x.prop) {",
" var /** { prop: ? } */ y = x;",
" }",
"}"));
// TODO(blickly): Currently, this warning is not good, referring to props of
// BOTTOM. Ideally, we could warn about accessing a prop on undefined.
typeCheck(Joiner.on('\n').join(
"/** @param {undefined} x */",
"function f(x) {",
" if (x.prop) {}",
"}"),
NewTypeInference.PROPERTY_ACCESS_ON_NONOBJECT);
typeCheck("null[123];", NewTypeInference.PROPERTY_ACCESS_ON_NONOBJECT);
typeCheck(
"function f(/** !Object */ x) { if (x[123]) { return 1; } }");
typeCheck(
"function f(/** undefined */ x) { if (x[123]) { return 1; } }",
NewTypeInference.PROPERTY_ACCESS_ON_NONOBJECT);
typeCheck(Joiner.on('\n').join(
"function f(/** (number|null) */ n) {",
" n.foo;",
"}"),
NewTypeInference.PROPERTY_ACCESS_ON_NONOBJECT);
typeCheck(Joiner.on('\n').join(
"function f(/** (number|null|undefined) */ n) {",
" n.foo;",
"}"),
NewTypeInference.PROPERTY_ACCESS_ON_NONOBJECT);
typeCheck(Joiner.on('\n').join(
"function f(/** (!Object|number|null|undefined) */ n) {",
" n.foo;",
"}"),
NewTypeInference.PROPERTY_ACCESS_ON_NONOBJECT);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"Foo.prototype.prop;",
"function f(/** (!Foo|undefined) */ n) {",
" n.prop;",
"}"),
NewTypeInference.NULLABLE_DEREFERENCE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"/** @type {string} */ Foo.prototype.prop1;",
"function g(/** Foo */ f) {",
" f.prop1.prop2 = 'str';",
"};"),
NewTypeInference.NULLABLE_DEREFERENCE);
}
public void testNonexistentProperty() {
typeCheck(Joiner.on('\n').join(
"/** @param {{ a: number }} obj */",
"function f(obj) {",
" 123, obj.b;",
" obj.b = 'str';",
"}"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck("({}).p < 'asdf';", TypeCheck.INEXISTENT_PROPERTY);
typeCheck("(/** @type {?} */ (null)).prop - 123;");
typeCheck("(/** @type {?} */ (null)).prop += 123;");
typeCheck("var x = {}; var y = x.a;", TypeCheck.INEXISTENT_PROPERTY);
typeCheck("var x = {}; x.y - 3; x.y = 5;", TypeCheck.INEXISTENT_PROPERTY);
}
public void testNullableDereference() {
typeCheck(
"function f(/** ?{ p : number } */ o) { return o.p; }",
NewTypeInference.NULLABLE_DEREFERENCE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() { /** @const */ this.p = 5; }",
"function g(/** ?Foo */ f) { return f.p; }"),
NewTypeInference.NULLABLE_DEREFERENCE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"Foo.prototype.p = function(){};",
"function g(/** ?Foo */ f) { f.p(); }"),
NewTypeInference.NULLABLE_DEREFERENCE);
typeCheck(
"var f = 5 ? function() {} : null; f();",
NewTypeInference.NULLABLE_DEREFERENCE);
typeCheck(
"var f = 5 ? function(/** number */ n) {} : null; f('str');",
NewTypeInference.NULLABLE_DEREFERENCE,
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** ?{ p : number } */ o) {",
" goog.asserts.assert(o);",
" return o.p;",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** ?{ p : number } */ o) {",
" goog.asserts.assertObject(o);",
" return o.p;",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** ?Array<string> */ a) {",
" goog.asserts.assertArray(a);",
" return a.length;",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @constructor */ function Foo() {}",
"Foo.prototype.p = function(){};",
"function g(/** ?Foo */ f) {",
" goog.asserts.assertInstanceof(f, Foo);",
" f.p();",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @constructor */ function Foo() {}",
"/** @constructor */ function Bar() {}",
"function g(/** !Bar */ o) {",
" goog.asserts.assertInstanceof(o, Foo);",
"}"),
NewTypeInference.ASSERT_FALSE);
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @constructor */ function Foo() {}",
"function g(/** !Foo */ o) {",
" goog.asserts.assertInstanceof(o, 42);",
"}"),
NewTypeInference.UNKNOWN_ASSERTION_TYPE);
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @constructor */ function Foo() {}",
"function Bar() {}",
"function g(/** !Foo */ o) {",
" goog.asserts.assertInstanceof(o, Bar);",
"}"),
NewTypeInference.UNKNOWN_ASSERTION_TYPE);
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @constructor */ function Foo() {}",
"/** @interface */ function Bar() {}",
"function g(/** !Foo */ o) {",
" goog.asserts.assertInstanceof(o, Bar);",
"}"),
NewTypeInference.UNKNOWN_ASSERTION_TYPE);
}
public void testAsserts() {
typeCheck(
Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** ({ p : string }|null|undefined) */ o) {",
" goog.asserts.assert(o);",
" o.p - 5;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @constructor */ function Foo() {}",
"function f(/** (Array<string>|Foo) */ o) {",
" goog.asserts.assert(o instanceof Array);",
" var /** string */ s = o.length;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @constructor */ function Foo() {}",
"Foo.prototype.p = function(/** number */ x){};",
"function f(/** (function(new:Foo)) */ ctor,",
" /** ?Foo */ o) {",
" goog.asserts.assertInstanceof(o, ctor);",
" o.p('str');",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/**",
" * @template T",
" * @param {T} x",
" */",
"function f(x) {",
" var y = x;",
" goog.asserts.assertInstanceof(y, Foo);",
"}"));
}
public void testDontInferBottom() {
typeCheck(
// Ensure we don't infer bottom for x here
"function f(x) { var /** string */ s; (s = x) - 5; } f(9);",
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testDontInferBottomReturn() {
typeCheck(
// Technically, BOTTOM is correct here, but since using dead code is error prone,
// we'd rather infer f to return TOP (and get a warning).
"function f() { throw ''; } f() - 5;",
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testAssignToInvalidObject() {
typeCheck(
"n.foo = 5; var n;",
// VariableReferenceCheck.EARLY_REFERENCE,
NewTypeInference.PROPERTY_ACCESS_ON_NONOBJECT);
}
public void testAssignmentDoesntFlowWrongInit() {
typeCheck(Joiner.on('\n').join(
"function f(/** number */ n) {",
" n = 'typo';",
" n - 5;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @param {{ n: number }} x */ function f(x) {",
" x.n = 'typo';",
" x.n - 5;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testPossiblyNonexistentProperties() {
typeCheck(Joiner.on('\n').join(
"/** @param {{ n: number }} x */ function f(x) {",
" if (x.p) {",
" return x.p;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @param {{ p : string }} x */ function reqHasPropP(x){}",
"/** @param {{ n: number }} x */ function f(x, cond) {",
" if (cond) {",
" x.p = 'str';",
" }",
" reqHasPropP(x);",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {{ n: number }} x */ function f(x, cond) {",
" if (cond) { x.p = 'str'; }",
" if (x.p) {",
" x.p - 5;",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** { n : number } */ x) {",
" x.s = 'str';",
" return x.inexistentProp;",
"}"),
TypeCheck.INEXISTENT_PROPERTY);
}
public void testDeclaredRecordTypes() {
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: number }} x */ function f(x) {",
" return x.p - 3;",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: string }} x */ function f(x) {",
" return x.p - 3;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {{ 'p': string }} x */ function f(x) {",
" return x.p - 3;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: number }} x */ function f(x) {",
" return x.q;",
"}"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: string }} obj */ function f(obj, x, y) {",
" x < y;",
" x - 5;",
" obj.p < y;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: number }} x */ function f(x) {",
" x.p = 3;",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: number }} x */ function f(x) {",
" x.p = 'str';",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: number }} x */ function f(x) {",
" x.q = 'str';",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: number }} x */ function f(x) {",
" x.q = 'str';",
"}",
"/** @param {{ p: number }} x */ function g(x) {",
" f(x);",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: number }} x */ function f(x) {",
" x.q = 'str';",
" return x.q;",
"}",
"/** @param {{ p: number }} x */ function g(x) {",
" f(x) - 5;",
"}"),
NewTypeInference.INVALID_INFERRED_RETURN_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: number }} x */ function f(x) {",
" x.q = 'str';",
" x.q = 7;",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** { prop: number} */ obj) {",
" obj.prop = 'asdf';",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(/** { prop: number} */ obj, cond) {",
" if (cond) { obj.prop = 123; } else { obj.prop = 234; }",
" obj.prop = 'asdf';",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(/** {p: number} */ x, /** {p: (number|null)} */ y) {",
" var z;",
" if (true) { z = x; } else { z = y; }",
"}"));
typeCheck(Joiner.on('\n').join(
"var /** { a: number } */ obj1 = { a: 321};",
"var /** { a: number, b: number } */ obj2 = obj1;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testSimpleObjectLiterals() {
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: number }} obj */",
"function f(obj) {",
" obj = { p: 123 };",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: number, p2: string }} obj */",
"function f(obj) {",
" obj = { p: 123 };",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: number }} obj */",
"function f(obj) {",
" obj = { p: 'str' };",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"var obj;",
"obj = { p: 123 };",
"obj.p < 'str';"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: number }} obj */",
"function f(obj, x) {",
" obj = { p: x };",
" x < 'str';",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: number }} obj */",
"function f(obj, x) {",
" obj = { p: 123, q: x };",
" obj.q - 5;",
" x < 'str';",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
// An example of how record types can hide away the extra properties and
// allow type misuse.
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: number }} obj */",
"function f(obj) {",
" obj.q = 123;",
"}",
"/** @param {{ p: number, q: string }} obj */",
"function g(obj) { f(obj); }"));
typeCheck(Joiner.on('\n').join(
"/** @param {{ p: number }} obj */",
"function f(obj) {}",
"var obj = {p: 5};",
"if (true) {",
" obj.q = 123;",
"}",
"f(obj);"));
typeCheck(
"function f(/** number */ n) {}; f({});",
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testInferPreciseTypeWithDeclaredUnknown() {
typeCheck(
"var /** ? */ x = 'str'; x - 123;",
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testSimpleLooseObjects() {
typeCheck("function f(obj) { obj.x = 1; obj.x - 5; }");
typeCheck(
"function f(obj) { obj.x = 'str'; obj.x - 5; }",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(obj) {",
" var /** number */ x = obj.p;",
" obj.p < 'str';",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(obj) {",
" var /** @type {{ p: number }} */ x = obj;",
" obj.p < 'str';",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(obj) {",
" obj.x = 1;",
" return obj.x;",
"}",
"f({x: 'str'});"));
typeCheck(Joiner.on('\n').join(
"function f(obj) {",
" obj.x - 1;",
"}",
"f({x: 'str'});"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(obj, cond) {",
" if (cond) {",
" obj.x = 'str';",
" }",
" obj.x - 5;",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(obj) {",
" obj.x - 1;",
" return obj;",
"}",
"var /** string */ s = (f({x: 5})).x;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testNestedLooseObjects() {
typeCheck(Joiner.on('\n').join(
"function f(obj) {",
" obj.a.b = 123;",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(obj) {",
" obj.a.b = 123;",
" obj.a.b < 'str';",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(obj, cond) {",
" (cond ? obj : obj).x - 1;",
" return obj.x;",
"}",
"f({x: 'str'}, true);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(obj) {",
" obj.a.b - 123;",
"}",
"f({a: {b: 'str'}})"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(obj) {",
" obj.a.b = 123;",
"}",
"f({a: {b: 'str'}})"));
typeCheck(Joiner.on('\n').join(
"function f(obj) {",
" var o;",
" (o = obj).x - 1;",
" return o.x;",
"}",
"f({x: 'str'});"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(obj) {",
" ({x: obj.foo}).x - 1;",
"}",
"f({foo: 'str'});"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" ({p: x++}).p = 'str';",
"}",
"f('str');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" ({p: 'str'}).p = x++;",
"}",
"f('str');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x, y, z) {",
" ({p: (y = x++), q: 'str'}).p = z = y;",
" z < 'str';",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testLooseObjectSubtyping() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @constructor */",
"function Bar() {}",
"function f(obj) { obj.prop - 5; }",
"var /** !Foo */ x = new Foo;",
"f(x);",
"var /** !Bar */ y = x;"),
NewTypeInference.INVALID_ARGUMENT_TYPE,
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"function f(obj) { obj.prop - 5; }",
"f(new Foo);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() { /** @type {string} */ this.prop = 'str'; }",
"function f(obj) { obj.prop - 5; }",
"f(new Foo);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() { /** @type {number} */ this.prop = 1; }",
"function g(obj) { var /** string */ s = obj.prop; return obj; }",
"var /** !Foo */ x = g({ prop: '' });"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
// Infer obj.a as loose, don't warn at the call to f.
typeCheck(Joiner.on('\n').join(
"function f(obj) { obj.a.num - 5; }",
"function g(obj) {",
" obj.a.str < 'str';",
" f(obj);",
"}"));
// A loose object is a subtype of Array even if it has a dotted property
typeCheck(Joiner.on('\n').join(
"function f(/** Array<?> */ x) {}",
"function g(obj) {",
" obj.x = 123;",
" f(obj);",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(g) {",
" if (g.randomName) {",
" } else {",
" return g();",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (x.a) {} else {}",
"}",
"f({ b: 123 }); "));
// TODO(dimvar): We could warn about this since x is callable and we're
// passing a non-function, but we don't catch it for now.
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (x.randomName) {",
" } else {",
" return x();",
" }",
"}",
"f({ abc: 123 }); "));
}
public void testUnionOfRecords() {
// The previous type inference doesn't warn because it keeps records
// separate in unions.
// We treat {x:number}|{y:number} as {x:number=, y:number=}
typeCheck(Joiner.on('\n').join(
"/** @param {({x:number}|{y:number})} obj */",
"function f(obj) {}",
"f({x: 5, y: 'asdf'});"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testUnionOfFunctionAndNumber() {
typeCheck("var x = function(/** number */ y){};");
// typeCheck("var x = function(/** number */ y){}; var x = 5",
// VariableReferenceCheck.REDECLARED_VARIABLE);
typeCheck(
"var x = function(/** number */ y){}; x('str');",
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(
"var x = true ? function(/** number */ y){} : 5; x('str');",
TypeCheck.NOT_CALLABLE);
}
public void testAnonymousNominalType() {
typeCheck(Joiner.on('\n').join(
"function f() { return {}; }",
"/** @constructor */",
"f().Foo = function() {};"),
GlobalTypeInfo.ANONYMOUS_NOMINAL_TYPE);
typeCheck(Joiner.on('\n').join(
"var x = {};",
"function f() { return x; }",
"/** @constructor */",
"f().Foo = function() {};",
"new (f().Foo)();"),
GlobalTypeInfo.ANONYMOUS_NOMINAL_TYPE);
}
public void testFoo() {
typeCheck(
"/** @constructor */ function Foo() {}; Foo();",
TypeCheck.CONSTRUCTOR_NOT_CALLABLE);
typeCheck(
"function Foo() {}; new Foo();", NewTypeInference.NOT_A_CONSTRUCTOR);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {};",
"function reqFoo(/** Foo */ f) {};",
"reqFoo(new Foo());"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {};",
"/** @constructor */ function Bar() {};",
"function reqFoo(/** Foo */ f) {};",
"reqFoo(new Bar());"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {};",
"function reqFoo(/** Foo */ f) {};",
"function g() {",
" /** @constructor */ function Foo() {};",
" reqFoo(new Foo());",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @param {number} x */",
"Foo.prototype.method = function(x) {};",
"/** @param {!Foo} x */",
"function f(x) { x.method('asdf'); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testComma() {
typeCheck(
"var x; var /** string */ s = (x = 1, x);",
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" var y = x;",
" y < (123, 'asdf');",
"}",
"f(123);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testTypeof() {
typeCheck("(typeof 'asdf') < 123;", NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" var y = x;",
" y < (typeof 123);",
"}",
"f(123);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (typeof x === 'string') {",
" x - 5;",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (typeof x != 'function') {",
" x - 5;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (typeof x == 'string') {",
" x - 5;",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if ('string' === typeof x) {",
" x - 5;",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (typeof x === 'number') {",
" x < 'asdf';",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (typeof x === 'boolean') {",
" x - 5;",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (typeof x === 'undefined') {",
" x - 5;",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (typeof x === 'function') {",
" x - 5;",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {*} x */",
"function f(x) {",
" if (typeof x === 'function') {",
" x();",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (typeof x === 'object') {",
" x - 5;",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (!(typeof x == 'number')) {",
" x.prop;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (!(typeof x == 'undefined')) {",
" x - 5;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @param {*} x */",
"function f(x) {",
" if (!(typeof x == 'undefined')) {",
" var /** undefined */ y = x;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @param {*} x */",
"function f(x) {",
" if (typeof x !== 'undefined') {",
" var /** undefined */ y = x;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @param {*} x */",
"function f(x) {",
" if (typeof x == 'undefined') {} else {",
" var /** undefined */ y = x;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(/** (number|undefined) */ x) {",
" if (typeof x !== 'undefined') {",
" x - 5;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f() {",
" return (typeof 123 == 'number' ||",
" typeof 123 == 'string' ||",
" typeof 123 == 'boolean' ||",
" typeof 123 == 'undefined' ||",
" typeof 123 == 'function' ||",
" typeof 123 == 'object' ||",
" typeof 123 == 'unknown');",
"}"));
typeCheck(
"function f(){ if (typeof 123 == 'numbr') return 321; }",
TypeValidator.UNKNOWN_TYPEOF_VALUE);
typeCheck(
"switch (typeof 123) { case 'foo': }",
TypeValidator.UNKNOWN_TYPEOF_VALUE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @param {(number|null|Foo)} x */",
"function f(x) {",
" if (!(typeof x === 'object')) {",
" var /** number */ n = x;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @param {(number|function(number):number)} x */",
"function f(x) {",
" if (!(typeof x === 'function')) {",
" var /** number */ n = x;",
" }",
"}"));
}
public void testAssignWithOp() {
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" var y = x, z = 0;",
" y < (z -= 123);",
"}",
"f('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" var y = x, z = { prop: 0 };",
" y < (z.prop -= 123);",
"}",
"f('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" var z = { prop: 0 };",
" x < z.prop;",
" z.prop -= 123;",
"}",
"f('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck("var x = 0; x *= 'asdf';", NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(
"var /** string */ x = 'asdf'; x *= 123;",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck("var x; x *= 123;", NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testClassConstructor() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {",
" /** @type {number} */ this.n = 5;",
"};",
"(new Foo()).n - 5;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {",
" /** @type {number} */ this.n = 5;",
"};",
"(new Foo()).n = 'str';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {",
" /** @type {number} */ this.n;",
"};",
"(new Foo()).n = 'str';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f() { (new Foo()).n = 'str'; }",
"/** @constructor */ function Foo() {",
" /** @type {number} */ this.n = 5;",
"};"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f() { var x = new Foo(); x.n = 'str'; }",
"/** @constructor */ function Foo() {",
" /** @type {number} */ this.n = 5;",
"};"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f() { var x = new Foo(); return x.n - 5; }",
"/** @constructor */ function Foo() {",
" this.n = 5;",
"};"));
typeCheck(Joiner.on('\n').join(
"function f() { var x = new Foo(); x.s = 'str'; x.s < x.n; }",
"/** @constructor */ function Foo() {",
" /** @type {number} */ this.n = 5;",
"};"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {",
" /** @type {number} */ this.n = 5;",
"};",
"function reqFoo(/** Foo */ x) {};",
"reqFoo({ n : 20 });"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f() { var x = new Foo(); x.n - 5; x.n < 'str'; }",
"/** @constructor */ function Foo() {",
" this.n = 5;",
"};"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testPropertyDeclarations() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @type {number} */ this.x = 'abc';",
" /** @type {string} */ this.x = 'def';",
"}"),
GlobalTypeInfo.REDECLARED_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @type {number} */ this.x = 5;",
" /** @type {number} */ this.x = 7;",
"}"),
GlobalTypeInfo.REDECLARED_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" this.x = 5;",
" /** @type {number} */ this.x = 7;",
"}",
"function g() { (new Foo()).x < 'str'; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @type {number} */ this.x = 7;",
" this.x = 5;",
"}",
"function g() { (new Foo()).x < 'str'; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @type {number} */ this.x = 7;",
" this.x < 'str';",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @type {?} */ this.x = 1;",
" /** @type {?} */ this.x = 1;",
"}"),
GlobalTypeInfo.REDECLARED_PROPERTY);
}
public void testPrototypePropertyAssignments() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @type {string} */ Foo.prototype.x = 'str';",
"function g() { (new Foo()).x - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"Foo.prototype.x = 'str';",
"function g() { var f = new Foo(); f.x - 5; f.x < 'str'; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @type {function(string)} s */",
"Foo.prototype.bar = function(s) {};",
"function g() { (new Foo()).bar(5); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {};",
"Foo.prototype.bar = function(s) {",
" /** @type {string} */ this.x = 'str';",
"};",
"(new Foo()).x - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"(function() { Foo.prototype.prop = 123; })();"),
GlobalTypeInfo.CTOR_IN_DIFFERENT_SCOPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function F() {}",
"F.prototype.bar = function() {};",
"F.prototype.bar = function() {};"),
GlobalTypeInfo.REDECLARED_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function F() {}",
"/** @return {void} */ F.prototype.bar = function() {};",
"F.prototype.bar = function() {};"),
GlobalTypeInfo.REDECLARED_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function C(){}",
"C.prototype.foo = {};",
"C.prototype.method = function() { this.foo.bar = 123; }"));
// TODO(dimvar): I think we can fix the next one with better deferred checks
// for prototype methods. Look into it.
// typeCheck(Joiner.on('\n').join(
// "/** @constructor */ function Foo() {};",
// "Foo.prototype.bar = function(s) { s < 'asdf'; };",
// "function g() { (new Foo()).bar(5); }"),
// NewTypeInference.INVALID_ARGUMENT_TYPE);
// TODO(blickly): Add fancier JSDoc annotation finding to jstypecreator
// typeCheck(Joiner.on('\n').join(
// "/** @constructor */ function Foo() {};",
// "/** @param {string} s */ Foo.prototype.bar = function(s) {};",
// "function g() { (new Foo()).bar(5); }"),
// NewTypeInference.INVALID_ARGUMENT_TYPE);
// typeCheck(Joiner.on('\n').join(
// "/** @constructor */ function Foo() {};",
// "Foo.prototype.bar = function(/** string */ s) {};",
// "function g() { (new Foo()).bar(5); }"),
// NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f() {}",
"function g() { f.prototype.prop = 123; }"));
typeCheck(Joiner.on('\n').join(
"/** @param {!Function} f */",
"function foo(f) { f.prototype.bar = function(x) {}; }"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prototype.method = function() {};",
"/** @type {number} */",
"Foo.prototype.method.pnum = 123;",
"var /** number */ n = Foo.prototype['method.pnum'];"),
TypeCheck.INEXISTENT_PROPERTY);
}
public void testPrototypeAssignment() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prototype = { a: 1, b: 2 };",
"var x = (new Foo).a;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prototype = { a: 1, b: 2 - 'asdf' };",
"var x = (new Foo).a;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prototype = { a: 1, /** @const */ b: 2 };",
"(new Foo).b = 3;"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prototype = { method: function(/** number */ x) {} };",
"(new Foo).method('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prototype = { method: function(/** number */ x) {} };",
"/** @constructor @extends {Foo} */",
"function Bar() {}",
"(new Bar).method('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testAssignmentsToPrototype() {
// TODO(dimvar): the 1st should pass, the 2nd we may stop catching
// if we decide to not check these assignments at all.
// typeCheck(Joiner.on('\n').join(
// "/** @constructor */",
// "function Foo() {}",
// "/** @constructor @extends {Foo} */",
// "function Bar() {}",
// "Bar.prototype = new Foo;",
// "Bar.prototype.method1 = function() {};"));
// typeCheck(Joiner.on('\n').join(
// "/**",
// " * @constructor",
// " * @struct",
// " */",
// "function Bar() {}",
// "Bar.prototype = {};"),
// TypeCheck.CONFLICTING_SHAPE_TYPE);
}
public void testConflictingPropertyDefinitions() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() { this.x = 'str1'; };",
"/** @type {string} */ Foo.prototype.x = 'str2';",
"(new Foo).x - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @type {string} */ Foo.prototype.x = 'str1';",
"Foo.prototype.x = 'str2';",
"(new Foo).x - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"Foo.prototype.x = 'str2';",
"/** @type {string} */ Foo.prototype.x = 'str1';",
"(new Foo).x - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() { /** @type {string} */ this.x = 'str1'; };",
"Foo.prototype.x = 'str2';",
"(new Foo).x - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() { this.x = 5; };",
"/** @type {string} */ Foo.prototype.x = 'str';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() { /** @type {string} */ this.x = 'str1'; };",
"Foo.prototype.x = 5;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() { /** @type {string} */ this.x = 'str'; };",
"/** @type {number} */ Foo.prototype.x = 'str';"),
GlobalTypeInfo.REDECLARED_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @type {number} */ Foo.prototype.x = 1;",
"/** @type {number} */ Foo.prototype.x = 2;"),
GlobalTypeInfo.REDECLARED_PROPERTY);
}
public void testPrototypeAliasing() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"Foo.prototype.x = 'str';",
"var fp = Foo.prototype;",
"fp.x - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testInstanceof() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"function takesFoos(/** Foo */ afoo) {}",
"function f(/** (number|Foo) */ x) {",
" takesFoos(x);",
" if (x instanceof Foo) { takesFoos(x); }",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(
"({} instanceof function(){});", NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"(123 instanceof Foo);"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"({} instanceof (true || Foo))"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"function takesFoos(/** Foo */ afoo) {}",
"function f(/** (number|Foo) */ x) {",
" if (x instanceof Foo) { takesFoos(x); }",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"function f(/** (number|!Foo) */ x) {",
" if (x instanceof Foo) {} else { x - 5; }",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"function f(/** (number|!Foo) */ x) {",
" if (!(x instanceof Foo)) { x - 5; }",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @constructor */ function Bar() {}",
"function takesFoos(/** Foo */ afoo) {}",
"function f(/** Foo */ x) {",
" if (x instanceof Bar) {} else { takesFoos(x); }",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"function takesFoos(/** Foo */ afoo) {}",
"/** @param {*} x */ function f(x) {",
" takesFoos(x);",
" if (x instanceof Foo) { takesFoos(x); }",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"var x = new Foo();",
"x.bar = 'asdf';",
"if (x instanceof Foo) { x.bar - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
// typeCheck(
// "function f(x) { if (x instanceof UndefinedClass) {} }",
// VarCheck.UNDEFINED_VAR_ERROR);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() { this.prop = 123; }",
"function f(x) { x = 123; if (x instanceof Foo) { x.prop; } }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @constructor @extends {Foo} */ function Bar() {}",
"/** @param {(number|!Bar)} x */",
"function f(x) {",
" if (!(x instanceof Foo)) {",
" var /** number */ n = x;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @enum {!Foo} */",
"var E = { ONE: new Foo };",
"/** @param {(number|E)} x */",
"function f(x) {",
" if (!(x instanceof Foo)) {",
" var /** number */ n = x;",
" }",
"}"));
}
public void testFunctionsExtendFunction() {
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (x instanceof Function) { x(); }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (x instanceof Function) { x(1); x('str') }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** (null|function()) */ x) {",
" if (x instanceof Function) { x(); }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** (null|function()) */ x) {",
" if (x instanceof Function) {} else { x(); }",
"}"),
TypeCheck.NOT_CALLABLE);
typeCheck("(function(){}).call(null);");
typeCheck(Joiner.on('\n').join(
"function greet(name) {}",
"greet.call(null, 'bob');",
"greet.apply(null, ['bob']);"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"Foo.prototype.greet = function(name){};",
"Foo.prototype.greet.call(new Foo, 'bob');"));
typeCheck(Joiner.on('\n').join(
"Function.prototype.method = function(/** string */ x){};",
"(function(){}).method(5);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(value) {",
" if (value instanceof Function) {} else if (value instanceof Object) {",
" return value.displayName || value.name || '';",
" }",
"};"));
}
public void testObjectsAreNotClassy() {
typeCheck(Joiner.on('\n').join(
"function g(obj) {",
" if (!(obj instanceof Object)) { throw -1; }",
" return obj.x - 5;",
"}",
"g(new Object);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testFunctionWithProps() {
typeCheck(Joiner.on('\n').join(
"function f() {}",
"f.x = 'asdf';",
"f.x - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testConstructorProperties() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @type {number} */ Foo.n = 1",
"/** @type {number} */ Foo.n = 1"),
GlobalTypeInfo.REDECLARED_PROPERTY);
typeCheck(Joiner.on('\n').join(
"function g() { Foo.bar - 5; }",
"/** @constructor */ function Foo() {}",
"Foo.bar = 42;"));
typeCheck(Joiner.on('\n').join(
"function g() { Foo.bar - 5; }",
"/** @constructor */ function Foo() {}",
"/** @type {string} */ Foo.bar = 'str';"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function g() { return (new Foo).bar; }",
"/** @constructor */ function Foo() {}",
"/** @type {string} */ Foo.bar = 'str';"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @type {string} */ Foo.prop = 'asdf';",
"var x = Foo;",
"x.prop - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function g() { Foo.prototype.baz = (new Foo).bar + Foo.bar; }",
"/** @constructor */ function Foo() {}",
"/** @type {number} */ Foo.prototype.bar = 5",
"/** @type {string} */ Foo.bar = 'str';"),
GlobalTypeInfo.CTOR_IN_DIFFERENT_SCOPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @type {number} */ Foo.n = 1;",
"Foo.n = 1;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @type {number} */ Foo.n;",
"Foo.n = '';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testTypeTighteningHeuristic() {
typeCheck(
"/** @param {*} x */ function f(x) { var /** ? */ y = x; x - 5; }",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** ? */ x) {",
" if (!(typeof x == 'number')) {",
" x < 'asdf';",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** { prop: ? } */ x) {",
" var /** (number|string) */ y = x.prop;",
" x.prop < 5;",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** (number|string) */ x, /** (number|string) */ y) {",
" var z;",
" if (1 < 2) {",
" z = x;",
" } else {",
" z = y;",
" }",
" z - 5;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testDeclaredPropertyIndirectly() {
typeCheck(Joiner.on('\n').join(
"function f(/** { n: number } */ obj) {",
" var o2 = obj;",
" o2.n = 'asdf';",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testNonRequiredArguments() {
typeCheck(Joiner.on('\n').join(
"function f(f1, /** function(string=) */ f2, cond) {",
" var y;",
" if (cond) {",
" f1();",
" y = f1;",
" } else {",
" y = f2;",
" }",
" return y;",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** ...number */ fnum) {}",
"f(); f(1, 2, 3); f(1, 2, 'asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(
"function f(/** number= */ x, /** number */ y) {}",
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"function f(/** number= */ x) {}",
"f(); f('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** number= */ x) {}",
"f(1, 2);"),
TypeCheck.WRONG_ARGUMENT_COUNT);
typeCheck(Joiner.on('\n').join(
"/** @param {function(...number)} fnum */",
"function f(fnum) {",
" fnum(); fnum(1, 2, 3, 'asdf');",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {function(number=, number)} g */",
"function f(g) {}"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"/** @param {number=} x */",
"function f(x) {}",
"f(); f('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {number=} x */",
"function f(x) {}",
"f(1, 2);"),
TypeCheck.WRONG_ARGUMENT_COUNT);
typeCheck(
"/** @type {number|function()} */ function f(x) {}",
GlobalTypeInfo.WRONG_PARAMETER_COUNT);
typeCheck(
"/** @type {number|function(number)} */ function f() {}",
GlobalTypeInfo.WRONG_PARAMETER_COUNT);
typeCheck(
"/** @type {function(number)} */ function f(/** number */ x) {}");
typeCheck(Joiner.on('\n').join(
"/**",
" * @param {number=} x",
" * @param {number} y",
" */",
"function f(x, y) {}"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"/** @type {function(number=)} */ function f(x) {}",
"f(); f('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(
"/** @type {function(number=, number)} */ function f(x, y) {}",
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(
"function /** number */ f() { return 'asdf'; }",
NewTypeInference.RETURN_NONDECLARED_TYPE);
typeCheck(
"/** @return {number} */ function /** number */ f() { return 1; }",
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(
"/** @type {function(): number} */ function /** number */ f() { return 1; }");
typeCheck(Joiner.on('\n').join(
"/** @type {function(...number)} */ function f() {}",
"f(); f(1, 2, 3); f(1, 2, 'asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {...number} var_args */ function f(var_args) {}",
"f(); f(1, 2, 3); f(1, 2, 'asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(
"/** @type {function(...number)} */ function f(x) {}");
typeCheck(Joiner.on('\n').join(
"/**",
" * @param {...number} var_args",
" * @param {number=} x",
" */",
"function f(var_args, x) {}"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"/** @type {function(number=, ...number)} */",
"function f(x) {}",
"f('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** function(number=) */ fnum,",
" /** function(string=) */ fstr, cond) {",
" var y;",
" if (cond) {",
" y = fnum;",
" } else {",
" y = fstr;",
" }",
" y();",
" y(123);",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** function(...number) */ fnum,",
" /** function(...string) */ fstr, cond) {",
" var y;",
" if (cond) {",
" y = fnum;",
" } else {",
" y = fstr;",
" }",
" y();",
" y(123);",
"}"),
TypeCheck.NOT_CALLABLE,
TypeCheck.NOT_CALLABLE);
typeCheck(Joiner.on('\n').join(
"function f(",
" /** function() */ f1, /** function(string=) */ f2, cond) {",
" var y;",
" if (cond) {",
" y = f1;",
" } else {",
" y = f2;",
" }",
" y(123);",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {function(string): *} x */ function g(x) {}",
"/** @param {function(...number): string} x */ function f(x) {",
" g(x);",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @param {number=} x",
" * @param {number=} y",
" */",
"function f(x, y) {}",
"f(undefined, 123);",
"f('str')"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** function(...) */ fun) {}",
"f(function() {});"));
// The restarg formal doesn't have to be called var_args.
// It shouldn't be used in the body of the function.
// typeCheck(
// "/** @param {...number} x */ function f(x) { x - 5; }",
// VarCheck.UNDEFINED_VAR_ERROR);
typeCheck(
"/** @param {number=} x */ function f(x) { x - 5; }",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(
"/** @param {number=} x */ function f(x) { if (x) { x - 5; } }");
typeCheck(Joiner.on('\n').join(
"function f(/** function(...number) */ x) {}",
"f(function() {});"));
typeCheck(Joiner.on('\n').join(
"function f(/** function() */ x) {}",
"f(/** @type {function(...number)} */ (function(nums) {}));"));
typeCheck(Joiner.on('\n').join(
"function f(/** function(string=) */ x) {}",
"f(/** @type {function(...number)} */ (function(nums) {}));"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** function(...number) */ x) {}",
"f(/** @type {function(string=)} */ (function(x) {}));"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {number} opt_num */ function f(opt_num) {}",
"f();"));
typeCheck(
"function f(opt_num, x) {}", RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck("function f(var_args) {} f(1, 2, 3);");
typeCheck(
"function f(var_args, x) {}", RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
}
public void testInferredOptionalFormals() {
typeCheck("function f(x) {} f();");
typeCheck("function f(/** number */ x, y) { x-5; } f(123);");
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (x !== undefined) {",
" return x-5;",
" } else {",
" return 0;",
" }",
"}",
"f() - 1;",
"f('str');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @return {function(number=)} */",
"function f() {",
" return function(x) {};",
"}",
"f()();",
"f()('str');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testSimpleClassInheritance() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Parent() {}",
"/** @constructor @extends{Parent} */",
"function Child() {}",
"Child.prototype = new Parent();"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Parent() {",
" /** @type {string} */ this.prop = 'asdf';",
"}",
"/** @constructor @extends{Parent} */",
"function Child() {}",
"Child.prototype = new Parent();",
"(new Child()).prop - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Parent() {",
" /** @type {string} */ this.prop = 'asdf';",
"}",
"/** @constructor @extends{Parent} */",
"function Child() {}",
"Child.prototype = new Parent();",
"(new Child()).prop = 5;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Parent() {}",
"/** @type {string} */ Parent.prototype.prop = 'asdf';",
"/** @constructor @extends{Parent} */",
"function Child() {}",
"Child.prototype = new Parent();",
"(new Child()).prop - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Parent() {}",
"/** @type {string} */ Parent.prototype.prop = 'asdf';",
"/** @constructor @extends{Parent} */",
"function Child() {",
" /** @type {number} */ this.prop = 5;",
"}",
"Child.prototype = new Parent();"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Parent() {}",
"/** @type {string} */ Parent.prototype.prop = 'asdf';",
"/** @constructor @extends{Parent} */",
"function Child() {}",
"Child.prototype = new Parent();",
"/** @type {number} */ Child.prototype.prop = 5;"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE,
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Parent() {}",
"/** @extends {Parent} */ function Child() {}"),
JSTypeCreatorFromJSDoc.EXTENDS_NOT_ON_CTOR_OR_INTERF);
typeCheck(
"/** @constructor @extends{number} */ function Foo() {}",
JSTypeCreatorFromJSDoc.EXTENDS_NON_OBJECT);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @implements {string}",
" */",
"function Foo() {}"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"/**",
" * @interface",
" * @extends {number}",
" */",
"function Foo() {}"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Foo() {}",
"/** @implements {Foo} */ function bar() {}"),
JSTypeCreatorFromJSDoc.IMPLEMENTS_WITHOUT_CONSTRUCTOR);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prototype.method = function(x) { x - 1; };",
"/** @constructor @extends {Foo} */",
"function Bar() {}",
"Bar.prototype.method = function(x, y) { x - y; };",
"Bar.prototype.method2 = function(x, y) {};",
"Bar.prototype.method = Bar.prototype.method2;"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
}
public void testInheritingTheParentClassInterfaces() {
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function High() {}",
"/** @type {number} */",
"High.prototype.p;",
"/** @constructor @implements {High} */",
"function Mid() {}",
"Mid.prototype.p = 123;",
// Low has p from Mid, no warning here
"/** @constructor @extends {Mid} */",
"function Low() {}"));
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function High() {}",
"/** @constructor @implements {High} */",
"function Mid() {}",
"/** @constructor @extends {Mid} */",
"function Low() {}",
"var /** !High */ x = new Low();"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @interface",
" * @template T",
" */",
"function High() {}",
"/**",
" * @constructor",
" * @template T",
" * @implements {High<T>}",
" */",
"function Mid() {}",
"/** @constructor @extends {Mid<number>} */",
"function Low() {}",
"var /** !High<string> */ x = new Low;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testInheritanceSubtyping() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Parent() {}",
"/** @constructor @extends{Parent} */ function Child() {}",
"(function(/** Parent */ x) {})(new Child);"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Parent() {}",
"/** @constructor @extends{Parent} */ function Child() {}",
"(function(/** Child */ x) {})(new Parent);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Parent() {}",
"/** @constructor @extends{Parent} */ function Child() {}",
"/** @constructor */",
"function Foo() { /** @type {Parent} */ this.x = new Child(); }",
"/** @type {Child} */ Foo.prototype.y = new Parent();"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function High() {}",
"/** @constructor @implements {High} */",
"function Low() {}",
"var /** !High */ x = new Low"));
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function High() {}",
"/** @interface @extends {High}*/",
"function Low() {}",
"function f(/** !High */ h, /** !Low */ l) { h = l; }"));
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function High() {}",
"/** @interface @extends {High}*/",
"function Low() {}",
"/** @constructor @implements {Low} */",
"function Foo() {}",
"var /** !High */ x = new Foo;"));
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function Foo() {}",
"/** @interface */",
"function High() {}",
"/** @interface @extends {High} */",
"function Med() {}",
"/**",
" * @interface",
" * @extends {Med}",
" * @extends {Foo}",
" */",
"function Low() {}",
"function f(/** !High */ x, /** !Low */ y) { x = y }"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @interface",
" * @template T",
" */",
"function Foo() {}",
"function f(/** !Foo<number> */ x, /** !Foo<string> */ y) { x = y; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @interface",
" * @template T",
" */",
"function Foo() {}",
"/**",
" * @constructor",
" * @implements {Foo<number>}",
" */",
"function Bar() {}",
"function f(/** !Foo<string> */ x, /** Bar */ y) { x = y; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @interface",
" * @template T",
" */",
"function Foo() {}",
"/**",
" * @constructor",
" * @template T",
" * @implements {Foo<T>}",
" */",
"function Bar() {}",
"function f(/** !Foo<string> */ x, /** !Bar<number> */ y) { x = y; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @interface",
" * @template T",
" */",
"function Foo() {}",
"/**",
" * @constructor",
" * @template T",
" * @implements {Foo<T>}",
" */",
"function Bar() {}",
"function f(/** !Foo<string> */ x, /** !Bar<string> */ y) {",
" x = y;",
"}"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @interface",
" * @template T",
" */",
"function Foo() {}",
"/**",
" * @constructor",
" * @template T",
" * @implements {Foo<T>}",
" */",
"function Bar() {}",
"/**",
" * @template T",
" * @param {!Foo<T>} x",
" * @param {!Bar<number>} y",
" */",
"function f(x, y) { x = y; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
// When getting a method signature from the parent, the receiver type is
// still the child's type.
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function High() {}",
"/** @param {number} x */",
"High.prototype.method = function (x) {};",
"/** @constructor @implements {High} */",
"function Low() {}",
"Low.prototype.method = function (x) {",
" var /** !Low */ y = this;",
"};"));
}
public void testInheritanceImplicitObjectSubtyping() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @override */ Foo.prototype.toString = function(){ return ''; };"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @override */ Foo.prototype.toString = function(){ return 5; };"),
NewTypeInference.RETURN_NONDECLARED_TYPE);
}
public void testRecordtypeSubtyping() {
// TODO(dimvar): fix
// typeCheck(Joiner.on('\n').join(
// "/** @interface */ function I() {}",
// "/** @type {number} */ I.prototype.prop;",
// "function f(/** !I */ x) {",
// " var /** { prop: number} */ y = x;",
// "}"));
}
public void testWarnAboutOverridesNotVisibleDuringGlobalTypeInfo() {
typeCheck(Joiner.on('\n').join(
"/** @constructor @extends {Parent} */ function Child() {}",
"/** @type {string} */ Child.prototype.y = 'str';",
"/** @constructor */ function Grandparent() {}",
"/** @type {number} */ Grandparent.prototype.y = 9;",
"/** @constructor @extends {Grandparent} */ function Parent() {}"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
}
public void testInvalidMethodPropertyOverride() {
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/** @type {number} */ Parent.prototype.y;",
"/** @constructor @implements {Parent} */ function Child() {}",
"/** @param {string} x */ Child.prototype.y = function(x) {};"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/** @param {string} x */ Parent.prototype.y = function(x) {};",
"/** @constructor @implements {Parent} */ function Child() {}",
"/** @type {number} */ Child.prototype.y = 9;"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Parent() {}",
"/** @type {number} */ Parent.prototype.y = 9;",
"/** @constructor @extends {Parent} */ function Child() {}",
"/** @param {string} x */ Child.prototype.y = function(x) {};"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Parent() {}",
"/** @param {string} x */ Parent.prototype.y = function(x) {};",
"/** @constructor @extends {Parent} */ function Child() {}",
"/** @type {number} */ Child.prototype.y = 9;"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
// TODO(dimvar): fix
// typeCheck(Joiner.on('\n').join(
// "/** @constructor */",
// "function Foo() {}",
// "Foo.prototype.f = function(/** number */ x, /** number */ y) {};",
// "/** @constructor @extends {Foo} */",
// "function Bar() {}",
// "/** @override */",
// "Bar.prototype.f = function(x) {};"),
// GlobalTypeInfo.INVALID_PROP_OVERRIDE);
}
public void testMultipleObjects() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @constructor */ function Bar() {}",
"/** @param {(Foo|Bar)} x */ function reqFooBar(x) {}",
"function f(cond) {",
" reqFooBar(cond ? new Foo : new Bar);",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @constructor */ function Bar() {}",
"/** @param {Foo} x */ function reqFoo(x) {}",
"function f(cond) {",
" reqFoo(cond ? new Foo : new Bar);",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @constructor */ function Bar() {}",
"/** @param {(Foo|Bar)} x */ function g(x) {",
" if (x instanceof Foo) {",
" var /** Foo */ y = x;",
" } else {",
" var /** Bar */ z = x;",
" }",
" var /** Foo */ w = x;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() { /** @type {string} */ this.s = 'str'; }",
"/** @param {(!Foo|{n:number, s:string})} x */ function g(x) {",
" if (x instanceof Foo) {",
" } else {",
" x.s - 5;",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @type {number} */ Foo.prototype.n = 5;",
"/** @param {{n : number}} x */ function reqRecord(x) {}",
"function f() {",
" reqRecord(new Foo);",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @type {number} */ Foo.prototype.n = 5;",
"/** @param {{n : string}} x */ function reqRecord(x) {}",
"function f() {",
" reqRecord(new Foo);",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @param {{n : number}|!Foo} x */",
"function f(x) {",
" x.n - 5;",
"}"),
NewTypeInference.POSSIBLY_INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @param {{n : number}|!Foo} x */",
"function f(x) {",
" x.abc - 5;",
"}"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @constructor */ function Bar() {}",
"/** @param {!Bar|!Foo} x */",
"function f(x) {",
" x.abc = 'str';",
" if (x instanceof Foo) {",
" x.abc - 5;",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testMultipleFunctionsInUnion() {
typeCheck(Joiner.on('\n').join(
"/** @param {function():string | function():number} x",
" * @return {string|number} */",
"function f(x) {",
" return x();",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @param {function(string)|function(number)} x",
" * @param {string|number} y */",
"function f(x, y) {",
" x(y);",
"}"),
JSTypeCreatorFromJSDoc.UNION_IS_UNINHABITABLE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template S, T",
" * @param {function(S):void | function(T):void} fun",
" */",
"function f(fun) {}"),
JSTypeCreatorFromJSDoc.UNION_IS_UNINHABITABLE);
}
public void testPrototypeOnNonCtorFunction() {
typeCheck("function Foo() {}; Foo.prototype.y = 5;");
typeCheck(Joiner.on('\n').join(
"function f(/** Function */ x) {",
" var y = x != null ? x.prototype : null;",
"}"));
}
public void testInvalidTypeReference() {
typeCheck(
"/** @type {gibberish} */ var x;",
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
typeCheck(
"/** @param {gibberish} x */ function f(x){};",
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
typeCheck(
"function f(/** gibberish */ x){};",
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
typeCheck(Joiner.on('\n').join(
"/** @returns {gibberish} */",
"function f(x) { return x; };"),
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
typeCheck(
"/** @interface @extends {gibberish} */ function Foo(){};",
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
typeCheck(
"/** @constructor @implements {gibberish} */ function Foo(){};",
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
typeCheck(
"/** @constructor @extends {gibberish} */ function Foo() {};",
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
}
public void testCircularDependencies() {
typeCheck(Joiner.on('\n').join(
"/** @constructor @extends {Bar}*/ function Foo() {}",
"/** @constructor */ function Bar() {}"));
typeCheck(Joiner.on('\n').join(
"/** @param {Foo} x */ function f(x) {}",
"/** @constructor */ function Foo() {}"));
typeCheck(Joiner.on('\n').join(
"f(new Bar)",
"/** @param {Foo} x */ function f(x) {}",
"/** @constructor */ function Foo() {}",
"/** @constructor */ function Bar() {}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor @param {Foo} x */ function Bar(x) {}",
"/** @constructor @param {Bar} x */ function Foo(x) {}",
"new Bar(new Foo(null));"));
typeCheck(Joiner.on('\n').join(
"/** @constructor @param {Foo} x */ function Bar(x) {}",
"/** @constructor @param {Bar} x */ function Foo(x) {}",
"new Bar(new Foo(undefined));"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor @extends {Bar} */ function Foo() {}",
"/** @constructor @extends {Foo} */ function Bar() {}"),
JSTypeCreatorFromJSDoc.INHERITANCE_CYCLE);
typeCheck(Joiner.on('\n').join(
"/** @interface @extends {Bar} */ function Foo() {}",
"/** @interface @extends {Foo} */ function Bar() {}"),
JSTypeCreatorFromJSDoc.INHERITANCE_CYCLE);
typeCheck(
"/** @constructor @extends {Foo} */ function Foo() {}",
JSTypeCreatorFromJSDoc.INHERITANCE_CYCLE);
}
public void testInvalidInitOfInterfaceProps() throws Exception {
typeCheck(Joiner.on('\n').join(
"/** @interface */ function T() {};",
"T.prototype.x = function() { return 'foo'; }"),
TypeCheck.INTERFACE_METHOD_NOT_EMPTY);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function I() {};",
"/** @type {number} */",
"I.prototype.n = 123;"),
GlobalTypeInfo.INVALID_INTERFACE_PROP_INITIALIZER);
}
public void testInterfaceSingleInheritance() {
typeCheck(Joiner.on('\n').join(
"/** @interface */ function I() {}",
"/** @type {string} */ I.prototype.prop;",
"/** @constructor @implements{I} */ function C() {}"),
TypeValidator.INTERFACE_METHOD_NOT_IMPLEMENTED);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function I() {}",
"/** @param {number} x */",
"I.prototype.method = function(x) {};",
"/** @constructor @implements{I} */ function C() {}"),
TypeValidator.INTERFACE_METHOD_NOT_IMPLEMENTED);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function IParent() {}",
"/** @type {number} */ IParent.prototype.prop;",
"/** @interface @extends{IParent} */ function IChild() {}",
"/** @constructor @implements{IChild} */",
"function C() { this.prop = 5; }",
"(new C).prop < 'adsf';"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function IParent() {}",
"/** @type {number} */ IParent.prototype.prop;",
"/** @interface @extends{IParent} */ function IChild() {}",
"/** @constructor @implements{IChild} */",
"function C() { this.prop = 'str'; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Parent() { /** @type {number} */ this.prop = 123; }",
"/** @constructor @extends {Parent} */ function Child() {}",
"(new Child).prop = 321;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Parent() { /** @type {number} */ this.prop = 123; }",
"/** @constructor @extends {Parent} */ function Child() {}",
"(new Child).prop = 'str';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function I() {}",
"/** @param {number} x */",
"I.prototype.method = function(x, y) {};",
"/** @constructor @implements{I} */ function C() {}",
"/** @param {string} y */",
"C.prototype.method = function(x, y) {};",
"(new C).method(5, 6);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function I() {}",
"/** @param {number} x */",
"I.prototype.method = function(x, y) {};",
"/** @constructor @implements{I} */ function C() {}",
"/** @param {string} y */",
"C.prototype.method = function(x, y) {};",
"(new C).method('asdf', 'fgr');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function I() {}",
"/** @param {number} x */",
"I.prototype.method = function(x) {};",
"/** @constructor @implements{I} */ function C() {}",
"C.prototype.method = function(x) {};",
"(new C).method('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function I1() {}",
"/** @param {number} x */ I1.prototype.method = function(x, y) {};",
"/** @interface */ function I2() {}",
"/** @param {string} y */ I2.prototype.method = function(x, y) {};",
"/** @constructor @implements{I1} @implements{I2} */ function C(){}",
"C.prototype.method = function(x, y) {};",
"(new C).method('asdf', 'fgr');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function I1() {}",
"/** @param {number} x */ I1.prototype.method = function(x, y) {};",
"/** @interface */ function I2() {}",
"/** @param {string} y */ I2.prototype.method = function(x, y) {};",
"/** @constructor @implements{I1} @implements{I2} */ function C(){}",
"C.prototype.method = function(x, y) {};",
"(new C).method(1, 2);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function I1() {}",
"/** @param {number} x */ I1.prototype.method = function(x) {};",
"/** @interface */ function I2() {}",
"/** @param {string} x */ I2.prototype.method = function(x) {};",
"/** @constructor @implements{I1} @implements{I2} */ function C(){}",
// Type of C.method is @param {(string|number)}
"C.prototype.method = function(x) {};"));
typeCheck(Joiner.on('\n').join(
"/** @interface */ function I1() {}",
"/** @param {number} x */ I1.prototype.method = function(x) {};",
"/** @interface */ function I2() {}",
"/** @param {string} x */ I2.prototype.method = function(x) {};",
"/** @constructor @implements{I1} @implements{I2} */ function C(){}",
// Type of C.method is @param {(string|number)}
"C.prototype.method = function(x) {};",
"(new C).method(true);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function I() {}",
"/** @param {number} x */ I.prototype.method = function(x) {};",
"/** @constructor */ function S() {}",
"/** @param {string} x */ S.prototype.method = function(x) {};",
"/** @constructor @implements{I} @extends{S} */ function C(){}",
// Type of C.method is @param {(string|number)}
"C.prototype.method = function(x) {};",
"(new C).method(true);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testInterfaceMultipleInheritanceNoCrash() {
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function I1() {}",
"I1.prototype.method = function(x) {};",
"/** @interface */",
"function I2() {}",
"I2.prototype.method = function(x) {};",
"/**",
" * @interface",
" * @extends {I1}",
" * @extends {I2}",
" */",
"function I3() {}",
"/** @constructor @implements {I3} */",
"function Foo() {}",
"Foo.prototype.method = function(x) {};"));
}
public void testInterfaceArgument() {
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function I() {}",
"/** @param {number} x */",
"I.prototype.method = function(x) {};",
"/** @param {!I} x */",
"function foo(x) { x.method('asdf'); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function IParent() {}",
"/** @param {number} x */",
"IParent.prototype.method = function(x) {};",
"/** @interface @extends {IParent} */",
"function IChild() {}",
"/** @param {!IChild} x */",
"function foo(x) { x.method('asdf'); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testExtendedInterfacePropertiesCompatibility() {
typeCheck(Joiner.on('\n').join(
"/** @interface */function Int0() {};",
"/** @interface */function Int1() {};",
"/** @type {number} */",
"Int0.prototype.foo;",
"/** @type {string} */",
"Int1.prototype.foo;",
"/** @interface \n @extends {Int0} \n @extends {Int1} */",
"function Int2() {};"),
TypeCheck.INCOMPATIBLE_EXTENDED_PROPERTY_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function Parent1() {}",
"/**",
" * @template T",
" * @param {T} x",
" * @return {number}",
" */",
"Parent1.prototype.method = function(x) {};",
"/** @interface */",
"function Parent2() {}",
"/**",
" * @template T",
" * @param {T} x",
" * @return {string}",
" */",
"Parent2.prototype.method = function(x) {};",
"/** @interface @extends {Parent1} @extends {Parent2} */",
"function Child() {}"),
TypeCheck.INCOMPATIBLE_EXTENDED_PROPERTY_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @constructor */ function Bar() {}",
"/** @interface */",
"function Parent1() {}",
"/** @type {!Foo} */",
"Parent1.prototype.obj;",
"/** @interface */",
"function Parent2() {}",
"/** @type {!Bar} */",
"Parent2.prototype.obj;",
"/** @interface @extends {Parent1} @extends {Parent2} */",
"function Child() {}"),
TypeCheck.INCOMPATIBLE_EXTENDED_PROPERTY_TYPE);
}
public void testTwoLevelExtendedInterface() {
typeCheck(Joiner.on('\n').join(
"/** @interface */function Int0() {};",
"/** @type {function()} */",
"Int0.prototype.foo;",
"/** @interface @extends {Int0} */function Int1() {};",
"/** @constructor \n @implements {Int1} */",
"function Ctor() {};"),
TypeValidator.INTERFACE_METHOD_NOT_IMPLEMENTED);
}
public void testConstructorExtensions() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function I() {}",
"/** @param {number} x */",
"I.prototype.method = function(x) {};",
"/** @constructor @extends{I} */ function C() {}",
"C.prototype.method = function(x) {};",
"(new C).method('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function I() {}",
"/** @param {number} x */",
"I.prototype.method = function(x, y) {};",
"/** @constructor @extends{I} */ function C() {}",
"/** @param {string} y */",
"C.prototype.method = function(x, y) {};",
"(new C).method('asdf', 'fgr');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testInterfaceAndConstructorInvalidConstructions() {
typeCheck(Joiner.on('\n').join(
"/** @constructor @extends {Bar} */",
"function Foo() {}",
"/** @interface */",
"function Bar() {}"),
TypeCheck.CONFLICTING_EXTENDED_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor @implements {Bar} */",
"function Foo() {}",
"/** @constructor */",
"function Bar() {}"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @interface @implements {Foo} */",
"function Bar() {}"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @interface @extends {Foo} */",
"function Bar() {}"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
}
public void testNot() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @constructor */",
"function Bar() { /** @type {string} */ this.prop = 'asdf'; }",
"function f(/** (!Foo|!Bar) */ obj) {",
" if (!(obj instanceof Foo)) {",
" obj.prop - 5;",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(cond) {",
" var x = cond ? null : 123;",
" if (!(x === null)) { x - 5; }",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){ this.prop = 123; }",
"function f(/** Foo */ obj) {",
" if (!obj) { obj.prop; }",
"}"),
NewTypeInference.PROPERTY_ACCESS_ON_NONOBJECT);
}
public void testNullability() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @param {Foo} x */",
"function f(x) {}",
"f(new Foo);"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){ this.prop = 123; }",
"function f(/** Foo */ obj) { obj.prop; }"),
NewTypeInference.NULLABLE_DEREFERENCE);
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function I() {}",
"I.prototype.method = function() {};",
"/** @param {I} x */",
"function foo(x) { x.method(); }"),
NewTypeInference.NULLABLE_DEREFERENCE);
}
public void testGetElem() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function C(){ /** @type {number} */ this.prop = 1; }",
"(new C)['prop'] < 'asdf';"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x, y) {",
" x < y;",
" ({})[y - 5];",
"}",
"f('asdf', 123);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
// We don't see the warning here b/c the formal param x is assigned to a
// string, and we use x's type at the end of the function to create the
// summary.
typeCheck(Joiner.on('\n').join(
"function f(x, y) {",
" x < y;",
" ({})[y - 5];",
" x = 'asdf';",
"}",
"f('asdf', 123);"));
typeCheck(Joiner.on('\n').join(
"function f(x, y) {",
" ({})[y - 5];",
" x < y;",
"}",
"f('asdf', 123);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" x['prop'] = 'str';",
" return x['prop'] - 5;",
"}",
"f({});"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck("function f(/** ? */ o) { return o[0].prop; }");
// TODO(blickly): The fact that this has no warnings is somewhat unpleasant.
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" x['prop'] = 7;",
" var p = 'prop';",
" x[p] = 'str';",
" return x['prop'] - 5;",
"}",
"f({});"));
}
public void testNamespaces() {
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @constructor */ ns.C = function() {};",
"ns.C();"),
TypeCheck.CONSTRUCTOR_NOT_CALLABLE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @param {number} x */ ns.f = function(x) {};",
"ns.f('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @constructor */ ns.C = function(){}",
"ns.C.prototype.method = function(/** string */ x){};",
"(new ns.C).method(5);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @const */ ns.ns2 = {};",
"/** @constructor */ ns.ns2.C = function() {};",
"ns.ns2.C();"),
TypeCheck.CONSTRUCTOR_NOT_CALLABLE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @const */ ns.ns2 = {};",
"/** @constructor */ ns.ns2.C = function() {};",
"ns.ns2.C.prototype.method = function(/** string */ x){};",
"(new ns.ns2.C).method(11);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function C1(){}",
"/** @constructor */ C1.C2 = function(){}",
"C1.C2.prototype.method = function(/** string */ x){};",
"(new C1.C2).method(1);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function C1(){};",
"/** @constructor */ C1.prototype.C2 = function(){};",
"(new C1).C2();"),
TypeCheck.CONSTRUCTOR_NOT_CALLABLE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @type {number} */ ns.N = 5;",
"ns.N();"),
TypeCheck.NOT_CALLABLE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @type {number} */ ns.foo = 123;",
"/** @type {string} */ ns.foo = '';"),
GlobalTypeInfo.REDECLARED_PROPERTY,
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @type {number} */ ns.foo;",
"/** @type {string} */ ns.foo;"),
GlobalTypeInfo.REDECLARED_PROPERTY);
// We warn for duplicate declarations even if they are the same type.
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @type {number} */ ns.foo;",
"/** @type {number} */ ns.foo;"),
GlobalTypeInfo.REDECLARED_PROPERTY);
// Without the @const, we don't consider it a namespace and don't warn.
typeCheck(Joiner.on('\n').join(
"var ns = {};",
"/** @type {number} */ ns.foo = 123;",
"/** @type {string} */ ns.foo = '';"));
// TODO(dimvar): warn about redeclared property
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"ns.x = 5;",
"/** @type {string} */",
"ns.x = 'str';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"ns.prop = 1;",
"function f() { var /** string */ s = ns.prop; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testNamespacesInExterns() {
typeCheckCustomExterns(
DEFAULT_EXTERNS + Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @type {number} */ ns.num;"),
"var /** number */ n = ns.num;");
typeCheckCustomExterns(
DEFAULT_EXTERNS + Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @type {number} */ ns.num;"),
"var /** string */ s = ns.num;",
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testSimpleInferNamespaces() {
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @const */ ns.numprop = 123;",
"/** @const */ var x = ns;",
"function f() { var /** string */ s = x.numprop; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */ var e = { FOO : 5 };",
"/** @const */ e.numprop = 123;",
"/** @const */ var x = e;",
"function f() { var /** string */ s = x.numprop; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @type {number} */ ns.n = 5;",
"/** @const */ var x = ns.n;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @const */",
"var Bar = Foo;",
"function g() { Bar(); }"),
TypeCheck.CONSTRUCTOR_NOT_CALLABLE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @constructor */",
"ns.Foo = function() {};",
"/** @type {string} */",
"ns.Foo.prop = 'asdf';",
"/** @const */ var Foo = ns.Foo;",
"function g() { Foo.prop - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @constructor */",
"ns.Foo = function() {};",
"/** @const */ var Foo = ns.Foo;",
"function g() { Foo(); }"),
TypeCheck.CONSTRUCTOR_NOT_CALLABLE);
typeCheck(Joiner.on('\n').join(
"function /** string */ f(/** string */ x) { return x; }",
"/** @const */",
"var g = f;",
"function h() { g('asdf') - 1; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @type {number} */ ns.n = 5;",
"/** @const */ var x = ns.n;",
"/** @type {string} */ ns.s = 'str';"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @type {number} */ Foo.n = 5;",
"/** @const */ var x = Foo.n;",
"/** @type {string} */ Foo.s = 'str';"));
}
public void testDontInferUndeclaredFunctionReturn() {
typeCheck(Joiner.on('\n').join(
"function f() {}",
"/** @const */ var x = f();"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"ns.f = function() {}",
"/** @const */ var x = f();"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE);
}
// public void testUndeclaredNamespaces() {
// typeCheck(Joiner.on('\n').join(
// "/** @constructor */ ns.Foo = function(){};",
// "ns.Foo.prototype.method = function(){};"),
// VarCheck.UNDEFINED_VAR_ERROR,
// VarCheck.UNDEFINED_VAR_ERROR);
// }
public void testNestedNamespaces() {
// In the previous type inference, ns.subns did not need a
// @const annotation, but we require it.
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @const */",
"ns.subns = {};",
"/** @type {string} */",
"ns.subns.n = 'str';",
"function f() { ns.subns.n - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testNonnamespaceLooksLikeANamespace() {
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @type {Object} */",
"ns.obj = null;",
"function setObj() {",
" ns.obj = {};",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @type {Object} */",
"ns.obj = null;",
"function setObj() {",
" ns.obj = {};",
" ns.obj.str = 'str';",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @type {Object} */",
"ns.obj = null;",
"ns.obj = {};",
"ns.obj.x = 'str';",
"ns.obj.x - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @type {Object} */",
"ns.obj = null;",
"ns.obj = { x : 1, y : 5};",
"ns.obj.x = 'str';"));
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @type {Object} */",
"ns.obj = null;",
"ns.obj = { x : 1, y : 5};",
"ns.obj.x = 'str';",
"ns.obj.x - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testNamespacedObjectsDontCrash() {
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @constructor */",
"ns.Foo = function() {",
" ns.Foo.obj.value = ns.Foo.VALUE;",
"};",
"ns.Foo.obj = {};",
"ns.Foo.VALUE = 128;"));
}
public void testRedeclaredNamespaces() {
// TODO(blickly): Consider a warning if RHS doesn't contain ||
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = ns || {}",
"/** @const */ var ns = ns || {}"));
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = ns || {}",
"ns.subns = ns.subns || {}",
"ns.subns = ns.subns || {}"));
}
public void testReferenceToNonexistentNamespace() {
// typeCheck(
// "/** @constructor */ ns.Foo = function(){};",
// VarCheck.UNDEFINED_VAR_ERROR);
// typeCheck(
// "ns.subns = {};",
// VarCheck.UNDEFINED_VAR_ERROR);
// typeCheck(
// "/** @enum {number} */ ns.NUM = { N : 1 };",
// VarCheck.UNDEFINED_VAR_ERROR);
// typeCheck(
// "/** @typedef {number} */ ns.NUM;",
// VarCheck.UNDEFINED_VAR_ERROR);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @constructor */ ns.subns.Foo = function(){};"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"ns.subns.subsubns = {};"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @enum {number} */ ns.subns.NUM = { N : 1 };"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @typedef {number} */ ns.subns.NUM;"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"Foo.subns.subsubns = {};"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"/** @constructor */ Foo.subns.Bar = function(){};"),
TypeCheck.INEXISTENT_PROPERTY);
}
public void testThrow() {
typeCheck("throw 123;");
typeCheck("var msg = 'hello'; throw msg;");
typeCheck(Joiner.on('\n').join(
"function f(cond, x, y) {",
" if (cond) {",
" x < y;",
" throw 123;",
" } else {",
" x < 2;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f() { }",
"function g() {",
" throw f();",
"}"));
typeCheck("throw (1 - 'asdf');", NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) { throw x - 1; }",
"f('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testQnameInJsdoc() {
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @constructor */ ns.C = function() {};",
"/** @param {!ns.C} x */ function f(x) {",
" 123, x.prop;",
"}"),
TypeCheck.INEXISTENT_PROPERTY);
}
public void testIncrementDecrements() {
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = { x : 5 };",
"ns.x++; ++ns.x; ns.x--; --ns.x;"));
typeCheck(
"function f(ns) { --ns.x; }; f({x : 'str'})",
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testAndOr() {
typeCheck("function f(x, y, z) { return x || y && z;}");
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x, /** string */ y) {",
" var /** number */ n = x || y;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x, /** string */ y) {",
" var /** number */ n = y || x;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function /** number */ f(/** ?number */ x) {",
" return x || 42;",
"}"));
typeCheck(Joiner.on('\n').join(
"function /** (number|string) */ f(/** ?number */ x) {",
" return x || 'str';",
"}"));
}
public void testNonStringComparisons() {
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (null == x) {",
" var /** (null|undefined) */ y = x;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (x == null) {",
" var /** (null|undefined) */ y = x;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (null == x) {",
" var /** null */ y = x;",
" var /** undefined */ z = x;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @param {*} x */",
"function f(x) {",
" if (5 == x) {",
" var /** (null|undefined) */ y = x;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @param {*} x */",
"function f(x) {",
" if (x == 5) {",
" var /** (null|undefined) */ y = x;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @param {*} x */",
"function f(x) {",
" if (null == x) {",
" } else {",
" var /** (null|undefined) */ y = x;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @param {*} x */",
"function f(x) {",
" if (x == null) {",
" } else {",
" var /** (null|undefined) */ y = x;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (null != x) {",
" } else {",
" var /** (null|undefined) */ y = x;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (x != null) {",
" } else {",
" var /** (null|undefined) */ y = x;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @param {*} x */",
"function f(x) {",
" if (5 != x) {",
" } else {",
" var /** (null|undefined) */ y = x;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @param {*} x */",
"function f(x) {",
" if (x != 5) {",
" } else {",
" var /** (null|undefined) */ y = x;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @param {*} x */",
"function f(x) {",
" if (null != x) {",
" var /** (null|undefined) */ y = x;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @param {*} x */",
"function f(x) {",
" if (x != null) {",
" var /** (null|undefined) */ y = x;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testAnalyzeLoopsBwd() {
typeCheck("for(;;);");
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" for (; x - 5 > 0; ) {}",
" x = undefined;",
"}",
"f(true);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" while (x - 5 > 0) {}",
" x = undefined;",
"}",
"f(true);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (x - 5 > 0) {}",
" x = undefined;",
"}",
"f(true);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" do {} while (x - 5 > 0);",
" x = undefined;",
"}",
"f(true);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testDontLoosenNominalTypes() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() { this.prop = 123; }",
"function f(x) { if (x instanceof Foo) { var y = x.prop; } }"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() { this.prop = 123; }",
"/** @constructor */ function Bar() { this.prop = 123; }",
"function f(cond, x) {",
" x = cond ? new Foo : new Bar;",
" var y = x.prop;",
"}"));
}
public void testFunctionsWithAbnormalExit() {
typeCheck("function f(x) { x = 1; throw x; }");
// TODO(dimvar): to fix these, we must collect all THROWs w/out an out-edge
// and use the envs from them in the summary calculation. (Rare case.)
// typeCheck(Joiner.on('\n').join(
// "function f(x) {",
// " var y = 1;",
// " x < y;",
// " throw 123;",
// "}",
// "f('asdf');"),
// NewTypeInference.INVALID_ARGUMENT_TYPE);
// typeCheck(Joiner.on('\n').join(
// "function f(x, cond) {",
// " if (cond) {",
// " var y = 1;",
// " x < y;",
// " throw 123;",
// " }",
// "}",
// "f('asdf', 'whatever');"),
// NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testAssignAdd() {
// Without a type annotation, we can't find the type error here.
typeCheck(Joiner.on('\n').join(
"function f(x, y) {",
" x < y;",
" var /** number */ z = 5;",
" z += y;",
"}",
"f('asdf', 5);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x, y) {",
" x < y;",
" var z = 5;",
" z += y;",
"}",
"f('asdf', 5);"));
typeCheck(
"var s = 'asdf'; (s += 'asdf') - 5;",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck("var s = 'asdf'; s += 5;");
typeCheck("var b = true; b += 5;", NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(
"var n = 123; n += 'asdf';", NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(
"var s = 'asdf'; s += true;", NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testTypeCoercions() {
typeCheck(Joiner.on('\n').join(
"function f(/** * */ x) {",
" var /** string */ s = !x;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(/** * */ x) {",
" var /** string */ s = +x;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(/** * */ x) {",
" var /** string */ s = '' + x;",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** * */ x) {",
" var /** number */ s = '' + x;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testSwitch() {
typeCheck(
"switch (1) { case 1: break; case 2: break; default: break; }");
typeCheck(Joiner.on('\n').join(
"switch (1) {",
" case 1:",
" 1 - 'asdf';",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"switch (1) {",
" default:",
" 1 - 'asdf';",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"switch (1 - 'asdf') {",
" case 1:",
" break;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"switch (1) {",
" case (1 - 'asdf'):",
" break;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"function f(/** Foo */ x) {",
" switch (x) {",
" case null:",
" break;",
" default:",
" var /** !Foo */ y = x;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" switch (x) {",
" case 123:",
" x - 5;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"function f(/** Foo */ x) {",
" switch (x) {",
" case null:",
" default:",
" var /** !Foo */ y = x;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" switch (x) {",
" case null:",
" x - 5;",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" switch (x) {",
" case null:",
" var /** undefined */ y = x;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
// Tests for fall-through
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" switch (x) {",
" case 1: x - 5;",
" case 'asdf': x < 123; x < 'asdf'; break;",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" switch (x) {",
" case 1: x - 5;",
" case 'asdf': break;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"function g(/** number */ x) { return 5; }",
"function f() {",
" switch (3) { case g('asdf'): return 123; }",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
// TODO(dimvar): warn for type mismatch between label and condition
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x, /** string */ y) {",
" switch (y) { case x: ; }",
"}"));
}
public void testForIn() {
typeCheck(Joiner.on('\n').join(
"function f(/** string */ y) {",
" for (var x in { a: 1, b: 2 }) { y = x; }",
" x = 234;",
" return 123;",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(y) {",
" var z = x + 234;",
" for (var x in { a: 1, b: 2 }) {}",
" return 123;",
"}"),
// VariableReferenceCheck.EARLY_REFERENCE,
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** number */ y) {",
" for (var x in { a: 1, b: 2 }) { y = x; }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(
"function f(/** Object? */ o) { for (var x in o); }",
NewTypeInference.NULLABLE_DEREFERENCE);
typeCheck("for (var x in 123) ;", NewTypeInference.FORIN_EXPECTS_OBJECT);
typeCheck(
"var /** number */ x = 5; for (x in {a : 1});",
NewTypeInference.FORIN_EXPECTS_STRING_KEY);
typeCheck(Joiner.on('\n').join(
"function f(/** undefined */ y) {",
" var x;",
" for (x in { a: 1, b: 2 }) { y = x; }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testTryCatch() {
// typeCheck(
// "try { e; } catch (e) {}",
// VariableReferenceCheck.EARLY_REFERENCE);
// typeCheck(
// "e; try {} catch (e) {}",
// VariableReferenceCheck.EARLY_REFERENCE);
typeCheck("try {} catch (e) { e; }");
// If the CFG can see that the TRY won't throw, it doesn't go to the catch.
typeCheck("try {} catch (e) { 1 - 'asdf'; }");
typeCheck(
"try { throw 123; } catch (e) { 1 - 'asdf'; }",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(
"try { throw 123; } catch (e) {} finally { 1 - 'asdf'; }",
NewTypeInference.INVALID_OPERAND_TYPE);
// Outside of the catch block, e is unknown, like any other global variable.
typeCheck(Joiner.on('\n').join(
"try {",
" throw new Error();",
"} catch (e) {}",
"var /** number */ n = e;"));
// // For this to pass, we must model local scopes properly.
// typeCheck(Joiner.on('\n').join(
// "var /** string */ e = 'str';",
// "try {",
// " throw new Error();",
// "} catch (e) {}",
// "e - 3;"),
// NewTypeInference.INVALID_OPERAND_TYPE);
// typeCheck(
// "var /** string */ e = 'asdf'; try {} catch (e) {} e - 5;",
// VariableReferenceCheck.REDECLARED_VARIABLE);
typeCheck(Joiner.on('\n').join(
"function f() {",
" try {",
" } catch (e) {",
" return e.stack;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f() {",
" try {",
" throw new Error();",
" } catch (e) {",
" var /** Error */ x = e;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f() {",
" try {",
" throw new Error();",
" } catch (e) {",
" var /** number */ x = e;",
" var /** string */ y = e;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testIn() {
typeCheck("(true in {});", NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck("('asdf' in 123);", NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(
"var /** number */ n = ('asdf' in {});",
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(/** { a: number } */ obj) {",
" if ('p' in obj) {",
" return obj.p;",
" }",
"}",
"f({ a: 123 });"));
typeCheck(Joiner.on('\n').join(
"function f(/** { a: number } */ obj) {",
" if (!('p' in obj)) {",
" return obj.p;",
" }",
"}"),
TypeCheck.INEXISTENT_PROPERTY);
}
public void testDelprop() {
typeCheck("delete ({ prop: 123 }).prop;");
typeCheck(
"var /** number */ x = delete ({ prop: 123 }).prop;",
NewTypeInference.MISTYPED_ASSIGN_RHS);
// We don't detect the missing property
typeCheck("var obj = { a: 1, b: 2 }; delete obj.a; obj.a;");
}
public void testArrayLit() {
typeCheck("[1, 2, 3 - 'asdf']", NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x, y) {",
" x < y;",
" [y - 5];",
"}",
"f('asdf', 123);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testArrayAccesses() {
typeCheck(
"var a = [1,2,3]; a['str'];", NewTypeInference.NON_NUMERIC_ARRAY_INDEX);
typeCheck(Joiner.on('\n').join(
"function f(/** !Array<number> */ arr, i) {",
" arr[i];",
"}",
"f([1, 2, 3], 'str');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testRegExpLit() {
typeCheck("/abc/");
}
public void testDifficultLvalues() {
typeCheck(Joiner.on('\n').join(
"function f() { return {}; }",
"f().x = 123;"));
typeCheck(Joiner.on('\n').join(
"function f() { return {}; }",
"f().ns = {};"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() { /** @type {number} */ this.a = 123; }",
"/** @return {!Foo} */",
"function retFoo() { return new Foo(); }",
"function f(cond) {",
" (retFoo()).a = 'asdf';",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"(new Foo).x += 123;"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() { /** @type {number} */ this.a = 123; }",
"function f(cond, /** !Foo */ foo1) {",
" var /** { a: number } */ x = { a: 321 };",
" (cond ? foo1 : x).a = 'asdf';",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(
"function f(obj) { obj[1 - 'str'] = 3; }",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(
"function f(/** undefined */ n, pname) { n[pname] = 3; }",
NewTypeInference.PROPERTY_ACCESS_ON_NONOBJECT);
}
public void testQuestionableUnionJsDoc() {
// 'string|?' is the same as '?'
typeCheck(
"/** @type {string|?} */ var x;",
JSTypeCreatorFromJSDoc.BAD_JSDOC_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"",
"/**",
" * @return {T|S}",
" * @template T, S",
" */",
"function f(){};"));
typeCheck("/** @param {(?)} x */ function f(x) {}");
}
public void testGenericsJsdocParsing() {
typeCheck("/** @template T\n@param {T} x */ function f(x) {}");
typeCheck(Joiner.on('\n').join(
"/** @template T\n @param {T} x\n @return {T} */",
"function f(x) { return x; };"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @constructor",
" * @param {T} x",
" * @extends {Bar<T>} // error, Bar is not templatized ",
" */",
"function Foo(x) {}",
"/** @constructor */",
"function Bar() {}"),
JSTypeCreatorFromJSDoc.INVALID_GENERICS_INSTANTIATION);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @constructor",
" * @param {T} x",
" */",
"function Foo(x) {}",
"/** @param {Foo<number, string>} x */",
"function f(x) {}"),
JSTypeCreatorFromJSDoc.INVALID_GENERICS_INSTANTIATION);
typeCheck("/** @type {Array<number>} */ var x;");
typeCheck("/** @type {Object<number>} */ var x;");
typeCheck(
"/** @template T\n@param {!T} x */ function f(x) {}",
JSTypeCreatorFromJSDoc.BAD_JSDOC_ANNOTATION);
}
public void testPolymorphicFunctionInstantiation() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"function id(x) { return x; }",
"id('str') - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"function f(x, y) {}",
"f(123, 'asdf');"),
NewTypeInference.NOT_UNIQUE_INSTANTIATION);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {(T|null)} x",
" * @return {(T|number)}",
" */",
"function f(x) { return x === null ? 123 : x; }",
"/** @return {(null|undefined)} */ function g() { return null; }",
"var /** (number|undefined) */ y = f(g());"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {(T|number)} x",
" */",
"function f(x) {}",
"/** @return {*} */ function g() { return 1; }",
"f(g());"),
NewTypeInference.FAILED_TO_UNIFY);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"function id(x) { return x; }",
"/** @return {*} */ function g() { return 1; }",
"id(g()) - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T, U",
" * @param {T} x",
" * @param {U} y",
" * @return {U}",
" */",
"function f(x, y) { return y; }",
"f(10, 'asdf') - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function g(x) {",
" /**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
" function f(x, y) {}",
" f(x, 5);",
"}",
"g('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function g(/** ? */ x) {",
" /**",
" * @template T",
" * @param {(T|number)} x",
" */",
" function f(x) {}",
" f(x)",
"}"));
// TODO(blickly): Catching the INVALID_ARGUMENT_TYPE here requires
// return-type unification.
typeCheck(Joiner.on('\n').join(
"function g(x) {",
" /**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
" function f(x) { return x; }",
" f(x) - 5;",
" x = 'asdf';",
"}",
"g('asdf');"));
// Empty instantiations
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {(T|number)} x",
" */",
"function f(x) {}",
"f(123);"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {(T|null)} x",
" * @param {(T|number)} y",
" */",
"function f(x, y) {}",
"f(null, 'str');"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){};",
"/**",
" * @template T",
" * @param {(T|Foo)} x",
" * @param {(T|number)} y",
" */",
"function f(x, y) {}",
"f(new Foo(), 'str');"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {function(T):T} f",
" * @param {T} x",
" */",
"function apply(f, x) { return f(x); }",
"/** @type {string} */",
"var out;",
"var result = apply(function(x){ out = x; return x; }, 0);"),
NewTypeInference.NOT_UNIQUE_INSTANTIATION);
typeCheck(Joiner.on('\n').join(
"/** @template T */",
"function f(/** T */ x, /** T */ y) {}",
"f(1, 'str');"),
NewTypeInference.NOT_UNIQUE_INSTANTIATION);
typeCheck(Joiner.on('\n').join(
"/** @template T */",
"function /** T */ f(/** T */ x) { return x; }",
"f('str') - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" */",
"function f(x) {",
" /** @constructor */",
" function Foo() {",
" /** @type {T} */",
" this.prop = x;",
" }",
" return (new Foo()).prop;",
"}",
"f('asdf') - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {*} x",
" */",
"function f(x) {}",
"f(123);"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" */",
"function Foo() {}",
"/**",
" * @template U",
" * @param {function(U)} x",
" */",
"Foo.prototype.f = function(x) { this.f(x); };"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {function(T)} x",
" */",
"function f(x) {}",
"function g(x) {}",
"f(g);"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {function(T=)} x",
" */",
"function f(x) {}",
"function g(/** (number|undefined) */ x) {}",
"f(g);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {function(...T)} x",
" */",
"function f(x) {}",
"function g() {}",
"f(g);"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @param {!Array<T>} arr",
" * @param {?function(this:S, T, number, ?) : boolean} f",
" * @param {S=} opt_obj",
" * @return {T|null}",
" * @template T,S",
" */",
"function gaf(arr, f, opt_obj) {",
" return null;",
"};",
"/** @type {number|null} */",
"var x = gaf([1, 2, 3], function(x, y, z) { return true; });"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {function(T):boolean} x",
" */",
"function f(x) {}",
"f(function(x) { return 'asdf'; });"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {function(T)} y",
" */",
"function f(x, y) {}",
"f(123, function(x) { var /** string */ s = x; });"),
NewTypeInference.NOT_UNIQUE_INSTANTIATION);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" */",
"function f(x) {}",
"var y = null;",
"if (!y) {",
"} else {",
" f(y)",
"}"));
}
public void testGenericReturnType() {
typeCheck(Joiner.on('\n').join(
"/** @return {T|string} @template T */",
"function f() { return 'str'; }"));
}
public void testUnificationWithGenericUnion() {
typeCheck(Joiner.on('\n').join(
"/** @constructor @template T */ function Foo(){}",
"/**",
" * @template T",
" * @param {!Array<T>|!Foo<T>} arr",
" * @return {T}",
" */",
"function get(arr) {",
" return arr[0];",
"}",
"var /** null */ x = get([5]);"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {Array<T>} arr",
" * @return {T|undefined}",
" */",
"function get(arr) {",
" if (arr === null || arr.length === 0) {",
" return undefined;",
" }",
" return arr[0];",
"}",
"var /** (number|undefined) */ x = get([5]);"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {Array<T>} arr",
" * @return {T|undefined}",
" */",
"function get(arr) {",
" if (arr === null || arr.length === 0) {",
" return undefined;",
" }",
" return arr[0];",
"}",
"var /** null */ x = get([5]);"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor @template U */ function Foo(/** U */ x){}",
"/**",
" * @template T",
" * @param {U|!Array<T>} arr",
" * @return {U}",
" */",
"Foo.prototype.get = function(arr, /** ? */ opt_arg) {",
" return opt_arg;",
"}",
"var /** null */ x = (new Foo('str')).get([5], 1);"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor @template U */ function Foo(/** U */ x){}",
"/**",
" * @template T",
" * @param {U|!Array<T>} arr",
" * @return {U}",
" */",
"Foo.prototype.get = function(arr, /** ? */ opt_arg) {",
" return opt_arg;",
"}",
"Foo.prototype.f = function() {",
" var /** null */ x = this.get([5], 1);",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @constructor",
" */",
"function Bar() {}",
"/** @constructor */",
"function Foo() {}",
"/**",
" * @template T",
" * @param {!Bar<(!Bar<T>|!Foo)>} x",
" */",
"function f(x) {}",
"f(/** @type {!Bar<!Bar<number>>} */ (new Bar));"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/**",
" * @template T",
" * @param {T|null} x",
" */",
"function f(x) {}",
"f(new Foo);"));
}
public void testBoxedUnification() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @param {V} value",
" * @constructor",
" * @template V",
" */",
"function Box(value) {};",
"/**",
" * @constructor",
" * @param {K} key",
" * @param {V} val",
" * @template K, V",
" */",
"function Map(key, val) {};",
"/**",
" * @param {!Map<K, (V | !Box<V>)>} inMap",
" * @constructor",
" * @template K, V",
" */",
"function WrappedMap(inMap){};",
"/** @return {(boolean |!Box<boolean>)} */",
"function getUnion(/** ? */ u) { return u; }",
"var inMap = new Map('asdf', getUnion(123));",
"/** @param {!WrappedMap<string, boolean>} x */",
"function getWrappedMap(x) {}",
"getWrappedMap(new WrappedMap(inMap));"));
}
public void testUnification() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){};",
"/** @constructor */ function Bar(){};",
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"function id(x) { return x; }",
"var /** Bar */ x = id(new Foo);"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"function id(x) { return x; }",
"id({}) - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"function id(x) { return x; }",
"var /** (number|string) */ x = id('str');"));
typeCheck(Joiner.on('\n').join(
"function f(/** * */ a, /** string */ b) {",
" /**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
" function f(x, y) {}",
" f(a, b);",
"}"),
NewTypeInference.NOT_UNIQUE_INSTANTIATION);
typeCheck(Joiner.on('\n').join(
"function f(/** string */ b) {",
" /**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
" function f(x, y) {}",
" f({p:5, r:'str'}, {p:20, r:b});",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** string */ b) {",
" /**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
" function f(x, y) {}",
" f({r:'str'}, {p:20, r:b});",
"}"),
NewTypeInference.NOT_UNIQUE_INSTANTIATION);
typeCheck(Joiner.on('\n').join(
"function g(x) {",
" /**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
" function f(x, y) {}",
" var /** boolean */ y = true;",
" f(x, y);",
"}",
"g('str');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {number} y",
" */",
"function f(x, y) {}",
"f(123, 'asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" */",
"function Foo() {}",
"/**",
" * @template T",
" * @param {Foo<T>} x",
" */",
"function takesFoo(x) {}",
"takesFoo(undefined);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T|undefined} x",
" */",
"function f(x) {}",
"/**",
" * @template T",
" * @param {T|undefined} x",
" */",
"function g(x) { f(x); }"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T|undefined} x",
" * @return {T}",
" */",
"function f(x) {",
" if (x === undefined) {",
" throw new Error('');",
" }",
" return x;",
"}",
"/**",
" * @template T",
" * @param {T|undefined} x",
" * @return {T}",
" */",
"function g(x) { return f(x); }",
"g(123) - 5;"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T|undefined} x",
" * @return {T}",
" */",
"function f(x) {",
" if (x === undefined) {",
" throw new Error('');",
" }",
" return x;",
"}",
"/**",
" * @template T",
" * @param {T|undefined} x",
" * @return {T}",
" */",
"function g(x) { return f(x); }",
"g(123) < 'asdf';"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testUnifyObjects() {
typeCheck(Joiner.on('\n').join(
"function f(b) {",
" /**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
" function f(x, y) {}",
" f({p:5, r:'str'}, {p:20, r:b});",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(b) {",
" /**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
" function f(x, y) {}",
" f({p:20, r:b}, {p:5, r:'str'});",
"}"));
typeCheck(Joiner.on('\n').join(
"function g(x) {",
" /**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
" function f(x, y) {}",
" f({prop: x}, {prop: 5});",
"}",
"g('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function g(x, cond) {",
" /**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
" function f(x, y) {}",
" var y = cond ? {prop: 'str'} : {prop: 5};",
" f({prop: x}, y);",
"}",
"g({}, true);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function g(x, cond) {",
" /**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
" function f(x, y) {}",
" /** @type {{prop : (string | number)}} */",
" var y = cond ? {prop: 'str'} : {prop: 5};",
" f({prop: x}, y);",
"}",
"g({}, true);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {{a: number, b: T}} x",
" * @return {T}",
" */",
"function f(x) { return x.b; }",
"f({a: 1, b: 'asdf'}) - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @return {T}",
" */",
"function f(x) { return x.b; }",
"f({b: 'asdf'}) - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testFunctionTypeUnifyUnknowns() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"function f(x, y) {}",
"/** @type {function(number)} */",
"function g(x) {}",
"/** @type {function(?)} */",
"function h(x) {}",
"f(g, h);"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"function f(x, y) {}",
"/** @type {function(number)} */",
"function g(x) {}",
"/** @type {function(string)} */",
"function h(x) {}",
"f(g, h);"),
NewTypeInference.NOT_UNIQUE_INSTANTIATION);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"function f(x, y) {}",
"/** @type {function(number)} */",
"function g(x) {}",
"/** @type {function(?, string)} */",
"function h(x, y) {}",
"f(g, h);"),
NewTypeInference.NOT_UNIQUE_INSTANTIATION);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"function f(x, y) {}",
"/** @type {function(number=, ...string)} */",
"function g(x) {}",
"/** @type {function(number=, ...?)} */",
"function h(x) {}",
"f(g, h);"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"function f(x, y) {}",
"/** @type {function(number):number} */",
"function g(x) { return 1; }",
"/** @type {function(?):string} */",
"function h(x) { return ''; }",
"f(g, h);"),
NewTypeInference.NOT_UNIQUE_INSTANTIATION);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"function f(x, y) {}",
"/** @constructor */ function Foo() {}",
"/** @type {function(new:Foo)} */",
"function g() {}",
"/** @type {function(new:Foo)} */",
"function h() {}",
"f(g, h);"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"function f(x, y) {}",
"/** @constructor */ function Foo() {}",
"/** @constructor */ function Bar() {}",
"/** @type {function(this:Foo)} */",
"function g() {}",
"/** @type {function(this:Bar)} */",
"function h() {}",
"f(g, h);"),
NewTypeInference.NOT_UNIQUE_INSTANTIATION);
}
public void testInstantiationInsideObjectTypes() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @template U",
" * @param {U} y",
" */",
"function g(y) {",
" /**",
" * @template T",
" * @param {{a: U, b: T}} x",
" * @return {T}",
" */",
" function f(x) { return x.b; }",
" f({a: y, b: 'asdf'}) - 5;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template U",
" * @param {U} y",
" */",
"function g(y) {",
" /**",
" * @template T",
" * @param {{b: T}} x",
" * @return {T}",
" */",
" function f(x) { return x.b; }",
" f({b: y}) - 5;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testInstantiateInsideFunctionTypes() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {function(T):T} fun",
" */",
"function f(x, fun) {}",
"function g(x) { return x - 5; }",
"f('asdf', g);"),
NewTypeInference.NOT_UNIQUE_INSTANTIATION);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {function(T):number} fun",
" */",
"function f(fun) {}",
"function g(x) { return 'asdf'; }",
"f(g);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {function(T=)} fun",
" */",
"function f(fun) {}",
"/** @param{string=} x */ function g(x) {}",
"f(g);"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {function(...T)} fun",
" */",
"function f(fun) {}",
"/** @param {...number} var_args */ function g(var_args) {}",
"f(g);"));
}
public void testPolymorphicFuncallsFromDifferentScope() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"function id(x) { return x; }",
"function g() {",
" id('asdf') - 5;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {number} y",
" */",
"function f(x, y) {}",
"function g() {",
" f('asdf', 'asdf');",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"function f(x, y) {}",
"function g() {",
" f(123, 'asdf');",
"}"),
NewTypeInference.NOT_UNIQUE_INSTANTIATION);
}
public void testOpacityOfTypeParameters() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" */",
"function f(x) {",
" x - 5;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {{ a: T }} x",
" */",
"function f(x) {",
" x.a - 5;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {function(T):T} fun",
" */",
"function f(x, fun) {",
" fun(x) - 5;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"function f(x) {",
" return 5;",
"}"),
NewTypeInference.RETURN_NONDECLARED_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" */",
"function f(x) {",
" var /** ? */ y = x;",
"}"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @return {(T|number)}",
" */",
"function f(x) {",
" var y;",
" if (1 < 2) {",
" y = x;",
" } else {",
" y = 123;",
" }",
" return y;",
"}"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @return {(T|number)}",
" */",
"function f(x) {",
" var y;",
" if (1 < 2) {",
" y = x;",
" } else {",
" y = 123;",
" }",
" return y;",
"}",
"f(123) - 5;"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @return {(T|number)}",
" */",
"function f(x) {",
" var y;",
" if (1 < 2) {",
" y = x;",
" } else {",
" y = 123;",
" }",
" return y;",
"}",
"var /** (number|boolean) */ z = f('asdf');"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" */",
"function f(x) {",
" var /** T */ y = x;",
" y - 5;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T, U",
" * @param {T} x",
" * @param {U} y",
" */",
"function f(x, y) {",
" x = y;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testGenericClassInstantiation() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @constructor",
" */",
"function Foo(x) {}",
"/** @param {T} y */",
"Foo.prototype.bar = function(y) {}",
"new Foo('str').bar(5)"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @constructor",
" */",
"function Foo(x) {}",
"/** @type {function(T)} y */",
"Foo.prototype.bar = function(y) {};",
"new Foo('str').bar(5)"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @constructor",
" */",
"function Foo(x) { /** @type {T} */ this.x = x; }",
"/** @return {T} */",
"Foo.prototype.bar = function() { return this.x; };",
"new Foo('str').bar() - 5"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @constructor",
" */",
"function Foo(x) { /** @type {T} */ this.x = x; }",
"/** @type {function() : T} */",
"Foo.prototype.bar = function() { return this.x; };",
"new Foo('str').bar() - 5"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @constructor",
" */",
"function Foo(x) {}",
"/** @type {function(this:Foo<T>, T)} */",
"Foo.prototype.bar = function(x) { this.x = x; };",
"new Foo('str').bar(5)"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @constructor",
" */",
"function Foo(x) {}",
"/** @param {!Foo<number>} x */",
"function f(x) {}",
"f(new Foo(7));"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @constructor",
" */",
"function Foo(x) {}",
"/** @param {Foo<number>} x */",
"function f(x) {}",
"f(new Foo('str'));"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @constructor",
" */",
"function Foo(x) {}",
"/** @param {T} x */",
"Foo.prototype.method = function(x) {};",
"/** @param {!Foo<number>} x */",
"function f(x) { x.method('asdf'); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" */",
"function Foo() {}",
"/** @param {T} x */",
"Foo.prototype.method = function(x) {};",
"var /** @type {Foo<string>} */ foo = null;",
"foo.method('asdf');"),
NewTypeInference.PROPERTY_ACCESS_ON_NONOBJECT);
}
public void testLooserCheckingForInferredProperties() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo(x) { this.prop = x; }",
"function f(/** !Foo */ obj) {",
" obj.prop = true ? 1 : 'asdf';",
" obj.prop - 5;",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo(x) { this.prop = x; }",
"function f(/** !Foo */ obj) {",
" if (!(typeof obj.prop == 'number')) {",
" obj.prop < 'asdf';",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo(x) { this.prop = x; }",
"function f(/** !Foo */ obj) {",
" obj.prop = true ? 1 : 'asdf';",
" obj.prop - 5;",
" obj.prop < 'asdf';",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function /** string */ f(/** ?number */ x) {",
" var o = { prop: 'str' };",
" if (x) {",
" o.prop = x;",
" }",
" return o.prop;",
"}"),
NewTypeInference.RETURN_NONDECLARED_TYPE);
}
public void testInheritanceWithGenerics() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @interface",
" */",
"function I() {}",
"/** @param {T} x */",
"I.prototype.bar = function(x) {};",
"/** @constructor @implements {I<number>} */",
"function Foo() {}",
"Foo.prototype.bar = function(x) {};",
"(new Foo).bar(123);"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @interface",
" */",
"function I() {}",
"/** @param {T} x */",
"I.prototype.bar = function(x) {};",
"/** @constructor @implements {I<number>} */",
"function Foo() {}",
"Foo.prototype.bar = function(x) {};",
"(new Foo).bar('str');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @interface",
" */",
"function I() {}",
"/** @param {T} x */",
"I.prototype.bar = function(x) {};",
"/** @constructor @implements {I<number>} */",
"function Foo() {}",
"/** @override */",
"Foo.prototype.bar = function(x) {};",
"new Foo().bar('str');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @interface",
" */",
"function I() {}",
"/** @param {T} x */",
"I.prototype.bar = function(x) {};",
"/**",
" * @template U",
" * @constructor",
" * @implements {I<U>}",
" * @param {U} x",
" */",
"function Foo(x) {}",
"Foo.prototype.bar = function(x) {};{}",
"new Foo(5).bar('str');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @interface",
" */",
"function I() {}",
"/** @param {T} x */",
"I.prototype.bar = function(x) {};",
"/** @constructor @implements {I<number>} */",
"function Foo() {}",
"Foo.prototype.bar = function(x) {};",
"/** @param {I<string>} x */ function f(x) {};",
"f(new Foo());"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @interface",
" */",
"function I() {}",
"/** @param {T} x */",
"I.prototype.bar = function(x) {};",
"/** @constructor @implements {I<number>} */",
"function Foo() {}",
"/** @param {string} x */",
"Foo.prototype.bar = function(x) {};"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @interface",
" */",
"function I() {}",
"/** @param {T} x */",
"I.prototype.bar = function(x) {};",
"/**",
" * @template T",
" * @param {T} x",
" * @constructor @implements {I<number>}",
" */",
"function Foo(x) {}",
"/** @param {T} x */",
"Foo.prototype.bar = function(x) {};"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @constructor",
" */",
"function Foo() {}",
"/** @param {T} x */",
"Foo.prototype.method = function(x) {};",
"/**",
" * @template T",
" * @constructor",
" * @extends {Foo<T>}",
" * @param {T} x",
" */",
"function Bar(x) {}",
"/** @param {number} x */",
"Bar.prototype.method = function(x) {};"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @constructor",
" */",
"function High() {}",
"/** @param {Low<T>} x */",
"High.prototype.method = function(x) {};",
"/**",
" * @template T",
" * @constructor",
" * @extends {High<T>}",
" */",
"function Low() {}"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @constructor",
" */",
"function High() {}",
"/** @param {Low<number>} x */",
"High.prototype.method = function(x) {};",
"/**",
" * @template T",
" * @constructor",
" * @extends {High<T>}",
" */",
"function Low() {}"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @constructor",
" */",
"function High() {}",
"/** @param {Low<T>} x */ // error, low is not templatized",
"High.prototype.method = function(x) {};",
"/**",
" * @constructor",
" * @extends {High<number>}",
" */",
"function Low() {}"),
JSTypeCreatorFromJSDoc.INVALID_GENERICS_INSTANTIATION);
// BAD INHERITANCE, WE DON'T HAVE A WARNING TYPE FOR THIS
// TODO(dimvar): fix
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @interface",
" */",
"function I() {}",
"/**",
" * @template T",
" * @constructor",
" * @implements {I<T>}",
" * @extends {Bar}",
" */",
"function Foo(x) {}",
"/**",
" * @constructor",
" * @implements {I<number>}",
" */",
"function Bar(x) {}"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @interface",
" * @template T",
" */",
"function Foo() {}",
"/** @constructor @implements {Foo<number>} */",
"function A() {}",
"var /** Foo<number> */ x = new A();"));
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function High() {}",
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"High.prototype.method = function (x) {};",
"/** @constructor @implements {High} */",
"function Low() {}",
"Low.prototype.method = function (x) {",
" return x;",
"};",
"(new Low).method(123) - 123;"));
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function High() {}",
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"High.prototype.method = function (x) {};",
"/** @constructor @implements {High} */",
"function Low() {}",
"Low.prototype.method = function (x) {",
" return x;",
"};",
"(new Low).method('str') - 123;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @interface",
" */",
"function High() {}",
"/** @return {T} */",
"High.prototype.method = function () {};",
"/** @constructor @implements {High} */",
"function Low() {}",
"Low.prototype.method = function () { return /** @type {?} */ (null); };",
"(new Low).method() - 123;",
"(new Low).method() < 'asdf';"));
}
public void testGenericsSubtyping() {
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"Parent.prototype.method = function(x, y){};",
"/** @constructor @implements {Parent} */",
"function Child() {}",
"/**",
" * @param {number} x",
" * @param {number} y",
" */",
"Child.prototype.method = function(x, y){};"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"Parent.prototype.method = function(x, y){};",
"/** @constructor @implements {Parent} */",
"function Child() {}",
"/**",
" * @param {?} x",
" * @param {number} y",
" */",
"Child.prototype.method = function(x, y){};"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"Parent.prototype.method = function(x, y){};",
"/** @constructor @implements {Parent} */",
"function Child() {}",
"/**",
" * @param {*} x",
" * @param {*} y",
" */",
"Child.prototype.method = function(x, y){};"));
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"Parent.prototype.method = function(x, y){};",
"/** @constructor @implements {Parent} */",
"function Child() {}",
"/**",
" * @param {?} x",
" * @param {?} y",
" */",
"Child.prototype.method = function(x, y){};"));
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"Parent.prototype.method = function(x){};",
"/** @constructor @implements {Parent} */",
"function Child() {}",
"/**",
" * @param {?} x",
" * @return {?}",
" */",
"Child.prototype.method = function(x){ return x; };"));
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"Parent.prototype.method = function(x){};",
"/** @constructor @implements {Parent} */",
"function Child() {}",
"/**",
" * @param {*} x",
" * @return {?}",
" */",
"Child.prototype.method = function(x){ return x; };"));
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"Parent.prototype.method = function(x){};",
"/** @constructor @implements {Parent} */",
"function Child() {}",
"/**",
" * @param {*} x",
" * @return {*}",
" */",
"Child.prototype.method = function(x){ return x; };"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"Parent.prototype.method = function(x){};",
"/** @constructor @implements {Parent} */",
"function Child() {}",
"/**",
" * @param {number} x",
" * @return {number}",
" */",
"Child.prototype.method = function(x){ return x; };"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"Parent.prototype.method = function(x){};",
"/** @constructor @implements {Parent} */",
"function Child() {}",
"/**",
" * @param {?} x",
" * @return {*}",
" */",
"Child.prototype.method = function(x){ return x; };"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/**",
" * @template T",
" * @param {function(T, T) : boolean} x",
" */",
"Parent.prototype.method = function(x){};",
"/** @constructor @implements {Parent} */",
"function Child() {}",
"/**",
" * @param {function(number, number) : boolean} x",
" */",
"Child.prototype.method = function(x){ return x; };"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" */",
"function f(x) {}",
"/** @param {function(number, number)} x */",
"function g(x) {}",
"g(f);"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" */",
"function f(x) {}",
"/** @param {function()} x */",
"function g(x) {}",
"g(f);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function Parent() {}",
"/**",
" * @template T",
" * @param {T} x",
" */",
"Parent.prototype.method = function(x) {};",
"/**",
" * @constructor",
" * @implements {Parent}",
" */",
"function Child() {}",
"/**",
" * @template U",
" * @param {U} x",
" */",
"Child.prototype.method = function(x) {};"));
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/** @param {string} x */",
"Parent.prototype.method = function(x){};",
"/** @constructor @implements {Parent} */",
"function Child() {}",
"/**",
" * @template T",
" * @param {T} x",
" */",
"Child.prototype.method = function(x){};"));
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/** @param {*} x */",
"Parent.prototype.method = function(x){};",
"/** @constructor @implements {Parent} */",
"function Child() {}",
"/**",
" * @template T",
" * @param {T} x",
" */",
"Child.prototype.method = function(x){};"));
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/** @param {?} x */",
"Parent.prototype.method = function(x){};",
"/** @constructor @implements {Parent} */",
"function Child() {}",
"/**",
" * @template T",
" * @param {T} x",
" */",
"Child.prototype.method = function(x){};"));
// This shows a bug in subtyping of generic functions.
// We don't catch the invalid prop override.
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/**",
" * @param {string} x",
" * @param {number} y",
" */",
"Parent.prototype.method = function(x, y){};",
"/** @constructor @implements {Parent} */",
"function Child() {}",
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"Child.prototype.method = function(x, y){};"));
// This shows a bug in subtyping of generic functions.
// We don't catch the invalid prop override.
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Parent() {}",
"/**",
" * @template A, B",
" * @param {A} x",
" * @param {B} y",
" * @return {A}",
" */",
"Parent.prototype.method = function(x, y){};",
"/** @constructor @implements {Parent} */",
"function Child() {}",
"/**",
" * @template A, B",
" * @param {A} x",
" * @param {B} y",
" * @return {B}",
" */",
"Child.prototype.method = function(x, y){ return y; };"));
}
public void testGenericsVariance() {
// Array generic parameter is co-variant
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @constructor @extends {Foo} */ function Bar() {}",
"var /** Array<Foo> */ a = [new Bar];"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @param {!Array<number|string>} x",
" * @return {!Array<number>}",
" */",
"function f(x) {",
" return /** @type {!Array<number>} */ (x);",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @constructor @extends {Foo} */ function Bar() {}",
"var /** Array<Bar> */ a = [new Foo];"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/**",
" * @template T",
" * @param {T} x",
" * @param {!Array<null|T>} y",
" */",
"function f(x, y) {}",
"f(new Foo, [new Foo]);"));
typeCheck(Joiner.on('\n').join(
"/** @constructor @param {T} x @template T */ function Gen(x){}",
"/** @constructor */ function Foo() {}",
"/** @constructor @extends {Foo} */ function Bar() {}",
"var /** Gen<Foo> */ a = new Gen(new Bar);"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor @param {T} x @template T */ function Gen(x){}",
"/** @constructor */ function Foo() {}",
"/** @constructor @extends {Foo} */ function Bar() {}",
"var /** Gen<Bar> */ a = new Gen(new Foo);"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testInferredArrayGenerics() {
typeCheck(
"/** @const */ var x = [];", GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE);
typeCheck(
"/** @const */ var x = [1, 'str'];",
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @constructor @extends {Foo} */ function Bar() {}",
"/** @const */ var x = [new Foo, new Bar];"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE);
typeCheck(
"var /** Array<string> */ a = [1, 2];",
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"var arr = [];",
"var /** Array<string> */ as = arr;"));
typeCheck(Joiner.on('\n').join(
"var arr = [1, 2, 3];",
"var /** Array<string> */ as = arr;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"var /** Array<string> */ a = [new Foo, new Foo];"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @constructor @extends {Foo} */ function Bar() {}",
"var /** Array<Foo> */ a = [new Foo, new Bar];"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @constructor @extends {Foo} */ function Bar() {}",
"var /** Array<Bar> */ a = [new Foo, new Bar];"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @const */ var x = [1, 2, 3];",
"function g() { var /** Array<string> */ a = x; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @constructor @extends {Foo} */ function Bar() {}",
"/** @const */ var x = [new Foo, new Foo];",
"function g() { var /** Array<Bar> */ a = x; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testSpecializedInstanceofCantGoToBottom() {
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"ns.f = function() {};",
"if (ns.f instanceof Function) {}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"/** @const */ var ns = {};",
"ns.f = new Foo;",
"if (ns.f instanceof Foo) {}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"/** @constructor */ function Bar(){}",
"/** @const */ var ns = {};",
"ns.f = new Foo;",
"if (ns.f instanceof Bar) {}"));
}
public void testDeclaredGenericArrayTypes() {
typeCheck(Joiner.on('\n').join(
"/** @type {Array<string>} */",
"var arr = ['str'];",
"arr[0]++;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"var arr = ['str'];",
"arr[0]++;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function foo (/** Array<string> */ a) {}",
"/** @type {Array<number>} */",
"var b = [1];",
"foo(b);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function foo (/** Array<string> */ a) {}",
"foo([1]);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @type {!Array<number>} */",
"var arr = [1, 2, 3];",
"arr[0] = 'str';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @type {!Array<number>} */",
"var arr = [1, 2, 3];",
"arr['0'] = 'str';"));
// We warn here even though the declared type of the lvalue includes null.
typeCheck(Joiner.on('\n').join(
"/** @type {Array<number>} */",
"var arr = [1, 2, 3];",
"arr[0] = 'str';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(/** Array<number> */ arr) {",
" arr[0] = 'str';",
"}"),
NewTypeInference.NULLABLE_DEREFERENCE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var arr = [1, 2, 3];",
"arr[0] = 'str';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"var arr = [1, 2, 3];",
"arr[0] = 'str';"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Super(){}",
"/** @constructor @extends {Super} */ function Sub(){}",
"/** @type {!Array<Super>} */ var arr = [new Sub];",
"arr[0] = new Super;"));
typeCheck(Joiner.on('\n').join(
"/** @type {Array<number>} */ var arr = [];",
"arr[0] = 'str';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @type {Array<number>} */ var arr = [];",
"(function (/** Array<string> */ x){})(arr);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function /** string */ f(/** !Array<number> */ arr) {",
" return arr[0];",
"}"),
NewTypeInference.RETURN_NONDECLARED_TYPE);
// TODO(blickly): Would be nice if we caught the MISTYPED_ASSIGN_RHS here
typeCheck(Joiner.on('\n').join(
"var arr = [];",
"arr[0] = 5;",
"var /** Array<string> */ as = arr;"));
}
public void testInferConstTypeFromGoogGetMsg() {
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var s = goog.getMsg('asdf');",
"s - 1;"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testInferConstTypeFromQualifiedName() {
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {}",
"/** @return {string} */ ns.f = function() { return 'str'; };",
"/** @const */ var s = ns.f();",
"function f() {",
" s - 1;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testInferConstTypeFromGenerics() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"function f(x) { return x; }",
"/** @const */ var x = f(5);",
"function g() { var /** null */ n = x; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @constructor",
" */",
"function Foo(x) {}",
"/** @const */ var foo_str = new Foo('str');",
"function g() { var /** !Foo<number> */ foo_num = foo_str; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"function f(x) { return x; }",
"/** @const */ var x = f(f ? 'str' : 5);"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" * @return {T}",
" */",
"function f(x, y) { return true ? y : x; }",
"/** @const */ var x = f(5, 'str');",
"function g() { var /** null */ n = x; }"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE,
NewTypeInference.NOT_UNIQUE_INSTANTIATION);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"function f(x) { return x; }",
"/** @const */",
"var y = f(1, 2);"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE,
TypeCheck.WRONG_ARGUMENT_COUNT);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"function f(x) { return x; }",
"/** @const */",
"var y = f();"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE,
TypeCheck.WRONG_ARGUMENT_COUNT);
}
public void testDifficultClassGenericsInstantiation() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @constructor",
" * @param {T} x",
" */",
"function Foo(x) {}",
"/** @param {Bar<T>} x */",
"Foo.prototype.method = function(x) {};",
"/**",
" * @template T",
" * @constructor",
" * @param {T} x",
" */",
"function Bar(x) {}",
"/** @param {Foo<T>} x */",
"Bar.prototype.method = function(x) {};",
"(new Foo(123)).method(new Bar('asdf'));"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @constructor",
" * @param {T} x",
" */",
"function Foo(x) {}",
"/** @param {Foo<Foo<T>>} x */",
"Foo.prototype.method = function(x) {};",
"(new Foo(123)).method(new Foo(new Foo('asdf')));"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface\n @template T */function A() {};",
"/** @return {T} */A.prototype.foo = function() {};",
"/** @interface\n @template U\n @extends {A<U>} */function B() {};",
"/** @constructor\n @implements {B<string>} */function C() {};",
"/** @return {string}\n @override */",
"C.prototype.foo = function() { return 123; };"),
NewTypeInference.RETURN_NONDECLARED_TYPE);
// Polymorphic method on a generic class.
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" * @param {T} x",
" */",
"function Foo(x) {}",
"/**",
" * @template U",
" * @param {U} x",
" * @return {U}",
" */",
"Foo.prototype.method = function(x) { return x; };",
"(new Foo(123)).method('asdf') - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
// typeCheck(Joiner.on('\n').join(
// "/**",
// " * @template T",
// " * @constructor",
// " */",
// "function Foo() {}",
// "/** @param {T} x */",
// "Foo.prototype.method = function(x) {};",
// "",
// "/**",
// " * @template T",
// " * @constructor",
// " * @extends {Foo<T>}",
// " * @param {T} x",
// " */",
// "function Bar(x) {}",
// // Invalid instantiation here, must be T, o/w bugs like the call to f
// "/** @param {number} x */",
// "Bar.prototype.method = function(x) {};",
// "",
// "/** @param {!Foo<string>} x */",
// "function f(x) { x.method('sadf'); };",
// "f(new Bar('asdf'));"),
// NewTypeInference.FAILED_TO_UNIFY);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T,U",
" */",
"function Foo() {}",
"Foo.prototype.m1 = function() {",
" this.m2(123);",
"};",
"/**",
" * @template U",
" * @param {U} x",
" */",
"Foo.prototype.m2 = function(x) {};"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T, U",
" */",
"function Foo() {}",
"/**",
" * @template T", // shadows Foo#T, U still visible
" * @param {T} x",
" * @param {U} y",
" */",
"Foo.prototype.method = function(x, y) {};",
"var obj = /** @type {!Foo<number, number>} */ (new Foo);",
"obj.method('asdf', 123);", // OK
"obj.method('asdf', 'asdf');"), // warning
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @interface",
" * @template T",
" */",
"function High() {}",
"/** @param {T} x */",
"High.prototype.method = function(x) {};",
"/**",
" * @constructor",
" * @implements {High<number>}",
" */",
"function Low() {}",
"/**",
" * @template T",
" * @param {T} x",
" */",
"Low.prototype.method = function(x) {};"));
}
public void testNominalTypeUnification() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T, U",
" * @param {T} x",
" */",
"function Foo(x) {}",
"/**",
" * @template T",
// {!Foo<T>} is instantiating only the 1st template var of Foo
" * @param {!Foo<T>} x",
" */",
"function fn(x) {}",
"fn(new Foo('asdf'));"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template S, T",
" * @param {S} x",
" */",
"function Foo(x) {",
" /** @type {S} */ this.prop = x;",
"}",
"/**",
" * @template T",
// {!Foo<T>} is instantiating only the 1st template var of Foo
" * @param {!Foo<T>} x",
" * @return {T}",
" */",
"function fn(x) { return x.prop; }",
"fn(new Foo('asdf')) - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testCasts() {
typeCheck(
"(/** @type {number} */ ('asdf'));",
NewTypeInference.INVALID_CAST);
typeCheck(Joiner.on('\n').join(
"function f(/** (number|string) */ x) {",
" var y = /** @type {number} */ (x);",
"}"));
typeCheck("(/** @type {(number|string)} */ (1));");
typeCheck("(/** @type {number} */ (/** @type {?} */ ('asdf')))");
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Parent() {}",
"/** @constructor @extends {Parent} */",
"function Child() {}",
"/** @type {Child|null} */ (new Parent);"));
typeCheck(Joiner.on('\n').join(
"function f(/** (number|string) */ x) {",
" return /** @type {number|boolean} */ (x);",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function High() {}",
"/** @constructor @extends {High} */",
"function Low() {}",
"/** @constructor */",
"function Foo() {}",
"function f(/** (!Foo|!Low) */ x) {",
" return /** @type {!High} */ (x);",
"}"));
}
public void testOverride() {
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function Intf() {}",
"/** @param {(number|string)} x */",
"Intf.prototype.method = function(x) {};",
"/**",
" * @constructor",
" * @implements {Intf}",
" */",
"function C() {}",
"/** @override */",
"C.prototype.method = function (x) { x - 1; };",
"(new C).method('asdf');"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function Intf() {}",
"/** @param {(number|string)} x */",
"Intf.prototype.method = function(x) {};",
"/**",
" * @constructor",
" * @implements {Intf}",
" */",
"function C() {}",
"/** @inheritDoc */",
"C.prototype.method = function (x) { x - 1; };",
"(new C).method('asdf');"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @override */",
"Foo.prototype.method = function() {};"),
TypeCheck.UNKNOWN_OVERRIDE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @inheritDoc */",
"Foo.prototype.method = function() {};"),
TypeCheck.UNKNOWN_OVERRIDE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function High() {}",
"/** @param {number=} x */",
"High.prototype.f = function(x) {};",
"/** @constructor @extends {High} */",
"function Low() {}",
"/** @override */",
"Low.prototype.f = function(x) {};",
"(new Low).f();",
"(new Low).f('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function F() {}",
"/**",
" * @param {string} x",
" * @param {...*} var_args",
" * @return {*}",
" */",
"F.prototype.method;",
"/**",
" * @constructor",
" * @extends {F}",
" */",
"function G() {}",
"/** @override */",
"G.prototype.method = function (x, opt_index) {};",
"(new G).method('asdf');"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function F() {}",
"/**",
" * @param {string} x",
" * @param {...number} var_args",
" * @return {number}",
" */",
"F.prototype.method;",
"/**",
" * @constructor",
" * @extends {F}",
" */",
"function G() {}",
"/** @override */",
"G.prototype.method = function (x, opt_index) {};",
"(new G).method('asdf', 'asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE,
CheckMissingReturn.MISSING_RETURN_STATEMENT);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prototype.m = function() {};",
"/** @constructor @extends {Foo}*/",
"function Bar() {}",
"/**",
" * @param {number=} x",
" * @override",
" */",
"Bar.prototype.m = function(x) {};",
"(new Bar).m(123);"));
typeCheck("(123).toString(16);");
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @constructor @extends {Foo}*/",
"function Bar() {}",
"/**",
" * @param {number=} x",
" * @override",
" */",
"Bar.prototype.m = function(x) {};",
"(new Bar).m(123);"),
TypeCheck.UNKNOWN_OVERRIDE);
}
public void testOverrideNoInitializer() {
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Intf() {}",
"/** @param {number} x */",
"Intf.prototype.method = function(x) {};",
"/** @interface @extends {Intf} */",
"function Subintf() {}",
"/** @override */",
"Subintf.prototype.method;",
"function f(/** !Subintf */ x) { x.method('asdf'); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Intf() {}",
"/** @param {number} x */",
"Intf.prototype.method = function(x) {};",
"/** @interface @extends {Intf} */",
"function Subintf() {}",
"Subintf.prototype.method;",
"function f(/** !Subintf */ x) { x.method('asdf'); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Intf() {}",
"/** @param {number} x */",
"Intf.prototype.method = function(x) {};",
"/** @constructor @implements {Intf} */",
"function C() {}",
"/** @override */",
"C.prototype.method = (function(){ return function(x){}; })();",
"(new C).method('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Intf() {}",
"/** @param {number} x */",
"Intf.prototype.method = function(x) {};",
"/** @constructor @implements {Intf} */",
"function C() {}",
"C.prototype.method = (function(){ return function(x){}; })();",
"(new C).method('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Intf() {}",
"/** @type {string} */",
"Intf.prototype.s;",
"/** @constructor @implements {Intf} */",
"function C() {}",
"/** @override */",
"C.prototype.s = 'str2';",
"(new C).s - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Intf() {}",
"/** @type {string} */",
"Intf.prototype.s;",
"/** @constructor @implements {Intf} */",
"function C() {}",
"/** @type {number} @override */",
"C.prototype.s = 72;"),
GlobalTypeInfo.INVALID_PROP_OVERRIDE);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Intf() {}",
"/** @type {string} */",
"Intf.prototype.s;",
"/** @constructor @implements {Intf} */",
"function C() {}",
"/** @override */",
"C.prototype.s = 72;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testFunctionConstructor() {
typeCheck(Joiner.on('\n').join(
"/** @type {Function} */ function topFun() {}",
"topFun(1);"));
typeCheck(
"/** @type {Function} */ function topFun(x) { return x - 5; }");
typeCheck(Joiner.on('\n').join(
"function f(/** Function */ fun) {}",
"f(function g(x) { return x - 5; });"));
typeCheck(
"function f(/** !Function */ fun) { return new fun(1, 2); }");
typeCheck("function f(/** !Function */ fun) { [] instanceof fun; }");
}
public void testConditionalExBranch() {
typeCheck(Joiner.on('\n').join(
"function g() { throw 1; }",
"function f() {",
" try {",
" if (g()) {}",
" } catch (e) {}",
"};"));
}
public void testGenericInterfaceDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @interface @template T */",
"ns.Interface = function(){}"));
}
public void testGetpropOnTopDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {};",
"/** @type {*} */ Foo.prototype.stuff;",
"function f(/** !Foo */ foo, x) {",
" (foo.stuff.prop = x) || false;",
"};"),
NewTypeInference.PROPERTY_ACCESS_ON_NONOBJECT);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {};",
"/** @type {*} */ Foo.prototype.stuff;",
"function f(/** Foo */ foo) {",
" foo.stuff.prop || false;",
"};"),
NewTypeInference.NULLABLE_DEREFERENCE);
}
public void testImplementsGenericInterfaceDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @interface @template Z */",
"function Foo(){}",
"Foo.prototype.getCount = function /** number */ (){};",
"/**",
" * @constructor @implements {Foo<T>}",
" * @template T",
" */",
"function Bar(){}",
"Bar.prototype.getCount = function /** number */ (){};"));
}
public void testDeadCodeDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"function f() {",
" throw 'Error';",
" return 5;",
"}"));
}
public void testSpecializeFunctionToNominalDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Foo() {}",
"function reqFoo(/** Foo */ foo) {};",
"/** @param {Function} fun */",
"function f(fun) {",
" reqFoo(fun);",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"function f(x) {",
" if (typeof x == 'function') {",
" var /** !Foo */ y = x;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(/** !Object */ x) {",
" if (x instanceof Function) {",
" x(123);",
" }",
"}"));
}
public void testPrototypeMethodOnUndeclaredDoesntCrash() {
typeCheck(
"Foo.prototype.method = function(){ this.x = 5; };",
// VarCheck.UNDEFINED_VAR_ERROR,
CheckGlobalThis.GLOBAL_THIS);
}
public void testFunctionGetpropDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"function g() {}",
"function f() {",
" g();",
" return g.prop;",
"}"),
TypeCheck.INEXISTENT_PROPERTY);
}
public void testUnannotatedBracketAccessDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"function f(foo, i, j) {",
" foo.array[i][j] = 5;",
"}"));
}
public void testUnknownTypeReferenceDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @interface */ function I(){}",
"/** @type {function(NonExistentClass)} */",
"I.prototype.method;"),
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
}
public void testSpecializingTypeVarDoesntGoToBottom() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" */",
"function f(x) {",
" if (typeof x === 'string') {",
" return x.length;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" */",
"function f(x) {",
" if (typeof x === 'string') {",
" return x - 5;",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" */",
"function f(x) {",
" if (typeof x === 'string') {",
" return x - 5;",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" */",
"function f(x) {",
" if (typeof x === 'number') {",
" (function(/** string */ y){})(x);",
" }",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testBottomPropAccessDoesntCrash() {
// TODO(blickly): This warning is not very good.
typeCheck(Joiner.on('\n').join(
"var obj = null;",
"if (obj) obj.prop += 7;"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prototype.m = function(/** number */ x) {};",
"/** @constructor */",
"function Bar() {}",
"Bar.prototype.m = function(/** string */ x) {};",
"function f(/** null|!Foo|!Bar */ x, y) {",
" if (x) {",
" return x.m(y);",
" }",
"}"),
NewTypeInference.BOTTOM_PROP);
}
public void testUnannotatedFunctionSummaryDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"var /** !Promise */ p;",
"function f(unused) {",
" function g(){ return 5; }",
" p.then(g);",
"}"));
typeCheck(Joiner.on('\n').join(
"var /** !Promise */ p;",
"function f(unused) {",
" function g(){ return 5; }",
" var /** null */ n = p.then(g);",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheckCustomExterns(
DEFAULT_EXTERNS + "function f(x, y, z) {}",
"f(1, 2, 3);");
}
public void testSpecializeLooseNullDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"function reqFoo(/** Foo */ x) {}",
"function f(x) {",
" x = null;",
" reqFoo(x);",
"}"));
}
public void testOuterVarDefinitionJoinDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"function f() {",
" if (true) {",
" function g() { new Foo; }",
" g();",
" }",
"}"));
// typeCheck(Joiner.on('\n').join(
// "function f() {",
// " if (true) {",
// " function g() { new Foo; }",
// " g();",
// " }",
// "}"),
// VarCheck.UNDEFINED_VAR_ERROR);
}
public void testUnparameterizedArrayDefinitionDoesntCrash() {
typeCheckCustomExterns(
DEFAULT_EXTERNS + Joiner.on('\n').join(
"/** @constructor */ function Function(){}",
"/** @constructor */ function Array(){}"),
Joiner.on('\n').join(
"function f(/** !Array */ arr) {",
" var newarr = [];",
" newarr[0] = arr[0];",
" newarr[0].prop1 = newarr[0].prop2;",
"};"));
}
public void testInstanceofGenericTypeDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @constructor @template T */ function Foo(){}",
"function f(/** !Foo<?> */ f) {",
" if (f instanceof Foo) return true;",
"};"));
}
public void testRedeclarationOfFunctionAsNamespaceDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = ns || {};",
"ns.fun = function(name) {};",
"ns.fun = ns.fun || {};",
"ns.fun.get = function(/** string */ name) {};"));
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = ns || {};",
"ns.fun = function(name) {};",
"ns.fun.get = function(/** string */ name) {};",
"ns.fun = ns.fun || {};"));
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = ns || {};",
"ns.fun = function(name) {};",
"/** @const */ ns.fun = ns.fun || {};",
"ns.fun.get = function(/** string */ name) {};"));
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = ns || {};",
"ns.fun = function(name) {};",
"ns.fun.get = function(/** string */ name) {};",
"/** @const */ ns.fun = ns.fun || {};"));
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = ns || {};",
"/** @param {string} name */",
"ns.fun = function(name) {};",
"ns.fun.get = function(/** string */ name) {};",
"/** @const */ ns.fun = ns.fun || {};",
"ns.fun(123);"),
TypeCheck.NOT_CALLABLE);
}
public void testInvalidEnumDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @enum {Array<number>} */",
"var FooEnum = {",
" BAR: [5]",
"};",
"/** @param {FooEnum} x */",
"function f(x) {",
" var y = x[0];",
"};"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"var ns = {};",
"function f() {",
" /** @enum {number} */ var EnumType = ns;",
"}"),
GlobalTypeInfo.MALFORMED_ENUM);
}
public void testRemoveNonexistentPropDoesntCrash() {
// TODO(blickly): Would be nice not to warn here,
// even if it means missing the warning below
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {",
" /** @type {!Object} */ this.obj = {arr : []}",
"}",
"Foo.prototype.bar = function() {",
" this.obj.arr.length = 0;",
"}"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {",
" /** @type {!Object} */ this.obj = {}",
"}",
"Foo.prototype.bar = function() {",
" this.obj.prop1.prop2 = 0;",
"}"),
TypeCheck.INEXISTENT_PROPERTY);
}
public void testDoublyAssignedPrototypeMethodDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"Foo.prototype.method = function(){};",
"var f = function() {",
" Foo.prototype.method = function(){};",
"}"),
GlobalTypeInfo.CTOR_IN_DIFFERENT_SCOPE);
}
public void testTopFunctionAsArgumentDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"function f(x) {}",
"function g(value) {",
" if (typeof value == 'function') {",
" f(value);",
" }",
"}"));
}
public void testGetpropDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Obj(){}",
"/** @constructor */ var Foo = function() {",
" /** @private {Obj} */ this.obj;",
"};",
"Foo.prototype.update = function() {",
" if (!this.obj) {}",
"};"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Obj(){}",
"/** @constructor */",
"var Foo = function() {",
" /** @private {Obj} */ this.obj;",
"};",
"Foo.prototype.update = function() {",
" if (!this.obj.size) {}",
"};"),
NewTypeInference.NULLABLE_DEREFERENCE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Obj(){}",
"/** @constructor */",
"var Foo = function() {",
" /** @private {Obj} */ this.obj;",
"};",
"/** @param {!Foo} x */",
"function f(x) {",
" if (!x.obj.size) {}",
"};"),
NewTypeInference.NULLABLE_DEREFERENCE);
}
public void testLooseFunctionSubtypeDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"var Foo = function() {};",
"/** @param {function(!Foo)} fooFun */",
"var reqFooFun = function(fooFun) {};",
"/** @type {function(!Foo)} */",
"var declaredFooFun;",
"function f(opt_fooFun) {",
" reqFooFun(opt_fooFun);",
" var fooFun = opt_fooFun || declaredFooFun;",
" reqFooFun(fooFun);",
"};"));
typeCheck(Joiner.on('\n').join(
"var /** @type {function(number)} */ f;",
"f = (function(x) {",
" x(1, 2);",
" return x;",
"})(function(x, y) {});"));
}
public void testMeetOfLooseObjAndNamedDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){ this.prop = 5; }",
"/** @constructor */ function Bar(){}",
"/** @param {function(!Foo)} func */",
"Bar.prototype.forEach = function(func) {",
" this.forEach(function(looseObj) { looseObj.prop; });",
"};"));
}
// public void testVarargs() {
// // TODO(blickly): Investigate why this doesn't pass
// typeCheck(Joiner.on('\n').join(
// "function foo(baz, /** ...number */ es6_rest_args) {",
// " var bar = [].slice.call(arguments, 0);",
// "}",
// "foo(); foo(3); foo(3, 4);"));
// }
// public void testAccessVarargsDoesntCrash() {
// // TODO(blickly): Support arguments so we only get one warning
// typeCheck(Joiner.on('\n').join(
// "/** @param {...} var_args */",
// "function f(var_args) { return true ? var_args : arguments; }"),
// VarCheck.UNDEFINED_VAR_ERROR,
// VarCheck.UNDEFINED_VAR_ERROR);
// }
public void testUninhabitableObjectTypeDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"function f(/** number */ n) {",
" if (typeof n == 'string') {",
" return { 'First': n, 'Second': 5 };",
" }",
"};"));
}
public void testMockedOutConstructorDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"/** @constructor */ Foo = function(){};"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testNamespacePropWithNoTypeDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @public */ ns.prop;"));
}
public void testArrayLiteralUsedGenericallyDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {!Array<T>} arr",
" * @return {T}",
" */",
"function f(arr) { return arr[0]; }",
"f([1,2,3]);"));
}
public void testSpecializeLooseFunctionDoesntCrash() {
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** !Function */ func) {};",
"function g(obj) {",
" if (goog.isFunction(obj)) {",
" f(obj);",
" }",
"};"));
typeCheck(Joiner.on('\n').join(
"function f(/** !Function */ func) {};",
"function g(obj) {",
" if (typeof obj === 'function') {",
" f(obj);",
" }",
"};"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @param {function(T)} fn",
" * @param {T} x",
" * @template T",
" */",
"function reqGenFun(fn, x) {};",
"function g(obj, str) {",
" var member = obj[str];",
" if (typeof member === 'function') {",
" reqGenFun(member, str);",
" }",
"};"));
}
public void testUnificationWithTopFunctionDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @param {*} value",
" * @param {function(new: T, ...)} type",
" * @template T",
" */",
"function assertInstanceof(value, type) {}",
"/** @const */ var ctor = unresolvedGlobalVar;",
"function f(obj) {",
" if (obj instanceof ctor) {",
" return assertInstanceof(obj, ctor);",
" }",
"}"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE,
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testGetpropOnPossiblyInexistentPropertyDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){};",
"function f() {",
" var obj = 3 ? new Foo : { prop : { subprop : 'str'}};",
" obj.prop.subprop = 'str';",
"};"),
NewTypeInference.POSSIBLY_INEXISTENT_PROPERTY);
}
public void testCtorManipulationDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ var X = function() {};",
"var f = function(ctor) {",
" /** @type {function(new: X)} */",
" function InstantiableCtor() {};",
" InstantiableCtor.prototype = ctor.prototype;",
"}"));
}
public void testAbstractMethodOverrides() {
typeCheck(Joiner.on('\n').join(
"/** @const */ var goog = {};",
"/** @type {!Function} */ goog.abstractMethod = function(){};",
"/** @interface */ function I() {}",
"/** @param {string=} opt_str */",
"I.prototype.done = goog.abstractMethod;",
"/** @implements {I} @constructor */ function Foo() {}",
"/** @override */ Foo.prototype.done = function(opt_str) {}",
"/** @param {I} stats */ function f(stats) {}",
"function g() {",
" var x = new Foo();",
" f(x);",
" x.done();",
"}"));
}
public void testThisReferenceUsedGenerically() {
typeCheck(Joiner.on('\n').join(
"/** @constructor @template T */",
"var Foo = function(t) {",
" /** @type {Foo<T>} */",
" this.parent_ = null;",
"}",
"Foo.prototype.method = function() {",
" var p = this;",
" while (p != null) p = p.parent_;",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor @template T */",
"var Foo = function(t) {",
" /** @type {Foo<T>} */",
" var p = this;",
"}"));
}
public void testGrandparentTemplatizedDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"/** @constructor @template VALUE */",
"var Grandparent = function() {};",
"/** @constructor @extends {Grandparent<number>} */",
"var Parent = function(){};",
"/** @constructor @extends {Parent} */ function Child(){}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor @template VALUE */",
"var Grandparent = function() {};",
"/** @constructor @extends {Grandparent} */",
"var Parent = function(){};",
"/** @constructor @extends {Parent} */ function Child(){}"));
}
public void testDirectPrototypeAssignmentDoesntCrash() {
typeCheck(Joiner.on('\n').join(
"function UndeclaredCtor(parent) {}",
"UndeclaredCtor.prototype = {__proto__: Object.prototype};"));
}
public void testDebuggerStatementDoesntCrash() {
typeCheck("debugger;");
}
public void testDeclaredMethodWithoutScope() {
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Foo(){}",
"/** @type {function(number)} */ Foo.prototype.bar;",
"/** @constructor @implements {Foo} */ function Bar(){}",
"Bar.prototype.bar = function(x){}"));
typeCheck(Joiner.on('\n').join(
"/** @type {!Function} */",
"var g = function() { throw 0; };",
"/** @constructor */ function Foo(){}",
"/** @type {function(number)} */ Foo.prototype.bar = g;",
"/** @constructor @extends {Foo} */ function Bar(){}",
"Bar.prototype.bar = function(x){}"));
typeCheck(Joiner.on('\n').join(
"/** @param {string} s */",
"var reqString = function(s) {};",
"/** @constructor */ function Foo(){}",
"/** @type {function(string)} */ Foo.prototype.bar = reqString;",
"/** @constructor @extends {Foo} */ function Bar(){}",
"Bar.prototype.bar = function(x){}"));
typeCheck(Joiner.on('\n').join(
"/** @param {string} s */",
"var reqString = function(s) {};",
"/** @constructor */ function Foo(){}",
"/** @type {function(number)} */ Foo.prototype.bar = reqString;",
"/** @constructor @extends {Foo} */ function Bar(){}",
"Bar.prototype.bar = function(x){}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"/** @type {Function} */ Foo.prototype.bar = null;",
"/** @constructor @extends {Foo} */ function Bar(){}",
"Bar.prototype.bar = function(){}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"/** @type {!Function} */ Foo.prototype.bar = null;",
"/** @constructor @extends {Foo} */ function Bar(){}",
"Bar.prototype.bar = function(){}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function I(){}",
"/** @return {void} */",
"I.prototype.method;"));
}
public void testDontOverrideNestedPropWithWorseType() {
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"var Bar = function() {};",
"/** @type {Function} */",
"Bar.prototype.method;",
"/** @interface */",
"var Baz = function() {};",
"Baz.prototype.method = function() {};",
"/** @constructor */",
"var Foo = function() {};",
"/** @type {!Bar|!Baz} */",
"Foo.prototype.obj;",
"Foo.prototype.set = function() {",
" this.obj.method = 5;",
"};"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(/** { prop: number } */ obj, x) {",
" x < obj.prop;",
" obj.prop < 'str';",
" obj.prop = 123;",
" x = 123;",
"}",
"f({ prop: 123}, 123)"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testPropNamesWithDot() {
typeCheck("var x = { '.': 1, ';': 2, '/': 3, '{': 4, '}': 5 }");
typeCheck(Joiner.on('\n').join(
"function f(/** { foo : { bar : string } } */ x) {",
" x['foo.bar'] = 5;",
"}"));
typeCheck(Joiner.on('\n').join(
"var x = { '.' : 'str' };",
"x['.'] - 5"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testObjLitDeclaredProps() {
typeCheck(
"({ /** @type {string} */ prop: 123 });",
NewTypeInference.INVALID_OBJLIT_PROPERTY_TYPE);
typeCheck(Joiner.on('\n').join(
"var lit = { /** @type {string} */ prop: 'str' };",
"lit.prop = 123;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"var lit = { /** @type {(number|string)} */ prop: 'str' };",
"var /** string */ s = lit.prop;"));
}
public void testCallArgumentsChecked() {
typeCheck(
"3(1 - 'str');",
TypeCheck.NOT_CALLABLE,
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testRecursiveFunctions() {
typeCheck(
"function foo(){ foo() - 123; return 'str'; }",
NewTypeInference.INVALID_INFERRED_RETURN_TYPE);
typeCheck(
"/** @return {string} */ function foo(){ foo() - 123; return 'str'; }",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @return {number} */",
"var f = function rec() { return rec; };"),
NewTypeInference.RETURN_NONDECLARED_TYPE);
}
public void testStructPropAccess() {
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */ function Foo() { this.prop = 123; }",
"(new Foo).prop;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */ function Foo() { this.prop = 123; }",
"(new Foo)['prop'];"),
TypeValidator.ILLEGAL_PROPERTY_ACCESS);
typeCheck(Joiner.on('\n').join(
"/** @interface */ function Foo() {}",
"/** @type {number} */ Foo.prototype.prop;",
"function f(/** !Foo */ x) { x['prop']; }"),
TypeValidator.ILLEGAL_PROPERTY_ACCESS);
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */ function Foo() {",
" this.prop = 123;",
" this['prop'] - 123;",
"}"),
TypeValidator.ILLEGAL_PROPERTY_ACCESS);
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */ function Foo() { this.prop = 123; }",
"(new Foo)['prop'] = 123;"),
TypeValidator.ILLEGAL_PROPERTY_ACCESS);
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */ function Foo() { this.prop = 123; }",
"function f(pname) { (new Foo)[pname] = 123; }"),
TypeValidator.ILLEGAL_PROPERTY_ACCESS);
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */ function Foo() { this.prop = {}; }",
"(new Foo)['prop'].newprop = 123;"),
TypeValidator.ILLEGAL_PROPERTY_ACCESS);
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */ function Foo() {}",
"/** @constructor */ function Bar() {}",
"function f(cond) {",
" var x;",
" if (cond) {",
" x = new Foo;",
" }",
" else {",
" x = new Bar;",
" }",
" x['prop'] = 123;",
"}"),
TypeValidator.ILLEGAL_PROPERTY_ACCESS);
typeCheck("(/** @struct */ { 'prop' : 1 });", TypeCheck.ILLEGAL_OBJLIT_KEY);
typeCheck(
"var lit = /** @struct */ { prop : 1 }; lit['prop'];",
TypeValidator.ILLEGAL_PROPERTY_ACCESS);
typeCheck(Joiner.on('\n').join(
"function f(cond) {",
" var x;",
" if (cond) {",
" x = /** @struct */ { a: 1 };",
" }",
" else {",
" x = /** @struct */ { a: 2 };",
" }",
" x['a'] = 123;",
"}"),
TypeValidator.ILLEGAL_PROPERTY_ACCESS);
typeCheck(Joiner.on('\n').join(
"function f(cond) {",
" var x;",
" if (cond) {",
" x = /** @struct */ { a: 1 };",
" }",
" else {",
" x = {};",
" }",
" x['random' + 'propname'] = 123;",
"}"),
TypeValidator.ILLEGAL_PROPERTY_ACCESS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @struct",
" */",
"function Foo() {",
" /** @type {number} */",
" this.prop;",
" this.prop = 'asdf';",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @struct",
" */",
"function Foo() {",
" /** @type {number} */",
" this.prop;",
"}",
"(new Foo).prop = 'asdf';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testDictPropAccess() {
typeCheck(Joiner.on('\n').join(
"/** @constructor @dict */ function Foo() { this['prop'] = 123; }",
"(new Foo)['prop'];"));
typeCheck(Joiner.on('\n').join(
"/** @constructor @dict */ function Foo() { this['prop'] = 123; }",
"(new Foo).prop;"),
TypeValidator.ILLEGAL_PROPERTY_ACCESS);
typeCheck(Joiner.on('\n').join(
"/** @constructor @dict */ function Foo() {",
" this['prop'] = 123;",
" this.prop - 123;",
"}"),
TypeValidator.ILLEGAL_PROPERTY_ACCESS);
typeCheck(Joiner.on('\n').join(
"/** @constructor @dict */ function Foo() { this['prop'] = 123; }",
"(new Foo).prop = 123;"),
TypeValidator.ILLEGAL_PROPERTY_ACCESS);
typeCheck(Joiner.on('\n').join(
"/** @constructor @dict */ function Foo() { this['prop'] = {}; }",
"(new Foo).prop.newprop = 123;"),
TypeValidator.ILLEGAL_PROPERTY_ACCESS);
typeCheck(Joiner.on('\n').join(
"/** @constructor @dict */ function Foo() {}",
"/** @constructor */ function Bar() {}",
"function f(cond) {",
" var x;",
" if (cond) {",
" x = new Foo;",
" }",
" else {",
" x = new Bar;",
" }",
" x.prop = 123;",
"}"),
TypeValidator.ILLEGAL_PROPERTY_ACCESS);
typeCheck("(/** @dict */ { prop : 1 });", TypeCheck.ILLEGAL_OBJLIT_KEY);
typeCheck(
"var lit = /** @dict */ { 'prop' : 1 }; lit.prop;",
TypeValidator.ILLEGAL_PROPERTY_ACCESS);
typeCheck(
"(/** @dict */ {}).toString();", TypeValidator.ILLEGAL_PROPERTY_ACCESS);
}
public void testStructWithIn() {
typeCheck("('prop' in /** @struct */ {});", TypeCheck.IN_USED_WITH_STRUCT);
typeCheck(
"for (var x in /** @struct */ {});", TypeCheck.IN_USED_WITH_STRUCT);
}
public void testStructDictSubtyping() {
typeCheck("var lit = { a: 1 }; lit.a - 2; lit['a'] + 5;");
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */ function Foo() {}",
"/** @constructor @dict */ function Bar() {}",
"function f(/** Foo */ x) {}",
"f(/** @dict */ {});"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** { a : number } */ x) {}",
"f(/** @dict */ { 'a' : 5 });"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testInferStructDictFormal() {
typeCheck(Joiner.on('\n').join(
"function f(obj) {",
" return obj.prop;",
"}",
"f(/** @dict */ { 'prop': 123 });"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(obj) {",
" return obj['prop'];",
"}",
"f(/** @struct */ { prop: 123 });"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */",
"function Foo() {}",
"function f(obj) { obj['prop']; return obj; }",
"var /** !Foo */ x = f({ prop: 123 });"));
// We infer unrestricted loose obj for mixed . and [] access
typeCheck(Joiner.on('\n').join(
"function f(obj) {",
" if (obj['p1']) {",
" obj.p2.p3 = 123;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(obj) {",
" return obj['a'] + obj.b;",
"}",
"f({ a: 123, 'b': 234 });"));
}
public void testStructDictInheritance() {
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */",
"function Foo() {}",
"/** @constructor @struct @extends {Foo} */",
"function Bar() {}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */",
"function Foo() {}",
"/** @constructor @unrestricted @extends {Foo} */",
"function Bar() {}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor @dict */",
"function Foo() {}",
"/** @constructor @dict @extends {Foo} */",
"function Bar() {}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor @unrestricted */",
"function Foo() {}",
"/** @constructor @struct @extends {Foo} */",
"function Bar() {}"),
JSTypeCreatorFromJSDoc.CONFLICTING_SHAPE_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor @unrestricted */",
"function Foo() {}",
"/** @constructor @dict @extends {Foo} */",
"function Bar() {}"),
JSTypeCreatorFromJSDoc.CONFLICTING_SHAPE_TYPE);
// Detect bad inheritance but connect the classes anyway
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @type {string} */",
" this.prop = 'asdf';",
"}",
"/**",
" * @constructor",
" * @extends {Foo}",
" * @struct",
" */",
"function Bar() {}",
"(new Bar).prop - 123;"),
JSTypeCreatorFromJSDoc.CONFLICTING_SHAPE_TYPE,
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function Foo() {}",
"/** @constructor @dict @implements {Foo} */",
"function Bar() {}"),
JSTypeCreatorFromJSDoc.DICT_IMPLEMENTS_INTERF);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/**",
" * @constructor",
" * @struct",
" * @extends {Foo}",
" * @suppress {newCheckTypesAllChecks}",
" */",
"function Bar() {}",
"var /** !Foo */ x = new Bar;"));
}
public void testStructPropCreation() {
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */",
"function Foo() { this.prop = 1; }",
"(new Foo).prop = 2;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */",
"function Foo() {}",
"Foo.prototype.method = function() { this.prop = 1; };"),
TypeCheck.ILLEGAL_PROPERTY_CREATION);
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */",
"function Foo() {}",
"Foo.prototype.method = function() { this.prop = 1; };",
"(new Foo).prop = 2;"),
TypeCheck.ILLEGAL_PROPERTY_CREATION,
TypeCheck.ILLEGAL_PROPERTY_CREATION);
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */",
"function Foo() {}",
"(new Foo).prop += 2;"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */",
"function Foo() {}",
"Foo.prototype.method = function() { this.prop = 1; };",
"(new Foo).prop++;"),
TypeCheck.ILLEGAL_PROPERTY_CREATION,
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(
"(/** @struct */ { prop: 1 }).prop2 = 123;",
TypeCheck.ILLEGAL_PROPERTY_CREATION);
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */",
"function Foo() {}",
"/** @constructor @struct @extends {Foo} */",
"function Bar() {}",
"Bar.prototype.prop = 123;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */",
"function Foo() {}",
"/** @constructor @struct @extends {Foo} */",
"function Bar() {}",
"Bar.prototype.prop = 123;",
"(new Foo).prop = 234;"),
TypeCheck.ILLEGAL_PROPERTY_CREATION);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @struct",
" */",
"function Foo() {",
" var t = this;",
" t.x = 123;",
"}"),
TypeCheck.ILLEGAL_PROPERTY_CREATION);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @struct",
" */",
"function Foo() {}",
"Foo.someprop = 123;"));
// TODO(dimvar): the current type inf also doesn't catch this.
// Consider warning when the prop is not an "own" prop.
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */",
"function Foo() {}",
"Foo.prototype.bar = 123;",
"(new Foo).bar = 123;"));
typeCheck(Joiner.on('\n').join(
"function f(obj) { obj.prop = 123; }",
"f(/** @struct */ {});"));
typeCheck(Joiner.on('\n').join(
"/** @constructor @struct */",
"function Foo() {}",
"function f(obj) { obj.prop - 5; return obj; }",
"var s = (1 < 2) ? new Foo : f({ prop: 123 });",
"s.newprop = 123;"),
TypeCheck.ILLEGAL_PROPERTY_CREATION);
}
public void testMisplacedStructDictAnnotation() {
typeCheck(
"/** @struct */ function Struct1() {}",
GlobalTypeInfo.STRUCTDICT_WITHOUT_CTOR);
typeCheck(
"/** @dict */ function Dict() {}",
GlobalTypeInfo.STRUCTDICT_WITHOUT_CTOR);
}
// public void testGlobalVariableInJoin() {
// typeCheck(
// "function f() { true ? globalVariable : 123; }",
// VarCheck.UNDEFINED_VAR_ERROR);
// }
// public void testGlobalVariableInAssign() {
// typeCheck(
// "u.prop = 123;",
// VarCheck.UNDEFINED_VAR_ERROR);
// }
public void testFunctionUnions() {
typeCheck("/** @type {?function()} */ function f() {};");
typeCheck(
"/** @type {?function()} */ function f() {}; f = 7;",
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck("/** @type {?function()} */ function f() {}; f = null;");
typeCheck(
"/** @const */ var ns = {}; /** @type {?function()} */ ns.f = function() {}; ns.f = 7;",
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(
"/** @const */var ns = {}; /** @type {?function()} */ns.f = function(){}; ns.f = null;");
typeCheck(
"/** @type {?function(string)} */ function f(x) { x-5; };",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(
"/** @const */var ns = {}; /** @type {?function(string)} */ns.f = function(x){ x-5; };",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"/** @type {?function()} */ Foo.prototype.f;",
"(new Foo).f = 7;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"/** @type {?function()} */ Foo.prototype.f;",
"(new Foo).f = null;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"/** @type {?function()} */ Foo.prototype.f = function() {};",
"(new Foo).f = 7;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){}",
"/** @type {?function()} */ Foo.prototype.f = function() {};",
"(new Foo).f = null;"));
}
public void testFunctionTypedefs() {
typeCheck("/** @typedef {function()} */ var Fun; /** @type {Fun} */ function f() {};");
typeCheck(Joiner.on('\n').join(
"/** @typedef {function(string)} */ var TakesString;",
"/** @type {TakesString} */ function f(x) {}",
"f(123);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @typedef {number|function()} */ var FunctionUnion;",
"/** @type {FunctionUnion} */ function f(x) {}"),
GlobalTypeInfo.WRONG_PARAMETER_COUNT);
}
public void testGetters() {
typeCheck(
"var x = { /** @return {string} */ get a() { return 1; } };",
NewTypeInference.RETURN_NONDECLARED_TYPE);
typeCheck(
"var x = { /** @param {number} n */ get a() {} };",
GlobalTypeInfo.INEXISTENT_PARAM);
typeCheck(
"var x = { /** @type {string} */ get a() {} };",
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"var x = {",
" /**",
" * @return {T|number} b",
" * @template T",
" */",
" get a() {}",
"};"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(
"var x = /** @dict */ { get a() {} };", TypeCheck.ILLEGAL_OBJLIT_KEY);
typeCheck(
"var x = /** @struct */ { get 'a'() {} };",
TypeCheck.ILLEGAL_OBJLIT_KEY);
typeCheck(
"var x = { get a() { 1 - 'asdf'; } };",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"var x = { get a() { return 1; } };",
"x.a < 'str';"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"var x = { get a() { return 1; } };",
"x.a();"),
TypeCheck.NOT_CALLABLE);
typeCheck(Joiner.on('\n').join(
"var x = { get 'a'() { return 1; } };",
"x['a']();"),
TypeCheck.NOT_CALLABLE);
// assigning to a getter doesn't remove it
typeCheck(Joiner.on('\n').join(
"var x = { get a() { return 1; } };",
"x.a = 'str';",
"x.a - 1;"));
typeCheck(
"var x = /** @struct */ { get a() {} }; x.a = 123;",
TypeCheck.ILLEGAL_PROPERTY_CREATION);
}
public void testSetters() {
typeCheck(
"var x = { /** @return {string} */ set a(b) { return ''; } };",
GlobalTypeInfo.SETTER_WITH_RETURN);
typeCheck(
"var x = { /** @type{function(number):number} */ set a(b) { return 5; } };",
GlobalTypeInfo.SETTER_WITH_RETURN);
typeCheck(Joiner.on('\n').join(
"var x = {",
" /**",
" * @param {T|number} b",
" * @template T",
" */",
" set a(b) {}",
"};"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(
"var x = { set a(b) { return 1; } };",
NewTypeInference.RETURN_NONDECLARED_TYPE);
typeCheck(
"var x = { /** @type {string} */ set a(b) {} };",
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(
"var x = /** @dict */ { set a(b) {} };", TypeCheck.ILLEGAL_OBJLIT_KEY);
typeCheck(
"var x = /** @struct */ { set 'a'(b) {} };",
TypeCheck.ILLEGAL_OBJLIT_KEY);
typeCheck(
"var x = { set a(b) { 1 - 'asdf'; } };",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(
"var x = { set a(b) {}, prop: 123 }; var y = x.a;",
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"var x = { /** @param {string} b */ set a(b) {} };",
"x.a = 123;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"var x = { set a(b) { b - 5; } };",
"x.a = 'str';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"var x = { set 'a'(b) { b - 5; } };",
"x['a'] = 'str';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testConstMissingInitializer() {
typeCheck("/** @const */ var x;", GlobalTypeInfo.CONST_WITHOUT_INITIALIZER);
typeCheck("/** @final */ var x;", GlobalTypeInfo.CONST_WITHOUT_INITIALIZER);
typeCheckCustomExterns(DEFAULT_EXTERNS + "/** @const {number} */ var x;", "");
// TODO(dimvar): must fix externs initialization
// typeCheck("/** @const {number} */ var x;", "x - 5;");
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @const */",
"Foo.prop;"),
GlobalTypeInfo.CONST_WITHOUT_INITIALIZER);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @const */ this.prop;",
"}"),
GlobalTypeInfo.CONST_WITHOUT_INITIALIZER);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @const */",
"Foo.prototype.prop;"),
GlobalTypeInfo.CONST_WITHOUT_INITIALIZER);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @const */",
"ns.prop;"),
GlobalTypeInfo.CONST_WITHOUT_INITIALIZER);
}
public void testMisplacedConstPropertyAnnotation() {
typeCheck(
"function f(obj) { /** @const */ obj.prop = 123; }",
GlobalTypeInfo.MISPLACED_CONST_ANNOTATION);
typeCheck(
"function f(obj) { /** @const */ obj.prop; }",
GlobalTypeInfo.MISPLACED_CONST_ANNOTATION);
typeCheck(
"var obj = { /** @const */ prop: 1 };",
GlobalTypeInfo.MISPLACED_CONST_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"Foo.prototype.method = function() {",
" /** @const */ this.prop = 1;",
"}"),
GlobalTypeInfo.MISPLACED_CONST_ANNOTATION);
// A final constructor isn't the same as a @const property
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /**",
" * @constructor",
" * @final",
" */",
" this.Bar = function() {};",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @enum */",
"ns.e = {/** @const */ A:1};"));
}
public void testConstVarsDontReassign() {
typeCheck(
"/** @const */ var x = 1; x = 2;", NewTypeInference.CONST_REASSIGNED);
typeCheck(
"/** @const */ var x = 1; x += 2;", NewTypeInference.CONST_REASSIGNED);
typeCheck(
"/** @const */ var x = 1; x -= 2;", NewTypeInference.CONST_REASSIGNED);
typeCheck(
"/** @const */ var x = 1; x++;", NewTypeInference.CONST_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @const */ var x = 1;",
"function f() { x = 2; }"),
NewTypeInference.CONST_REASSIGNED);
typeCheckCustomExterns(
DEFAULT_EXTERNS + "/** @const {number} */ var x;", "x = 2;",
NewTypeInference.CONST_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @const */ var x = 1;",
"function g() {",
" var x = 2;",
" x = x + 3;",
"}"));
}
public void testConstPropertiesDontReassign() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @const */ this.prop = 1;",
"}",
"var obj = new Foo;",
"obj.prop = 2;"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @const {number} */",
" this.prop = 1;",
"}",
"var obj = new Foo;",
"obj.prop = 2;"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @const */ this.prop = 1;",
"}",
"var obj = new Foo;",
"obj.prop += 2;"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @const */ this.prop = 1;",
"}",
"var obj = new Foo;",
"obj.prop++;"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @const */",
"ns.prop = 1;",
"ns.prop = 2;"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @const */",
"ns.prop = 1;",
"function f() { ns.prop = 2; }"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @const {number} */",
"ns.prop = 1;",
"ns.prop = 2;"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @const */",
"ns.prop = 1;",
"ns.prop++;"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @const */ Foo.prop = 1;",
"Foo.prop = 2;"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @const {number} */ Foo.prop = 1;",
"Foo.prop++;"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @const */ Foo.prototype.prop = 1;",
"Foo.prototype.prop = 2;"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @const */ Foo.prototype.prop = 1;",
"var protoAlias = Foo.prototype;",
"protoAlias.prop = 2;"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() { /** @const */ this.X = 4; }",
"/** @constructor */",
"function Bar() { /** @const */ this.X = 5; }",
"var fb = true ? new Foo : new Bar;",
"fb.X++;"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
}
public void testConstantByConvention() {
typeCheck(Joiner.on('\n').join(
"var ABC = 123;",
"ABC = 321;"),
NewTypeInference.CONST_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" this.ABC = 123;",
"}",
"(new Foo).ABC = 321;"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
}
public void testDontOverrideFinalMethods() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @final */",
"Foo.prototype.method = function(x) {};",
"/** @constructor @extends {Foo} */",
"function Bar() {}",
"Bar.prototype.method = function(x) {};"),
GlobalTypeInfo.CANNOT_OVERRIDE_FINAL_METHOD);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @final */",
"Foo.prototype.num = 123;",
"/** @constructor @extends {Foo} */",
"function Bar() {}",
"Bar.prototype.num = 2;"));
// // TODO(dimvar): fix
// typeCheck(Joiner.on('\n').join(
// "/** @constructor */",
// "function High() {}",
// "/**",
// " * @param {number} x",
// " * @final",
// " */",
// "High.prototype.method = function(x) {};",
// "/** @constructor @extends {High} */",
// "function Mid() {}",
// "/** @constructor @extends {Mid} */",
// "function Low() {}",
// "Low.prototype.method = function(x) {};"),
// GlobalTypeInfo.CANNOT_OVERRIDE_FINAL_METHOD);
}
public void testInferenceOfConstType() {
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var s = 'str';",
"function f() { s - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** string */ x) {",
" /** @const */",
" var s = x;",
" function g() { s - 5; }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function RegExp(){}",
"/** @const */",
"var r = /find/;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function RegExp(){}",
"/** @const */",
"var r = /find/;",
"function g() { r - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var a = [5];"));
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var a = [5];",
"function g() { a - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"var x;",
"/** @const */ var o = x = {};",
"function g() { return o.prop; }"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @const */ var o = (0,{});",
"function g() { return o.prop; }"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @const */ var s = true ? null : null;",
"function g() { s - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var s = true ? void 0 : undefined;",
"function g() { s - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var b = true ? (1<2) : ('' in {});",
"function g() { b - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var n = 0 || 6;",
"function g() { n < 'str'; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var s = 'str' + 5;",
"function g() { s - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
// TODO(dimvar): must fix externs initialization
// typeCheck(Joiner.on('\n').join(
// "var /** string */ x;",
// "/** @const */",
// "var s = x;",
// "function g() { s - 5; }"),
// NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @const */",
" this.prop = 'str';",
"}",
"(new Foo).prop - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @const */",
"Foo.prop = 'str';",
"function g() { Foo.prop - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** string */ s) {",
" /** @constructor */",
" function Foo() {}",
" /** @const */",
" Foo.prototype.prop = s;",
" function g() {",
" (new Foo).prop - 5;",
" }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @const */",
"ns.prop = 'str';",
"function f() {",
" ns.prop - 5;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x, y) {",
" /** @const */",
" var n = x - y;",
" function g() { n < 'str'; }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" /** @const */",
" var notx = !x;",
" function g() { notx - 5; }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var lit = { a: 'a', b: 'b' };",
"function g() { lit.a - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var n = ('str', 123);",
"function f() { n < 'str'; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var s = x;",
"var /** string */ x;"),
// VariableReferenceCheck.EARLY_REFERENCE,
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" /** @const */",
" var c = x;",
"}"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" /** @const */",
" var c = { a: 1, b: x };",
"}"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @param {{ a: string }} x",
" */",
"function Foo(x) {",
" /** @const */",
" this.prop = x.a;",
"}",
"(new Foo({ a: ''})).prop - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @return {string} */",
"function f() { return ''; }",
"/** @const */",
"var s = f();",
"function g() { s - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var s = f();",
"/** @return {string} */",
"function f() { return ''; }"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @constructor */",
"function Bar() {}",
"/** @const */",
"var foo = new Foo;",
"function g() {",
" var /** Bar */ bar = foo;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var n1 = 1;",
"/** @const */",
"var n2 = n1;",
"function g() { n2 < 'str'; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
// Don't treat aliased constructors as if they were const variables.
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Bar() {}",
"/**",
" * @constructor",
" * @final",
" */",
"var Foo = Bar;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Bar() {}",
"/** @const */",
"var ns = {};",
"/**",
" * @constructor",
" * @final",
" */",
"ns.Foo = Bar;"));
// (Counterintuitive) On a constructor, @final means don't subclass, not
// that it's a const. We don't warn about reassignment.
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @final",
" */",
"var Foo = function() {};",
"Foo = /** @type {?} */ (function() {});"));
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var x = whatever.prop;"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE);
}
public void testSuppressions() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @fileoverview",
" * @suppress {newCheckTypes}",
" */",
"123();"));
typeCheck(Joiner.on('\n').join(
"123();",
"/** @suppress {newCheckTypes} */",
"function f() { 123(); }"),
TypeCheck.NOT_CALLABLE);
typeCheck(Joiner.on('\n').join(
"123();",
"/** @suppress {newCheckTypes} */",
"function f() { 1 - 'str'; }"),
TypeCheck.NOT_CALLABLE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @type {Object} */",
"ns.obj = { prop: 123 };",
"/**",
" * @suppress {duplicate}",
" * @type {Object}",
" */",
"ns.obj = null;"));
typeCheck(Joiner.on('\n').join(
"function f() {",
" /** @const */",
" var ns = {};",
" /** @type {number} */",
" ns.prop = 1;",
" /**",
" * @type {number}",
" * @suppress {duplicate}",
" */",
" ns.prop = 2;",
"}"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @suppress {constantProperty}",
" */",
"function Foo() {",
" /** @const */ this.bar = 3; this.bar += 4;",
"}"));
}
public void testTypedefs() {
typeCheck(Joiner.on('\n').join(
"/** @typedef {number} */",
"var num = 1;"),
GlobalTypeInfo.CANNOT_INIT_TYPEDEF);
// typeCheck(Joiner.on('\n').join(
// "/** @typedef {number} */",
// "var num;",
// "num - 5;"),
// VarCheck.UNDEFINED_VAR_ERROR);
typeCheck(Joiner.on('\n').join(
"/** @typedef {NonExistentType} */",
"var t;",
"function f(/** t */ x) { x - 1; }"),
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
// typeCheck(Joiner.on('\n').join(
// "/** @typedef {number} */",
// "var dup;",
// "/** @typedef {number} */",
// "var dup;"),
// VariableReferenceCheck.REDECLARED_VARIABLE);
typeCheck(Joiner.on('\n').join(
"/** @typedef {number} */",
"var dup;",
"/** @typedef {string} */",
"var dup;",
"var /** dup */ n = 'str';"),
// VariableReferenceCheck.REDECLARED_VARIABLE,
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @typedef {number} */",
"var num;",
"/** @type {num} */",
"var n = 1;"));
typeCheck(Joiner.on('\n').join(
"/** @typedef {number} */",
"var num;",
"/** @type {num} */",
"var n = 'str';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @type {num} */",
"var n = 'str';",
"/** @typedef {number} */",
"var num;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @typedef {number} */",
"var num;",
"function f() {",
" /** @type {num} */",
" var n = 'str';",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @type {num2} */",
"var n = 'str';",
"/** @typedef {num} */",
"var num2;",
"/** @typedef {number} */",
"var num;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @typedef {rec2} */",
"var rec1;",
"/** @typedef {rec1} */",
"var rec2;"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"/** @typedef {{ prop: rec2 }} */",
"var rec1;",
"/** @typedef {{ prop: rec1 }} */",
"var rec2;"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @typedef {Foo} */",
"var Bar;",
"var /** Bar */ x = null;"));
// NOTE(dimvar): I don't know if long term we want to support ! on anything
// other than a nominal-type name, but for now it's good to have this test.
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @typedef {Foo} */",
"var Bar;",
"var /** !Bar */ x = null;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @typedef {number} */",
"var N;",
"function f() {",
" /** @constructor */",
" function N() {}",
" function g(/** N */ obj) { obj - 5; }",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testLends() {
typeCheck(
"(/** @lends {InexistentType} */ { a: 1 });",
GlobalTypeInfo.LENDS_ON_BAD_TYPE);
typeCheck(
"(/** @lends {number} */ { a: 1 });", GlobalTypeInfo.LENDS_ON_BAD_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"(/** @lends {Foo.badname} */ { a: 1 });"),
GlobalTypeInfo.LENDS_ON_BAD_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function Foo() {}",
"(/** @lends {Foo} */ { a: 1 });"),
GlobalTypeInfo.LENDS_ON_BAD_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function Foo() {}",
"(/** @lends {Foo.prototype} */ { a: 1 });"),
GlobalTypeInfo.LENDS_ON_BAD_TYPE);
typeCheck(
"(/** @lends {Inexistent.Type} */ { a: 1 });",
GlobalTypeInfo.LENDS_ON_BAD_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"(/** @lends {ns} */ { /** @type {number} */ prop : 1 });",
"function f() { ns.prop = 'str'; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"(/** @lends {ns} */ { /** @type {number} */ prop : 1 });",
"/** @const */ var ns = {};",
"function f() { ns.prop = 'str'; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"(/** @lends {ns} */ { prop : 1 });",
"function f() { var /** string */ s = ns.prop; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @const */",
"ns.subns = {};",
"(/** @lends {ns.subns} */ { prop: 1 });",
"var /** string */ s = ns.subns.prop;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"(/** @lends {Foo} */ { prop: 1 });",
"var /** string */ s = Foo.prop;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"(/** @lends {Foo} */ { prop: 1 });",
"function f() { var /** string */ s = Foo.prop; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @constructor */",
"ns.Foo = function() {};",
"(/** @lends {ns.Foo} */ { prop: 1 });",
"function f() { var /** string */ s = ns.Foo.prop; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"(/** @lends {Foo.prototype} */ { /** @type {number} */ a: 1 });",
"var /** string */ s = Foo.prototype.a;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"(/** @lends {Foo.prototype} */ { /** @type {number} */ a: 1 });",
"var /** string */ s = (new Foo).a;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() { /** @type {number} */ this.prop = 1; }",
"(/** @lends {Foo.prototype} */",
" { /** @return {number} */ m: function() { return this.prop; } });",
"var /** string */ s = (new Foo).m();"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testEnumBasicTyping() {
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E = {",
" ONE: 1,",
" TWO: 2",
"};",
"function f(/** E */ x) { x < 'str'; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @enum */",
// No type annotation defaults to number
"var E = {",
" ONE: 1,",
" TWO: 2",
"};",
"function f(/** E */ x) { x < 'str'; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E = {",
" ONE: 1,",
" TWO: 2",
"};",
"function f(/** E */ x) {}",
"function g(/** number */ x) {}",
"f(E.TWO);",
"g(E.TWO);"));
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E = {",
" ONE: 1,",
" TWO: 2",
"};",
"function f(/** E */ x) {}",
"f(1);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E = {",
" ONE: 1,",
" TWO: 2",
"};",
"function f() { E.THREE - 5; }"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @enum {!Foo} */",
"var E = { ONE: new Foo };",
"/** @constructor */",
"function Foo() {}"));
typeCheck(Joiner.on('\n').join(
"/** @typedef {number} */",
"var num;",
"/** @enum {num} */",
"var E = { ONE: 1 };",
"function f(/** E */ x) { x < 'str'; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testEnumsWithNonScalarDeclaredType() {
typeCheck(Joiner.on('\n').join(
"/** @enum {!Object} */ var E = {FOO: { prop: 1 }};",
"E.FOO.prop - 5;"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @enum {{prop: number}} */ var E = {FOO: { prop: 1 }};",
"E.FOO.prop - 5;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @const */ this.prop = 1;",
"}",
"/** @enum {!Foo} */",
"var E = { ONE: new Foo() };",
"function f(/** E */ x) { x.prop < 'str'; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @const */ this.prop = 1;",
"}",
"/** @enum {!Foo} */",
"var E = { ONE: new Foo() };",
"function f(/** E */ x) { x.prop = 2; }"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @enum {!Foo} */",
"var E = { A: new Foo };",
"function f(/** E */ x) { x instanceof Foo; }"));
}
public void testEnumBadInitializer() {
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E;"),
GlobalTypeInfo.MALFORMED_ENUM);
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E = {};"),
GlobalTypeInfo.MALFORMED_ENUM);
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E = 1;"),
GlobalTypeInfo.MALFORMED_ENUM);
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E = {",
" ONE: 1,",
" TWO: true",
"};"),
NewTypeInference.INVALID_OBJLIT_PROPERTY_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E = { a: 1 };"),
TypeCheck.ENUM_NOT_CONSTANT);
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E = { A: 1, A: 2 };"),
GlobalTypeInfo.DUPLICATE_PROP_IN_ENUM);
}
public void testEnumPropertiesConstant() {
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E = {",
" ONE: 1,",
" TWO: 2",
"};",
"E.THREE = 3;"));
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E = {",
" ONE: 1,",
" TWO: 2",
"};",
"E.ONE = E.TWO;"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E = {",
" ONE: 1,",
" TWO: 2",
"};",
"function f(/** E */) { E.ONE = E.TWO; }"),
NewTypeInference.CONST_PROPERTY_REASSIGNED);
}
public void testEnumIllegalRecursion() {
typeCheck(Joiner.on('\n').join(
"/** @enum {Type2} */",
"var Type1 = {",
" ONE: null",
"};",
"/** @enum {Type1} */",
"var Type2 = {",
" ONE: null",
"};"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION,
// This warning is a side-effect of the fact that, when there is a
// cycle, the resolution of one enum will fail but the others will
// complete successfully.
NewTypeInference.INVALID_OBJLIT_PROPERTY_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @enum {Type2} */",
"var Type1 = {",
" ONE: null",
"};",
"/** @typedef {Type1} */",
"var Type2;"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
}
public void testEnumBadDeclaredType() {
typeCheck(Joiner.on('\n').join(
"/** @enum {InexistentType} */",
"var E = { ONE : null };"),
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
typeCheck(Joiner.on('\n').join(
"/** @enum {*} */",
"var E = { ONE: 1, STR: '' };"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
// No free type variables in enums
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" */",
"function f(x) {",
" /** @enum {function(T):number} */",
" var E = { ONE: x };",
"}"),
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" */",
"function f(x) {",
" /** @enum {T} */",
" var E1 = { ONE: 1 };",
" /** @enum {function(E1):E1} */",
" var E2 = { ONE: function(x) { return x; } };",
"}"),
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" */",
"function f(x) {",
" /** @typedef {T} */ var AliasT;",
" /** @enum {T} */",
" var E1 = { ONE: 1 };",
" /** @enum {function(E1):T} */",
" var E2 = { ONE: function(x) { return x; } };",
"}"),
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME,
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME,
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
// No unions in enums
typeCheck(Joiner.on('\n').join(
"/** @enum {number|string} */",
"var E = { ONE: 1, STR: '' };"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @enum {Foo} */",
"var E = { ONE: new Foo, TWO: null };"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"/** @typedef {number|string} */",
"var NOS;",
"/** @enum {NOS} */",
"var E = { ONE: 1, STR: '' };"),
RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
}
public void testEnumsWithGenerics() {
typeCheck(Joiner.on('\n').join(
"/** @enum */ var E1 = { A: 1};",
"/**",
" * @template T",
" * @param {(T|E1)} x",
" * @return {(T|E1)}",
" */",
"function f(x) { return x; }",
"var /** string */ n = f('str');"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @enum */ var E1 = { A: 1};",
"/** @enum */ var E2 = { A: 2};",
"/**",
" * @template T",
" * @param {(T|E1)} x",
" * @return {(T|E1)}",
" */",
"function f(x) { return x; }",
"var /** (E2|string) */ x = f('str');"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @enum */",
"var E = { A: 1 };",
"/**",
" * @template T",
" * @param {number|!Array<T>} x",
" */",
"function f(x) {}",
"f(E.A);",
"f(123);"));
typeCheck(Joiner.on('\n').join(
"/** @enum {string} */",
"var e1 = { A: '' };",
"/** @enum {string} */",
"var e2 = { B: '' };",
"/**",
" * @template T",
" * @param {T|e1} x",
" * @return {T}",
" */",
"function f(x) { return /** @type {T} */ (x); }",
"/** @param {number|e2} x */",
"function g(x) { f(x) - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testEnumJoinSpecializeMeet() {
// join: enum {number} with number
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E = { ONE: 1 };",
"function f(cond) {",
" var x = cond ? E.ONE : 5;",
" x - 2;",
" var /** E */ y = x;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
// join: enum {Low} with High, to High
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function High() {}",
"/** @constructor @extends {High} */",
"function Low() {}",
"/** @enum {!Low} */",
"var E = { A: new Low };",
"function f(cond) {",
" var x = cond ? E.A : new High;",
" var /** High */ y = x;",
" var /** E */ z = x;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
// join: enum {High} with Low, to (enum{High}|Low)
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function High() {}",
"/** @constructor @extends {High} */",
"function Low() {}",
"/** @enum {!High} */",
"var E = { A: new High };",
"function f(cond) {",
" var x = cond ? E.A : new Low;",
" if (!(x instanceof Low)) { var /** E */ y = x; }",
"}"));
// meet: enum {?} with string, to enum {?}
typeCheck(Joiner.on('\n').join(
"/** @enum {?} */",
"var E = { A: 123 };",
"function f(x) {",
" var /** string */ s = x;",
" var /** E */ y = x;",
" s = x;",
"}",
"f('str');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
// meet: E1|E2 with E1|E3, to E1
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E1 = { ONE: 1 };",
"/** @enum {number} */",
"var E2 = { TWO: 1 };",
"/** @enum {number} */",
"var E3 = { THREE: 1 };",
"function f(x) {",
" var /** (E1|E2) */ y = x;",
" var /** (E1|E3) */ z = x;",
" var /** E1 */ w = x;",
"}",
"f(E2.TWO);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
// meet: enum {number} with number, to enum {number}
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E = { ONE: 1 };",
"function f(x) {",
" var /** E */ y = x;",
" var /** number */ z = x;",
"}",
"f(123);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
// meet: enum {Low} with High, to enum {Low}
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function High() {}",
"/** @constructor @extends {High} */",
"function Low() {}",
"/** @enum {!Low} */",
"var E = { A: new Low };",
"function f(x) {",
" var /** !High */ y = x;",
" var /** E */ z = x;",
"}",
"f(new High);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
// meet: enum {Low} with (High1|High2), to enum {Low}
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function High1() {}",
"/** @interface */",
"function High2() {}",
"/** @constructor @implements {High1} @implements {High2} */",
"function Low() {}",
"/** @enum {!Low} */",
"var E = { A: new Low };",
"function f(x) {",
" var /** (!High1 | !High2) */ y = x;",
" var /** E */ z = x;",
"}",
"f(/** @type {!High1} */ (new Low));"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
// meet: enum {High} with Low
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function High() {}",
"/** @constructor @extends {High} */",
"function Low() {}",
"/** @enum {!High} */",
"var E = { A: new High };",
"/** @param {function(E)|function(!Low)} x */",
"function f(x) { x(123); }"),
JSTypeCreatorFromJSDoc.UNION_IS_UNINHABITABLE);
}
public void testEnumAliasing() {
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var e1 = { A: 1 };",
"/** @enum {number} */",
"var e2 = e1;"));
typeCheck(Joiner.on('\n').join(
"var x;",
"/** @enum {number} */",
"var e1 = { A: 1 };",
"/** @enum {number} */",
"var e2 = x;"),
GlobalTypeInfo.MALFORMED_ENUM);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns1 = {};",
"/** @enum {number} */",
"ns1.e1 = { A: 1 };",
"/** @const */",
"var ns2 = {};",
"/** @enum {number} */",
"ns2.e2 = ns1.e1;"));
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var e1 = { A: 1 };",
"/** @enum {number} */",
"var e2 = e1;",
"function f(/** e2 */ x) {}",
"f(e1.A);"));
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var e1 = { A: 1 };",
"/** @enum {number} */",
"var e2 = e1;",
"function f(/** e2 */ x) {}",
"f(e2.A);"));
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var e1 = { A: 1 };",
"/** @enum {number} */",
"var e2 = e1;",
"function f(/** e2 */ x) {}",
"f('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns1 = {};",
"/** @enum {number} */",
"ns1.e1 = { A: 1 };",
"/** @const */",
"var ns2 = {};",
"/** @enum {number} */",
"ns2.e2 = ns1.e1;",
"function f(/** ns2.e2 */ x) {}",
"f(ns1.e1.A);"));
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns1 = {};",
"/** @enum {number} */",
"ns1.e1 = { A: 1 };",
"/** @const */",
"var ns2 = {};",
"/** @enum {number} */",
"ns2.e2 = ns1.e1;",
"function f(/** ns1.e1 */ x) {}",
"f(ns2.e2.A);"));
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns1 = {};",
"/** @enum {number} */",
"ns1.e1 = { A: 1 };",
"function g() {",
" /** @const */",
" var ns2 = {};",
" /** @enum {number} */",
" ns2.e2 = ns1.e1;",
" function f(/** ns1.e1 */ x) {}",
" f(ns2.e2.A);",
"}"));
}
public void testNoDoubleWarnings() {
typeCheck(
"if ((4 - 'str') && true) { 4 + 5; }",
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck("(4 - 'str') ? 5 : 6;", NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testRecordSpecializeNominalPreservesRequired() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() { /** @type {number|string} */ this.x = 5 };",
"var o = true ? {x:5} : {y:'str'};",
"if (o instanceof Foo) {",
" var /** {x:number} */ o2 = o;",
"}",
"(function(/** {x:number} */ o3){})(o);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testGoogIsPredicatesNoSpecializedContext() {
typeCheck(CLOSURE_BASE + "goog.isNull();", TypeCheck.WRONG_ARGUMENT_COUNT);
typeCheck(
CLOSURE_BASE + "goog.isNull(1, 2, 5 - 'str');",
TypeCheck.WRONG_ARGUMENT_COUNT,
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(CLOSURE_BASE
+ "function f(x) { var /** boolean */ b = goog.isNull(x); }");
}
public void testGoogIsPredicatesTrue() {
typeCheck(CLOSURE_BASE
+ "function f(x) { if (goog.isNull(x)) { var /** undefined */ y = x; } }",
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @param {number=} x */",
"function f(x) {",
" if (goog.isDef(x)) {",
" x - 5;",
" }",
" x - 5;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @constructor */",
"function Foo() {}",
"/** @param {Foo=} x */",
"function f(x) {",
" var /** !Foo */ y;",
" if (goog.isDefAndNotNull(x)) {",
" y = x;",
" }",
" y = x;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** (Array<number>|number) */ x) {",
" var /** Array<number> */ a;",
" if (goog.isArray(x)) {",
" a = x;",
" }",
" a = x;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @param {null|function(number)} x */ ",
"function f(x) {",
" if (goog.isFunction(x)) {",
" x('str');",
" }",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(x) {",
" if (goog.isObject(x)) {",
" var /** null */ y = x;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** (number|string) */ x) {",
" if (goog.isString(x)) {",
" x < 'str';",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** (number|string) */ x) {",
" if (goog.isNumber(x)) {",
" x - 5;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** (number|boolean) */ x) {",
" if (goog.isBoolean(x)) {",
" var /** boolean */ b = x;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/**",
" * @param {number|string} x",
" * @return {string}",
" */",
"function f(x) {",
" return goog.isString(x) && (1 < 2) ? x : 'a';",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/**",
" * @param {*} o1",
" * @param {*} o2",
" * @return {boolean}",
" */",
"function deepEquals(o1, o2) {",
" if (goog.isObject(o1) && goog.isObject(o2)) {",
" if (o1.length != o2.length) {",
" return true;",
" }",
" }",
" return false;",
"}"));
}
public void testGoogIsPredicatesFalse() {
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @constructor */",
"function Foo() {}",
"function f(/** Foo */ x) {",
" var /** !Foo */ y;",
" if (!goog.isNull(x)) {",
" y = x;",
" }",
" y = x;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @param {number=} x */",
"function f(x) {",
" if (!goog.isDef(x)) {",
" var /** undefined */ u = x;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @constructor */",
"function Foo() {}",
"/** @param {Foo=} x */",
"function f(x) {",
" if (!goog.isDefAndNotNull(x)) {",
" var /** (null|undefined) */ y = x;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** (number|string) */ x) {",
" if (!goog.isString(x)) {",
" x - 5;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** (number|string) */ x) {",
" if (!goog.isNumber(x)) {",
" x < 'str';",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** (number|boolean) */ x) {",
" if (!goog.isBoolean(x)) {",
" x - 5;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** (number|!Array<number>) */ x) {",
" if (!goog.isArray(x)) {",
" x - 5;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(x) {",
" if (goog.isArray(x)) {",
" return x[0] - 5;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** (number|function(number)) */ x) {",
" if (!goog.isFunction(x)) {",
" x - 5;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @constructor */",
"function Foo() {}",
"/** @param {?Foo} x */",
"function f(x) {",
" if (!goog.isObject(x)) {",
" var /** null */ y = x;",
" }",
"}"));
}
public void testGoogTypeof() {
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** (number|string) */ x) {",
" if (goog.typeOf(x) === 'number') {",
" var /** number */ n = x;",
" } else {",
" var /** string */ s = x;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** (number|string) */ x) {",
" if ('number' === goog.typeOf(x)) {",
" var /** number */ n = x;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"function f(/** (number|string) */ x) {",
" if (goog.typeOf(x) == 'number') {",
" var /** number */ n = x;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @param {number=} x */",
"function f(x) {",
" if (goog.typeOf(x) === 'undefined') {",
" var /** undefined */ u = x;",
" } else {",
" var /** number */ n = x;",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
CLOSURE_BASE,
"/** @param {string} x */",
"function f(x, other) {",
" if (goog.typeOf(x) === other) {",
" var /** null */ n = x;",
" } else {",
" x - 5;",
" }",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS,
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testSuperClassCtorProperty() throws Exception {
String CLOSURE_DEFS = Joiner.on('\n').join(
"/** @const */ var goog = {};",
"goog.inherits = function(child, parent){};");
typeCheck(CLOSURE_DEFS + Joiner.on('\n').join(
"/** @constructor */function base() {}",
"/** @return {number} */ ",
" base.prototype.foo = function() { return 1; };",
"/** @extends {base}\n * @constructor */function derived() {}",
"goog.inherits(derived, base);",
"var /** number */ n = derived.superClass_.foo()"));
typeCheck(CLOSURE_DEFS + Joiner.on('\n').join(
"/** @constructor */ function OldType() {}",
"/** @param {?function(new:OldType)} f */ function g(f) {",
" /**",
" * @constructor",
" * @extends {OldType}",
" */",
" function NewType() {};",
" goog.inherits(NewType, f);",
" NewType.prototype.method = function() {",
" NewType.superClass_.foo.call(this);",
" };",
"}"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(CLOSURE_DEFS + Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"goog.inherits(Foo, Object);",
"var /** !Object */ b = Foo.superClass_;"));
typeCheck(CLOSURE_DEFS + Joiner.on('\n').join(
"/** @constructor */ function base() {}",
"/** @constructor @extends {base} */ function derived() {}",
"goog.inherits(derived, base);",
"var /** null */ b = derived.superClass_"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(
CLOSURE_DEFS + "var /** !Object */ b = Object.superClass_",
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(
CLOSURE_DEFS + "var o = {x: 'str'}; var q = o.superClass_;",
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(CLOSURE_DEFS
+ "var o = {superClass_: 'str'}; var /** string */ s = o.superClass_;");
}
public void testAcrossScopeNamespaces() {
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"(function() {",
" /** @constructor */",
" ns.Foo = function() {};",
"})();",
"ns.Foo();"),
TypeCheck.CONSTRUCTOR_NOT_CALLABLE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"(function() {",
" /** @type {string} */",
" ns.str = 'str';",
"})();",
"ns.str - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"(function() {",
" /** @constructor */",
" ns.Foo = function() {};",
"})();",
"function f(/** ns.Foo */ x) {}",
"f(1);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"(function() {",
" /** @constructor */",
" ns.Foo = function() {};",
"})();",
"var /** ns.Foo */ x = 123;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testQualifiedNamedTypes() {
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @constructor */",
"ns.Foo = function() {};",
"ns.Foo();"),
TypeCheck.CONSTRUCTOR_NOT_CALLABLE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @typedef {number} */",
"ns.num;",
"var /** ns.num */ y = 'str';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @enum {number} */",
"ns.Foo = { A: 1 };",
"var /** ns.Foo */ y = 'str';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var E = { A: 1 };",
"/** @typedef {number} */",
"E.num;",
"var /** E.num */ x = 'str';"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testEnumsAsNamespaces() {
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @enum {number} */",
"ns.E = {",
" ONE: 1,",
" TWO: true",
"};"),
NewTypeInference.INVALID_OBJLIT_PROPERTY_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @enum */",
"var E = { A: 1 };",
"/** @enum */",
"E.E2 = { B: true };",
"var /** E */ x = E.A;"),
NewTypeInference.INVALID_OBJLIT_PROPERTY_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @enum */",
"var E = { A: 1 };",
"/** @constructor */",
"E.Foo = function(x) {};",
"var /** E */ x = E.A;"));
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @enum {number} */",
"ns.E = { A: 1 };",
"/** @constructor */",
"ns.E.Foo = function(x) {};"));
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @enum {number} */",
"ns.E = { A: 1 };",
"/** @constructor */",
"ns.E.Foo = function(x) {};",
"function f() { ns.E.Foo(); }"),
TypeCheck.CONSTRUCTOR_NOT_CALLABLE);
}
public void testStringMethods() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function String(){}",
"/** @this {String|string} */",
"String.prototype.substr = function(start) {};",
"/** @const */ var ns = {};",
"/** @const */ var s = 'str';",
"ns.r = s.substr(2);"));
}
public void testOutOfOrderDeclarations() {
// This is technically valid JS, but we don't support it
typeCheck("Foo.STATIC = 5; /** @constructor */ function Foo(){}");
}
public void testAbstractMethodsAreTypedCorrectly() {
typeCheck(Joiner.on('\n').join(
"/** @type {!Function} */",
"var abstractMethod = function(){};",
"/** @constructor */ function Foo(){};",
"/** @constructor @extends {Foo} */ function Bar(){};",
"/** @param {number} index */",
"Foo.prototype.m = abstractMethod;",
"/** @override */",
"Bar.prototype.m = function(index) {};"));
typeCheck(Joiner.on('\n').join(
"/** @type {!Function} */",
"var abstractMethod = function(){};",
"/** @constructor */ function Foo(){};",
"/** @constructor @extends {Foo} */ function Bar(){};",
"/** @param {number} index */",
"Foo.prototype.m = abstractMethod;",
"/** @override */",
"Bar.prototype.m = function(index) {};",
"(new Bar).m('str');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @type {!Function} */",
"var abstractMethod = function(){};",
"/** @constructor */ function Foo(){};",
"/** @constructor @extends {Foo} */ function Bar(){};",
"/**",
" * @param {number} b",
" * @param {string} a",
" */",
"Foo.prototype.m = abstractMethod;",
"/** @override */",
"Bar.prototype.m = function(a, b) {};",
"(new Bar).m('str', 5);"),
NewTypeInference.INVALID_ARGUMENT_TYPE,
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @type {!Function} */",
"var abstractMethod = function(){};",
"/** @constructor */ function Foo(){};",
"/** @constructor @extends {Foo} */ function Bar(){};",
"/** @type {function(number, string)} */",
"Foo.prototype.m = abstractMethod;",
"/** @override */",
"Bar.prototype.m = function(a, b) {};",
"(new Bar).m('str', 5);"),
NewTypeInference.INVALID_ARGUMENT_TYPE,
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testUseJsdocOfCalleeForUnannotatedFunctionsInArgumentPosition() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() { /** @type {string} */ this.prop = 'asdf'; }",
"/** @param {function(!Foo)} fun */",
"function f(fun) {}",
"f(function(x) { x.prop = 123; });"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() { /** @type {string} */ this.prop = 'asdf'; }",
"function f(/** function(this:Foo) */ x) {}",
"f(function() { this.prop = 123; });"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @param {function(string)} fun */",
"function f(fun) {}",
"f(function(str) { str - 5; });"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {function(number, number=)} fun */",
"function f(fun) {}",
"f(function(num, maybeNum) { num - maybeNum; });"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {function(string, ...string)} fun */",
"function f(fun) {}",
"f(function(str, maybeStrs) { str - 5; });"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @param {function(string)} fun */",
"ns.f = function(fun) {}",
"ns.f(function(str) { str - 5; });"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @type {function(function(string))} */",
"ns.f = function(fun) {}",
"ns.f(function(str) { str - 5; });"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @param {function(string)} fun */",
"Foo.f = function(fun) {}",
"Foo.f(function(str) { str - 5; });"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"(/** @param {function(string)} fun */ function(fun) {})(",
" function(str) { str - 5; });"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @param {function(function(function(string)))} outerFun */",
"ns.f = function(outerFun) {};",
"ns.f(function(innerFun) {",
" innerFun(function(str) { str - 5; });",
"});"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testNamespacesWithNonEmptyObjectLiteral() {
typeCheck("/** @const */ var o = { /** @const */ PROP: 5 };");
typeCheck(
"var x = 5; /** @const */ var o = { /** @const {number} */ PROP: x };");
typeCheck(Joiner.on('\n').join(
"var x = 'str';",
"/** @const */ var o = { /** @const {string} */ PROP: x };",
"function g() { o.PROP - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @const */ ns.o = { /** @const */ PROP: 5 };"));
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"var x = 5;",
"/** @const */ ns.o = { /** @const {number} */ PROP: x };"));
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"var x = 'str';",
"/** @const */ ns.o = { /** @const {string} */ PROP: x };",
"function g() { ns.o.PROP - 5; }"),
NewTypeInference.INVALID_OPERAND_TYPE);
// These declarations are not considered namespaces
typeCheck(
"(function(){ return {}; })().ns = { /** @const */ PROP: 5 };",
GlobalTypeInfo.MISPLACED_CONST_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"function f(/** { x : string } */ obj) {",
" obj.ns = { /** @const */ PROP: 5 };",
"}"),
GlobalTypeInfo.MISPLACED_CONST_ANNOTATION);
}
// TODO(dimvar): fix
public void testAllTestsShouldHaveDupPropWarnings() {
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @const */",
"ns.Foo = {};",
"ns.Foo = { a: 123 };"));
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @const */",
"ns.Foo = {};",
"/** @const */",
"ns.Foo = { a: 123 };"));
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @const */",
"ns.Foo = {};",
"/**",
" * @const",
// @suppress is ignored here b/c there is no @type in the jsdoc.
" * @suppress {duplicate}",
" */",
"ns.Foo = { a: 123 };"));
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @const */",
"ns.Foo = {};",
"/** @type {number} */",
"ns.Foo = 123;"));
typeCheck(Joiner.on('\n').join(
"/** @enum {number} */",
"var en = { A: 5 };",
"/** @const */",
"en.Foo = {};",
"/** @type {number} */",
"en.Foo = 123;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @const */",
"Foo.ns = {};",
"/** @const */",
"Foo.ns = {};"));
}
public void testNominalTypeAliasing() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @constructor */",
"var Bar = Foo;",
"var /** !Bar */ x = new Foo();"));
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @constructor */",
"ns.Foo = function() {};",
"/** @constructor */",
"ns.Bar = ns.Foo;",
"function g() {",
" var /** !ns.Bar */ x = new ns.Foo();",
" var /** !ns.Bar */ y = new ns.Bar();",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @type {number} */",
"var n = 123;",
"/** @constructor */",
"var Foo = n;"),
GlobalTypeInfo.EXPECTED_CONSTRUCTOR);
typeCheck(Joiner.on('\n').join(
"/** @type {number} */",
"var n = 123;",
"/** @interface */",
"var Foo = n;"),
GlobalTypeInfo.EXPECTED_INTERFACE);
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function Foo() {}",
"/** @constructor */",
"var Bar = Foo;"),
GlobalTypeInfo.EXPECTED_CONSTRUCTOR);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @interface */",
"var Bar = Foo;"),
GlobalTypeInfo.EXPECTED_INTERFACE);
// TODO(dimvar): When we allow unknown type names, eg, for fwd-declared
// types, then we can also fix this.
// Currently, the type checker doesn't know what !Foo is.
typeCheckCustomExterns(
DEFAULT_EXTERNS + "var Bar;",
Joiner.on('\n').join(
"/**",
" * @constructor",
" * @final",
" */",
"var Foo = Bar;",
"var /** !Foo */ x;"),
GlobalTypeInfo.EXPECTED_CONSTRUCTOR);
}
public void testTypeVariablesVisibleInPrototypeMethods() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" */",
"function Foo() {}",
"Foo.prototype.method = function() {",
" /** @type {T} */",
" this.prop = 123;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" */",
"function Foo() {}",
"/** @param {T} x */",
"Foo.prototype.method = function(x) {",
" x = 123;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" */",
"function Foo() {}",
"/** @param {T} x */",
"Foo.prototype.method = function(x) {",
" this.prop = x;",
"}"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" */",
"function Foo() {}",
"/** @param {T} x */",
"Foo.prototype.method = function(x) {",
" /** @const */",
" this.prop = x;",
"}"),
GlobalTypeInfo.MISPLACED_CONST_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" */",
"function Parent() {}",
"/**",
" * @constructor",
" * @extends {Parent<string>}",
" */",
"function Child() {}",
"Child.prototype.method = function() {",
" /** @type {T} */",
" this.prop = 123;",
"}"),
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
}
public void testInferConstTypeFromEnumProps() {
typeCheck(Joiner.on('\n').join(
"/** @enum */",
"var e = { A: 1 };",
"/** @const */",
"var numarr = [ e.A ];"));
typeCheck(Joiner.on('\n').join(
"/** @enum */",
"var e = { A: 1 };",
"/** @type {number} */",
"e.prop = 123;",
"/** @const */",
"var x = e.prop;"));
}
private static final String FORWARD_DECLARATION_DEFINITIONS = Joiner.on('\n').join(
"/** @const */ var goog = {};",
"goog.addDependency = function(file, provides, requires){};",
"goog.forwardDeclare = function(name){};");
public void testForwardDeclarations() {
typeCheck(Joiner.on('\n').join(FORWARD_DECLARATION_DEFINITIONS,
"goog.addDependency('', ['Foo'], []);",
"goog.forwardDeclare('Bar');",
"function f(/** !Foo */ x) {}",
"function g(/** !Bar */ y) {}"));
typeCheck(Joiner.on('\n').join(FORWARD_DECLARATION_DEFINITIONS,
"/** @const */ var ns = {};",
"goog.addDependency('', ['ns.Foo'], []);",
"goog.forwardDeclare('ns.Bar');",
"function f(/** !ns.Foo */ x) {}",
"function g(/** !ns.Bar */ y) {}"));
typeCheck(Joiner.on('\n').join(FORWARD_DECLARATION_DEFINITIONS,
"/** @const */ var ns = {};",
"goog.forwardDeclare('ns.Bar');",
"function f(/** !ns.Baz */ x) {}"),
GlobalTypeInfo.UNRECOGNIZED_TYPE_NAME);
typeCheck(Joiner.on('\n').join(FORWARD_DECLARATION_DEFINITIONS,
"goog.addDependency('', ['Foo'], []);",
"goog.forwardDeclare('Bar');",
"var f = new Foo;",
"var b = new Bar;"));
typeCheck(Joiner.on('\n').join(FORWARD_DECLARATION_DEFINITIONS,
"/** @const */ var ns = {};",
"goog.addDependency('', ['ns.Foo'], []);",
"goog.forwardDeclare('ns.Bar');",
"var f = new ns.Foo;",
"var b = new ns.Bar;"));
typeCheck(Joiner.on('\n').join(FORWARD_DECLARATION_DEFINITIONS,
"/** @const */ var ns = {};",
"goog.addDependency('', ['ns.subns.Foo'], []);",
"goog.forwardDeclare('ns.subns.Bar');",
"var f = new ns.subns.Foo;",
"var b = new ns.subns.Bar;"));
typeCheck(Joiner.on('\n').join(FORWARD_DECLARATION_DEFINITIONS,
"goog.addDependency('', ['ns.subns.Foo'], []);",
"goog.forwardDeclare('ns.subns.Bar');",
"var f = new ns.subns.Foo;",
"var b = new ns.subns.Bar;"));
typeCheck(Joiner.on('\n').join(FORWARD_DECLARATION_DEFINITIONS,
"goog.forwardDeclare('ns.subns');",
"goog.forwardDeclare('ns.subns.Bar');",
"var b = new ns.subns.Bar;"));
typeCheck(Joiner.on('\n').join(FORWARD_DECLARATION_DEFINITIONS,
"goog.forwardDeclare('num');",
"/** @type {number} */ var num = 5;",
"function f() { var /** null */ o = num; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(FORWARD_DECLARATION_DEFINITIONS,
"goog.forwardDeclare('Foo');",
"/** @constructor */ function Foo(){}",
"function f(/** !Foo */ x) { var /** null */ n = x; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(FORWARD_DECLARATION_DEFINITIONS,
"goog.forwardDeclare('ns.Foo');",
"/** @const */ var ns = {};",
"/** @constructor */ ns.Foo = function(){}",
"function f(/** !ns.Foo */ x) { var /** null */ n = x; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
// In the following cases the old type inference warned about arg type,
// but we allow rather than create synthetic named type
typeCheck(Joiner.on('\n').join(FORWARD_DECLARATION_DEFINITIONS,
"goog.forwardDeclare('Foo');",
"function f(/** !Foo */ x) {}",
"/** @constructor */ function Bar(){}",
"f(new Bar);"));
typeCheck(Joiner.on('\n').join(FORWARD_DECLARATION_DEFINITIONS,
"/** @const */ var ns = {};",
"goog.forwardDeclare('ns.Foo');",
"function f(/** !ns.Foo */ x) {}",
"/** @constructor */ function Bar(){}",
"f(new Bar);"));
typeCheck(Joiner.on('\n').join(FORWARD_DECLARATION_DEFINITIONS,
"goog.forwardDeclare('ns.Foo');",
"/** @const */",
"var ns = {};",
"/** @const */",
"var c = ns;"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE);
typeCheck(Joiner.on('\n').join(FORWARD_DECLARATION_DEFINITIONS,
"goog.forwardDeclare('ns.ns2.Foo');",
"/** @const */",
"var ns = {};",
"/** @const */",
"ns.ns2 = {};",
"/** @const */",
"var c = ns;",
"var x = new ns.ns2.Foo();"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE,
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(FORWARD_DECLARATION_DEFINITIONS,
"goog.forwardDeclare('Foo.Bar');",
"/** @constructor */",
"function Foo() {}",
"var x = new Foo.Bar()"));
}
public void testDontLookupInParentScopeForNamesWithoutDeclaredType() {
typeCheck(Joiner.on('\n').join(
"/** @type {number} */",
"var x;",
"function f() {",
" var x = true;",
"}"));
}
public void testSpecializationInPropertyAccesses() {
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @type {?number} */ ns.n = 123;",
"if (ns.n === null) {",
"} else {",
" ns.n - 5;",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @type {?number} */ ns.n = 123;",
"if (ns.n !== null) {",
" ns.n - 5;",
"}"));
typeCheck(Joiner.on('\n').join(
"var obj = { n: (1 < 2 ? null : 123) };",
"if (obj.n !== null) {",
" obj.n - 123;",
"}"));
typeCheck(Joiner.on('\n').join(
"var obj = { n: (1 < 2 ? null : 123) };",
"if (obj.n !== null) {",
" obj.n - 123;",
"}",
"obj.n - 123;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" this.a = 123;",
"}",
"/** @constructor */",
"function Bar(x) {",
" /** @type {Foo} */",
" this.b = x;",
" if (this.b != null) {",
" return this.b.a;",
" }",
"}"));
}
public void testAutoconvertBoxedNumberToNumber() {
typeCheck(
"var /** !Number */ n = 123;", NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(
"var /** number */ n = new Number(123);",
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(/** !Number */ x, y) {",
" return x - y;",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(x, /** !Number */ y) {",
" return x - y;",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** !Number */ x) {",
" return x + 'asdf';",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** !Number */ x) {",
" return -x;",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** !Number */ x) {",
" x -= 123;",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** !Number */ x, y) {",
" y -= x;",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** !Number */ x, /** !Array<string>*/ arr) {",
" return arr[x];",
"}"));
}
public void testAutoconvertBoxedStringToString() {
typeCheck(
"var /** !String */ s = '';", NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(
"var /** string */ s = new String('');",
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f() {",
" var /** !String */ x;",
" for (x in { p1: 123, p2: 234 }) ;",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** !String */ x) {",
" return x + 1;",
"}"));
}
public void testAutoconvertBoxedBooleanToBoolean() {
typeCheck(
"var /** !Boolean */ b = true;", NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(
"var /** boolean */ b = new Boolean(true);",
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(/** !Boolean */ x) {",
" if (x) { return 123; };",
"}"));
}
public void testAutoconvertScalarsToBoxedScalars() {
typeCheck(Joiner.on('\n').join(
"var /** number */ n = 123;",
"n.toString();"));
typeCheck(Joiner.on('\n').join(
"var /** boolean */ b = true;",
"b.toString();"));
typeCheck(Joiner.on('\n').join(
"var /** string */ s = '';",
"s.toString();"));
typeCheck(Joiner.on('\n').join(
"var /** number */ n = 123;",
"n.prop = 0;",
"n.prop - 5;"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"var /** number */ n = 123;",
"n['to' + 'String'];"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @type {number} */",
" this.prop = 123;",
"}",
"(new Foo).prop.newprop = 5;"));
typeCheck(Joiner.on('\n').join(
"/** @enum */",
"var E = { A: 1 };",
"function f(/** E */ x) {",
" return x.toString();",
"}"),
NewTypeInference.PROPERTY_ACCESS_ON_NONOBJECT);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prototype.toString = function() { return ''; };",
"function f(/** (number|!Foo) */ x) {",
" return x.toString();",
"}"));
}
public void testConstructorsCalledWithoutNew() {
typeCheck(Joiner.on('\n').join(
"var n = new Number();",
"n.prop = 0;",
"n.prop - 5;"));
typeCheck(Joiner.on('\n').join(
"var n = Number();",
"n.prop = 0;",
"n.prop - 5;"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor @return {number} */ function Foo(){ return 5; }",
"var /** !Foo */ f = new Foo;",
"var /** number */ n = Foo();"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo(){ return 5; }",
"var /** !Foo */ f = new Foo;",
"var n = Foo();"),
TypeCheck.CONSTRUCTOR_NOT_CALLABLE);
// For constructors, return of ? is interpreted the same as undeclared
typeCheck(Joiner.on('\n').join(
"/** @constructor @return {?} */ function Foo(){}",
"var /** !Foo */ f = new Foo;",
"var n = Foo();"),
TypeCheck.CONSTRUCTOR_NOT_CALLABLE);
}
public void testFunctionBind() {
// Don't handle specially
typeCheck(Joiner.on('\n').join(
"var obj = { bind: function() { return 'asdf'; } };",
"obj.bind() - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) { return x; }",
"f.bind(null, 1, 2);"),
TypeCheck.WRONG_ARGUMENT_COUNT);
typeCheck(Joiner.on('\n').join(
"function f(x) { return x; }",
"f.bind();"),
TypeCheck.WRONG_ARGUMENT_COUNT);
typeCheck(Joiner.on('\n').join(
"function f(x) { return x - 1; }",
"var g = f.bind(null);",
"g();"),
TypeCheck.WRONG_ARGUMENT_COUNT);
typeCheck(Joiner.on('\n').join(
"function f() {}",
"f.bind(1);"),
NewTypeInference.INVALID_THIS_TYPE_IN_BIND);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @constructor */",
"function Bar() {}",
"/** @this {!Foo} */",
"function f() {}",
"f.bind(new Bar);"),
NewTypeInference.INVALID_THIS_TYPE_IN_BIND);
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x, /** number */ y) { return x - y; }",
"var g = f.bind(null, 123);",
"g('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x, y) { return x - y; }",
"var g = f.bind(null, 123);",
"g('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x) { return x - 1; }",
"var g = f.bind(null, 'asdf');",
"g() - 3;"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {number=} x */",
"function f(x) {}",
"var g = f.bind(null);",
"g();",
"g('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {...number} var_args */",
"function f(var_args) {}",
"var g = f.bind(null);",
"g();",
"g(123, 'asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {number=} x */",
"function f(x) {}",
"f.bind(null, undefined);"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"function f(x, y) {}",
"f.bind(null, 1, 2);"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"function f(x, y) {}",
"var g = f.bind(null, 1);",
"g(2);",
"g('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
// T was instantiated to ? in the f.bind call.
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"function f(x, y) {}",
"var g = f.bind(null);",
"g(2, 'asdf');"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"function f(x, y) {}",
"f.bind(null, 1, 'asdf');"),
NewTypeInference.NOT_UNIQUE_INSTANTIATION);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" * @param {T} x",
" */",
" function Foo(x) {}",
"/**",
" * @template T",
" * @this {Foo<T>}",
" * @param {T} x",
" * @param {T} y",
" */",
"function f(x, y) {}",
"f.bind(new Foo('asdf'), 1, 2);"),
NewTypeInference.INVALID_THIS_TYPE_IN_BIND);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" * @param {T} x",
" */",
" function Foo(x) {}",
"/**",
" * @template T",
" * @param {T} x",
" * @param {T} y",
" */",
"Foo.prototype.f = function(x, y) {};",
"Foo.prototype.f.bind(new Foo('asdf'), 1, 2);"),
NewTypeInference.INVALID_THIS_TYPE_IN_BIND);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.bind(new Foo);"),
NewTypeInference.CANNOT_BIND_CTOR);
// We can't detect that f takes a string
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" * @param {T} x",
" */",
"function Foo(x) {}",
"/**",
" * @template T",
" * @this {Foo<T>}",
" * @param {T} x",
" */",
"function poly(x) {}",
"function f(x) {",
" poly.bind(new Foo('asdf'), x);",
"}",
"f(123);"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @type {string} */",
" this.p = 'asdf';",
"}",
"(function() { this.p - 5; }).bind(new Foo);"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @type {number} */",
" this.p = 123;",
"}",
"(function(x) { this.p - x; }).bind(new Foo, 321);"));
}
public void testClosureStyleFunctionBind() {
typeCheck(
"goog.bind(123, null);", NewTypeInference.GOOG_BIND_EXPECTS_FUNCTION);
typeCheck(Joiner.on('\n').join(
"function f(x) { return x; }",
"goog.bind(f, null, 1, 2);"),
TypeCheck.WRONG_ARGUMENT_COUNT);
typeCheck(Joiner.on('\n').join(
"function f(x) { return x; }",
"goog.bind(f);"),
TypeCheck.WRONG_ARGUMENT_COUNT);
typeCheck(Joiner.on('\n').join(
"function f() {}",
"goog.bind(f, 1);"),
NewTypeInference.INVALID_THIS_TYPE_IN_BIND);
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x, /** number */ y) { return x - y; }",
"var g = goog.bind(f, null, 123);",
"g('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x) { return x - 1; }",
"var g = goog.partial(f, 'asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x) { return x - 1; }",
"var g = goog.partial(f, 'asdf');",
"g() - 3;"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" if (typeof x == 'function') {",
" goog.bind(x, {}, 1, 2);",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @type {string} */",
" this.p = 'asdf';",
"}",
"goog.bind(function() { this.p - 5; }, new Foo);"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck("goog.partial(function(x) {}, 123)");
typeCheck("goog.bind(function() {}, null)();");
}
public void testPlusBackwardInference() {
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x, w) {",
" var y = x + 2;",
" function g() { return (y + 2) - 5; }",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x, w) {",
" function h() { return (w + 2) - 5; }",
"}"));
}
public void testPlus() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @param {!Foo} x */",
"function f(x, i) {",
" var /** string */ s = x[i];",
" var /** number */ y = x[i] + 123;",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** ? */ x) {",
" var /** string */ s = '' + x;",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** ? */ x) {",
" var /** number */ s = '' + x;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(/** ? */ x, /** ? */ y) {",
" var /** number */ s = x + y;",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** * */ x) {",
" var /** number */ n = x + 1;",
" var /** string */ s = 1 + x;",
"}"),
NewTypeInference.INVALID_OPERAND_TYPE,
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"var /** number */ n = 1 + null;",
"var /** string */ s = 1 + null;"),
NewTypeInference.INVALID_OPERAND_TYPE,
NewTypeInference.INVALID_OPERAND_TYPE,
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"var /** number */ n = undefined + 2;",
"var /** string */ s = undefined + 2;"),
NewTypeInference.INVALID_OPERAND_TYPE,
NewTypeInference.INVALID_OPERAND_TYPE,
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"var /** number */ n = 3 + true;",
"var /** string */ s = 3 + true;"),
NewTypeInference.INVALID_OPERAND_TYPE,
NewTypeInference.INVALID_OPERAND_TYPE,
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheckCustomExterns(
DEFAULT_EXTERNS + "/** @type {number} */ var NaN;",
Joiner.on('\n').join(
"var /** number */ n = NaN + 1;",
"var /** string */ s = NaN + 1;"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testUndefinedFunctionCtorNoCrash() {
typeCheckCustomExterns("", "function f(x) {}",
GlobalTypeInfo.FUNCTION_CONSTRUCTOR_NOT_DEFINED);
// Test that NTI is not run
typeCheckCustomExterns("", "function f(x) { 1 - 'asdf'; }",
GlobalTypeInfo.FUNCTION_CONSTRUCTOR_NOT_DEFINED);
}
public void testTrickyPropertyJoins() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @type {number} */",
"Foo.prototype.length;",
"/** @param {{length:number}|!Foo} x */",
"function f(x) {",
" return x.length - 123;",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @type {number} */",
"Foo.prototype.length;",
"/** @param {null|{length:number}|!Foo} x */",
"function f(x) {",
" return x.length - 123;",
"}"),
NewTypeInference.NULLABLE_DEREFERENCE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @type {number} */",
"Foo.prototype.length;",
"/** @param {null|!Foo|{length:number}} x */",
"function f(x) {",
" return x.length - 123;",
"}"),
NewTypeInference.NULLABLE_DEREFERENCE);
}
public void testJoinOfClassyAndLooseObject() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo(){}",
"/** @type {number} */",
"Foo.prototype.p = 5;",
"function f(o) {",
" if (o.p == 5) {",
" (function(/** !Foo */ x){})(o);",
" }",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() { this.p = 123; }",
"function f(x) {",
" var y;",
" if (x.p) {",
" y = x;",
" } else {",
" y = new Foo;",
" y.prop = 'asdf';",
" }",
" y.p -123;",
"}"));
}
public void testUnificationWithSubtyping() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {}",
"/** @constructor @extends {Foo} */ function Bar() {}",
"/** @constructor @extends {Foo} */ function Baz() {}",
"/**",
" * @template T",
" * @param {T|!Foo} x",
" * @param {T} y",
" * @return {T}",
" */",
"function f(x, y) { return y; }",
"/** @param {!Bar|!Baz} x */",
"function g(x) {",
" f(x, 123) - 123;",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Parent() {}",
"/** @constructor @extends {Parent} */",
"function Child() {}",
"/**",
" * @template T",
" * @param {T|!Parent} x",
" * @return {T}",
" */",
"function f(x) { return /** @type {?} */ (x); }",
"function g(/** (number|!Child) */ x) {",
" f(x) - 5;",
"}"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" */",
"function Parent() {}",
"/**",
" * @constructor",
" * @extends {Parent<number>}",
" */",
"function Child() {}",
"/**",
" * @template T",
" * @param {!Parent<T>} x",
" */",
"function f(x) {}",
"/**",
" * @param {!Child} x",
" */",
"function g(x) { f(x); }"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" */",
"function Parent() {}",
"/**",
" * @constructor",
" * @template U",
" * @extends {Parent<U>}",
" */",
"function Child() {}",
"/**",
" * @template T",
" * @param {!Child<T>} x",
" */",
"function f(x) {}",
"/**",
" * @param {!Parent<number>} x",
" */",
"function g(x) { f(x); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @constructor",
" */",
"function High() {}",
"/** @constructor @extends {High<number>} */",
"function Low() {}",
"/**",
" * @template T",
" * @param {!High<T>} x",
" * @return {T}",
" */",
"function f(x) { return /** @type {?} */ (null); }",
"var /** string */ s = f(new Low);"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" */",
"function High() {}",
"/** @return {T} */",
"High.prototype.get = function() { return /** @type {?} */ (null); };",
"/**",
" * @constructor",
" * @template U",
" * @extends {High<U>}",
" */",
"function Low() {}",
"/**",
" * @template V",
" * @param {!High<V>} x",
" * @return {V}",
" */",
"function f(x) { return x.get(); }",
"/** @param {!Low<number>} x */",
"function g(x) {",
" var /** number */ n = f(x);",
" var /** string */ s = f(x);",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @interface",
" * @template T",
" */",
"function High() {}",
"/**",
" * @constructor",
" * @template T",
" * @implements {High<T>}",
" */",
"function Mid() {}",
"/**",
" * @constructor",
" * @template T",
" * @extends {Mid<T>}",
" * @param {T} x",
" */",
"function Low(x) {}",
"/**",
" * @template T",
" * @param {!High<T>} x",
" * @return {T}",
" */",
"function f(x) {",
" return /** @type {?} */ (null);",
"}",
"f(new Low('asdf')) - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testArgumentsArray() {
typeCheck("arguments = 123;",
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(
"function f(x, i) { return arguments[i]; }");
typeCheck(
"function f(x) { return arguments['asdf']; }",
NewTypeInference.NON_NUMERIC_ARRAY_INDEX);
// Arguments is array-like, but not Array
typeCheck(
"function f() { return arguments.splice(); }",
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"function f(x, i) { return arguments[i]; }",
"f(123, 'asdf')"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f() {",
" var arguments = 1;",
" return arguments - 1;",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @param {string} var_args */",
"function f(var_args) {",
" return arguments[0];",
"}",
"f('asdf') - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @param {string} var_args */",
"function f(var_args) {",
" var x = arguments;",
" return x[0];",
"}",
"f('asdf') - 5;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x, i) {",
" x < i;",
" arguments[i];",
"}",
"f('asdf', 0);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testGenericResolutionWithPromises() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @param {function():(T|!Promise<T>)} x",
" * @return {!Promise<T>}",
" * @template T",
" */",
"function f(x) { return /** @type {?} */ (null); }",
"function g(/** function(): !Promise<number> */ x) {",
" var /** !Promise<number> */ n = f(x);",
"}"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {(T|!Promise<T>)} x",
" * @return {T}",
" */",
"function f(x) { return /** @type {?} */ (null); }",
"function g(/** !Promise<number> */ x) {",
" var /** number */ n = f(x);",
" var /** string */ s = f(x);",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testFunctionCallProperty() {
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x) {}",
"f.call(null, 'asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x) {}",
"f.call(null);"),
TypeCheck.WRONG_ARGUMENT_COUNT);
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x) {}",
"f.call(null, 1, 2);"),
TypeCheck.WRONG_ARGUMENT_COUNT);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @param {number} x */",
"Foo.prototype.f = function(x) {};",
"Foo.prototype.f.call({ a: 123}, 1);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
// We don't infer anything about a loose function from a .call invocation.
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" x(123) - 5;",
" x.call(null, 'asdf');",
"}",
"f(function(/** string */ s) { return s; });"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"function f(x) { return x; }",
"var /** number */ n = f.call(null, 'asdf');"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"new Foo.call(null);"),
NewTypeInference.NOT_A_CONSTRUCTOR);
}
public void testFunctionApplyProperty() {
// We only check the receiver argument of a .apply invocation
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x) {}",
"f.apply(null, ['asdf']);"));
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x) {}",
"f.apply(null, 'asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
// We don't check arity in the array argument
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x) {}",
"f.apply(null, []);"));
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x) {}",
"f.apply(null, [], 1, 2);"),
TypeCheck.WRONG_ARGUMENT_COUNT);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @param {number} x */",
"Foo.prototype.f = function(x) {};",
"Foo.prototype.f.apply({ a: 123}, [1]);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
// We don't infer anything about a loose function from a .apply invocation.
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" x(123) - 5;",
" x.apply(null, ['asdf']);",
"}",
"f(function(/** string */ s) { return s; });"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @return {T}",
" */",
"function f(x) { return x; }",
"var /** number */ n = f.apply(null, ['asdf']);"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"new Foo.apply(null);"),
NewTypeInference.NOT_A_CONSTRUCTOR);
typeCheck(Joiner.on('\n').join(
"function f(x) {}",
"function g() { f.apply(null, arguments); }"));
}
public void testDontWarnOnPropAccessOfBottom() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Bar() {",
" /** @type {?Object} */",
" this.obj;",
"}",
"Bar.prototype.f = function() {",
" this.obj = {};",
" if (this.obj != null) {}",
"};"));
typeCheck(Joiner.on('\n').join(
"var x = {};",
"x.obj = {};",
"if (x.obj != null) {}"));
typeCheck(Joiner.on('\n').join(
"var x = {};",
"x.obj = {};",
"if (x['obj'] != null) {}"));
}
public void testClasslessObjectsHaveBuiltinProperties() {
typeCheck(Joiner.on('\n').join(
"function f(/** !Object */ x) {",
" return x.hasOwnProperty('asdf');",
"}"));
typeCheck(Joiner.on('\n').join(
"function f(/** { a: number } */ x) {",
" return x.hasOwnProperty('asdf');",
"}"));
typeCheck(Joiner.on('\n').join(
"var x = {};",
"x.hasOwnProperty('asdf');"));
typeCheck(Joiner.on('\n').join(
"var x = /** @struct */ { a: 1 };",
"x.hasOwnProperty('asdf');"));
typeCheck(Joiner.on('\n').join(
"var x = /** @dict */ { 'a': 1 };",
"x['hasOwnProperty']('asdf');"));
}
public void testInferThisInSimpleInferExprType() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @const */ var x = this",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @type {string} */",
" this.p = 'asdf';",
"}",
"Foo.prototype.m = function() {",
" goog.bind(function() { this.p - 5; }, this);",
"};"),
NewTypeInference.INVALID_OPERAND_TYPE);
}
public void testNoInexistentPropWarningsForDicts() {
typeCheck(Joiner.on('\n').join(
"/** @constructor @dict */",
"function Foo() {}",
"(new Foo)['prop'] - 1;"));
}
public void testAddingPropsToExpandosInWhateverScopes() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"function f(/** !Foo */ x) {",
" x.prop = 123;",
"}",
"(new Foo).prop - 1;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"function f() {",
" (new Foo).prop = 123;",
"}",
"var s = (new Foo).prop;"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"function f(/** !Foo */ x) {",
" x.prop = 'asdf';", // we don't declare the type to be string
"}",
"(new Foo).prop - 1;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"function f(/** !Foo */ x) {",
" var y = x.prop;",
"}",
"var z = (new Foo).prop;"),
TypeCheck.INEXISTENT_PROPERTY,
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"function f() {",
" var x = new Foo;",
" x.prop = 123;", // x not inferred as Foo during GTI
"}",
"(new Foo).prop - 1;"),
TypeCheck.INEXISTENT_PROPERTY);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"function f(/** !Foo */ x) {",
" /** @const */",
" x.prop = 123;",
"}",
"(new Foo).prop - 1;"),
GlobalTypeInfo.MISPLACED_CONST_ANNOTATION);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"function f(/** !Foo */ x) {",
" /** @type {string} */",
" x.prop = 'asdf';",
"}",
"(new Foo).prop - 123;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function High() {}",
"function f(/** !High */ x) {",
" /** @type {string} */",
" x.prop = 'asdf';",
"}",
"/** @constructor @extends {High} */",
"function Low() {}",
"(new Low).prop - 123;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @type {number} */",
" this.prop = 123;",
"}",
"function f(/** !Foo */ x) {",
" /** @type {string} */",
" x.prop = 'asdf';",
"}"),
GlobalTypeInfo.REDECLARED_PROPERTY,
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @type {number} */",
" this.prop = 123;",
"}",
"function f(/** !Foo */ x) {",
" x.prop = 'asdf';",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @type {number} */",
"Foo.prototype.prop = 123;",
"function f(/** !Foo */ x) {",
" x.prop = 'asdf';",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" */",
"function Foo() {}",
"function f(/** !Foo<string> */ x) {",
" x.prop = 123;",
"}",
"(new Foo).prop - 1;"));
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @template T",
" */",
"function Foo(/** T */ x) {}",
"/** @template U */",
"function addProp(/** !Foo<U> */ x, /** U */ y) {",
" /** @type {U} */ x.prop = y;",
" return x;",
"}",
"addProp(new Foo(1), 5).prop - 1;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prototype.m = function() {",
" this.prop = 123;",
"}",
"function f(/** !Foo */ x) {",
" /** @type {number} */",
" x.prop = 123;",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prototype.prop = 123;",
"/** @type {!Foo} */",
"var x = new Foo;",
"/** @type {number} */",
"x.prop = 123;"));
}
public void testAddingPropsToObject() {
typeCheck(Joiner.on('\n').join(
"Object.prototype.m = function() {",
" /** @type {string} */",
" this.prop = 'asdf';",
"};",
"(new Object).prop - 123;"),
NewTypeInference.INVALID_OPERAND_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** !Object */ x) {",
" /** @type {string} */",
" x.prop = 'asdf';",
"}",
"(new Object).prop - 123;"),
TypeCheck.INEXISTENT_PROPERTY);
}
public void testFunctionSubtypingWithReceiverTypes() {
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {function(this:T)} x",
" */",
"function f(x) {}",
"/** @constructor */",
"function Foo() {}",
"f(/** @this{Foo} */ function () {});"));
// We don't catch the NOT_UNIQUE_INSTANTIATION warning
typeCheck(Joiner.on('\n').join(
"/**",
" * @template T",
" * @param {T} x",
" * @param {function(this:T)} y",
" */",
"function f(x, y) {}",
"/** @constructor */",
"function Foo() {}",
"/** @constructor */",
"function Bar() {}",
"f(new Bar, /** @this{Foo} */function () {});"));
// Sets Bar#p to a number but we don't catch it
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @constructor */",
"function Bar() {",
" /** @type {string} */ this.p = 'asdf';",
"}",
"/**",
" * @this {Foo}",
" * @param {number} x",
" */",
"function f(x) { this.p = x; }",
"/** @param {function(number)} x */",
"function g(x) { x.call(new Bar, 123); }",
"g(f);"));
}
public void testBadWorksetConstruction() {
typeCheck(Joiner.on('\n').join(
"function f(x) {",
" for (var i = 0; i < 10; i++) {",
" break;",
" }",
" x++;",
"};"));
}
public void testFunctionNamespacesThatArentProperties() {
typeCheck(Joiner.on('\n').join(
"function f(x) {}",
"/** @type {number} */",
"f.prop = 123;",
"function h() {",
" var /** string */ s = f.prop;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(x) {}",
"function g() {",
" /** @type {number} */",
" f.prop = 123;",
"}",
"function h() {",
" var /** string */ s = f.prop;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f(x) {}",
"/** @constructor */",
"f.Foo = function() {};",
"/** @param {!f.Foo} x */",
"function g(x) {}",
"function h() { g(new f.Foo()); }"));
typeCheck(Joiner.on('\n').join(
"function f(x) {}",
"/** @constructor */",
"f.Foo = function() {};",
"/** @param {!f.Foo} x */",
"function g(x) {}",
"function h() { g(123); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x) {}",
"/** @type {number} */",
"f.prop = 123;",
"f('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(/** number */ x) {}",
"/** @type {string} */",
"f.prop = 'str';",
"function g() { f(f.prop); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) { return x - 1; }",
"/** @type {string} */",
"f.prop = 'str';",
"function g() { f(f.prop); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
// f is ? in NTI, so we get no warning for f.e.A.
typeCheck(Joiner.on('\n').join(
"f = function() {};",
"/** @enum */",
"f.e = { A: 1 };",
"function g() { var /** string */ s = f.e.A; }"));
typeCheck(Joiner.on('\n').join(
"var f = function() {};",
"/** @enum */",
"f.e = { A: 1 };",
"function g() { var /** string */ s = f.e.A; }"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheckCustomExterns(
Joiner.on('\n').join(
DEFAULT_EXTERNS,
"function f(x) {}",
"/** @type {number} */",
"f.prop;"),
Joiner.on('\n').join(
"function h() {",
" var /** string */ s = f.prop;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheckCustomExterns(
Joiner.on('\n').join(
DEFAULT_EXTERNS,
"function f(x) {}",
"/** @constructor */",
"f.Foo = function() {};"),
Joiner.on('\n').join(
"/** @param {!f.Foo} x */",
"function g(x) {}",
"function h() { g(123); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"function f(x) {};",
"/** @const */ f.subns = {};",
"function g() {",
" /** @type {number} */",
" f.subns.prop = 123;",
"}",
"function h() {",
" var /** string */ s = f.subns.prop;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"function f() {",
" f.prop = function() {};",
"}"));
}
public void testFunctionNamespacesThatAreProperties() {
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"ns.f = function(x) {};",
"/** @type {number} */",
"ns.f.prop = 123;",
"function h() {",
" var /** string */ s = ns.f.prop;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"ns.f = function(x) {};",
"function g() {",
" /** @type {number} */",
" ns.f.prop = 123;",
"}",
"function h() {",
" var /** string */ s = ns.f.prop;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"ns.f = function(x) {};",
"/** @constructor */",
"ns.f.Foo = function() {};",
"/** @param {!ns.f.Foo} x */",
"function g(x) {}",
"function h() { g(new ns.f.Foo()); }"));
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"ns.f = function(x) {};",
"/** @constructor */",
"ns.f.Foo = function() {};",
"/** @param {!ns.f.Foo} x */",
"function g(x) {}",
"function h() { g(123); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"ns.f = function(/** number */ x) {};",
"/** @type {number} */",
"ns.f.prop = 123;",
"ns.f('asdf');"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"ns.f = function(/** number */ x) {};",
"/** @type {string} */",
"ns.f.prop = 'str';",
"function g() { ns.f(ns.f.prop); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"ns.f = function(x) { return x - 1; };",
"/** @type {string} */",
"ns.f.prop = 'asdf';",
"ns.f(ns.f.prop);"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
// TODO(dimvar): Needs deferred checks for known property-functions.
// typeCheck(Joiner.on('\n').join(
// "/** @const */ var ns = {};",
// "ns.f = function(x) { return x - 1; };",
// "/** @type {string} */",
// "ns.f.prop = 'asdf';",
// "function g() { ns.f(ns.f.prop); }"),
// NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheckCustomExterns(
Joiner.on('\n').join(
DEFAULT_EXTERNS,
"/** @const */ var ns = {};",
"ns.f = function(/** number */ x) {};",
"/** @type {number} */",
"ns.f.prop;"),
Joiner.on('\n').join(
"function h() {",
" var /** string */ s = ns.f.prop;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheckCustomExterns(
Joiner.on('\n').join(
DEFAULT_EXTERNS,
"/** @const */ var ns = {};",
"ns.f = function(/** number */ x) {};",
"/** @constructor */",
"ns.f.Foo = function() {};"),
Joiner.on('\n').join(
"/** @param {!ns.f.Foo} x */",
"function g(x) {}",
"function h() { g(123); }"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @enum */ var e = { A: 1 };",
"e.f = function(x) {};",
"function g() {",
" /** @type {number} */",
" e.f.prop = 123;",
"}",
"function h() {",
" var /** string */ s = e.f.prop;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */ function Foo() {};",
"Foo.f = function(x) {};",
"function g() {",
" /** @type {number} */",
" Foo.f.prop = 123;",
"}",
"function h() {",
" /** @type {string} */",
" Foo.f.prop = 'asdf';",
"}"),
GlobalTypeInfo.REDECLARED_PROPERTY,
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"ns.f = function(x) {};",
"/** @const */ ns.f.subns = {};",
"function g() {",
" /** @type {number} */",
" ns.f.subns.prop = 123;",
"}",
"function h() {",
" var /** string */ s = ns.f.subns.prop;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testInterfaceMethodNoReturn() {
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @interface */",
"ns.Foo = function() {};",
"/** @return {number} */",
"ns.Foo.prototype.m = function() {};"));
// Don't crash when ns.Foo is not defined.
typeCheck("ns.Foo.prototype.m = function() {};");
}
public void testUnknownNewAndThisFunctionAnnotations() {
// Don't warn for unknown this
typeCheck(Joiner.on('\n').join(
"/** @this {Number|String} */",
"function f() {",
" return this.toString();",
"}"));
// Don't warn for unknown this
typeCheck(Joiner.on('\n').join(
"/** @type {function(this:(Number|String))} */",
"function f() {",
" return this.toString();",
"}"));
// Don't warn that f isn't a constructor
typeCheck(Joiner.on('\n').join(
"/** @type {function(new:(Number|String))} */",
"function f() {}",
"var x = new f();"));
}
public void testDontAddPropsToNamespacesAfterEarlyFinalization() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @const */",
"var Bar = Foo;",
"Foo.prop = 123;"),
GlobalTypeInfo.NAMESPACE_MODIFIED_AFTER_FINALIZATION);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @constructor @extends {Foo} */",
"function Bar() {}",
"/** @const */",
"var Baz = Bar;",
"Foo.prop = 123;"),
GlobalTypeInfo.NAMESPACE_MODIFIED_AFTER_FINALIZATION);
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function Foo() {}",
"/** @constructor @implements {Foo} */",
"function Bar() {}",
"/** @const */",
"var Baz = Bar;",
"Foo.prototype.prop = function() {};"),
GlobalTypeInfo.NAMESPACE_MODIFIED_AFTER_FINALIZATION);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @const */",
"var Bar = Foo;",
"Foo.prototype.prop = 123;"),
GlobalTypeInfo.NAMESPACE_MODIFIED_AFTER_FINALIZATION);
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function Foo() {}",
"/** @constructor @implements {Foo} */",
"function Bar() {}",
"/** @const */",
"var Baz = Bar;",
"Foo.prop = 123;"),
GlobalTypeInfo.NAMESPACE_MODIFIED_AFTER_FINALIZATION);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {}",
"/** @const */",
"var x = ns;",
"ns.prop = 123;"),
GlobalTypeInfo.NAMESPACE_MODIFIED_AFTER_FINALIZATION);
typeCheck(Joiner.on('\n').join(
"/** @enum */",
"var e = { A: 1 }",
"/** @const */",
"var x = e;",
"e.prop = 123;"),
GlobalTypeInfo.NAMESPACE_MODIFIED_AFTER_FINALIZATION);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @constructor */",
"ns.Foo = function() {};",
"/** @const */",
"var x = ns;",
"/** @type {number} */",
"ns.Foo.prop = 123;"),
GlobalTypeInfo.NAMESPACE_MODIFIED_AFTER_FINALIZATION);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Bar() {}",
"/** @constructor */",
"Bar.Foo = function() {};",
"/** @const */",
"var x = Bar;",
"/** @type {number} */",
"Bar.Foo.prop = 123;"),
GlobalTypeInfo.NAMESPACE_MODIFIED_AFTER_FINALIZATION);
typeCheck(Joiner.on('\n').join(
"/** @enum */",
"var e = {A:1};",
"/** @constructor */",
"e.Foo = function() {};",
"/** @const */",
"var x = e;",
"/** @type {number} */",
"e.Foo.prop = 123;"),
GlobalTypeInfo.NAMESPACE_MODIFIED_AFTER_FINALIZATION);
}
public void testFixAdditionOfStaticCtorProps() {
// TODO(dimvar): The expected formal type is string if g appears before f
// and number o/w. Also, we allow adding named types to ctors in any scope,
// but other properties only in the same scope where the ctor is defined.
// 1) Must warn about redeclared prop.
// 2) Must be consistent about which scopes can add new props.
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"function g() {",
" /**",
" * @constructor",
" * @param {string} x",
" */",
" Foo.Bar = function(x) {};",
"}",
"function f() {",
" /**",
" * @constructor",
" * @param {number} x",
" */",
" Foo.Bar = function(x) {};",
"}",
"function h() {",
" return new Foo.Bar(true);",
"}"),
NewTypeInference.INVALID_ARGUMENT_TYPE);
}
public void testAddingPropsToNominalTypesAfterFinalization() {
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {",
" /** @type {number} */",
" this.prop = 123;",
"}",
"/** @const */",
"var exports = Foo;",
"function f() {",
" var /** string */ s = (new Foo).prop;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @const */",
"var exports = Foo;",
"Foo.prototype.method = function() {",
" /** @type {number} */",
" this.prop = 123;",
"};",
"function f() {",
" var /** string */ s = (new Foo).prop;",
"}"),
GlobalTypeInfo.NAMESPACE_MODIFIED_AFTER_FINALIZATION,
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @const */",
"var exports = Foo;",
"function f(/** !Foo */ x) {",
" /** @type {number} */",
" x.prop = 123;",
"}",
"function g(/** !Foo */ x) {",
" var /** string */ s = x.prop;",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prop = 123;",
"/** @const */",
"var exports = Foo;",
"Foo.prop = 234;"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prop = 123;",
"/** @const */",
"var exports = Foo;",
"function f() {",
" Foo.prop = 234;",
"}"));
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prop = 123;",
"/** @const */",
"var exports = Foo;",
"Foo.prop2 = 234;"),
GlobalTypeInfo.NAMESPACE_MODIFIED_AFTER_FINALIZATION);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"Foo.prop = 123;",
"/** @const */",
"var exports = Foo;",
"function f() {",
" /** @type {number} */",
" Foo.prop = 234;",
"}"),
GlobalTypeInfo.NAMESPACE_MODIFIED_AFTER_FINALIZATION);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @const */",
"var exports = Foo;",
"Foo.prototype.method = function() {",
" /** @type {number} */",
" this.prop = 123;",
"};",
"function f() {",
" var /** string */ s = (new Foo).prop;",
"}"),
GlobalTypeInfo.NAMESPACE_MODIFIED_AFTER_FINALIZATION,
NewTypeInference.MISTYPED_ASSIGN_RHS);
}
public void testSubnamespacesNotFinalized() {
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @constructor @implements {Parent} */",
"ns.Child = function() {}",
"/** @const */",
"var exports = ns;",
"/** @interface */",
"function Parent() {}"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @const */",
"ns.ns2 = {};",
"/** @constructor @implements {Parent} */",
"ns.ns2.Child = function() {}",
"/** @const */",
"var exports = ns;",
"/** @interface */",
"function Parent() {}"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE);
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @enum */",
"ns.e = {A:1};",
"/** @constructor @implements {Parent} */",
"ns.e.Child = function() {}",
"/** @const */",
"var exports = ns;",
"/** @interface */",
"function Parent() {}"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE);
}
public void testFinalizationOfImplementedInterfaces() {
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function I1() {}",
"/** @return {number} */",
"I1.prototype.method = function() {};",
"/**",
" * @constructor",
" * @implements {I1}",
" */",
"function Foo() {}",
"Foo.prototype.method = function() { return 1; };",
"/** @const */",
"var exports = Foo;",
"function f() {",
" var /** string */ s = (new exports).method();",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
typeCheck(Joiner.on('\n').join(
"/**",
" * @constructor",
" * @implements {I1}",
" */",
"function Foo() {}",
"Foo.prototype.method = function() { return 1; };",
"/** @const */",
"var exports = Foo;",
"/** @interface */",
"function I1() {}",
"/** @return {number} */",
"I1.prototype.method = function() {};"),
GlobalTypeInfo.COULD_NOT_INFER_CONST_TYPE);
}
public void testImprecisePrototypeDueToEarlyFinalization() {
// Can't find the type mismatch because the prototype property of
// exports was created before finalizing Foo.
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function Parent() {}",
"/** @return {number} */",
"Parent.prototype.method = function() {};",
"/** @constructor @implements {Parent} */",
"function Foo() {}",
"Foo.prototype.method = function() { return 1; };",
"/** @const */",
"var exports = Foo;",
"function f() {",
" var /** null */ x = exports.prototype.method.call(new Foo);",
"}"));
// The exports object itself does have the newest type information
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function Parent() {}",
"/** @return {number} */",
"Parent.prototype.method = function() {};",
"/** @constructor @implements {Parent} */",
"function Foo() {}",
"Foo.prototype.method = function() { return 1; };",
"/** @const */",
"var exports = Foo;",
"function f() {",
" var /** null */ x = (new exports).method();",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
// The exports object itself does have the newest type information
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function Parent() {}",
"/** @return {number} */",
"Parent.prototype.method = function() {};",
"/** @constructor @implements {Parent} */",
"function Foo() {}",
"Foo.prototype.method = function() { return 1; };",
"/** @const */",
"var exports = new Foo;",
"function f() {",
" var /** null */ x = exports.method();",
"}"),
NewTypeInference.MISTYPED_ASSIGN_RHS);
// Can't find the type mismatch because the prototype property of
// exports was created before finalizing Foo.
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function I1() {}",
"/** @return {number|string} */",
"I1.prototype.method = function() {};",
"/** @interface */",
"function I2() {}",
"/** @return {number|boolean} */",
"I2.prototype.method = function() {};",
"/**",
" * @constructor",
" * @implements {I1}",
" * @implements {I2}",
" */",
"function Foo() {}",
"Foo.prototype.method = function() { return 1; };",
"/** @const */",
"var exports = Foo;",
"function f() {",
" var /** null */ x = exports.prototype.method.call(new Foo);",
"}"));
}
public void testFinalizingRecursiveSubnamespaces() {
typeCheck(Joiner.on('\n').join(
"/** @const */",
"var ns = {};",
"/** @constructor */",
"ns.Foo = function() {};",
"/** @const */",
"ns.Foo.ns2 = ns;"),
GlobalTypeInfo.NAMESPACE_MODIFIED_AFTER_FINALIZATION);
typeCheck(Joiner.on('\n').join(
"/** @constructor */",
"function Foo() {}",
"/** @const */",
"Foo.alias = Foo;"),
GlobalTypeInfo.NAMESPACE_MODIFIED_AFTER_FINALIZATION);
typeCheck(Joiner.on('\n').join(
"/** @interface */",
"function Foo() {}",
"/** @constructor @implements {Foo} */",
"Foo.Bar = function() {};",
"/** @const */",
"var exports = Foo;"));
}
public void testAddingPropsToTypedefs() {
typeCheckCustomExterns(
Joiner.on('\n').join(
DEFAULT_EXTERNS,
"/** @typedef {number} */",
"var num2;",
"/** @type {number} */",
"num2.prop;"),
"/** empty code */",
GlobalTypeInfo.CANNOT_ADD_PROPERTIES_TO_TYPEDEF);
typeCheckCustomExterns(
Joiner.on('\n').join(
DEFAULT_EXTERNS,
"/** @const */ var ns = {};",
"/** @typedef {number} */",
"ns.num2;",
"/** @type {number} */",
"ns.num2.prop;"),
"/** empty code */",
GlobalTypeInfo.CANNOT_ADD_PROPERTIES_TO_TYPEDEF);
typeCheck(Joiner.on('\n').join(
"/** @typedef {number} */",
"var num2;",
"/** @type {number} */",
"num2.prop;"),
GlobalTypeInfo.CANNOT_ADD_PROPERTIES_TO_TYPEDEF);
typeCheck(Joiner.on('\n').join(
"/** @const */ var ns = {};",
"/** @typedef {number} */",
"ns.num2;",
"/** @type {number} */",
"ns.num2.prop = 123;"),
GlobalTypeInfo.CANNOT_ADD_PROPERTIES_TO_TYPEDEF);
}
}
| pauldraper/closure-compiler | test/com/google/javascript/jscomp/NewTypeInferenceES5OrLowerTest.java | Java | apache-2.0 | 413,768 |
// Copyright 2015 go-swagger maintainers
//
// 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 analysis
import (
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"sort"
"strconv"
"testing"
"github.com/stretchr/testify/require"
"github.com/go-openapi/spec"
"github.com/go-openapi/swag"
"github.com/stretchr/testify/assert"
)
func schemeNames(schemes [][]SecurityRequirement) []string {
var names []string
for _, scheme := range schemes {
for _, v := range scheme {
names = append(names, v.Name)
}
}
sort.Strings(names)
return names
}
func makeFixturepec(pi, pi2 spec.PathItem, formatParam *spec.Parameter) *spec.Swagger {
return &spec.Swagger{
SwaggerProps: spec.SwaggerProps{
Consumes: []string{"application/json"},
Produces: []string{"application/json"},
Security: []map[string][]string{
{"apikey": nil},
},
SecurityDefinitions: map[string]*spec.SecurityScheme{
"basic": spec.BasicAuth(),
"apiKey": spec.APIKeyAuth("api_key", "query"),
"oauth2": spec.OAuth2AccessToken("http://authorize.com", "http://token.com"),
},
Parameters: map[string]spec.Parameter{"format": *formatParam},
Paths: &spec.Paths{
Paths: map[string]spec.PathItem{
"/": pi,
"/items": pi2,
},
},
},
}
}
func TestAnalyzer(t *testing.T) {
formatParam := spec.QueryParam("format").Typed("string", "")
limitParam := spec.QueryParam("limit").Typed("integer", "int32")
limitParam.Extensions = spec.Extensions(map[string]interface{}{})
limitParam.Extensions.Add("go-name", "Limit")
skipParam := spec.QueryParam("skip").Typed("integer", "int32")
pi := spec.PathItem{}
pi.Parameters = []spec.Parameter{*limitParam}
op := &spec.Operation{}
op.Consumes = []string{"application/x-yaml"}
op.Produces = []string{"application/x-yaml"}
op.Security = []map[string][]string{
{"oauth2": {}},
{"basic": nil},
}
op.ID = "someOperation"
op.Parameters = []spec.Parameter{*skipParam}
pi.Get = op
pi2 := spec.PathItem{}
pi2.Parameters = []spec.Parameter{*limitParam}
op2 := &spec.Operation{}
op2.ID = "anotherOperation"
op2.Parameters = []spec.Parameter{*skipParam}
pi2.Get = op2
spec := makeFixturepec(pi, pi2, formatParam)
analyzer := New(spec)
assert.Len(t, analyzer.consumes, 2)
assert.Len(t, analyzer.produces, 2)
assert.Len(t, analyzer.operations, 1)
assert.Equal(t, analyzer.operations["GET"]["/"], spec.Paths.Paths["/"].Get)
expected := []string{"application/x-yaml"}
sort.Strings(expected)
consumes := analyzer.ConsumesFor(spec.Paths.Paths["/"].Get)
sort.Strings(consumes)
assert.Equal(t, expected, consumes)
produces := analyzer.ProducesFor(spec.Paths.Paths["/"].Get)
sort.Strings(produces)
assert.Equal(t, expected, produces)
expected = []string{"application/json"}
sort.Strings(expected)
consumes = analyzer.ConsumesFor(spec.Paths.Paths["/items"].Get)
sort.Strings(consumes)
assert.Equal(t, expected, consumes)
produces = analyzer.ProducesFor(spec.Paths.Paths["/items"].Get)
sort.Strings(produces)
assert.Equal(t, expected, produces)
expectedSchemes := [][]SecurityRequirement{
{
{Name: "oauth2", Scopes: []string{}},
{Name: "basic", Scopes: nil},
},
}
schemes := analyzer.SecurityRequirementsFor(spec.Paths.Paths["/"].Get)
assert.Equal(t, schemeNames(expectedSchemes), schemeNames(schemes))
securityDefinitions := analyzer.SecurityDefinitionsFor(spec.Paths.Paths["/"].Get)
assert.Equal(t, *spec.SecurityDefinitions["basic"], securityDefinitions["basic"])
assert.Equal(t, *spec.SecurityDefinitions["oauth2"], securityDefinitions["oauth2"])
parameters := analyzer.ParamsFor("GET", "/")
assert.Len(t, parameters, 2)
operations := analyzer.OperationIDs()
assert.Len(t, operations, 2)
producers := analyzer.RequiredProduces()
assert.Len(t, producers, 2)
consumers := analyzer.RequiredConsumes()
assert.Len(t, consumers, 2)
authSchemes := analyzer.RequiredSecuritySchemes()
assert.Len(t, authSchemes, 3)
ops := analyzer.Operations()
assert.Len(t, ops, 1)
assert.Len(t, ops["GET"], 2)
op, ok := analyzer.OperationFor("get", "/")
assert.True(t, ok)
assert.NotNil(t, op)
op, ok = analyzer.OperationFor("delete", "/")
assert.False(t, ok)
assert.Nil(t, op)
// check for duplicates in sec. requirements for operation
pi.Get.Security = []map[string][]string{
{"oauth2": {}},
{"basic": nil},
{"basic": nil},
}
spec = makeFixturepec(pi, pi2, formatParam)
analyzer = New(spec)
securityDefinitions = analyzer.SecurityDefinitionsFor(spec.Paths.Paths["/"].Get)
assert.Len(t, securityDefinitions, 2)
assert.Equal(t, *spec.SecurityDefinitions["basic"], securityDefinitions["basic"])
assert.Equal(t, *spec.SecurityDefinitions["oauth2"], securityDefinitions["oauth2"])
// check for empty (optional) in sec. requirements for operation
pi.Get.Security = []map[string][]string{
{"oauth2": {}},
{"": nil},
{"basic": nil},
}
spec = makeFixturepec(pi, pi2, formatParam)
analyzer = New(spec)
securityDefinitions = analyzer.SecurityDefinitionsFor(spec.Paths.Paths["/"].Get)
assert.Len(t, securityDefinitions, 2)
assert.Equal(t, *spec.SecurityDefinitions["basic"], securityDefinitions["basic"])
assert.Equal(t, *spec.SecurityDefinitions["oauth2"], securityDefinitions["oauth2"])
}
func TestDefinitionAnalysis(t *testing.T) {
doc, err := loadSpec(filepath.Join("fixtures", "definitions.yml"))
if assert.NoError(t, err) {
analyzer := New(doc)
definitions := analyzer.allSchemas
// parameters
assertSchemaRefExists(t, definitions, "#/parameters/someParam/schema")
assertSchemaRefExists(t, definitions, "#/paths/~1some~1where~1{id}/parameters/1/schema")
assertSchemaRefExists(t, definitions, "#/paths/~1some~1where~1{id}/get/parameters/1/schema")
// responses
assertSchemaRefExists(t, definitions, "#/responses/someResponse/schema")
assertSchemaRefExists(t, definitions, "#/paths/~1some~1where~1{id}/get/responses/default/schema")
assertSchemaRefExists(t, definitions, "#/paths/~1some~1where~1{id}/get/responses/200/schema")
// definitions
assertSchemaRefExists(t, definitions, "#/definitions/tag")
assertSchemaRefExists(t, definitions, "#/definitions/tag/properties/id")
assertSchemaRefExists(t, definitions, "#/definitions/tag/properties/value")
assertSchemaRefExists(t, definitions, "#/definitions/tag/definitions/category")
assertSchemaRefExists(t, definitions, "#/definitions/tag/definitions/category/properties/id")
assertSchemaRefExists(t, definitions, "#/definitions/tag/definitions/category/properties/value")
assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalProps")
assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalProps/additionalProperties")
assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalItems")
assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalItems/items/0")
assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalItems/items/1")
assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalItems/additionalItems")
assertSchemaRefExists(t, definitions, "#/definitions/withNot")
assertSchemaRefExists(t, definitions, "#/definitions/withNot/not")
assertSchemaRefExists(t, definitions, "#/definitions/withAnyOf")
assertSchemaRefExists(t, definitions, "#/definitions/withAnyOf/anyOf/0")
assertSchemaRefExists(t, definitions, "#/definitions/withAnyOf/anyOf/1")
assertSchemaRefExists(t, definitions, "#/definitions/withAllOf")
assertSchemaRefExists(t, definitions, "#/definitions/withAllOf/allOf/0")
assertSchemaRefExists(t, definitions, "#/definitions/withAllOf/allOf/1")
assertSchemaRefExists(t, definitions, "#/definitions/withOneOf/oneOf/0")
assertSchemaRefExists(t, definitions, "#/definitions/withOneOf/oneOf/1")
allOfs := analyzer.allOfs
assert.Len(t, allOfs, 1)
assert.Contains(t, allOfs, "#/definitions/withAllOf")
}
}
func loadSpec(path string) (*spec.Swagger, error) {
spec.PathLoader = func(path string) (json.RawMessage, error) {
ext := filepath.Ext(path)
if ext == ".yml" || ext == ".yaml" {
return swag.YAMLDoc(path)
}
data, err := swag.LoadFromFileOrHTTP(path)
if err != nil {
return nil, err
}
return json.RawMessage(data), nil
}
data, err := swag.YAMLDoc(path)
if err != nil {
return nil, err
}
var sw spec.Swagger
if err := json.Unmarshal(data, &sw); err != nil {
return nil, err
}
return &sw, nil
}
func TestReferenceAnalysis(t *testing.T) {
doc, err := loadSpec(filepath.Join("fixtures", "references.yml"))
if assert.NoError(t, err) {
an := New(doc)
definitions := an.references
// parameters
assertRefExists(t, definitions.parameters, "#/paths/~1some~1where~1{id}/parameters/0")
assertRefExists(t, definitions.parameters, "#/paths/~1some~1where~1{id}/get/parameters/0")
// path items
assertRefExists(t, definitions.pathItems, "#/paths/~1other~1place")
// responses
assertRefExists(t, definitions.responses, "#/paths/~1some~1where~1{id}/get/responses/404")
// definitions
assertRefExists(t, definitions.schemas, "#/responses/notFound/schema")
assertRefExists(t, definitions.schemas, "#/paths/~1some~1where~1{id}/get/responses/200/schema")
assertRefExists(t, definitions.schemas, "#/definitions/tag/properties/audit")
// items
// Supported non-swagger 2.0 constructs ($ref in simple schema items)
assertRefExists(t, definitions.allRefs, "#/paths/~1some~1where~1{id}/get/parameters/1/items")
assertRefExists(t, definitions.allRefs, "#/paths/~1some~1where~1{id}/get/parameters/2/items")
assertRefExists(t, definitions.allRefs,
"#/paths/~1some~1where~1{id}/get/responses/default/headers/x-array-header/items")
assert.Lenf(t, an.AllItemsReferences(), 3, "Expected 3 items references in this spec")
assertRefExists(t, definitions.parameterItems, "#/paths/~1some~1where~1{id}/get/parameters/1/items")
assertRefExists(t, definitions.parameterItems, "#/paths/~1some~1where~1{id}/get/parameters/2/items")
assertRefExists(t, definitions.headerItems,
"#/paths/~1some~1where~1{id}/get/responses/default/headers/x-array-header/items")
}
}
func assertRefExists(t testing.TB, data map[string]spec.Ref, key string) bool {
if _, ok := data[key]; !ok {
return assert.Fail(t, fmt.Sprintf("expected %q to exist in the ref bag", key))
}
return true
}
func assertSchemaRefExists(t testing.TB, data map[string]SchemaRef, key string) bool {
if _, ok := data[key]; !ok {
return assert.Fail(t, fmt.Sprintf("expected %q to exist in schema ref bag", key))
}
return true
}
func TestPatternAnalysis(t *testing.T) {
doc, err := loadSpec(filepath.Join("fixtures", "patterns.yml"))
if assert.NoError(t, err) {
an := New(doc)
pt := an.patterns
// parameters
assertPattern(t, pt.parameters, "#/parameters/idParam", "a[A-Za-Z0-9]+")
assertPattern(t, pt.parameters, "#/paths/~1some~1where~1{id}/parameters/1", "b[A-Za-z0-9]+")
assertPattern(t, pt.parameters, "#/paths/~1some~1where~1{id}/get/parameters/0", "[abc][0-9]+")
// responses
assertPattern(t, pt.headers, "#/responses/notFound/headers/ContentLength", "[0-9]+")
assertPattern(t, pt.headers,
"#/paths/~1some~1where~1{id}/get/responses/200/headers/X-Request-Id", "d[A-Za-z0-9]+")
// definitions
assertPattern(t, pt.schemas,
"#/paths/~1other~1place/post/parameters/0/schema/properties/value", "e[A-Za-z0-9]+")
assertPattern(t, pt.schemas, "#/paths/~1other~1place/post/responses/200/schema/properties/data", "[0-9]+[abd]")
assertPattern(t, pt.schemas, "#/definitions/named", "f[A-Za-z0-9]+")
assertPattern(t, pt.schemas, "#/definitions/tag/properties/value", "g[A-Za-z0-9]+")
// items
assertPattern(t, pt.items, "#/paths/~1some~1where~1{id}/get/parameters/1/items", "c[A-Za-z0-9]+")
assertPattern(t, pt.items, "#/paths/~1other~1place/post/responses/default/headers/Via/items", "[A-Za-z]+")
// patternProperties (beyond Swagger 2.0)
_, ok := an.spec.Definitions["withPatternProperties"]
assert.True(t, ok)
_, ok = an.allSchemas["#/definitions/withPatternProperties/patternProperties/^prop[0-9]+$"]
assert.True(t, ok)
}
}
func assertPattern(t testing.TB, data map[string]string, key, pattern string) bool {
if assert.Contains(t, data, key) {
return assert.Equal(t, pattern, data[key])
}
return false
}
func panickerParamsAsMap() {
s := prepareTestParamsInvalid("fixture-342.yaml")
if s == nil {
return
}
m := make(map[string]spec.Parameter)
if pi, ok := s.spec.Paths.Paths["/fixture"]; ok {
pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters
s.paramsAsMap(pi.Parameters, m, nil)
}
}
func panickerParamsAsMap2() {
s := prepareTestParamsInvalid("fixture-342-2.yaml")
if s == nil {
return
}
m := make(map[string]spec.Parameter)
if pi, ok := s.spec.Paths.Paths["/fixture"]; ok {
pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters
s.paramsAsMap(pi.Parameters, m, nil)
}
}
func panickerParamsAsMap3() {
s := prepareTestParamsInvalid("fixture-342-3.yaml")
if s == nil {
return
}
m := make(map[string]spec.Parameter)
if pi, ok := s.spec.Paths.Paths["/fixture"]; ok {
pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters
s.paramsAsMap(pi.Parameters, m, nil)
}
}
func TestAnalyzer_paramsAsMap(Pt *testing.T) {
s := prepareTestParamsValid()
if assert.NotNil(Pt, s) {
m := make(map[string]spec.Parameter)
pi, ok := s.spec.Paths.Paths["/items"]
if assert.True(Pt, ok) {
s.paramsAsMap(pi.Parameters, m, nil)
assert.Len(Pt, m, 1)
p, ok := m["query#Limit"]
assert.True(Pt, ok)
assert.Equal(Pt, p.Name, "limit")
}
}
// An invalid spec, but passes this step (errors are figured out at a higher level)
s = prepareTestParamsInvalid("fixture-1289-param.yaml")
if assert.NotNil(Pt, s) {
m := make(map[string]spec.Parameter)
pi, ok := s.spec.Paths.Paths["/fixture"]
if assert.True(Pt, ok) {
pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters
s.paramsAsMap(pi.Parameters, m, nil)
assert.Len(Pt, m, 1)
p, ok := m["body#DespicableMe"]
assert.True(Pt, ok)
assert.Equal(Pt, p.Name, "despicableMe")
}
}
}
func TestAnalyzer_paramsAsMapWithCallback(Pt *testing.T) {
s := prepareTestParamsInvalid("fixture-342.yaml")
if assert.NotNil(Pt, s) {
// No bail out callback
m := make(map[string]spec.Parameter)
e := []string{}
pi, ok := s.spec.Paths.Paths["/fixture"]
if assert.True(Pt, ok) {
pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters
s.paramsAsMap(pi.Parameters, m, func(param spec.Parameter, err error) bool {
//Pt.Logf("ERROR on %+v : %v", param, err)
e = append(e, err.Error())
return true // Continue
})
}
assert.Contains(Pt, e, `resolved reference is not a parameter: "#/definitions/sample_info/properties/sid"`)
assert.Contains(Pt, e, `invalid reference: "#/definitions/sample_info/properties/sids"`)
// bail out callback
m = make(map[string]spec.Parameter)
e = []string{}
pi, ok = s.spec.Paths.Paths["/fixture"]
if assert.True(Pt, ok) {
pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters
s.paramsAsMap(pi.Parameters, m, func(param spec.Parameter, err error) bool {
//Pt.Logf("ERROR on %+v : %v", param, err)
e = append(e, err.Error())
return false // Bail out
})
}
// We got one then bail out
assert.Len(Pt, e, 1)
}
// Bail out after ref failure: exercising another path
s = prepareTestParamsInvalid("fixture-342-2.yaml")
if assert.NotNil(Pt, s) {
// bail out callback
m := make(map[string]spec.Parameter)
e := []string{}
pi, ok := s.spec.Paths.Paths["/fixture"]
if assert.True(Pt, ok) {
pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters
s.paramsAsMap(pi.Parameters, m, func(param spec.Parameter, err error) bool {
//Pt.Logf("ERROR on %+v : %v", param, err)
e = append(e, err.Error())
return false // Bail out
})
}
// We got one then bail out
assert.Len(Pt, e, 1)
}
// Bail out after ref failure: exercising another path
s = prepareTestParamsInvalid("fixture-342-3.yaml")
if assert.NotNil(Pt, s) {
// bail out callback
m := make(map[string]spec.Parameter)
e := []string{}
pi, ok := s.spec.Paths.Paths["/fixture"]
if assert.True(Pt, ok) {
pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters
s.paramsAsMap(pi.Parameters, m, func(param spec.Parameter, err error) bool {
//Pt.Logf("ERROR on %+v : %v", param, err)
e = append(e, err.Error())
return false // Bail out
})
}
// We got one then bail out
assert.Len(Pt, e, 1)
}
}
func TestAnalyzer_paramsAsMap_Panic(Pt *testing.T) {
assert.Panics(Pt, panickerParamsAsMap)
// Specifically on invalid resolved type
assert.Panics(Pt, panickerParamsAsMap2)
// Specifically on invalid ref
assert.Panics(Pt, panickerParamsAsMap3)
}
func TestAnalyzer_SafeParamsFor(Pt *testing.T) {
s := prepareTestParamsInvalid("fixture-342.yaml")
if assert.NotNil(Pt, s) {
e := []string{}
pi, ok := s.spec.Paths.Paths["/fixture"]
if assert.True(Pt, ok) {
pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters
for range s.SafeParamsFor("Get", "/fixture", func(param spec.Parameter, err error) bool {
e = append(e, err.Error())
return true // Continue
}) {
assert.Fail(Pt, "There should be no safe parameter in this testcase")
}
}
assert.Contains(Pt, e, `resolved reference is not a parameter: "#/definitions/sample_info/properties/sid"`)
assert.Contains(Pt, e, `invalid reference: "#/definitions/sample_info/properties/sids"`)
}
}
func panickerParamsFor() {
s := prepareTestParamsInvalid("fixture-342.yaml")
pi, ok := s.spec.Paths.Paths["/fixture"]
if ok {
pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters
s.ParamsFor("Get", "/fixture")
}
}
func TestAnalyzer_ParamsFor(Pt *testing.T) {
// Valid example
s := prepareTestParamsValid()
if assert.NotNil(Pt, s) {
params := s.ParamsFor("Get", "/items")
assert.True(Pt, len(params) > 0)
}
// Invalid example
assert.Panics(Pt, panickerParamsFor)
}
func TestAnalyzer_SafeParametersFor(Pt *testing.T) {
s := prepareTestParamsInvalid("fixture-342.yaml")
if assert.NotNil(Pt, s) {
e := []string{}
pi, ok := s.spec.Paths.Paths["/fixture"]
if assert.True(Pt, ok) {
pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters
for range s.SafeParametersFor("fixtureOp", func(param spec.Parameter, err error) bool {
e = append(e, err.Error())
return true // Continue
}) {
assert.Fail(Pt, "There should be no safe parameter in this testcase")
}
}
assert.Contains(Pt, e, `resolved reference is not a parameter: "#/definitions/sample_info/properties/sid"`)
assert.Contains(Pt, e, `invalid reference: "#/definitions/sample_info/properties/sids"`)
}
}
func panickerParametersFor() {
s := prepareTestParamsInvalid("fixture-342.yaml")
if s == nil {
return
}
pi, ok := s.spec.Paths.Paths["/fixture"]
if ok {
pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters
//func (s *Spec) ParametersFor(operationID string) []spec.Parameter {
s.ParametersFor("fixtureOp")
}
}
func TestAnalyzer_ParametersFor(Pt *testing.T) {
// Valid example
s := prepareTestParamsValid()
params := s.ParamsFor("Get", "/items")
assert.True(Pt, len(params) > 0)
// Invalid example
assert.Panics(Pt, panickerParametersFor)
}
func prepareTestParamsValid() *Spec {
formatParam := spec.QueryParam("format").Typed("string", "")
limitParam := spec.QueryParam("limit").Typed("integer", "int32")
limitParam.Extensions = spec.Extensions(map[string]interface{}{})
limitParam.Extensions.Add("go-name", "Limit")
skipParam := spec.QueryParam("skip").Typed("integer", "int32")
pi := spec.PathItem{}
pi.Parameters = []spec.Parameter{*limitParam}
op := &spec.Operation{}
op.Consumes = []string{"application/x-yaml"}
op.Produces = []string{"application/x-yaml"}
op.Security = []map[string][]string{
{"oauth2": {}},
{"basic": nil},
}
op.ID = "someOperation"
op.Parameters = []spec.Parameter{*skipParam}
pi.Get = op
pi2 := spec.PathItem{}
pi2.Parameters = []spec.Parameter{*limitParam}
op2 := &spec.Operation{}
op2.ID = "anotherOperation"
op2.Parameters = []spec.Parameter{*skipParam}
pi2.Get = op2
spec := makeFixturepec(pi, pi2, formatParam)
analyzer := New(spec)
return analyzer
}
func prepareTestParamsInvalid(fixture string) *Spec {
cwd, _ := os.Getwd()
bp := filepath.Join(cwd, "fixtures", fixture)
spec, err := loadSpec(bp)
if err != nil {
log.Printf("Warning: fixture %s could not be loaded: %v", fixture, err)
return nil
}
analyzer := New(spec)
return analyzer
}
func TestSecurityDefinitionsFor(t *testing.T) {
spec := prepareTestParamsAuth()
pi1 := spec.spec.Paths.Paths["/"].Get
pi2 := spec.spec.Paths.Paths["/items"].Get
defs1 := spec.SecurityDefinitionsFor(pi1)
require.Contains(t, defs1, "oauth2")
require.Contains(t, defs1, "basic")
require.NotContains(t, defs1, "apiKey")
defs2 := spec.SecurityDefinitionsFor(pi2)
require.Contains(t, defs2, "oauth2")
require.Contains(t, defs2, "basic")
require.Contains(t, defs2, "apiKey")
}
func TestSecurityRequirements(t *testing.T) {
spec := prepareTestParamsAuth()
pi1 := spec.spec.Paths.Paths["/"].Get
pi2 := spec.spec.Paths.Paths["/items"].Get
scopes := []string{"the-scope"}
reqs1 := spec.SecurityRequirementsFor(pi1)
require.Len(t, reqs1, 2)
require.Len(t, reqs1[0], 1)
require.Equal(t, reqs1[0][0].Name, "oauth2")
require.Equal(t, reqs1[0][0].Scopes, scopes)
require.Len(t, reqs1[1], 1)
require.Equal(t, reqs1[1][0].Name, "basic")
require.Empty(t, reqs1[1][0].Scopes)
reqs2 := spec.SecurityRequirementsFor(pi2)
require.Len(t, reqs2, 3)
require.Len(t, reqs2[0], 1)
require.Equal(t, reqs2[0][0].Name, "oauth2")
require.Equal(t, reqs2[0][0].Scopes, scopes)
require.Len(t, reqs2[1], 1)
require.Empty(t, reqs2[1][0].Name)
require.Empty(t, reqs2[1][0].Scopes)
require.Len(t, reqs2[2], 2)
//
//require.Equal(t, reqs2[2][0].Name, "basic")
require.Contains(t, reqs2[2], SecurityRequirement{Name: "basic", Scopes: []string{}})
require.Empty(t, reqs2[2][0].Scopes)
//require.Equal(t, reqs2[2][1].Name, "apiKey")
require.Contains(t, reqs2[2], SecurityRequirement{Name: "apiKey", Scopes: []string{}})
require.Empty(t, reqs2[2][1].Scopes)
}
func TestSecurityRequirementsDefinitions(t *testing.T) {
spec := prepareTestParamsAuth()
pi1 := spec.spec.Paths.Paths["/"].Get
pi2 := spec.spec.Paths.Paths["/items"].Get
reqs1 := spec.SecurityRequirementsFor(pi1)
defs11 := spec.SecurityDefinitionsForRequirements(reqs1[0])
require.Contains(t, defs11, "oauth2")
defs12 := spec.SecurityDefinitionsForRequirements(reqs1[1])
require.Contains(t, defs12, "basic")
require.NotContains(t, defs12, "apiKey")
reqs2 := spec.SecurityRequirementsFor(pi2)
defs21 := spec.SecurityDefinitionsForRequirements(reqs2[0])
require.Len(t, defs21, 1)
require.Contains(t, defs21, "oauth2")
require.NotContains(t, defs21, "basic")
require.NotContains(t, defs21, "apiKey")
defs22 := spec.SecurityDefinitionsForRequirements(reqs2[1])
require.NotNil(t, defs22)
require.Empty(t, defs22)
defs23 := spec.SecurityDefinitionsForRequirements(reqs2[2])
require.Len(t, defs23, 2)
require.NotContains(t, defs23, "oauth2")
require.Contains(t, defs23, "basic")
require.Contains(t, defs23, "apiKey")
}
func prepareTestParamsAuth() *Spec {
formatParam := spec.QueryParam("format").Typed("string", "")
limitParam := spec.QueryParam("limit").Typed("integer", "int32")
limitParam.Extensions = spec.Extensions(map[string]interface{}{})
limitParam.Extensions.Add("go-name", "Limit")
skipParam := spec.QueryParam("skip").Typed("integer", "int32")
pi := spec.PathItem{}
pi.Parameters = []spec.Parameter{*limitParam}
op := &spec.Operation{}
op.Consumes = []string{"application/x-yaml"}
op.Produces = []string{"application/x-yaml"}
op.Security = []map[string][]string{
{"oauth2": {"the-scope"}},
{"basic": nil},
}
op.ID = "someOperation"
op.Parameters = []spec.Parameter{*skipParam}
pi.Get = op
pi2 := spec.PathItem{}
pi2.Parameters = []spec.Parameter{*limitParam}
op2 := &spec.Operation{}
op2.ID = "anotherOperation"
op2.Security = []map[string][]string{
{"oauth2": {"the-scope"}},
{},
{
"basic": {},
"apiKey": {},
},
}
op2.Parameters = []spec.Parameter{*skipParam}
pi2.Get = op2
oauth := spec.OAuth2AccessToken("http://authorize.com", "http://token.com")
oauth.AddScope("the-scope", "the scope gives access to ...")
spec := &spec.Swagger{
SwaggerProps: spec.SwaggerProps{
Consumes: []string{"application/json"},
Produces: []string{"application/json"},
Security: []map[string][]string{
{"apikey": nil},
},
SecurityDefinitions: map[string]*spec.SecurityScheme{
"basic": spec.BasicAuth(),
"apiKey": spec.APIKeyAuth("api_key", "query"),
"oauth2": oauth,
},
Parameters: map[string]spec.Parameter{"format": *formatParam},
Paths: &spec.Paths{
Paths: map[string]spec.PathItem{
"/": pi,
"/items": pi2,
},
},
},
}
analyzer := New(spec)
return analyzer
}
func TestMoreParamAnalysis(t *testing.T) {
cwd, _ := os.Getwd()
bp := filepath.Join(cwd, "fixtures", "parameters", "fixture-parameters.yaml")
sp, err := loadSpec(bp)
if !assert.NoError(t, err) {
t.FailNow()
return
}
an := New(sp)
res := an.AllPatterns()
assert.Lenf(t, res, 6, "Expected 6 patterns in this spec")
res = an.SchemaPatterns()
assert.Lenf(t, res, 1, "Expected 1 schema pattern in this spec")
res = an.HeaderPatterns()
assert.Lenf(t, res, 2, "Expected 2 header pattern in this spec")
res = an.ItemsPatterns()
assert.Lenf(t, res, 2, "Expected 2 items pattern in this spec")
res = an.ParameterPatterns()
assert.Lenf(t, res, 1, "Expected 1 simple param pattern in this spec")
refs := an.AllRefs()
assert.Lenf(t, refs, 10, "Expected 10 reference usage in this spec")
references := an.AllReferences()
assert.Lenf(t, references, 14, "Expected 14 reference usage in this spec")
references = an.AllItemsReferences()
assert.Lenf(t, references, 0, "Expected 0 items reference in this spec")
references = an.AllPathItemReferences()
assert.Lenf(t, references, 1, "Expected 1 pathItem reference in this spec")
references = an.AllResponseReferences()
assert.Lenf(t, references, 3, "Expected 3 response references in this spec")
references = an.AllParameterReferences()
assert.Lenf(t, references, 6, "Expected 6 parameter references in this spec")
schemaRefs := an.AllDefinitions()
assert.Lenf(t, schemaRefs, 14, "Expected 14 schema definitions in this spec")
//for _, refs := range schemaRefs {
// t.Logf("Schema Ref: %s (%s)", refs.Name, refs.Ref.String())
//}
schemaRefs = an.SchemasWithAllOf()
assert.Lenf(t, schemaRefs, 1, "Expected 1 schema with AllOf definition in this spec")
method, path, op, found := an.OperationForName("postSomeWhere")
assert.Equal(t, "POST", method)
assert.Equal(t, "/some/where", path)
if assert.NotNil(t, op) && assert.True(t, found) {
sec := an.SecurityRequirementsFor(op)
assert.Nil(t, sec)
secScheme := an.SecurityDefinitionsFor(op)
assert.Nil(t, secScheme)
bag := an.ParametersFor("postSomeWhere")
assert.Lenf(t, bag, 6, "Expected 6 parameters for this operation")
}
method, path, op, found = an.OperationForName("notFound")
assert.Equal(t, "", method)
assert.Equal(t, "", path)
assert.Nil(t, op)
assert.False(t, found)
// does not take ops under pathItem $ref
ops := an.OperationMethodPaths()
assert.Lenf(t, ops, 3, "Expected 3 ops")
ops = an.OperationIDs()
assert.Lenf(t, ops, 3, "Expected 3 ops")
assert.Contains(t, ops, "postSomeWhere")
assert.Contains(t, ops, "GET /some/where/else")
assert.Contains(t, ops, "GET /some/where")
}
func Test_EdgeCases(t *testing.T) {
// check return values are consistent in some nil/empty edge cases
sp := Spec{}
res1 := sp.AllPaths()
assert.Nil(t, res1)
res2 := sp.OperationIDs()
assert.Nil(t, res2)
res3 := sp.OperationMethodPaths()
assert.Nil(t, res3)
res4 := sp.structMapKeys(nil)
assert.Nil(t, res4)
res5 := sp.structMapKeys(make(map[string]struct{}, 10))
assert.Nil(t, res5)
// check AllRefs() skips empty $refs
sp.references.allRefs = make(map[string]spec.Ref, 3)
for i := 0; i < 3; i++ {
sp.references.allRefs["ref"+strconv.Itoa(i)] = spec.Ref{}
}
assert.Len(t, sp.references.allRefs, 3)
res6 := sp.AllRefs()
assert.Len(t, res6, 0)
// check AllRefs() skips duplicate $refs
sp.references.allRefs["refToOne"] = spec.MustCreateRef("#/ref1")
sp.references.allRefs["refToOneAgain"] = spec.MustCreateRef("#/ref1")
res7 := sp.AllRefs()
assert.NotNil(t, res7)
assert.Len(t, res7, 1)
}
func TestEnumAnalysis(t *testing.T) {
doc, err := loadSpec(filepath.Join("fixtures", "enums.yml"))
if assert.NoError(t, err) {
an := New(doc)
en := an.enums
// parameters
assertEnum(t, en.parameters, "#/parameters/idParam", []interface{}{"aA", "b9", "c3"})
assertEnum(t, en.parameters, "#/paths/~1some~1where~1{id}/parameters/1", []interface{}{"bA", "ba", "b9"})
assertEnum(t, en.parameters, "#/paths/~1some~1where~1{id}/get/parameters/0", []interface{}{"a0", "b1", "c2"})
// responses
assertEnum(t, en.headers, "#/responses/notFound/headers/ContentLength", []interface{}{"1234", "123"})
assertEnum(t, en.headers,
"#/paths/~1some~1where~1{id}/get/responses/200/headers/X-Request-Id", []interface{}{"dA", "d9"})
// definitions
assertEnum(t, en.schemas,
"#/paths/~1other~1place/post/parameters/0/schema/properties/value", []interface{}{"eA", "e9"})
assertEnum(t, en.schemas, "#/paths/~1other~1place/post/responses/200/schema/properties/data",
[]interface{}{"123a", "123b", "123d"})
assertEnum(t, en.schemas, "#/definitions/named", []interface{}{"fA", "f9"})
assertEnum(t, en.schemas, "#/definitions/tag/properties/value", []interface{}{"gA", "ga", "g9"})
assertEnum(t, en.schemas, "#/definitions/record",
[]interface{}{`{"createdAt": "2018-08-31"}`, `{"createdAt": "2018-09-30"}`})
// array enum
assertEnum(t, en.parameters, "#/paths/~1some~1where~1{id}/get/parameters/1",
[]interface{}{[]interface{}{"cA", "cz", "c9"}, []interface{}{"cA", "cz"}, []interface{}{"cz", "c9"}})
// items
assertEnum(t, en.items, "#/paths/~1some~1where~1{id}/get/parameters/1/items", []interface{}{"cA", "cz", "c9"})
assertEnum(t, en.items, "#/paths/~1other~1place/post/responses/default/headers/Via/items",
[]interface{}{"AA", "Ab"})
res := an.AllEnums()
assert.Lenf(t, res, 14, "Expected 14 enums in this spec, but got %d", len(res))
res = an.ParameterEnums()
assert.Lenf(t, res, 4, "Expected 4 enums in this spec, but got %d", len(res))
res = an.SchemaEnums()
assert.Lenf(t, res, 6, "Expected 6 schema enums in this spec, but got %d", len(res))
res = an.HeaderEnums()
assert.Lenf(t, res, 2, "Expected 2 header enums in this spec, but got %d", len(res))
res = an.ItemsEnums()
assert.Lenf(t, res, 2, "Expected 2 items enums in this spec, but got %d", len(res))
}
}
func assertEnum(t testing.TB, data map[string][]interface{}, key string, enum []interface{}) bool {
if assert.Contains(t, data, key) {
return assert.Equal(t, enum, data[key])
}
return false
}
| enj/origin | vendor/github.com/go-openapi/analysis/analyzer_test.go | GO | apache-2.0 | 31,632 |
# Copyright (c) 2020 PaddlePaddle 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.
from __future__ import print_function
import unittest
import numpy
import paddle.fluid.core as core
import paddle.fluid as fluid
class TestExecutor(unittest.TestCase):
def net(self):
lr = fluid.data(name="lr", shape=[1], dtype='float32')
x = fluid.data(name="x", shape=[None, 1], dtype='float32')
y = fluid.data(name="y", shape=[None, 1], dtype='float32')
y_predict = fluid.layers.fc(input=x, size=1, act=None)
cost = fluid.layers.square_error_cost(input=y_predict, label=y)
avg_cost = fluid.layers.mean(cost)
opt = fluid.optimizer.Adam(learning_rate=lr)
opt.minimize(avg_cost)
return lr, avg_cost
def test_program_check_feed(self):
main_program = fluid.Program()
startup_program = fluid.Program()
scope = fluid.Scope()
with fluid.program_guard(main_program, startup_program):
with fluid.scope_guard(scope):
cpu = fluid.CPUPlace()
exe = fluid.Executor(cpu)
lr, cost = self.net()
exe.run(startup_program)
train_data = [[1.0], [2.0], [3.0], [4.0]]
y_true = [[2.0], [4.0], [6.0], [8.0]]
a = 0
with self.assertRaises(ValueError):
exe.run(feed={'x': train_data,
'lr': a},
fetch_list=[lr, cost],
return_numpy=False,
use_prune=True)
def test_compiled_program_check_feed(self):
main_program = fluid.Program()
startup_program = fluid.Program()
scope = fluid.Scope()
with fluid.program_guard(main_program, startup_program):
with fluid.scope_guard(scope):
cpu = fluid.CPUPlace()
exe = fluid.Executor(cpu)
lr, cost = self.net()
exe.run(startup_program)
compiled_prog = fluid.CompiledProgram(
main_program).with_data_parallel(loss_name=cost.name)
train_data = [[1.0], [2.0], [3.0], [4.0]]
y_true = [[2.0], [4.0], [6.0], [8.0]]
a = 0
with self.assertRaises(ValueError):
exe.run(compiled_prog,
feed={'x': train_data,
'lr': a},
fetch_list=[lr, cost],
return_numpy=False,
use_prune=True)
if __name__ == '__main__':
unittest.main()
| PaddlePaddle/Paddle | python/paddle/fluid/tests/unittests/test_executor_check_feed.py | Python | apache-2.0 | 3,210 |
##############################################################################
##############################################################################
### T E S T I N G ###
##############################################################################
##############################################################################
# --------------------------------------------------------------------
# Copy all the HDF5 files from the test directory into the source directory
# --------------------------------------------------------------------
set (LIST_HDF5_TEST_FILES
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_basic1.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_basic2.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_types.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_dtypes.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_attr1.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_attr2.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_dset1.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_dset2.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_hyper1.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_hyper2.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_empty.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_links.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_softlinks.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_linked_softlink.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_extlink_src.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_extlink_trg.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_ext2softlink_src.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_ext2softlink_trg.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_dset_zero_dim_size1.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_dset_zero_dim_size2.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_danglelinks1.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_danglelinks2.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_grp_recurse1.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_grp_recurse2.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_grp_recurse_ext1.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_grp_recurse_ext2-1.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_grp_recurse_ext2-2.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_grp_recurse_ext2-3.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_exclude1-1.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_exclude1-2.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_exclude2-1.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_exclude2-2.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_exclude3-1.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_exclude3-2.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_comp_vl_strs.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_attr_v_level1.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_attr_v_level2.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/compounds_array_vlen1.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/compounds_array_vlen2.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/non_comparables1.h5
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/non_comparables2.h5
)
set (LIST_OTHER_TEST_FILES
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_10.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_100.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_101.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_102.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_103.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_104.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_11.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_12.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_13.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_14.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_15.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_16_1.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_16_2.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_16_3.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_17.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_171.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_172.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_18_1.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_18.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_20.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_200.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_201.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_202.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_203.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_204.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_205.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_206.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_207.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_208.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_220.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_221.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_222.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_223.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_224.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_21.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_22.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_23.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_24.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_25.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_26.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_27.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_28.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_300.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_400.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_401.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_402.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_403.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_404.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_405.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_406.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_407.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_408.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_409.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_410.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_411.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_412.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_413.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_414.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_415.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_416.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_417.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_418.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_419.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_420.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_421.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_422.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_423.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_424.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_425.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_450.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_451.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_452.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_453.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_454.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_455.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_456.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_457.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_458.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_459.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_465.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_466.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_467.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_468.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_469.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_471.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_472.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_473.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_474.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_475.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_480.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_481.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_482.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_483.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_484.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_485.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_486.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_487.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_50.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_51.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_52.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_53.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_54.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_55.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_56.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_57.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_58.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_59.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_500.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_501.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_502.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_503.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_504.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_505.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_506.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_507.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_508.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_509.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_510.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_511.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_512.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_513.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_514.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_515.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_516.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_517.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_518.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_530.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_540.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_600.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_601.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_603.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_604.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_605.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_606.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_607.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_608.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_609.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_610.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_612.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_613.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_614.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_615.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_616.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_617.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_618.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_619.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_621.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_622.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_623.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_624.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_625.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_626.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_627.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_628.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_629.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_630.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_631.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_640.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_641.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_642.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_643.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_644.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_645.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_646.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_70.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_700.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_701.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_702.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_703.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_704.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_705.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_706.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_707.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_708.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_709.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_710.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_80.txt
${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_90.txt
)
# Make testfiles dir under build dir
file (MAKE_DIRECTORY "${PROJECT_BINARY_DIR}/testfiles")
#
# copy test files from source to build dir
#
foreach (h5_tstfiles ${LIST_HDF5_TEST_FILES} ${LIST_OTHER_TEST_FILES})
GET_FILENAME_COMPONENT(fname "${h5_tstfiles}" NAME)
set (dest "${PROJECT_BINARY_DIR}/testfiles/${fname}")
#message (STATUS " Copying ${fname}")
add_custom_command (
TARGET h5diff
POST_BUILD
COMMAND ${CMAKE_COMMAND}
ARGS -E copy_if_different ${h5_tstfiles} ${dest}
)
endforeach (h5_tstfiles ${LIST_HDF5_TEST_FILES} ${LIST_OTHER_TEST_FILES})
#
# Overwrite system dependent files (Windows)
#
if (WIN32)
add_custom_command (
TARGET h5diff
POST_BUILD
COMMAND ${CMAKE_COMMAND}
ARGS -E copy_if_different ${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_101w.txt ${PROJECT_BINARY_DIR}/testfiles/h5diff_101.txt
)
add_custom_command (
TARGET h5diff
POST_BUILD
COMMAND ${CMAKE_COMMAND}
ARGS -E copy_if_different ${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_102w.txt ${PROJECT_BINARY_DIR}/testfiles/h5diff_102.txt
)
add_custom_command (
TARGET h5diff
POST_BUILD
COMMAND ${CMAKE_COMMAND}
ARGS -E copy_if_different ${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_103w.txt ${PROJECT_BINARY_DIR}/testfiles/h5diff_103.txt
)
add_custom_command (
TARGET h5diff
POST_BUILD
COMMAND ${CMAKE_COMMAND}
ARGS -E copy_if_different ${HDF5_TOOLS_H5DIFF_SOURCE_DIR}/testfiles/h5diff_104w.txt ${PROJECT_BINARY_DIR}/testfiles/h5diff_104.txt
)
endif (WIN32)
##############################################################################
##############################################################################
### T H E T E S T S M A C R O S ###
##############################################################################
##############################################################################
MACRO (ADD_H5_TEST resultfile resultcode)
# If using memchecker add tests without using scripts
if (HDF5_ENABLE_USING_MEMCHECKER)
add_test (NAME H5DIFF-${resultfile} COMMAND $<TARGET_FILE:h5diff> ${ARGN})
set_tests_properties (H5DIFF-${resultfile} PROPERTIES WORKING_DIRECTORY "${PROJECT_BINARY_DIR}/testfiles")
if (NOT ${resultcode} STREQUAL "0")
set_tests_properties (H5DIFF-${resultfile} PROPERTIES WILL_FAIL "true")
endif (NOT ${resultcode} STREQUAL "0")
if (NOT "${last_test}" STREQUAL "")
set_tests_properties (H5DIFF-${resultfile} PROPERTIES DEPENDS ${last_test})
endif (NOT "${last_test}" STREQUAL "")
else (HDF5_ENABLE_USING_MEMCHECKER)
add_test (
NAME H5DIFF-${resultfile}-clear-objects
COMMAND ${CMAKE_COMMAND}
-E remove ./testfiles/${resultfile}.out ./testfiles/${resultfile}.out.err
)
add_test (
NAME H5DIFF-${resultfile}
COMMAND "${CMAKE_COMMAND}"
-D "TEST_PROGRAM=$<TARGET_FILE:h5diff>"
-D "TEST_ARGS:STRING=${ARGN}"
-D "TEST_FOLDER=${PROJECT_BINARY_DIR}/testfiles"
-D "TEST_OUTPUT=${resultfile}.out"
-D "TEST_EXPECT=${resultcode}"
-D "TEST_REFERENCE=${resultfile}.txt"
-D "TEST_APPEND=EXIT CODE:"
-P "${HDF_RESOURCES_EXT_DIR}/runTest.cmake"
)
set_tests_properties (H5DIFF-${resultfile} PROPERTIES DEPENDS "H5DIFF-${resultfile}-clear-objects")
endif (HDF5_ENABLE_USING_MEMCHECKER)
if (H5_HAVE_PARALLEL)
ADD_PH5_TEST (${resultfile} ${resultcode} ${ARGN})
endif (H5_HAVE_PARALLEL)
ENDMACRO (ADD_H5_TEST file)
MACRO (ADD_PH5_TEST resultfile resultcode)
# If using memchecker add tests without using scripts
if (HDF5_ENABLE_USING_MEMCHECKER)
add_test (NAME PH5DIFF-${resultfile} COMMAND $<TARGET_FILE:ph5diff> ${MPIEXEC} ${MPIEXEC_PREFLAGS} ${MPIEXEC_NUMPROC_FLAG} ${MPIEXEC_MAX_NUMPROCS} ${MPIEXEC_POSTFLAGS} ${ARGN})
set_tests_properties (PH5DIFF-${resultfile} PROPERTIES WORKING_DIRECTORY "${PROJECT_BINARY_DIR}/testfiles")
if (NOT ${resultcode} STREQUAL "0")
set_tests_properties (PH5DIFF-${resultfile} PROPERTIES WILL_FAIL "true")
endif (NOT ${resultcode} STREQUAL "0")
if (NOT "${last_test}" STREQUAL "")
set_tests_properties (PH5DIFF-${resultfile} PROPERTIES DEPENDS ${last_test})
endif (NOT "${last_test}" STREQUAL "")
else (HDF5_ENABLE_USING_MEMCHECKER)
add_test (
NAME PH5DIFF-${resultfile}-clear-objects
COMMAND ${CMAKE_COMMAND}
-E remove ./testfiles/${resultfile}_p.out ./testfiles/${resultfile}_p.out.err
)
add_test (
NAME PH5DIFF-${resultfile}
COMMAND "${CMAKE_COMMAND}"
-D "TEST_PROGRAM=${MPIEXEC};${MPIEXEC_PREFLAGS};${MPIEXEC_NUMPROC_FLAG};${MPIEXEC_MAX_NUMPROCS};${MPIEXEC_POSTFLAGS};$<TARGET_FILE:ph5diff>"
-D "TEST_ARGS:STRING=${ARGN}"
-D "TEST_FOLDER=${PROJECT_BINARY_DIR}/testfiles"
-D "TEST_OUTPUT=P_${resultfile}.out"
-D "TEST_EXPECT=${resultcode}"
-D "TEST_REFERENCE=${resultfile}.txt"
# -D "TEST_APPEND=EXIT CODE: [0-9]"
# -D "TEST_REF_FILTER=EXIT CODE: 0"
-D "TEST_SKIP_COMPARE=TRUE"
-P "${HDF_RESOURCES_EXT_DIR}/prunTest.cmake"
)
set_tests_properties (PH5DIFF-${resultfile} PROPERTIES DEPENDS "PH5DIFF-${resultfile}-clear-objects")
endif (HDF5_ENABLE_USING_MEMCHECKER)
ENDMACRO (ADD_PH5_TEST file)
# ADD_H5_NO_OUTPUT_TEST
# Purpose to verify only exitcode without output comparison
# Don't use this if possible; this may be removed.
MACRO (ADD_H5_NO_OUTPUT_TEST testname resultcode)
# If using memchecker add tests without using scripts
if (NOT HDF5_ENABLE_USING_MEMCHECKER)
add_test (
NAME H5DIFF-${testname}-clear-objects
COMMAND ${CMAKE_COMMAND}
-E remove ./testfiles/${testname}.out ./testfiles/${testname}.out.err
)
# if there was a previous test
if (NOT "${last_test}" STREQUAL "")
set_tests_properties (H5DIFF-${testname}-clear-objects PROPERTIES DEPENDS ${last_test})
endif (NOT "${last_test}" STREQUAL "")
endif (NOT HDF5_ENABLE_USING_MEMCHECKER)
add_test (NAME H5DIFF-${testname} COMMAND $<TARGET_FILE:h5diff> ${ARGN})
if (NOT ${resultcode} STREQUAL "0")
set_tests_properties (H5DIFF-${testname} PROPERTIES WILL_FAIL "true")
endif (NOT ${resultcode} STREQUAL "0")
if (HDF5_ENABLE_USING_MEMCHECKER)
if (NOT "${last_test}" STREQUAL "")
set_tests_properties (H5DIFF-${testname} PROPERTIES DEPENDS ${last_test})
endif (NOT "${last_test}" STREQUAL "")
else (HDF5_ENABLE_USING_MEMCHECKER)
set_tests_properties (H5DIFF-${testname} PROPERTIES DEPENDS H5DIFF-${testname}-clear-objects)
endif (HDF5_ENABLE_USING_MEMCHECKER)
ENDMACRO (ADD_H5_NO_OUTPUT_TEST)
##############################################################################
##############################################################################
### T H E T E S T S ###
##############################################################################
##############################################################################
# --------------------------------------------------------------------
# test file names
# --------------------------------------------------------------------
set (FILE1 h5diff_basic1.h5)
set (FILE2 h5diff_basic2.h5)
set (FILE3 h5diff_types.h5)
set (FILE4 h5diff_dtypes.h5)
set (FILE5 h5diff_attr1.h5)
set (FILE6 h5diff_attr2.h5)
set (FILE7 h5diff_dset1.h5)
set (FILE8 h5diff_dset2.h5)
set (FILE9 h5diff_hyper1.h5)
set (FILE10 h5diff_hyper2.h5)
set (FILE11 h5diff_empty.h5)
set (FILE12 h5diff_links.h5)
set (FILE13 h5diff_softlinks.h5)
set (FILE14 h5diff_linked_softlink.h5)
set (FILE15 h5diff_extlink_src.h5)
set (FILE16 h5diff_extlink_trg.h5)
set (FILE17 h5diff_ext2softlink_src.h5)
set (FILE18 h5diff_ext2softlink_trg.h5)
set (FILE19 h5diff_dset_zero_dim_size1.h5)
set (FILE20 h5diff_dset_zero_dim_size2.h5)
set (DANGLE_LINK_FILE1 h5diff_danglelinks1.h5)
set (DANGLE_LINK_FILE2 h5diff_danglelinks2.h5)
set (GRP_RECURSE_FILE1 h5diff_grp_recurse1.h5)
set (GRP_RECURSE_FILE2 h5diff_grp_recurse2.h5)
# group recursive - same structure via external links through files
set (GRP_RECURSE1_EXT h5diff_grp_recurse_ext1.h5)
set (GRP_RECURSE2_EXT1 h5diff_grp_recurse_ext2-1.h5)
set (GRP_RECURSE2_EXT2 h5diff_grp_recurse_ext2-2.h5)
set (GRP_RECURSE2_EXT3 h5diff_grp_recurse_ext2-3.h5)
# same structure, same obj name with different value
set (EXCLUDE_FILE1_1 h5diff_exclude1-1.h5)
set (EXCLUDE_FILE1_2 h5diff_exclude1-2.h5)
# different structure and obj names
set (EXCLUDE_FILE2_1 h5diff_exclude2-1.h5)
set (EXCLUDE_FILE2_2 h5diff_exclude2-2.h5)
# Only one file contains unique objs. Common objs are same.
set (EXCLUDE_FILE3_1 h5diff_exclude3-1.h5)
set (EXCLUDE_FILE3_2 h5diff_exclude3-2.h5)
# compound type with multiple vlen string types
set (COMP_VL_STRS_FILE h5diff_comp_vl_strs.h5)
# container types (array,vlen) with multiple nested compound types
set (COMPS_ARRAY_VLEN_FILE1 compounds_array_vlen1.h5)
set (COMPS_ARRAY_VLEN_FILE2 compounds_array_vlen2.h5)
# attrs with verbose option level
set (ATTR_VERBOSE_LEVEL_FILE1 h5diff_attr_v_level1.h5)
set (ATTR_VERBOSE_LEVEL_FILE2 h5diff_attr_v_level2.h5)
if (HDF5_ENABLE_USING_MEMCHECKER)
# Remove any output file left over from previous test run
add_test (
NAME H5DIFF-clearall-objects
COMMAND ${CMAKE_COMMAND}
-E remove
h5diff_10.out
h5diff_10.out.err
h5diff_100.out
h5diff_100.out.err
h5diff_101.out
h5diff_101.out.err
h5diff_102.out
h5diff_102.out.err
h5diff_103.out
h5diff_103.out.err
h5diff_104.out
h5diff_104.out.err
h5diff_11.out
h5diff_11.out.err
h5diff_12.out
h5diff_12.out.err
h5diff_13.out
h5diff_13.out.err
h5diff_14.out
h5diff_14.out.err
h5diff_15.out
h5diff_15.out.err
h5diff_16_1.out
h5diff_16_1.out.err
h5diff_16_2.out
h5diff_16_2.out.err
h5diff_16_3.out
h5diff_16_3.out.err
h5diff_17.out
h5diff_17.out.err
h5diff_171.out
h5diff_171.out.err
h5diff_172.out
h5diff_172.out.err
h5diff_18_1.out
h5diff_18_1.out.err
h5diff_18.out
h5diff_18.out.err
h5diff_20.out
h5diff_20.out.err
h5diff_200.out
h5diff_200.out.err
h5diff_201.out
h5diff_201.out.err
h5diff_202.out
h5diff_202.out.err
h5diff_203.out
h5diff_203.out.err
h5diff_204.out
h5diff_204.out.err
h5diff_205.out
h5diff_205.out.err
h5diff_206.out
h5diff_206.out.err
h5diff_207.out
h5diff_207.out.err
h5diff_208.out
h5diff_208.out.err
h5diff_220.out
h5diff_220.out.err
h5diff_221.out
h5diff_221.out.err
h5diff_222.out
h5diff_222.out.err
h5diff_223.out
h5diff_223.out.err
h5diff_224.out
h5diff_224.out.err
h5diff_21.out
h5diff_21.out.err
h5diff_22.out
h5diff_22.out.err
h5diff_23.out
h5diff_23.out.err
h5diff_24.out
h5diff_24.out.err
h5diff_25.out
h5diff_25.out.err
h5diff_26.out
h5diff_26.out.err
h5diff_27.out
h5diff_27.out.err
h5diff_28.out
h5diff_28.out.err
h5diff_300.out
h5diff_300.out.err
h5diff_400.out
h5diff_400.out.err
h5diff_401.out
h5diff_401.out.err
h5diff_402.out
h5diff_402.out.err
h5diff_403.out
h5diff_403.out.err
h5diff_404.out
h5diff_404.out.err
h5diff_405.out
h5diff_405.out.err
h5diff_406.out
h5diff_406.out.err
h5diff_407.out
h5diff_407.out.err
h5diff_408.out
h5diff_408.out.err
h5diff_409.out
h5diff_409.out.err
h5diff_410.out
h5diff_410.out.err
h5diff_411.out
h5diff_411.out.err
h5diff_412.out
h5diff_412.out.err
h5diff_413.out
h5diff_413.out.err
h5diff_414.out
h5diff_414.out.err
h5diff_415.out
h5diff_415.out.err
h5diff_416.out
h5diff_416.out.err
h5diff_417.out
h5diff_417.out.err
h5diff_418.out
h5diff_418.out.err
h5diff_419.out
h5diff_419.out.err
h5diff_420.out
h5diff_420.out.err
h5diff_421.out
h5diff_421.out.err
h5diff_422.out
h5diff_422.out.err
h5diff_423.out
h5diff_423.out.err
h5diff_424.out
h5diff_424.out.err
h5diff_425.out
h5diff_425.out.err
h5diff_450.out
h5diff_450.out.err
h5diff_451.out
h5diff_451.out.err
h5diff_452.out
h5diff_452.out.err
h5diff_453.out
h5diff_453.out.err
h5diff_454.out
h5diff_454.out.err
h5diff_455.out
h5diff_455.out.err
h5diff_456.out
h5diff_456.out.err
h5diff_457.out
h5diff_457.out.err
h5diff_458.out
h5diff_458.out.err
h5diff_459.out
h5diff_459.out.err
h5diff_465.out
h5diff_465.out.err
h5diff_466.out
h5diff_466.out.err
h5diff_467.out
h5diff_467.out.err
h5diff_468.out
h5diff_468.out.err
h5diff_469.out
h5diff_469.out.err
h5diff_471.out
h5diff_471.out.err
h5diff_472.out
h5diff_472.out.err
h5diff_473.out
h5diff_473.out.err
h5diff_474.out
h5diff_474.out.err
h5diff_475.out
h5diff_475.out.err
h5diff_480.out
h5diff_480.out.err
h5diff_481.out
h5diff_481.out.err
h5diff_482.out
h5diff_482.out.err
h5diff_483.out
h5diff_483.out.err
h5diff_484.out
h5diff_484.out.err
h5diff_50.out
h5diff_50.out.err
h5diff_51.out
h5diff_51.out.err
h5diff_52.out
h5diff_52.out.err
h5diff_53.out
h5diff_53.out.err
h5diff_54.out
h5diff_54.out.err
h5diff_55.out
h5diff_55.out.err
h5diff_56.out
h5diff_56.out.err
h5diff_57.out
h5diff_57.out.err
h5diff_58.out
h5diff_58.out.err
h5diff_59.out
h5diff_59.out.err
h5diff_500.out
h5diff_500.out.err
h5diff_501.out
h5diff_501.out.err
h5diff_502.out
h5diff_502.out.err
h5diff_503.out
h5diff_503.out.err
h5diff_504.out
h5diff_504.out.err
h5diff_505.out
h5diff_505.out.err
h5diff_506.out
h5diff_506.out.err
h5diff_507.out
h5diff_507.out.err
h5diff_508.out
h5diff_508.out.err
h5diff_509.out
h5diff_509.out.err
h5diff_510.out
h5diff_510.out.err
h5diff_511.out
h5diff_511.out.err
h5diff_512.out
h5diff_512.out.err
h5diff_513.out
h5diff_513.out.err
h5diff_514.out
h5diff_514.out.err
h5diff_515.out
h5diff_515.out.err
h5diff_516.out
h5diff_516.out.err
h5diff_517.out
h5diff_517.out.err
h5diff_518.out
h5diff_518.out.err
h5diff_530.out
h5diff_530.out.err
h5diff_540.out
h5diff_540.out.err
h5diff_600.out
h5diff_600.out.err
h5diff_601.out
h5diff_601.out.err
h5diff_603.out
h5diff_603.out.err
h5diff_604.out
h5diff_604.out.err
h5diff_605.out
h5diff_605.out.err
h5diff_606.out
h5diff_606.out.err
h5diff_607.out
h5diff_607.out.err
h5diff_608.out
h5diff_608.out.err
h5diff_609.out
h5diff_609.out.err
h5diff_610.out
h5diff_610.out.err
h5diff_612.out
h5diff_612.out.err
h5diff_613.out
h5diff_613.out.err
h5diff_614.out
h5diff_614.out.err
h5diff_615.out
h5diff_615.out.err
h5diff_616.out
h5diff_616.out.err
h5diff_617.out
h5diff_617.out.err
h5diff_618.out
h5diff_618.out.err
h5diff_619.out
h5diff_619.out.err
h5diff_621.out
h5diff_621.out.err
h5diff_622.out
h5diff_622.out.err
h5diff_623.out
h5diff_623.out.err
h5diff_624.out
h5diff_624.out.err
h5diff_625.out
h5diff_625.out.err
h5diff_626.out
h5diff_626.out.err
h5diff_627.out
h5diff_627.out.err
h5diff_628.out
h5diff_628.out.err
h5diff_629.out
h5diff_629.out.err
h5diff_640.out
h5diff_640.out.err
h5diff_641.out
h5diff_641.out.err
h5diff_642.out
h5diff_642.out.err
h5diff_643.out
h5diff_643.out.err
h5diff_644.out
h5diff_644.out.err
h5diff_645.out
h5diff_645.out.err
h5diff_646.out
h5diff_646.out.err
h5diff_70.out
h5diff_70.out.err
h5diff_700.out
h5diff_700.out.err
h5diff_701.out
h5diff_701.out.err
h5diff_702.out
h5diff_702.out.err
h5diff_703.out
h5diff_703.out.err
h5diff_704.out
h5diff_704.out.err
h5diff_705.out
h5diff_705.out.err
h5diff_706.out
h5diff_706.out.err
h5diff_707.out
h5diff_707.out.err
h5diff_708.out
h5diff_708.out.err
h5diff_709.out
h5diff_709.out.err
h5diff_710.out
h5diff_710.out.err
h5diff_80.out
h5diff_80.out.err
h5diff_90.out
h5diff_90.out.err
)
set_tests_properties (H5DIFF-clearall-objects PROPERTIES WORKING_DIRECTORY "${PROJECT_BINARY_DIR}/testfiles")
if (NOT "${last_test}" STREQUAL "")
set_tests_properties (H5DIFF-clearall-objects PROPERTIES DEPENDS ${last_test})
endif (NOT "${last_test}" STREQUAL "")
set (last_test "H5DIFF-clearall-objects")
endif (HDF5_ENABLE_USING_MEMCHECKER)
# ############################################################################
# # Common usage
# ############################################################################
# 1.0
ADD_H5_TEST (h5diff_10 0 -h)
# 1.1 normal mode
ADD_H5_TEST (h5diff_11 1 ${FILE1} ${FILE2})
# 1.2 normal mode with objects
ADD_H5_TEST (h5diff_12 1 ${FILE1} ${FILE2} g1/dset1 g1/dset2)
# 1.3 report mode
ADD_H5_TEST (h5diff_13 1 -r ${FILE1} ${FILE2})
# 1.4 report mode with objects
ADD_H5_TEST (h5diff_14 1 -r ${FILE1} ${FILE2} g1/dset1 g1/dset2)
# 1.5 with -d
ADD_H5_TEST (h5diff_15 1 --report --delta=5 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 1.6.1 with -p (int)
ADD_H5_TEST (h5diff_16_1 1 -v -p 0.02 ${FILE1} ${FILE1} g1/dset5 g1/dset6)
# 1.6.2 with -p (unsigned long_long)
ADD_H5_TEST (h5diff_16_2 1 --verbose --relative=0.02 ${FILE1} ${FILE1} g1/dset7 g1/dset8)
# 1.6.3 with -p (double)
ADD_H5_TEST (h5diff_16_3 1 -v -p 0.02 ${FILE1} ${FILE1} g1/dset9 g1/dset10)
# 1.7 verbose mode
ADD_H5_TEST (h5diff_17 1 -v ${FILE1} ${FILE2})
# 1.7 test 32-bit INFINITY
ADD_H5_TEST (h5diff_171 0 -v ${FILE1} ${FILE1} /g1/fp19 /g1/fp19_COPY)
# 1.7 test 64-bit INFINITY
ADD_H5_TEST (h5diff_172 0 -v ${FILE1} ${FILE1} /g1/fp20 /g1/fp20_COPY)
# 1.8 quiet mode
ADD_H5_TEST (h5diff_18 1 -q ${FILE1} ${FILE2})
# 1.8 -v and -q
ADD_H5_TEST (h5diff_18_1 2 -v -q ${FILE1} ${FILE2})
# ##############################################################################
# # not comparable types
# ##############################################################################
# 2.0
ADD_H5_TEST (h5diff_20 0 -v ${FILE3} ${FILE3} dset g1)
# 2.1
ADD_H5_TEST (h5diff_21 0 -v ${FILE3} ${FILE3} dset l1)
# 2.2
ADD_H5_TEST (h5diff_22 0 -v ${FILE3} ${FILE3} dset t1)
# ##############################################################################
# # compare groups, types, links (no differences and differences)
# ##############################################################################
# 2.3
ADD_H5_TEST (h5diff_23 0 -v ${FILE3} ${FILE3} g1 g1)
# 2.4
ADD_H5_TEST (h5diff_24 0 -v ${FILE3} ${FILE3} t1 t1)
# 2.5
ADD_H5_TEST (h5diff_25 0 -v ${FILE3} ${FILE3} l1 l1)
# 2.6
ADD_H5_TEST (h5diff_26 0 -v ${FILE3} ${FILE3} g1 g2)
# 2.7
ADD_H5_TEST (h5diff_27 1 -v ${FILE3} ${FILE3} t1 t2)
# 2.8
ADD_H5_TEST (h5diff_28 1 -v ${FILE3} ${FILE3} l1 l2)
# ##############################################################################
# # Dataset datatypes
# ##############################################################################
# 5.0
ADD_H5_TEST (h5diff_50 1 -v ${FILE4} ${FILE4} dset0a dset0b)
# 5.1
ADD_H5_TEST (h5diff_51 1 -v ${FILE4} ${FILE4} dset1a dset1b)
# 5.2
ADD_H5_TEST (h5diff_52 1 -v ${FILE4} ${FILE4} dset2a dset2b)
# 5.3
ADD_H5_TEST (h5diff_53 1 -v ${FILE4} ${FILE4} dset3a dset4b)
# 5.4
ADD_H5_TEST (h5diff_54 1 -v ${FILE4} ${FILE4} dset4a dset4b)
# 5.5
ADD_H5_TEST (h5diff_55 1 -v ${FILE4} ${FILE4} dset5a dset5b)
# 5.6
ADD_H5_TEST (h5diff_56 1 -v ${FILE4} ${FILE4} dset6a dset6b)
# 5.7
ADD_H5_TEST (h5diff_57 0 -v ${FILE4} ${FILE4} dset7a dset7b)
# 5.8 (region reference)
ADD_H5_TEST (h5diff_58 1 -v ${FILE7} ${FILE8} refreg)
# test for both dset and attr with same type but with different size
# ( HDDFV-7942 )
ADD_H5_TEST (h5diff_59 0 -v ${FILE4} ${FILE4} dset11a dset11b)
# ##############################################################################
# # Error messages
# ##############################################################################
# 6.0: Check if the command line number of arguments is less than 3
ADD_H5_TEST (h5diff_600 1 ${FILE1})
# 6.1: Check if non-exist object name is specified
ADD_H5_TEST (h5diff_601 2 ${FILE1} ${FILE1} nono_obj)
# ##############################################################################
# # -d
# ##############################################################################
# 6.3: negative value
ADD_H5_TEST (h5diff_603 1 -d -4 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.4: zero
ADD_H5_TEST (h5diff_604 1 -d 0 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.5: non number
ADD_H5_TEST (h5diff_605 1 -d u ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.6: hexadecimal
ADD_H5_TEST (h5diff_606 1 -d 0x1 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.7: string
ADD_H5_TEST (h5diff_607 1 -d "1" ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.8: use system epsilon
ADD_H5_TEST (h5diff_608 1 --use-system-epsilon ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.9: number larger than biggest difference
ADD_H5_TEST (h5diff_609 0 -d 200 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.10: number smaller than smallest difference
ADD_H5_TEST (h5diff_610 1 -d 1 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# ##############################################################################
# # -p
# ##############################################################################
# 6.12: negative value
ADD_H5_TEST (h5diff_612 1 -p -4 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.13: zero
ADD_H5_TEST (h5diff_613 1 -p 0 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.14: non number
ADD_H5_TEST (h5diff_614 1 -p u ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.15: hexadecimal
ADD_H5_TEST (h5diff_615 1 -p 0x1 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.16: string
ADD_H5_TEST (h5diff_616 1 -p "0.21" ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.17: repeated option
ADD_H5_TEST (h5diff_617 1 -p 0.21 -p 0.22 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.18: number larger than biggest difference
ADD_H5_TEST (h5diff_618 0 -p 2 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.19: number smaller than smallest difference
ADD_H5_TEST (h5diff_619 1 -p 0.005 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# ##############################################################################
# # -n
# ##############################################################################
# 6.21: negative value
ADD_H5_TEST (h5diff_621 1 -n -4 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.22: zero
ADD_H5_TEST (h5diff_622 1 -n 0 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.23: non number
ADD_H5_TEST (h5diff_623 1 -n u ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.24: hexadecimal
ADD_H5_TEST (h5diff_624 1 -n 0x1 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.25: string
ADD_H5_TEST (h5diff_625 1 -n "2" ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.26: repeated option
ADD_H5_TEST (h5diff_626 1 -n 2 -n 3 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.27: number larger than biggest difference
ADD_H5_TEST (h5diff_627 1 --count=200 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# 6.28: number smaller than smallest difference
ADD_H5_TEST (h5diff_628 1 -n 1 ${FILE1} ${FILE2} g1/dset3 g1/dset4)
# Disabling this test as it hangs - LRK 20090618
# 6.29 non valid files
#ADD_H5_TEST (h5diff_629 2 file1.h6 file2.h6)
# ##############################################################################
# # NaN
# ##############################################################################
# 6.30: test (NaN == NaN) must be true based on our documentation -- XCAO
ADD_H5_TEST (h5diff_630 0 -v -d "0.0001" ${FILE1} ${FILE1} g1/fp18 g1/fp18_COPY)
ADD_H5_TEST (h5diff_631 0 -v --use-system-epsilon ${FILE1} ${FILE1} g1/fp18 g1/fp18_COPY)
# ##############################################################################
# 7. attributes
# ##############################################################################
ADD_H5_TEST (h5diff_70 1 -v ${FILE5} ${FILE6})
# ##################################################
# attrs with verbose option level
# ##################################################
ADD_H5_TEST (h5diff_700 1 -v1 ${FILE5} ${FILE6})
ADD_H5_TEST (h5diff_701 1 -v2 ${FILE5} ${FILE6})
ADD_H5_TEST (h5diff_702 1 --verbose=1 ${FILE5} ${FILE6})
ADD_H5_TEST (h5diff_703 1 --verbose=2 ${FILE5} ${FILE6})
# same attr number , all same attr name
ADD_H5_TEST (h5diff_704 1 -v2 ${ATTR_VERBOSE_LEVEL_FILE1} ${ATTR_VERBOSE_LEVEL_FILE2} /g)
# same attr number , some same attr name
ADD_H5_TEST (h5diff_705 1 -v2 ${ATTR_VERBOSE_LEVEL_FILE1} ${ATTR_VERBOSE_LEVEL_FILE2} /dset)
# same attr number , all different attr name
ADD_H5_TEST (h5diff_706 1 -v2 ${ATTR_VERBOSE_LEVEL_FILE1} ${ATTR_VERBOSE_LEVEL_FILE2} /ntype)
# different attr number , same attr name (intersected)
ADD_H5_TEST (h5diff_707 1 -v2 ${ATTR_VERBOSE_LEVEL_FILE1} ${ATTR_VERBOSE_LEVEL_FILE2} /g2)
# different attr number , all different attr name
ADD_H5_TEST (h5diff_708 1 -v2 ${ATTR_VERBOSE_LEVEL_FILE1} ${ATTR_VERBOSE_LEVEL_FILE2} /g3)
# when no attributes exist in both objects
ADD_H5_TEST (h5diff_709 0 -v2 ${ATTR_VERBOSE_LEVEL_FILE1} ${ATTR_VERBOSE_LEVEL_FILE2} /g4)
# file vs file
ADD_H5_TEST (h5diff_710 1 -v2 ${ATTR_VERBOSE_LEVEL_FILE1} ${ATTR_VERBOSE_LEVEL_FILE2})
# ##############################################################################
# 8. all dataset datatypes
# ##############################################################################
ADD_H5_TEST (h5diff_80 1 -v ${FILE7} ${FILE8})
# 9. compare a file with itself
ADD_H5_TEST (h5diff_90 0 -v ${FILE2} ${FILE2})
# 10. read by hyperslab, print indexes
#if test -n "$pmode" -a "$mydomainname" = hdfgroup.uiuc.edu; then
# # skip this test which sometimes hangs in some THG machines
# message (STATUS "SKIP -v ${FILE9} ${FILE10})
#else
# ADD_H5_TEST (h5diff_100 1 -v ${FILE9} ${FILE10})
#fi
# 11. floating point comparison
ADD_H5_TEST (h5diff_101 1 -v ${FILE1} ${FILE1} g1/d1 g1/d2)
ADD_H5_TEST (h5diff_102 1 -v ${FILE1} ${FILE1} g1/fp1 g1/fp2)
# with --use-system-epsilon for double value. expect less differences
ADD_H5_TEST (h5diff_103 1 -v --use-system-epsilon ${FILE1} ${FILE1} g1/d1
g1/d2)
# with --use-system-epsilon for float value. expect less differences
ADD_H5_TEST (h5diff_104 1 -v --use-system-epsilon ${FILE1} ${FILE1} g1/fp1
g1/fp2)
# not comparable -c flag
ADD_H5_TEST (h5diff_200 0 ${FILE2} ${FILE2} g2/dset1 g2/dset2)
ADD_H5_TEST (h5diff_201 0 -c ${FILE2} ${FILE2} g2/dset1 g2/dset2)
ADD_H5_TEST (h5diff_202 0 -c ${FILE2} ${FILE2} g2/dset2 g2/dset3)
ADD_H5_TEST (h5diff_203 0 -c ${FILE2} ${FILE2} g2/dset3 g2/dset4)
ADD_H5_TEST (h5diff_204 0 -c ${FILE2} ${FILE2} g2/dset4 g2/dset5)
ADD_H5_TEST (h5diff_205 0 -c ${FILE2} ${FILE2} g2/dset5 g2/dset6)
# not comparable in compound
ADD_H5_TEST (h5diff_206 0 -c ${FILE2} ${FILE2} g2/dset7 g2/dset8)
ADD_H5_TEST (h5diff_207 0 -c ${FILE2} ${FILE2} g2/dset8 g2/dset9)
# not comparable in dataspace of zero dimension size
ADD_H5_TEST (h5diff_208 0 -c ${FILE19} ${FILE20})
# non-comparable dataset with comparable attribute, and other comparable datasets.
# All the rest comparables should display differences.
ADD_H5_TEST (h5diff_220 1 -c non_comparables1.h5 non_comparables2.h5 /g1)
# comparable dataset with non-comparable attribute and other comparable attributes.
# Also test non-compatible attributes with different type, dimention, rank.
# All the rest comparables should display differences.
ADD_H5_TEST (h5diff_221 1 -c non_comparables1.h5 non_comparables2.h5 /g2)
# entire file
# All the rest comparables should display differences
ADD_H5_TEST (h5diff_222 1 -c non_comparables1.h5 non_comparables2.h5)
# non-comparable test for common objects (same name) with different object types
# (HDFFV-7644)
ADD_H5_TEST (h5diff_223 0 -c non_comparables1.h5 non_comparables2.h5 /diffobjtypes)
# swap files
ADD_H5_TEST (h5diff_224 0 -c non_comparables2.h5 non_comparables1.h5 /diffobjtypes)
# ##############################################################################
# # Links compare without --follow-symlinks nor --no-dangling-links
# ##############################################################################
# test for bug1749
ADD_H5_TEST (h5diff_300 1 -v ${FILE12} ${FILE12} /link_g1 /link_g2)
# ##############################################################################
# # Links compare with --follow-symlinks Only
# ##############################################################################
# soft links file to file
ADD_H5_TEST (h5diff_400 0 --follow-symlinks -v ${FILE13} ${FILE13})
# softlink vs dset"
ADD_H5_TEST (h5diff_401 1 --follow-symlinks -v ${FILE13} ${FILE13} /softlink_dset1_1 /target_dset2)
# dset vs softlink"
ADD_H5_TEST (h5diff_402 1 --follow-symlinks -v ${FILE13} ${FILE13} /target_dset2 /softlink_dset1_1)
# softlink vs softlink"
ADD_H5_TEST (h5diff_403 1 --follow-symlinks -v ${FILE13} ${FILE13} /softlink_dset1_1 /softlink_dset2)
# extlink vs extlink (FILE)"
ADD_H5_TEST (h5diff_404 0 --follow-symlinks -v ${FILE15} ${FILE15})
# extlink vs dset"
ADD_H5_TEST (h5diff_405 1 --follow-symlinks -v ${FILE15} ${FILE16} /ext_link_dset1 /target_group2/x_dset)
# dset vs extlink"
ADD_H5_TEST (h5diff_406 1 --follow-symlinks -v ${FILE16} ${FILE15} /target_group2/x_dset /ext_link_dset1)
# extlink vs extlink"
ADD_H5_TEST (h5diff_407 1 --follow-symlinks -v ${FILE15} ${FILE15} /ext_link_dset1 /ext_link_dset2)
# softlink vs extlink"
ADD_H5_TEST (h5diff_408 1 --follow-symlinks -v ${FILE13} ${FILE15} /softlink_dset1_1 /ext_link_dset2)
# extlink vs softlink "
ADD_H5_TEST (h5diff_409 1 --follow-symlinks -v ${FILE15} ${FILE13} /ext_link_dset2 /softlink_dset1_1)
# linked_softlink vs linked_softlink (FILE)"
ADD_H5_TEST (h5diff_410 0 --follow-symlinks -v ${FILE14} ${FILE14})
# dset2 vs linked_softlink_dset1"
ADD_H5_TEST (h5diff_411 1 --follow-symlinks -v ${FILE14} ${FILE14} /target_dset2 /softlink1_to_slink2)
# linked_softlink_dset1 vs dset2"
ADD_H5_TEST (h5diff_412 1 --follow-symlinks -v ${FILE14} ${FILE14} /softlink1_to_slink2 /target_dset2)
# linked_softlink_to_dset1 vs linked_softlink_to_dset2"
ADD_H5_TEST (h5diff_413 1 --follow-symlinks -v ${FILE14} ${FILE14} /softlink1_to_slink2 /softlink2_to_slink2)
# group vs linked_softlink_group1"
ADD_H5_TEST (h5diff_414 1 --follow-symlinks -v ${FILE14} ${FILE14} /target_group /softlink3_to_slink2)
# linked_softlink_group1 vs group"
ADD_H5_TEST (h5diff_415 1 --follow-symlinks -v ${FILE14} ${FILE14} /softlink3_to_slink2 /target_group)
# linked_softlink_to_group1 vs linked_softlink_to_group2"
ADD_H5_TEST (h5diff_416 0 --follow-symlinks -v ${FILE14} ${FILE14} /softlink3_to_slink2 /softlink4_to_slink2)
# non-exist-softlink vs softlink"
ADD_H5_TEST (h5diff_417 1 --follow-symlinks -v ${FILE13} ${FILE13} /softlink_noexist /softlink_dset2)
# softlink vs non-exist-softlink"
ADD_H5_TEST (h5diff_418 1 --follow-symlinks -v ${FILE13} ${FILE13} /softlink_dset2 /softlink_noexist)
# non-exist-extlink_file vs extlink"
ADD_H5_TEST (h5diff_419 1 --follow-symlinks -v ${FILE15} ${FILE15} /ext_link_noexist2 /ext_link_dset2)
# exlink vs non-exist-extlink_file"
ADD_H5_TEST (h5diff_420 1 --follow-symlinks -v ${FILE15} ${FILE15} /ext_link_dset2 /ext_link_noexist2)
# extlink vs non-exist-extlink_obj"
ADD_H5_TEST (h5diff_421 1 --follow-symlinks -v ${FILE15} ${FILE15} /ext_link_dset2 /ext_link_noexist1)
# non-exist-extlink_obj vs extlink"
ADD_H5_TEST (h5diff_422 1 --follow-symlinks -v ${FILE15} ${FILE15} /ext_link_noexist1 /ext_link_dset2)
# extlink_to_softlink_to_dset1 vs dset2"
ADD_H5_TEST (h5diff_423 1 --follow-symlinks -v ${FILE17} ${FILE18} /ext_link_to_slink1 /dset2)
# dset2 vs extlink_to_softlink_to_dset1"
ADD_H5_TEST (h5diff_424 1 --follow-symlinks -v ${FILE18} ${FILE17} /dset2 /ext_link_to_slink1)
# extlink_to_softlink_to_dset1 vs extlink_to_softlink_to_dset2"
ADD_H5_TEST (h5diff_425 1 --follow-symlinks -v ${FILE17} ${FILE17} /ext_link_to_slink1 /ext_link_to_slink2)
# ##############################################################################
# # Dangling links compare (--follow-symlinks and --no-dangling-links)
# ##############################################################################
# dangling links --follow-symlinks (FILE to FILE)
ADD_H5_TEST (h5diff_450 1 --follow-symlinks -v ${DANGLE_LINK_FILE1} ${DANGLE_LINK_FILE2})
# dangling links --follow-symlinks and --no-dangling-links (FILE to FILE)
ADD_H5_TEST (h5diff_451 2 --follow-symlinks -v --no-dangling-links ${DANGLE_LINK_FILE1} ${DANGLE_LINK_FILE2})
# try --no-dangling-links without --follow-symlinks options
ADD_H5_TEST (h5diff_452 2 --no-dangling-links ${FILE13} ${FILE13})
# dangling link found for soft links (FILE to FILE)
ADD_H5_TEST (h5diff_453 2 --follow-symlinks -v --no-dangling-links ${FILE13} ${FILE13})
# dangling link found for soft links (obj to obj)
ADD_H5_TEST (h5diff_454 2 --follow-symlinks -v --no-dangling-links ${FILE13} ${FILE13} /softlink_dset2 /softlink_noexist)
# dangling link found for soft links (obj to obj) Both dangle links
ADD_H5_TEST (h5diff_455 2 --follow-symlinks -v --no-dangling-links ${FILE13} ${FILE13} /softlink_noexist /softlink_noexist)
# dangling link found for ext links (FILE to FILE)
ADD_H5_TEST (h5diff_456 2 --follow-symlinks -v --no-dangling-links ${FILE15} ${FILE15})
# dangling link found for ext links (obj to obj). target file exist
ADD_H5_TEST (h5diff_457 2 --follow-symlinks -v --no-dangling-links ${FILE15} ${FILE15} /ext_link_dset1 /ext_link_noexist1)
# dangling link found for ext links (obj to obj). target file NOT exist
ADD_H5_TEST (h5diff_458 2 --follow-symlinks -v --no-dangling-links ${FILE15} ${FILE15} /ext_link_dset1 /ext_link_noexist2)
# dangling link found for ext links (obj to obj). Both dangle links
ADD_H5_TEST (h5diff_459 2 --follow-symlinks -v --no-dangling-links ${FILE15} ${FILE15} /ext_link_noexist1 /ext_link_noexist2)
# dangling link --follow-symlinks (obj vs obj)
# (HDFFV-7836)
ADD_H5_TEST (h5diff_465 0 --follow-symlinks h5diff_danglelinks1.h5 h5diff_danglelinks2.h5 /soft_link1)
# (HDFFV-7835)
# soft dangling vs. soft dangling
ADD_H5_TEST (h5diff_466 0 -v --follow-symlinks h5diff_danglelinks1.h5 h5diff_danglelinks2.h5 /soft_link1)
# soft link vs. soft dangling
ADD_H5_TEST (h5diff_467 1 -v --follow-symlinks h5diff_danglelinks1.h5 h5diff_danglelinks2.h5 /soft_link2)
# ext dangling vs. ext dangling
ADD_H5_TEST (h5diff_468 0 -v --follow-symlinks h5diff_danglelinks1.h5 h5diff_danglelinks2.h5 /ext_link4)
# ext link vs. ext dangling
ADD_H5_TEST (h5diff_469 1 -v --follow-symlinks h5diff_danglelinks1.h5 h5diff_danglelinks2.h5 /ext_link2)
#---------------------------------------------------
# dangling links without follow symlink
# (HDFFV-7998)
# test - soft dangle links (same and different paths),
# - external dangle links (same and different paths)
ADD_H5_TEST (h5diff_471 1 -v h5diff_danglelinks1.h5 h5diff_danglelinks2.h5)
ADD_H5_TEST (h5diff_472 0 -v h5diff_danglelinks1.h5 h5diff_danglelinks2.h5 /soft_link1)
ADD_H5_TEST (h5diff_473 1 -v h5diff_danglelinks1.h5 h5diff_danglelinks2.h5 /soft_link4)
ADD_H5_TEST (h5diff_474 0 -v h5diff_danglelinks1.h5 h5diff_danglelinks2.h5 /ext_link4)
ADD_H5_TEST (h5diff_475 1 -v h5diff_danglelinks1.h5 h5diff_danglelinks2.h5 /ext_link1)
# ##############################################################################
# # test for group diff recursivly
# ##############################################################################
# root
ADD_H5_TEST (h5diff_500 1 -v ${GRP_RECURSE_FILE1} ${GRP_RECURSE_FILE2} / /)
ADD_H5_TEST (h5diff_501 1 -v --follow-symlinks ${GRP_RECURSE_FILE1} ${GRP_RECURSE_FILE2} / /)
# root vs group
ADD_H5_TEST (h5diff_502 1 -v ${GRP_RECURSE_FILE1} ${GRP_RECURSE_FILE2} / /grp1/grp2/grp3)
# group vs group (same name and structure)
ADD_H5_TEST (h5diff_503 0 -v ${GRP_RECURSE_FILE1} ${GRP_RECURSE_FILE2} /grp1 /grp1)
# group vs group (different name and structure)
ADD_H5_TEST (h5diff_504 1 -v ${GRP_RECURSE_FILE1} ${GRP_RECURSE_FILE2} /grp1/grp2 /grp1/grp2/grp3)
# groups vs soft-link
ADD_H5_TEST (h5diff_505 0 -v ${GRP_RECURSE_FILE1} ${GRP_RECURSE_FILE2} /grp1 /slink_grp1)
ADD_H5_TEST (h5diff_506 0 -v --follow-symlinks ${GRP_RECURSE_FILE1} ${GRP_RECURSE_FILE2} /grp1/grp2 /slink_grp2)
# groups vs ext-link
ADD_H5_TEST (h5diff_507 0 -v ${GRP_RECURSE_FILE1} ${GRP_RECURSE_FILE2} /grp1 /elink_grp1)
ADD_H5_TEST (h5diff_508 0 -v --follow-symlinks ${GRP_RECURSE_FILE1} ${GRP_RECURSE_FILE2} /grp1 /elink_grp1)
# soft-link vs ext-link
ADD_H5_TEST (h5diff_509 0 -v ${GRP_RECURSE_FILE1} ${GRP_RECURSE_FILE2} /slink_grp1 /elink_grp1)
ADD_H5_TEST (h5diff_510 0 -v --follow-symlinks ${GRP_RECURSE_FILE1} ${GRP_RECURSE_FILE2} /slink_grp1 /elink_grp1)
# circled ext links
ADD_H5_TEST (h5diff_511 1 -v ${GRP_RECURSE_FILE1} ${GRP_RECURSE_FILE2} /grp10 /grp11)
ADD_H5_TEST (h5diff_512 1 -v --follow-symlinks ${GRP_RECURSE_FILE1} ${GRP_RECURSE_FILE2} /grp10 /grp11)
# circled soft2ext-link vs soft2ext-link
ADD_H5_TEST (h5diff_513 1 -v ${GRP_RECURSE_FILE1} ${GRP_RECURSE_FILE2} /slink_grp10 /slink_grp11)
ADD_H5_TEST (h5diff_514 1 -v --follow-symlinks ${GRP_RECURSE_FILE1} ${GRP_RECURSE_FILE2} /slink_grp10 /slink_grp11)
###############################################################################
# Test for group recursive diff via multi-linked external links
# With follow-symlinks, file $GRP_RECURSE1_EXT and $GRP_RECURSE2_EXT1 should
# be same with the external links.
###############################################################################
# file vs file
ADD_H5_TEST (h5diff_515 1 -v ${GRP_RECURSE1_EXT} ${GRP_RECURSE2_EXT1})
ADD_H5_TEST (h5diff_516 0 -v --follow-symlinks ${GRP_RECURSE1_EXT} ${GRP_RECURSE2_EXT1})
# group vs group
ADD_H5_TEST (h5diff_517 1 -v ${GRP_RECURSE1_EXT} ${GRP_RECURSE2_EXT1} /g1)
ADD_H5_TEST (h5diff_518 0 -v --follow-symlinks ${GRP_RECURSE1_EXT} ${GRP_RECURSE2_EXT1} /g1)
# ##############################################################################
# # Exclude path (--exclude-path)
# ##############################################################################
#
# Same structure, same names and different value.
#
# Exclude the object with different value. Expect return - same
ADD_H5_TEST (h5diff_480 0 -v --exclude-path /group1/dset3 ${EXCLUDE_FILE1_1} ${EXCLUDE_FILE1_2})
# Verify different by not excluding. Expect return - diff
ADD_H5_TEST (h5diff_481 1 -v ${EXCLUDE_FILE1_1} ${EXCLUDE_FILE1_2})
#
# Different structure, different names.
#
# Exclude all the different objects. Expect return - same
ADD_H5_TEST (h5diff_482 0 -v --exclude-path "/group1" --exclude-path "/dset1" ${EXCLUDE_FILE2_1} ${EXCLUDE_FILE2_2})
# Exclude only some different objects. Expect return - diff
ADD_H5_TEST (h5diff_483 1 -v --exclude-path "/group1" ${EXCLUDE_FILE2_1} ${EXCLUDE_FILE2_2})
# Exclude from group compare
ADD_H5_TEST (h5diff_484 0 -v --exclude-path "/dset3" ${EXCLUDE_FILE1_1} ${EXCLUDE_FILE1_2} /group1)
#
# Only one file contains unique objs. Common objs are same.
# (HDFFV-7837)
#
ADD_H5_TEST (h5diff_485 0 -v --exclude-path "/group1" h5diff_exclude3-1.h5 h5diff_exclude3-2.h5)
ADD_H5_TEST (h5diff_486 0 -v --exclude-path "/group1" h5diff_exclude3-2.h5 h5diff_exclude3-1.h5)
ADD_H5_TEST (h5diff_487 1 -v --exclude-path "/group1/dset" h5diff_exclude3-1.h5 h5diff_exclude3-2.h5)
# ##############################################################################
# # diff various multiple vlen and fixed strings in a compound type dataset
# ##############################################################################
ADD_H5_TEST (h5diff_530 0 -v ${COMP_VL_STRS_FILE} ${COMP_VL_STRS_FILE} /group /group_copy)
# ##############################################################################
# # Test container types (array,vlen) with multiple nested compound types
# # Complex compound types in dataset and attribute
# ##############################################################################
ADD_H5_TEST (h5diff_540 1 -v ${COMPS_ARRAY_VLEN_FILE1} ${COMPS_ARRAY_VLEN_FILE2})
# ##############################################################################
# # Test mutually exclusive options
# ##############################################################################
#
# Test with -d , -p and --use-system-epsilon.
ADD_H5_TEST (h5diff_640 1 -v -d 5 -p 0.05 --use-system-epsilon ${FILE1} ${FILE2} /g1/dset3 /g1/dset4)
ADD_H5_TEST (h5diff_641 1 -v -d 5 -p 0.05 ${FILE1} ${FILE2} /g1/dset3 /g1/dset4)
ADD_H5_TEST (h5diff_642 1 -v -p 0.05 -d 5 ${FILE1} ${FILE2} /g1/dset3 /g1/dset4)
ADD_H5_TEST (h5diff_643 1 -v -d 5 --use-system-epsilon ${FILE1} ${FILE2} /g1/dset3 /g1/dset4)
ADD_H5_TEST (h5diff_644 1 -v --use-system-epsilon -d 5 ${FILE1} ${FILE2} /g1/dset3 /g1/dset4)
ADD_H5_TEST (h5diff_645 1 -v -p 0.05 --use-system-epsilon ${FILE1} ${FILE2} /g1/dset3 /g1/dset4)
ADD_H5_TEST (h5diff_646 1 -v --use-system-epsilon -p 0.05 ${FILE1} ${FILE2} /g1/dset3 /g1/dset4)
| opencb/hpg-pore | src/main/third-party/hdf5-1.8.14/tools/h5diff/CMakeTests.cmake | CMake | apache-2.0 | 58,625 |
package com.belling.admin.service;
import java.util.List;
import com.belling.admin.model.RolePermission;
import com.belling.base.service.BaseService;
/**
* 角色权限映射服务接口
*
* @author Sunny
*/
public interface RolePermissionService extends BaseService<RolePermission, Integer> {
/**
* 根据角色ID查询映射
* @param roleId 角色ID
* @return
*/
public List<RolePermission> findByRoleId(Integer roleId);
/**
* 根据角色ID给角色授权
* @param roleId 角色ID
* @param list 角色权限映射集合
* @return
*/
public void allocate(Integer roleId, List<RolePermission> list);
/**
* 根据权限ID集合删除映射
* @param idList 权限ID集合
* @return
*/
public void deleteByPermissionIds(List<Integer> idList);
/**
* 根据角色ID集合删除映射
* @param idList 角色ID集合
* @return
*/
public void deleteByRoleIds(List<Integer> idList);
}
| butter-fly/belling-admin | src/main/java/com/belling/admin/service/RolePermissionService.java | Java | apache-2.0 | 935 |
<?php
/**
* This file is part of PHP Mess Detector.
*
* Copyright (c) 2008-2017, Manuel Pichler <mapi@phpmd.org>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Manuel Pichler nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @author Manuel Pichler <mapi@phpmd.org>
* @copyright 2008-2017 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
*/
namespace PHPMD\Node;
use PHPMD\Rule;
/**
* Collection of code annotations.
*
* @author Manuel Pichler <mapi@phpmd.org>
* @copyright 2008-2017 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
*/
class Annotations
{
/**
* Detected annotations.
*
* @var \PHPMD\Node\Annotation[]
*/
private $annotations = array();
/**
* Regexp used to extract code annotations.
*
* @var string
*/
private $regexp = '(@([a-z_][a-z0-9_]+)\(([^\)]+)\))i';
/**
* Constructs a new collection instance.
*
* @param \PHPMD\AbstractNode $node
*/
public function __construct(\PHPMD\AbstractNode $node)
{
preg_match_all($this->regexp, $node->getDocComment(), $matches);
foreach (array_keys($matches[0]) as $i) {
$name = $matches[1][$i];
$value = trim($matches[2][$i], '" ');
$this->annotations[] = new Annotation($name, $value);
}
}
/**
* Checks if one of the annotations suppresses the given rule.
*
* @param \PHPMD\Rule $rule
* @return boolean
*/
public function suppresses(Rule $rule)
{
foreach ($this->annotations as $annotation) {
if ($annotation->suppresses($rule)) {
return true;
}
}
return false;
}
}
| MasaharuKomuro/kitakupics | vendor/phpmd/phpmd/src/main/php/PHPMD/Node/Annotations.php | PHP | apache-2.0 | 3,274 |
import { Component } from '@angular/core';
import { TooltipModule } from 'ngx-bootstrap';
import { Contexts } from 'ngx-fabric8-wit';
import { AuthenticationService, UserService } from 'ngx-login-client';
import { empty, of, throwError } from 'rxjs';
import { initContext } from 'testing/test-context';
import { ProviderService } from '../../../shared/account/provider.service';
import { TenantService } from '../../services/tenant.service';
import { ConnectedAccountsComponent } from './connected-accounts.component';
@Component({
template: `
<alm-connected-accounts></alm-connected-accounts>
`,
})
class SampleTestComponent {}
describe('Connected Accounts Component', () => {
const expectedOsoUser: string = 'oso-test-user';
const ctx: any = {
user: {
attributes: {
username: expectedOsoUser,
},
},
};
const mockTenantData: any = {
attributes: {
namespaces: [
{
'cluster-console-url': 'http://example.cluster-name.something.com',
},
],
},
};
const contextsMock: any = jasmine.createSpy('Contexts');
const authMock: any = jasmine.createSpyObj('AuthenticationService', ['isOpenShiftConnected']);
const providersMock: any = jasmine.createSpyObj('ProviderService', [
'getGitHubStatus',
'getOpenShiftStatus',
]);
const userServiceMock: any = jasmine.createSpy('UserService');
const tenantSeriveMock: any = jasmine.createSpyObj('TenantService', ['getTenant']);
describe('User has only OpenShift account connected', (): void => {
beforeAll(
(): void => {
authMock.gitHubToken = empty();
// authMock.openShiftToken = of('oso-token');
authMock.isOpenShiftConnected.and.returnValue(of(true));
contextsMock.current = of(ctx);
userServiceMock.loggedInUser = empty();
userServiceMock.currentLoggedInUser = ctx.user;
providersMock.getGitHubStatus.and.returnValue(throwError('failure'));
providersMock.getOpenShiftStatus.and.returnValue(of({ username: expectedOsoUser }));
tenantSeriveMock.getTenant.and.returnValue(of(mockTenantData));
},
);
const testContext = initContext(ConnectedAccountsComponent, SampleTestComponent, {
imports: [TooltipModule.forRoot()],
providers: [
{ provide: AuthenticationService, useValue: authMock },
{ provide: Contexts, useValue: contextsMock },
{ provide: UserService, useValue: userServiceMock },
{ provide: ProviderService, useValue: providersMock },
{ provide: TenantService, useValue: tenantSeriveMock },
],
});
it('should have absence of GitHub connection indicated', (): void => {
const actualText: string = testContext.testedElement.textContent;
expect(actualText).toMatch(new RegExp('GitHub\\s+Disconnected'));
});
it('should have OpenShift connection indicated', (): void => {
const actualText: string = testContext.testedElement.textContent;
expect(actualText).toMatch(new RegExp(expectedOsoUser));
});
it('should set cluster name and cluster url by calling tenant service', (): void => {
expect(testContext.testedDirective.consoleUrl).toBe(
'http://example.cluster-name.something.com',
);
expect(testContext.testedDirective.clusterName).toBe('cluster-name');
});
});
describe('User has both Github and OpenShift accounts connected', (): void => {
beforeAll(
(): void => {
authMock.gitHubToken = of('gh-test-user');
// authMock.openShiftToken = of('oso-token');
authMock.isOpenShiftConnected.and.returnValue(of(true));
contextsMock.current = of(ctx);
userServiceMock.loggedInUser = empty();
userServiceMock.currentLoggedInUser = ctx.user;
providersMock.getGitHubStatus.and.returnValue(of({ username: 'username' }));
providersMock.getOpenShiftStatus.and.returnValue(of({ username: expectedOsoUser }));
},
);
const testContext = initContext(ConnectedAccountsComponent, SampleTestComponent, {
imports: [TooltipModule.forRoot()],
providers: [
{ provide: AuthenticationService, useValue: authMock },
{ provide: Contexts, useValue: contextsMock },
{ provide: UserService, useValue: userServiceMock },
{ provide: ProviderService, useValue: providersMock },
{ provide: TenantService, useValue: tenantSeriveMock },
],
});
it('should have GitHub connection indicated', (): void => {
const actualText: string = testContext.testedElement.textContent;
expect(actualText).toContain('username');
});
it('should have OpenShift connection indicated', (): void => {
const actualText: string = testContext.testedElement.textContent;
expect(actualText).toMatch(new RegExp(expectedOsoUser));
});
});
});
| fabric8-ui/fabric8-ui | packages/fabric8-ui/src/app/profile/settings/connected-accounts/connected-accounts.spec.ts | TypeScript | apache-2.0 | 4,868 |

Example Go (golang) web app with dependency injection and graceful shutdown. Acts like a mini Twitter clone.
## Dependencies
Building requires [Go](https://golang.org/doc/install), [Godep](https://github.com/tools/godep), [Docker](https://docs.docker.com/installation/), & Make.
Code dependencies are vendored with Godep:
- [Facebook's Grace library](http://github.com/facebookgo/grace) - graceful shutdown
- [Inject](http://github.com/karlkfi/inject) - dependency injection
- [Humanize](http://github.com/dustin/go-humanize) - readable units
- [Logrus](http://github.com/Sirupsen/logrus) - structured, leveled logging
## Compilation
Build a local binary:
```
make
```
Build a docker image:
```
# make the build image first
make build-image
make image
```
## Operation
There are several ways to launch the Tweeter server.
### Source
Run from local source code:
```
go run main.go
```
(ctrl-c to quit)
### Docker
Run in Docker:
```
docker run -d --name tweeter -p 0.0.0.0:8080:8080 mesosphere/tweeter-go:latest
```
With Cassandra:
```
docker run -d --name cassandra cassandra:2.2.3
docker run -d --name tweeter --link cassandra:cassandra -p 0.0.0.0:8080:8080 mesosphere/tweeter-go:latest --cassandra-addr=cassandra
```
Find Tweeter IP:
```
docker inspect --format "{{.NetworkSettings.IPAddress}}" tweeter
```
### Marathon
Run in [Marathon](https://mesosphere.github.io/marathon/):
```
curl -H 'Content-Type: application/json' -X POST -d @"marathon.json" ${MARATHON_URL}/v2/apps
```
### Kubernetes
Run in [Kubernetes](http://kubernetes.io/):
```
kubectl create -f kubernetes.yaml
```
By default, `kubernetes.yaml` assumes you have 3 public slave nodes and want 1 Tweeter instance on each. With this configuration, Tweeter can be reached on the default HTTP port (80) through the public slave DNS URL. On AWS, the DNS should automatically handle round-robin for requests to Tweeter. Load Balancing could also be configured, using AWS Elastic Load Balancing.
## Usage
Visit the home page at http://localhost:8080/
Enter handle & message & hit Tweet.
See past tweets on the right-hand side of the home page.
## License
Copyright 2015-2017 Mesosphere, Inc.
Licensed under the [Apache License Version 2.0](LICENSE) (the "License");
you may not use this project except in compliance with the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| mesosphere/oinker-go | README.md | Markdown | apache-2.0 | 2,783 |
/*
* Copyright (C) 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 com.google.android.exoplayer2.analytics;
import android.net.NetworkInfo;
import android.view.Surface;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.decoder.DecoderCounters;
import com.google.android.exoplayer2.metadata.Metadata;
import com.google.android.exoplayer2.source.MediaSourceEventListener.LoadEventInfo;
import com.google.android.exoplayer2.source.MediaSourceEventListener.MediaLoadData;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import java.io.IOException;
/**
* {@link AnalyticsListener} allowing selective overrides. All methods are implemented as no-ops.
*/
public abstract class DefaultAnalyticsListener implements AnalyticsListener {
@Override
public void onPlayerStateChanged(EventTime eventTime, boolean playWhenReady, int playbackState) {}
@Override
public void onTimelineChanged(EventTime eventTime, int reason) {}
@Override
public void onPositionDiscontinuity(EventTime eventTime, int reason) {}
@Override
public void onSeekStarted(EventTime eventTime) {}
@Override
public void onSeekProcessed(EventTime eventTime) {}
@Override
public void onPlaybackParametersChanged(
EventTime eventTime, PlaybackParameters playbackParameters) {}
@Override
public void onRepeatModeChanged(EventTime eventTime, int repeatMode) {}
@Override
public void onShuffleModeChanged(EventTime eventTime, boolean shuffleModeEnabled) {}
@Override
public void onLoadingChanged(EventTime eventTime, boolean isLoading) {}
@Override
public void onPlayerError(EventTime eventTime, ExoPlaybackException error) {}
@Override
public void onTracksChanged(
EventTime eventTime, TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {}
@Override
public void onLoadStarted(
EventTime eventTime, LoadEventInfo loadEventInfo, MediaLoadData mediaLoadData) {}
@Override
public void onLoadCompleted(
EventTime eventTime, LoadEventInfo loadEventInfo, MediaLoadData mediaLoadData) {}
@Override
public void onLoadCanceled(
EventTime eventTime, LoadEventInfo loadEventInfo, MediaLoadData mediaLoadData) {}
@Override
public void onLoadError(
EventTime eventTime,
LoadEventInfo loadEventInfo,
MediaLoadData mediaLoadData,
IOException error,
boolean wasCanceled) {}
@Override
public void onDownstreamFormatChanged(EventTime eventTime, MediaLoadData mediaLoadData) {}
@Override
public void onUpstreamDiscarded(EventTime eventTime, MediaLoadData mediaLoadData) {}
@Override
public void onMediaPeriodCreated(EventTime eventTime) {}
@Override
public void onMediaPeriodReleased(EventTime eventTime) {}
@Override
public void onReadingStarted(EventTime eventTime) {}
@Override
public void onBandwidthEstimate(
EventTime eventTime, int totalLoadTimeMs, long totalBytesLoaded, long bitrateEstimate) {}
@Override
public void onViewportSizeChange(EventTime eventTime, int width, int height) {}
@Override
public void onNetworkTypeChanged(EventTime eventTime, NetworkInfo networkInfo) {}
@Override
public void onMetadata(EventTime eventTime, Metadata metadata) {}
@Override
public void onDecoderEnabled(
EventTime eventTime, int trackType, DecoderCounters decoderCounters) {}
@Override
public void onDecoderInitialized(
EventTime eventTime, int trackType, String decoderName, long initializationDurationMs) {}
@Override
public void onDecoderInputFormatChanged(EventTime eventTime, int trackType, Format format) {}
@Override
public void onDecoderDisabled(
EventTime eventTime, int trackType, DecoderCounters decoderCounters) {}
@Override
public void onAudioSessionId(EventTime eventTime, int audioSessionId) {}
@Override
public void onAudioUnderrun(
EventTime eventTime, int bufferSize, long bufferSizeMs, long elapsedSinceLastFeedMs) {}
@Override
public void onDroppedVideoFrames(EventTime eventTime, int droppedFrames, long elapsedMs) {}
@Override
public void onVideoSizeChanged(
EventTime eventTime,
int width,
int height,
int unappliedRotationDegrees,
float pixelWidthHeightRatio) {}
@Override
public void onRenderedFirstFrame(EventTime eventTime, Surface surface) {}
@Override
public void onDrmKeysLoaded(EventTime eventTime) {}
@Override
public void onDrmSessionManagerError(EventTime eventTime, Exception error) {}
@Override
public void onDrmKeysRestored(EventTime eventTime) {}
@Override
public void onDrmKeysRemoved(EventTime eventTime) {}
}
| MaTriXy/ExoPlayer | library/core/src/main/java/com/google/android/exoplayer2/analytics/DefaultAnalyticsListener.java | Java | apache-2.0 | 5,397 |
<div class="padding-15">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<pfng-action class="my-actions"
[config]="actionConfig"
[template]="menuTemplate"
(onActionSelect)="handleAction($event)">
<ng-template #menuTemplate>
<span class="dropdown primary-action" dropdown>
<button class="btn btn-default dropdown-toggle" type="button" dropdownToggle>
Menu Action<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" *dropdownMenu>
<li role="menuitem">
<a class="dropdown-item secondary-action" (click)="optionSelected(1)">Option 1</a>
</li>
<li role="menuitem">
<a class="dropdown-item secondary-action" role="menuitem" (click)="optionSelected(2)">Option 2</a>
</li>
<li role="menuitem">
<a class="dropdown-item secondary-action" role="menuitem" (click)="optionSelected(3)">Option 3</a>
</li>
<li role="menuitem">
<a class="dropdown-item secondary-action" role="menuitem" (click)="optionSelected(4)">Option 4</a>
</li>
</ul>
</span>
</ng-template>
</pfng-action>
</div>
</div>
</div>
<div class="row padding-top-10">
<div class="col-sm-12">
<h4 class="actions-label">Actions</h4>
<hr/>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<textarea rows="3" class="col-sm-12">{{actionsText}}</textarea>
</div>
</div>
<div class="row padding-top-10">
<div class="col-sm-12">
<h4>Code</h4>
<hr/>
</div>
</div>
<div>
<tabset>
<tab heading="api">
<iframe class="demoframe" src="docs/classes/actioncomponent.html"></iframe>
</tab>
<tab heading="html">
<include-content src="src/app/action/example/action-basic-example.component.html"></include-content>
</tab>
<tab heading="typescript">
<include-content src="src/app/action/example/action-basic-example.component.ts"></include-content>
</tab>
</tabset>
</div>
</div>
| dlabrecq/patternfly-ng | src/app/action/example/action-basic-example.component.html | HTML | apache-2.0 | 2,312 |
Install coap-cli. Assuming you have Node.js and NPM installed on your Windows/Linux/MacOS machine, execute the following command:
```bash
npm install coap-cli -g
```
{: .copy-code}
Replace $THINGSBOARD_HOST_NAME and $ACCESS_TOKEN with corresponding values.
```bash
echo -n '{"temperature": 25}' | coap post coap://$THINGSBOARD_HOST_NAME/api/v1/$ACCESS_TOKEN/telemetry
```
{: .copy-code}
For example, $THINGSBOARD_HOST_NAME reference live demo server, $ACCESS_TOKEN is ABC123:
```bash
echo -n '{"temperature": 25}' | coap post coap://demo.thingsboard.io/api/v1/ABC123/telemetry
```
{: .copy-code}
For example, $THINGSBOARD_HOST_NAME reference your local installation, $ACCESS_TOKEN is ABC123:
```bash
echo -n '{"temperature": 25}' | coap post coap://localhost/api/v1/ABC123/telemetry
```
{: .copy-code}
<br/>
<br/>
| volodymyr-babak/thingsboard.github.io | _includes/templates/helloworld/coap.md | Markdown | apache-2.0 | 823 |
@extends('master')
@section('header')
@stop
@section('content')
{{ Notification::showAll() }}
<div class='col-md-2 text-center slidbar_bg'>
<h3 class="acolor">
专业搜索
</h3>
<p class='t1'>九子高考志愿匹配网为您提供全面的专业数据库搜索功能,以便于您可以根据搜索结果,查询所需要的专业信息。</p>
</div>
<div class='col-md-7 bottom top'>
<div class="input-group">
<span class="input-group-btn">
{{ Form::open(array('route' => array('PostSpecialtiysearch','method' => 'post'))) }}
<div class="col-xs-2">
<button type="submit" class="btn btn-default" type="button">专业搜索</button>
</div>
</span>
<div class="col-xs-9">
{{Form::text('specialty', null, array('class'=>'fc_search form-control','placeholder'=>'专业搜索'))}}
</div>
</div><!-- /input-group -->
{{ Form::close() }}
<div class='row top bottom marginlr'>
<p>
<div class="btn-group">
<button class="btn btn-large btn-primary" type="button">本科专业列表</button>
<button class="btn btn-large" type="button">专科专业列表</button>
</div>
</p>
<div class="scrollingBox">
<ul class="list-inline button" id="zy1">
<li><a href="#a1" class="button">哲学</a></li>
<li><a href="#a2" class="button">经济学</a></li>
<li><a href="#a3" class="button">法学</a></li>
<li><a href="#a4" class="button">教育学</a></li>
<li><a href="#a5" class="button">文学</a></li>
<li><a href="#a6" class="button">历史学</a></li>
<li><a href="#a7" class="button" >理学</a></li>
<li><a href="#a8" class="button">工学</a></li>
<li><a href="#a9" class="button">农学</a></li>
<li><a href="#a10" class="button">医学</a></li>
<li><a href="#a11" class="button">管理学</a></li>
<li class="last"><a href="#a12" class="button">艺术学</a></li>
</ul>
<ul class="list-inline notshow anchors" id="zy2">
<li><a href="#ab6" class="button" >土建</a></li>
<li><a href="#ab7" class="button" >水利</a></li>
<li><a href="#ab8" class="button">制造</a></li>
<li><a href="#ab12" class="button">财经</a></li>
<li><a href="#ab14" class="button">旅游</a></li>
<li><a href="#ab18" class="button">公安</a></li>
<li><a href="#ab19" class="button">法律</a></li>
<li><a href="#ab1" class="button">农林牧渔</a></li>
<li><a href="#ab2" class="button">交通运输</a></li>
<li><a href="#ab9" class="button">电子信息</a></li>
<li> <a href="#ab11" class="button">轻纺食品</a></li>
<li><a href="#ab13" class="button">医药卫生</a></li>
<li><a href="#ab15" class="button">公共事业</a></li>
<li><a href="#ab16" class="button">文化教育</a></li>
<li><a href="#ab3" class="button">生化与药品</a></li>
<li><a href="#ab5" class="button">材料与能源</a></li>
<li><a href="#ab4" class="button">资源开发与测绘</a></li>
<li><a href="#ab10" class="button">环保、气象与安全</a></li>
<li><a href="#ab17" class="button">艺术设计传媒</a></li>
</ul>
</div>
</div>
@include('specialties.search.bklist')
@include('specialties.search.zklist')
</div>
<div class='col-md-3'>
<div class='row top bottom'>
@include('ads')
</div>
</div>
@stop
@section('bootor')
@include('script')
@stop | wtdragon/gxzypp | app/views/specialties/search/index.blade.php | PHP | apache-2.0 | 3,351 |
"""Test the IPython.kernel public API
Authors
-------
* MinRK
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
import nose.tools as nt
from IPython.testing import decorators as dec
from IPython.kernel import launcher, connect
from IPython import kernel
#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
@dec.parametric
def test_kms():
for base in ("", "Multi"):
KM = base + "KernelManager"
yield nt.assert_true(KM in dir(kernel), KM)
@dec.parametric
def test_kcs():
for base in ("", "Blocking"):
KM = base + "KernelClient"
yield nt.assert_true(KM in dir(kernel), KM)
@dec.parametric
def test_launcher():
for name in launcher.__all__:
yield nt.assert_true(name in dir(kernel), name)
@dec.parametric
def test_connect():
for name in connect.__all__:
yield nt.assert_true(name in dir(kernel), name)
| noslenfa/tdjangorest | uw/lib/python2.7/site-packages/IPython/kernel/tests/test_public_api.py | Python | apache-2.0 | 1,308 |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>parse_example (Spec::Runner::Options)</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="../../../.././rdoc-style.css" type="text/css" media="screen" />
</head>
<body class="standalone-code">
<pre><span class="ruby-comment cmt"># File lib/spec/runner/options.rb, line 181</span>
<span class="ruby-keyword kw">def</span> <span class="ruby-identifier">parse_example</span>(<span class="ruby-identifier">example</span>)
<span class="ruby-keyword kw">if</span>(<span class="ruby-constant">File</span>.<span class="ruby-identifier">file?</span>(<span class="ruby-identifier">example</span>))
<span class="ruby-ivar">@examples</span> = [<span class="ruby-constant">File</span>.<span class="ruby-identifier">open</span>(<span class="ruby-identifier">example</span>).<span class="ruby-identifier">read</span>.<span class="ruby-identifier">split</span>(<span class="ruby-value str">"\n"</span>)].<span class="ruby-identifier">flatten</span>
<span class="ruby-keyword kw">else</span>
<span class="ruby-ivar">@examples</span> = [<span class="ruby-identifier">example</span>]
<span class="ruby-keyword kw">end</span>
<span class="ruby-keyword kw">end</span></pre>
</body>
</html> | turbine-rpowers/gocd-add-agent-sandbox-config | tools/jruby/lib/ruby/gems/1.8/doc/rspec-1.2.6/rdoc/classes/Spec/Runner/Options.src/M000444.html | HTML | apache-2.0 | 1,501 |
<!DOCTYPE html>
<html>
<head>
<script>
// TOC: This test isn't so meaningful any more, since we're not
// actually automatic addition of numbering. Perhaps add a TOC,
// to test that it's reflected?
function performTest(api)
{
api.tests.TestLib.setupOutlineNumbering();
api.Outline.init();
api.PostponedActions.perform();
api.tests.TestLib.setNumbering(true);
api.PostponedActions.perform();
api.Formatting.applyFormattingChanges("H1",{});
api.PostponedActions.perform();
}
</script>
</head>
<body>
<nav class="tableofcontents"></nav>
<h1>One</h1>
<h2>[One - first subsection]</h2>
<h2>One - second subsection</h2>
</body>
</html>
| corinthia/corinthia-editorlib | tests/outline/changeHeadingType-input.html | HTML | apache-2.0 | 669 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.psi.search;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.QueryExecutorBase;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.UsageSearchContext;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.util.Processor;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.PythonFileType;
import com.jetbrains.python.psi.PyClass;
import com.jetbrains.python.psi.PyFunction;
import org.jetbrains.annotations.NotNull;
/**
* @author yole
*/
public class PyInitReferenceSearchExecutor extends QueryExecutorBase<PsiReference, ReferencesSearch.SearchParameters> {
public void processQuery(@NotNull ReferencesSearch.SearchParameters queryParameters, @NotNull final Processor<? super PsiReference> consumer) {
PsiElement element = queryParameters.getElementToSearch();
if (!(element instanceof PyFunction)) {
return;
}
ApplicationManager.getApplication().runReadAction(() -> {
String className;
SearchScope searchScope;
PyFunction function;
function = (PyFunction)element;
if (!PyNames.INIT.equals(function.getName())) {
return;
}
final PyClass pyClass = function.getContainingClass();
if (pyClass == null) {
return;
}
className = pyClass.getName();
if (className == null) {
return;
}
searchScope = queryParameters.getEffectiveSearchScope();
if (searchScope instanceof GlobalSearchScope) {
searchScope = GlobalSearchScope.getScopeRestrictedByFileTypes((GlobalSearchScope)searchScope, PythonFileType.INSTANCE);
}
queryParameters.getOptimizer().searchWord(className, searchScope, UsageSearchContext.IN_CODE, true, function);
});
}
}
| jk1/intellij-community | python/src/com/jetbrains/python/psi/search/PyInitReferenceSearchExecutor.java | Java | apache-2.0 | 2,095 |
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.social.linkedin.api.impl.json;
import org.springframework.social.linkedin.api.UrlResource;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class UpdateContentMixin extends LinkedInObjectMixin {
@JsonCreator
UpdateContentMixin(
@JsonProperty("id") String id,
@JsonProperty("firstName") String firstName,
@JsonProperty("lastName") String lastName,
@JsonProperty("headline") String headline,
@JsonProperty("industry") String industry,
@JsonProperty("publicProfileUrl") String publicProfileUrl,
@JsonProperty("siteStandardProfileRequest") UrlResource siteStandardProfileRequest,
@JsonProperty("pictureUrl") String profilePictureUrl) {}
}
| pkdevbox/spring-social-linkedin | spring-social-linkedin/src/main/java/org/springframework/social/linkedin/api/impl/json/UpdateContentMixin.java | Java | apache-2.0 | 1,483 |
/**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.nodemanager.containermanager.resourceplugin.fpga;
import java.io.Serializable;
import org.apache.hadoop.thirdparty.com.google.common.base.Preconditions;
/** A class that represents an FPGA card. */
public class FpgaDevice implements Serializable {
private static final long serialVersionUID = -4678487141824092751L;
private final String type;
private final int major;
private final int minor;
// the alias device name. Intel use acl number acl0 to acl31
private final String aliasDevName;
// IP file identifier. matrix multiplication for instance (mutable)
private String IPID;
// SHA-256 hash of the uploaded aocx file (mutable)
private String aocxHash;
// cached hash value
private Integer hashCode;
public String getType() {
return type;
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public String getIPID() {
return IPID;
}
public String getAocxHash() {
return aocxHash;
}
public void setAocxHash(String hash) {
this.aocxHash = hash;
}
public void setIPID(String IPID) {
this.IPID = IPID;
}
public String getAliasDevName() {
return aliasDevName;
}
public FpgaDevice(String type, int major, int minor, String aliasDevName) {
this.type = Preconditions.checkNotNull(type, "type must not be null");
this.major = major;
this.minor = minor;
this.aliasDevName = Preconditions.checkNotNull(aliasDevName,
"aliasDevName must not be null");
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
FpgaDevice other = (FpgaDevice) obj;
if (aliasDevName == null) {
if (other.aliasDevName != null) {
return false;
}
} else if (!aliasDevName.equals(other.aliasDevName)) {
return false;
}
if (major != other.major) {
return false;
}
if (minor != other.minor) {
return false;
}
if (type == null) {
if (other.type != null) {
return false;
}
} else if (!type.equals(other.type)) {
return false;
}
return true;
}
@Override
public int hashCode() {
if (hashCode == null) {
final int prime = 31;
int result = 1;
result = prime * result + major;
result = prime * result + type.hashCode();
result = prime * result + minor;
result = prime * result + aliasDevName.hashCode();
hashCode = result;
}
return hashCode;
}
@Override
public String toString() {
return "FPGA Device:(Type: " + this.type + ", Major: " + this.major
+ ", Minor: " + this.minor + ", IPID: " + this.IPID + ", Hash: "
+ this.aocxHash + ")";
}
}
| apurtell/hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/resourceplugin/fpga/FpgaDevice.java | Java | apache-2.0 | 3,672 |
# $NetBSD: Makefile,v 1.12 2011/07/10 08:43:50 mrg Exp $
# from: @(#)Makefile 5.4 (Berkeley) 5/11/90
.include <bsd.own.mk>
# Build ELF to ecoff tools on mips, for old bootblocks/PROMs.
.if ${MACHINE_CPU} == "mips"
PROG= elf2ecoff
.endif
MAN= elf2ecoff.1
.include <bsd.prog.mk>
| execunix/vinos | usr.bin/elf2ecoff/Makefile | Makefile | apache-2.0 | 281 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="Javadoc API documentation for Fresco." />
<link rel="shortcut icon" type="image/x-icon" href="../../../../favicon.ico" />
<title>
NoOpDiskTrimmableRegistry - Fresco API
| Fresco
</title>
<link href="../../../../../assets/doclava-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../../../../../assets/customizations.css" rel="stylesheet" type="text/css" />
<script src="../../../../../assets/search_autocomplete.js" type="text/javascript"></script>
<script src="../../../../../assets/jquery-resizable.min.js" type="text/javascript"></script>
<script src="../../../../../assets/doclava-developer-docs.js" type="text/javascript"></script>
<script src="../../../../../assets/prettify.js" type="text/javascript"></script>
<script type="text/javascript">
setToRoot("../../../../", "../../../../../assets/");
</script>
<script src="../../../../../assets/doclava-developer-reference.js" type="text/javascript"></script>
<script src="../../../../../assets/navtree_data.js" type="text/javascript"></script>
<script src="../../../../../assets/customizations.js" type="text/javascript"></script>
<noscript>
<style type="text/css">
html,body{overflow:auto;}
#body-content{position:relative; top:0;}
#doc-content{overflow:visible;border-left:3px solid #666;}
#side-nav{padding:0;}
#side-nav .toggle-list ul {display:block;}
#resize-packages-nav{border-bottom:3px solid #666;}
</style>
</noscript>
</head>
<body class="">
<div id="header">
<div id="headerLeft">
<span id="masthead-title"><a href="../../../../packages.html">Fresco</a></span>
</div>
<div id="headerRight">
<div id="search" >
<div id="searchForm">
<form accept-charset="utf-8" class="gsc-search-box"
onsubmit="return submit_search()">
<table class="gsc-search-box" cellpadding="0" cellspacing="0"><tbody>
<tr>
<td class="gsc-input">
<input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off"
title="search developer docs" name="q"
value="search developer docs"
onFocus="search_focus_changed(this, true)"
onBlur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../')"
onkeyup="return search_changed(event, false, '../../../../')" />
<div id="search_filtered_div" class="no-display">
<table id="search_filtered" cellspacing=0>
</table>
</div>
</td>
<!-- <td class="gsc-search-button">
<input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" />
</td>
<td class="gsc-clear-button">
<div title="clear results" class="gsc-clear-button"> </div>
</td> -->
</tr></tbody>
</table>
</form>
</div><!-- searchForm -->
</div><!-- search -->
</div>
</div><!-- header -->
<div class="g-section g-tpl-240" id="body-content">
<div class="g-unit g-first side-nav-resizable" id="side-nav">
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav">
<div id="index-links">
<a href="../../../../packages.html" >Packages</a> |
<a href="../../../../classes.html" >Classes</a>
</div>
<ul>
<li class="api apilevel-">
<a href="../../../../com/facebook/animated/gif/package-summary.html">com.facebook.animated.gif</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/animated/webp/package-summary.html">com.facebook.animated.webp</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/binaryresource/package-summary.html">com.facebook.binaryresource</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/cache/common/package-summary.html">com.facebook.cache.common</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/cache/disk/package-summary.html">com.facebook.cache.disk</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/activitylistener/package-summary.html">com.facebook.common.activitylistener</a></li>
<li class="selected api apilevel-">
<a href="../../../../com/facebook/common/disk/package-summary.html">com.facebook.common.disk</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/executors/package-summary.html">com.facebook.common.executors</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/file/package-summary.html">com.facebook.common.file</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/internal/package-summary.html">com.facebook.common.internal</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/lifecycle/package-summary.html">com.facebook.common.lifecycle</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/logging/package-summary.html">com.facebook.common.logging</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/media/package-summary.html">com.facebook.common.media</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/memory/package-summary.html">com.facebook.common.memory</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/references/package-summary.html">com.facebook.common.references</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/soloader/package-summary.html">com.facebook.common.soloader</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/statfs/package-summary.html">com.facebook.common.statfs</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/streams/package-summary.html">com.facebook.common.streams</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/time/package-summary.html">com.facebook.common.time</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/util/package-summary.html">com.facebook.common.util</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/common/webp/package-summary.html">com.facebook.common.webp</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/datasource/package-summary.html">com.facebook.datasource</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawable/base/package-summary.html">com.facebook.drawable.base</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/backends/pipeline/package-summary.html">com.facebook.drawee.backends.pipeline</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/backends/volley/package-summary.html">com.facebook.drawee.backends.volley</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/components/package-summary.html">com.facebook.drawee.components</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/controller/package-summary.html">com.facebook.drawee.controller</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/debug/package-summary.html">com.facebook.drawee.debug</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/drawable/package-summary.html">com.facebook.drawee.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/generic/package-summary.html">com.facebook.drawee.generic</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/gestures/package-summary.html">com.facebook.drawee.gestures</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/interfaces/package-summary.html">com.facebook.drawee.interfaces</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/span/package-summary.html">com.facebook.drawee.span</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/drawee/view/package-summary.html">com.facebook.drawee.view</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/backend/package-summary.html">com.facebook.fresco.animation.backend</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/bitmap/package-summary.html">com.facebook.fresco.animation.bitmap</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/bitmap/cache/package-summary.html">com.facebook.fresco.animation.bitmap.cache</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/bitmap/preparation/package-summary.html">com.facebook.fresco.animation.bitmap.preparation</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/bitmap/wrapper/package-summary.html">com.facebook.fresco.animation.bitmap.wrapper</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/drawable/package-summary.html">com.facebook.fresco.animation.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/drawable/animator/package-summary.html">com.facebook.fresco.animation.drawable.animator</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/factory/package-summary.html">com.facebook.fresco.animation.factory</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/fresco/animation/frame/package-summary.html">com.facebook.fresco.animation.frame</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imageformat/package-summary.html">com.facebook.imageformat</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/animated/base/package-summary.html">com.facebook.imagepipeline.animated.base</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/animated/factory/package-summary.html">com.facebook.imagepipeline.animated.factory</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/animated/impl/package-summary.html">com.facebook.imagepipeline.animated.impl</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/animated/util/package-summary.html">com.facebook.imagepipeline.animated.util</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/backends/okhttp3/package-summary.html">com.facebook.imagepipeline.backends.okhttp3</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/backends/volley/package-summary.html">com.facebook.imagepipeline.backends.volley</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/bitmaps/package-summary.html">com.facebook.imagepipeline.bitmaps</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/cache/package-summary.html">com.facebook.imagepipeline.cache</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/common/package-summary.html">com.facebook.imagepipeline.common</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/core/package-summary.html">com.facebook.imagepipeline.core</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/datasource/package-summary.html">com.facebook.imagepipeline.datasource</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/decoder/package-summary.html">com.facebook.imagepipeline.decoder</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/drawable/package-summary.html">com.facebook.imagepipeline.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/image/package-summary.html">com.facebook.imagepipeline.image</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/listener/package-summary.html">com.facebook.imagepipeline.listener</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/memory/package-summary.html">com.facebook.imagepipeline.memory</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/nativecode/package-summary.html">com.facebook.imagepipeline.nativecode</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/platform/package-summary.html">com.facebook.imagepipeline.platform</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/postprocessors/package-summary.html">com.facebook.imagepipeline.postprocessors</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/producers/package-summary.html">com.facebook.imagepipeline.producers</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imagepipeline/request/package-summary.html">com.facebook.imagepipeline.request</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/imageutils/package-summary.html">com.facebook.imageutils</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/webpsupport/package-summary.html">com.facebook.webpsupport</a></li>
<li class="api apilevel-">
<a href="../../../../com/facebook/widget/text/span/package-summary.html">com.facebook.widget.text.span</a></li>
</ul><br/>
</div> <!-- end packages -->
</div> <!-- end resize-packages -->
<div id="classes-nav">
<ul>
<li><h2>Interfaces</h2>
<ul>
<li class="api apilevel-"><a href="../../../../com/facebook/common/disk/DiskTrimmable.html">DiskTrimmable</a></li>
<li class="api apilevel-"><a href="../../../../com/facebook/common/disk/DiskTrimmableRegistry.html">DiskTrimmableRegistry</a></li>
</ul>
</li>
<li><h2>Classes</h2>
<ul>
<li class="selected api apilevel-"><a href="../../../../com/facebook/common/disk/NoOpDiskTrimmableRegistry.html">NoOpDiskTrimmableRegistry</a></li>
</ul>
</li>
</ul><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none">
<div id="index-links">
<a href="../../../../packages.html" >Packages</a> |
<a href="../../../../classes.html" >Classes</a>
</div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
</div> <!-- end side-nav -->
<script>
if (!isMobile) {
//$("<a href='#' id='nav-swap' onclick='swapNav();return false;' style='font-size:10px;line-height:9px;margin-left:1em;text-decoration:none;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>").appendTo("#side-nav");
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("../../../../");
} else {
addLoadEvent(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
}
//$("#swapper").css({borderBottom:"2px solid #aaa"});
} else {
swapNav(); // tree view should be used on mobile
}
</script>
<div class="g-unit" id="doc-content">
<div id="api-info-block">
<div class="sum-details-links">
Summary:
<a href="#pubmethods">Methods</a>
| <a href="#inhmethods">Inherited Methods</a>
| <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a>
</div><!-- end sum-details-links -->
<div class="api-level">
</div>
</div><!-- end api-info-block -->
<!-- ======== START OF CLASS DATA ======== -->
<div id="jd-header">
public
class
<h1>NoOpDiskTrimmableRegistry</h1>
extends Object<br/>
implements
<a href="../../../../com/facebook/common/disk/DiskTrimmableRegistry.html">DiskTrimmableRegistry</a>
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-">
<table class="jd-inheritance-table">
<tr>
<td colspan="2" class="jd-inheritance-class-cell">java.lang.Object</td>
</tr>
<tr>
<td class="jd-inheritance-space"> ↳</td>
<td colspan="1" class="jd-inheritance-class-cell">com.facebook.common.disk.NoOpDiskTrimmableRegistry</td>
</tr>
</table>
<div class="jd-descr">
<h2>Class Overview</h2>
<p>Implementation of <code><a href="../../../../com/facebook/common/disk/DiskTrimmableRegistry.html">DiskTrimmableRegistry</a></code> that does not do anything.
</p>
</div><!-- jd-descr -->
<div class="jd-descr">
<h2>Summary</h2>
<!-- ========== METHOD SUMMARY =========== -->
<table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
synchronized
static
<a href="../../../../com/facebook/common/disk/NoOpDiskTrimmableRegistry.html">NoOpDiskTrimmableRegistry</a>
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/common/disk/NoOpDiskTrimmableRegistry.html#getInstance()">getInstance</a></span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/common/disk/NoOpDiskTrimmableRegistry.html#registerDiskTrimmable(com.facebook.common.disk.DiskTrimmable)">registerDiskTrimmable</a></span>(<a href="../../../../com/facebook/common/disk/DiskTrimmable.html">DiskTrimmable</a> trimmable)
<div class="jd-descrdiv">Register an object.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/common/disk/NoOpDiskTrimmableRegistry.html#unregisterDiskTrimmable(com.facebook.common.disk.DiskTrimmable)">unregisterDiskTrimmable</a></span>(<a href="../../../../com/facebook/common/disk/DiskTrimmable.html">DiskTrimmable</a> trimmable)
<div class="jd-descrdiv">Unregister an object.</div>
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="inhmethods" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Methods</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed"
><img id="inherited-methods-java.lang.Object-trigger"
src="../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From class
java.lang.Object
<div id="inherited-methods-java.lang.Object">
<div id="inherited-methods-java.lang.Object-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-java.lang.Object-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
Object
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">clone</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
boolean
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">equals</span>(Object arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">finalize</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
Class<?>
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">getClass</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
int
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">hashCode</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">notify</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">notifyAll</span>()
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
String
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">toString</span>()
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">wait</span>(long arg0, int arg1)
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">wait</span>(long arg0)
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
final
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad">wait</span>()
</td></tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-com.facebook.common.disk.DiskTrimmableRegistry" class="jd-expando-trigger closed"
><img id="inherited-methods-com.facebook.common.disk.DiskTrimmableRegistry-trigger"
src="../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From interface
<a href="../../../../com/facebook/common/disk/DiskTrimmableRegistry.html">com.facebook.common.disk.DiskTrimmableRegistry</a>
<div id="inherited-methods-com.facebook.common.disk.DiskTrimmableRegistry">
<div id="inherited-methods-com.facebook.common.disk.DiskTrimmableRegistry-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-com.facebook.common.disk.DiskTrimmableRegistry-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
abstract
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/common/disk/DiskTrimmableRegistry.html#registerDiskTrimmable(com.facebook.common.disk.DiskTrimmable)">registerDiskTrimmable</a></span>(<a href="../../../../com/facebook/common/disk/DiskTrimmable.html">DiskTrimmable</a> trimmable)
<div class="jd-descrdiv">Register an object.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">
abstract
void
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../com/facebook/common/disk/DiskTrimmableRegistry.html#unregisterDiskTrimmable(com.facebook.common.disk.DiskTrimmable)">unregisterDiskTrimmable</a></span>(<a href="../../../../com/facebook/common/disk/DiskTrimmable.html">DiskTrimmable</a> trimmable)
<div class="jd-descrdiv">Unregister an object.</div>
</td></tr>
</table>
</div>
</div>
</td></tr>
</table>
</div><!-- jd-descr (summary) -->
<!-- Details -->
<!-- XML Attributes -->
<!-- Enum Values -->
<!-- Constants -->
<!-- Fields -->
<!-- Public ctors -->
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<!-- Protected ctors -->
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methdos -->
<h2>Public Methods</h2>
<a id="getInstance()"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
synchronized
<a href="../../../../com/facebook/common/disk/NoOpDiskTrimmableRegistry.html">NoOpDiskTrimmableRegistry</a>
</span>
<span class="sympad">getInstance</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<a id="registerDiskTrimmable(com.facebook.common.disk.DiskTrimmable)"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
void
</span>
<span class="sympad">registerDiskTrimmable</span>
<span class="normal">(<a href="../../../../com/facebook/common/disk/DiskTrimmable.html">DiskTrimmable</a> trimmable)</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Register an object. </p></div>
</div>
</div>
<a id="unregisterDiskTrimmable(com.facebook.common.disk.DiskTrimmable)"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
void
</span>
<span class="sympad">unregisterDiskTrimmable</span>
<span class="normal">(<a href="../../../../com/facebook/common/disk/DiskTrimmable.html">DiskTrimmable</a> trimmable)</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Unregister an object. </p></div>
</div>
</div>
<!-- ========= METHOD DETAIL ======== -->
<!-- ========= END OF CLASS DATA ========= -->
<a id="navbar_top"></a>
<div id="footer">
+Generated by <a href="http://code.google.com/p/doclava/">Doclava</a>.
+</div> <!-- end footer - @generated -->
</div> <!-- jd-content -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
<script type="text/javascript">
init(); /* initialize doclava-developer-docs.js */
</script>
</body>
</html>
| weiwenqiang/GitHub | expert/fresco/docs/javadoc/reference/com/facebook/common/disk/NoOpDiskTrimmableRegistry.html | HTML | apache-2.0 | 28,731 |
/*<![CDATA[*/
function criaLocalStorageLogin() {
var linhas = document.getElementById("tabelaUsuario")
.getElementsByTagName("tbody")[0].getElementsByTagName("tr");
var table = document.getElementById("tabelaUsuario");
for (i = 0; i < linhas.length; i++) {
linhas[i].onclick = function() {
var t = this.rowIndex + 1;
var tabela = table.rows[t - 1].cells.namedItem("loginUsuario").innerHTML;
localStorage.login = tabela;
window.close();
}
}
};
function criaLocalStorageMotoboy() {
var linhas = document.getElementById("tabelaMotoboy")
.getElementsByTagName("tbody")[0].getElementsByTagName("tr");
var table = document.getElementById("tabelaMotoboy");
for (i = 0; i < linhas.length; i++) {
linhas[i].onclick = function() {
var t = this.rowIndex + 1;
var tabela = table.rows[t - 1].cells.namedItem("nomeMotoboy").innerHTML;
localStorage.motoboy = tabela;
window.close();
}
}
};
function criaLocalStoragePerfil() {
var linhas = document.getElementById("tabela")
.getElementsByTagName("tbody")[0].getElementsByTagName("tr");
var table = document.getElementById("tabela");
for (i = 0; i < linhas.length; i++) {
linhas[i].onclick = function() {
var t = this.rowIndex + 1;
var tabela = table.rows[t - 1].cells.namedItem("tipoAcesso").innerHTML;
localStorage.perfil = tabela;
window.close();
}
}
};
function criaLocalStorageContatoCliente() {
var linhas = document.getElementById("tabelaContato")
.getElementsByTagName("tbody")[0].getElementsByTagName("tr");
var table = document.getElementById("tabelaContato");
for (i = 0; i < linhas.length; i++) {
linhas[i].onclick = function() {
var t = this.rowIndex + 1;
var tabela = table.rows[t - 1].cells.namedItem("nomeContato").innerHTML;
localStorage.contato = tabela;
window.close();
}
}
};
function criaLocalStorageCliente() {
var linhas = document.getElementById("tabelaCliente")
.getElementsByTagName("tbody")[0].getElementsByTagName("tr");
var table = document.getElementById("tabelaCliente");
for (i = 0; i < linhas.length; i++) {
linhas[i].onclick = function() {
var t = this.rowIndex + 1;
var tabela = table.rows[t - 1].cells.namedItem("nomeCliente").innerHTML;
localStorage.cliente = tabela;
window.close();
}
}
};
function criaLocalStorageFuncionario() {
delete window.localStorage["usuario"];
if (document.getElementById("funcao").value == "Motoboy") {
var nome = document.getElementById("nome").value;
localStorage.funcionario = nome;
} else {
delete window.localStorage["funcionario"];
}
};
function setaFuncionarioMotoboy() {
if (localStorage.funcionario) {
document.getElementById("nome").value = localStorage.funcionario;
document.getElementById("cpfMotoboy").value = localStorage.cpf;
}
};
function setaPerfil() {
document.getElementById("tipoAcesso").value = "";
if (localStorage.perfil) {
$.ajax({
url: "/usuario/cadastra",
type: 'POST',
data: localStorage.perfil,
success: function() {
document.getElementById("tipoAcesso").value = localStorage.perfil;
},
error: function() {
alert("Deu erro!");
}
});
};
};
function setaUsuario() {
document.getElementById("login").value = "";
if(localStorage.login){
$.ajax({
url: "/funcionario/cadastra",
type: 'POST',
data: localStorage.login,
success: function() {
document.getElementById("login").value = localStorage.login;
},
error: function() {
alert("Deu erro!");
}
});
};
};
var array = [];
function setaMotoboy() {
var indice;
if(document.getElementById("motoboy").name != null){
indice = document.getElementById("motoboy").name;
}
$.ajax({
url: "/pedido/cadastra",
type: 'POST',
data: localStorage.motoboy,
success: function() {
document.getElementById("motoboy").id = indice;
document.getElementById(indice).value = localStorage.motoboy;
document.getElementById(indice).name = "motoboy";
array.push(document.getElementById(indice).value);
$("#modalDetalhes #motoboyslbl").append("<br>" + array[array.length-1] + ", ");
},
error: function() {
alert("Deu erro!");
}
})
};
function setaCliente() {
document.getElementById("nomeClientePedido").value = "";
if(localStorage.cliente){
$.ajax({
url: "/pedido/cadastra",
type: 'POST',
data: localStorage.contato,
success: function() {
document.getElementById("nomeClientePedido").value = localStorage.cliente;
},
error: function() {
alert("Deu erro!");
}
});
};
};
function limpaLocalStorageCliente(){
delete window.localStorage["cliente"];
}
function salvaAlocacaoAjax() {
var $form = $('#formPedido');
$.ajax({
url: "/alocacao/salva?motoboy="+array+"&tipoperiodo="+$('#tipoPeriodo').val()+
"&numeroPedidoAlocacao="+JSON.stringify(parseInt($('#numeroPedidoAlocacao').val()))+
"&dataAlocacao="+$('#dataAlocacao').val()+
"&qtdeMotoboy="+JSON.stringify(parseInt($('#qtdeMotoboy').val())),
type: 'post',
data: $form.serialize()
});
}
$(document).ready(function(){
$("#confirmaAlocacao").click(function(){
$('#modalCalendar').modal('hide');
delete window.localStorage["motoboy"];
});
$("#cancelaAlocacao").click(function(){
array = [];
delete window.localStorage["motoboy"];
});
$("#enviarPedido").click(function(){
delete window.localStorage["cliente"];
})
});
function setaContatoCliente() {
document.getElementById("nomeContato").value = "";
if(localStorage.contato){
$.ajax({
url: "/cliente/cadastra",
type: 'POST',
data: localStorage.contato,
success: function() {
document.getElementById("nomeContato").value = localStorage.contato;
},
error: function() {
alert("Deu erro!");
}
});
};
};
function limpaLocalStorageFuncionarioMotoboy() {
delete window.localStorage["funcionario"];
delete window.localStorage["cpf"];
}
function limpaLocalStorageContato() {
delete window.localStorage["contato"]
}
function limpaLocalStoragePerfil(){
delete window.localStorage["perfil"];
}
$(document).ready(function() {
$("#cpf").blur(function() {
var cpf = document.getElementById("cpf").value;
cpf = cpf.replace(/[^a-zA-Z0-9 ]/g, "");
localStorage.cpf = cpf;
});
});
/* ]]> */ | rubenscorrea20/Centinyx | target/classes/static/javascript/buscaDados.js | JavaScript | apache-2.0 | 6,985 |
/**
* Copyright (C) 2013 – 2017 SLUB Dresden & Avantgarde Labs GmbH (<code@dswarm.org>)
*
* 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.dswarm.converter.flow;
import org.culturegraph.mf.framework.ObjectReceiver;
import org.culturegraph.mf.types.Triple;
import rx.Observable;
import rx.functions.Func1;
import rx.subjects.PublishSubject;
import rx.subjects.Subject;
final class ObservableTripleReceiver implements ObjectReceiver<Triple> {
private static final Func1<Triple, Boolean> NOT_NULL = m -> m != null;
private final Subject<Triple, Triple> tripleSubject = PublishSubject.create();
@Override
public void process(final Triple triple) {
tripleSubject.onNext(triple);
}
@Override
public void resetStream() {
// TODO ?
}
@Override
public void closeStream() {
tripleSubject.onCompleted();
}
public void propagateError(final Throwable error) {
tripleSubject.onError(error);
}
public Observable<Triple> getObservable() {
return tripleSubject.filter(NOT_NULL);
}
}
| dswarm/dswarm | converter/src/main/java/org/dswarm/converter/flow/ObservableTripleReceiver.java | Java | apache-2.0 | 1,535 |
<?php
/**
* This file has been @generated by a phing task by {@link GeneratePhonePrefixData}.
* See [README.md](README.md#generating-data) for more information.
*
* Pull requests changing data in these files will not be accepted. See the
* [FAQ in the README](README.md#problems-with-invalid-numbers] on how to make
* metadata changes.
*
* Do not modify this file directly!
*/
return array (
1901 => 'Tennessee',
1901213 => 'Memphis, TN',
1901226 => 'Memphis, TN',
1901252 => 'Memphis, TN',
1901259 => 'Memphis, TN',
1901260 => 'Memphis, TN',
1901266 => 'Memphis, TN',
190127 => 'Memphis, TN',
1901287 => 'Memphis, TN',
1901308 => 'Memphis, TN',
1901312 => 'Memphis, TN',
1901320 => 'Memphis, TN',
1901322 => 'Memphis, TN',
1901323 => 'Memphis, TN',
1901324 => 'Memphis, TN',
1901327 => 'Memphis, TN',
1901332 => 'Memphis, TN',
1901345 => 'Memphis, TN',
1901346 => 'Memphis, TN',
1901348 => 'Memphis, TN',
1901353 => 'Memphis, TN',
1901357 => 'Memphis, TN',
1901358 => 'Memphis, TN',
190136 => 'Memphis, TN',
190137 => 'Memphis, TN',
190138 => 'Memphis, TN',
1901396 => 'Memphis, TN',
1901398 => 'Memphis, TN',
1901405 => 'Memphis, TN',
1901416 => 'Memphis, TN',
1901417 => 'Memphis, TN',
1901433 => 'Memphis, TN',
1901435 => 'Memphis, TN',
1901448 => 'Memphis, TN',
1901452 => 'Memphis, TN',
1901454 => 'Memphis, TN',
1901457 => 'Collierville, TN',
1901458 => 'Memphis, TN',
1901465 => 'Somerville, TN',
1901475 => 'Covington, TN',
1901476 => 'Covington, TN',
1901495 => 'Memphis, TN',
1901507 => 'Memphis, TN',
1901516 => 'Memphis, TN',
190152 => 'Memphis, TN',
1901542 => 'Memphis, TN',
1901543 => 'Memphis, TN',
1901544 => 'Memphis, TN',
1901545 => 'Memphis, TN',
1901546 => 'Memphis, TN',
1901552 => 'Memphis, TN',
1901565 => 'Memphis, TN',
1901576 => 'Memphis, TN',
1901577 => 'Memphis, TN',
1901578 => 'Memphis, TN',
1901590 => 'Memphis, TN',
1901595 => 'Memphis, TN',
1901672 => 'Memphis, TN',
190168 => 'Memphis, TN',
1901722 => 'Memphis, TN',
1901725 => 'Memphis, TN',
1901726 => 'Memphis, TN',
1901729 => 'Memphis, TN',
1901730 => 'Memphis, TN',
1901743 => 'Memphis, TN',
1901744 => 'Memphis, TN',
1901746 => 'Memphis, TN',
1901747 => 'Memphis, TN',
1901748 => 'Memphis, TN',
1901761 => 'Memphis, TN',
1901763 => 'Memphis, TN',
1901765 => 'Memphis, TN',
1901766 => 'Memphis, TN',
1901767 => 'Memphis, TN',
1901774 => 'Memphis, TN',
1901775 => 'Memphis, TN',
1901785 => 'Memphis, TN',
1901789 => 'Memphis, TN',
1901791 => 'Memphis, TN',
1901794 => 'Memphis, TN',
1901795 => 'Memphis, TN',
1901797 => 'Memphis, TN',
1901818 => 'Memphis, TN',
1901820 => 'Memphis, TN',
1901821 => 'Memphis, TN',
1901850 => 'Collierville, TN',
1901853 => 'Collierville, TN',
1901854 => 'Collierville, TN',
1901861 => 'Collierville, TN',
1901866 => 'Memphis, TN',
1901867 => 'Arlington, TN',
1901872 => 'Millington, TN',
1901873 => 'Millington, TN',
1901881 => 'Memphis, TN',
1901937 => 'Memphis, TN',
1901942 => 'Memphis, TN',
1901946 => 'Memphis, TN',
1901947 => 'Memphis, TN',
1901948 => 'Memphis, TN',
1902 => 'Nova Scotia/Prince Edward Island',
1902224 => 'Chéticamp, NS',
1902245 => 'Digby, NS',
1902254 => 'Parrsboro, NS',
1902275 => 'Chester, NS',
1902295 => 'Baddeck, NS',
1902354 => 'Liverpool, NS',
1902367 => 'Charlottetown, PE',
1902368 => 'Charlottetown, PE',
1902370 => 'Charlottetown, PE',
1902393 => 'Charlottetown, PE',
1902396 => 'New Glasgow, NS',
1902404 => 'Halifax, NS',
1902405 => 'Halifax, NS',
1902406 => 'Halifax, NS',
1902407 => 'Halifax, NS',
190242 => 'Halifax, NS',
1902431 => 'Halifax, NS',
1902434 => 'Dartmouth, NS',
1902435 => 'Dartmouth, NS',
1902436 => 'Summerside, PE',
1902442 => 'Halifax, NS',
1902443 => 'Halifax, NS',
1902444 => 'Halifax, NS',
1902445 => 'Halifax, NS',
1902446 => 'Halifax, NS',
190245 => 'Halifax, NS',
190246 => 'Dartmouth, NS',
1902471 => 'Halifax, NS',
1902477 => 'Halifax, NS',
1902479 => 'Halifax, NS',
1902481 => 'Dartmouth, NS',
1902482 => 'Halifax, NS',
1902485 => 'Pictou, NS',
1902488 => 'Halifax, NS',
1902492 => 'Halifax, NS',
1902494 => 'Halifax, NS',
1902497 => 'Halifax, NS',
1902499 => 'Halifax, NS',
1902527 => 'Bridgewater, NS',
1902530 => 'Bridgewater, NS',
1902532 => 'Annapolis Royal, NS',
1902535 => 'St. Peter\'s, NS',
1902538 => 'Berwick, NS',
1902539 => 'Sydney, NS',
1902542 => 'Wolfville, NS',
1902543 => 'Bridgewater, NS',
1902562 => 'Sydney, NS',
1902564 => 'Sydney, NS',
1902566 => 'Charlottetown, PE',
1902567 => 'Sydney, NS',
1902569 => 'Charlottetown, PE',
1902582 => 'Canning, NS',
1902624 => 'Mahone Bay, NS',
1902625 => 'Port Hawkesbury, NS',
1902626 => 'Charlottetown, PE',
1902628 => 'Charlottetown, PE',
1902629 => 'Charlottetown, PE',
1902634 => 'Lunenburg, NS',
1902637 => 'Barrington, NS',
1902657 => 'Tatamagouche, NS',
1902661 => 'Amherst, NS',
1902662 => 'Debert, NS',
1902665 => 'Bridgetown, NS',
1902667 => 'Amherst, NS',
1902678 => 'Kentville, NS',
1902679 => 'Kentville, NS',
1902687 => 'Souris, PE',
1902695 => 'New Glasgow, NS',
1902736 => 'North Sydney, NS',
1902742 => 'Yarmouth, NS',
1902752 => 'New Glasgow, NS',
1902755 => 'New Glasgow, NS',
1902758 => 'Shubenacadie, NS',
1902762 => 'Pubnico, NS',
1902765 => 'Kingston, NS',
1902769 => 'Saulnierville, NS',
1902794 => 'North Sydney, NS',
1902798 => 'Windsor, NS',
1902825 => 'Middleton, NS',
1902826 => 'St Margaret Village, NS',
1902827 => 'Chezzetcook, NS',
1902830 => 'Halifax, NS',
1902836 => 'Kensington, PE',
1902837 => 'Weymouth, NS',
1902838 => 'Montague, PE',
1902842 => 'Glace Bay, NS',
1902843 => 'Truro, NS',
1902849 => 'Glace Bay, NS',
1902853 => 'Alberton, PE',
1902857 => 'Hubbards, NS',
1902859 => 'O\'Leary, PE',
1902860 => 'Waverley, NS',
1902861 => 'Waverley, NS',
1902862 => 'New Waterford, NS',
1902863 => 'Antigonish, NS',
1902875 => 'Shelburne, NS',
1902876 => 'Halifax, NS',
1902882 => 'Tignish, PE',
1902883 => 'Elmsdale, NS',
1902888 => 'Summerside, PE',
1902889 => 'Musquodoboit Harbour, NS',
1902892 => 'Charlottetown, PE',
1902893 => 'Truro, NS',
1902894 => 'Charlottetown, PE',
1902895 => 'Truro, NS',
1902897 => 'Truro, NS',
1902963 => 'Rusticoville, PE',
1903 => 'Texas',
1903212 => 'Longview, TX',
1903223 => 'Texarkana, TX',
1903234 => 'Longview, TX',
1903236 => 'Longview, TX',
1903237 => 'Longview, TX',
1903238 => 'Longview, TX',
1903291 => 'Longview, TX',
1903295 => 'Longview, TX',
1903297 => 'Longview, TX',
1903315 => 'Longview, TX',
1903322 => 'Buffalo, TX',
1903334 => 'Texarkana, TX',
1903342 => 'Winnsboro, TX',
1903356 => 'Quinlan, TX',
1903364 => 'Whitewright, TX',
1903378 => 'Honey Grove, TX',
1903383 => 'Yantis, TX',
1903389 => 'Fairfield, TX',
1903395 => 'Cooper, TX',
1903408 => 'Greenville, TX',
1903416 => 'Denison, TX',
1903427 => 'Clarksville, TX',
1903438 => 'Sulphur Springs, TX',
1903439 => 'Sulphur Springs, TX',
1903447 => 'Quinlan, TX',
1903450 => 'Greenville, TX',
1903451 => 'Mabank, TX',
1903454 => 'Greenville, TX',
1903455 => 'Greenville, TX',
1903463 => 'Denison, TX',
1903465 => 'Denison, TX',
1903473 => 'Emory, TX',
1903482 => 'Van Alstyne, TX',
1903489 => 'Malakoff, TX',
1903498 => 'Kemp, TX',
1903509 => 'Tyler, TX',
1903510 => 'Tyler, TX',
1903525 => 'Tyler, TX',
1903526 => 'Tyler, TX',
1903527 => 'Caddo Mills, TX',
1903531 => 'Tyler, TX',
1903533 => 'Tyler, TX',
1903534 => 'Tyler, TX',
1903535 => 'Tyler, TX',
1903536 => 'Centerville, TX',
1903537 => 'Mount Vernon, TX',
1903547 => 'Hooks, TX',
1903553 => 'Longview, TX',
1903561 => 'Tyler, TX',
1903564 => 'Whitesboro, TX',
1903566 => 'Tyler, TX',
1903567 => 'Canton, TX',
1903569 => 'Mineola, TX',
1903572 => 'Mount Pleasant, TX',
1903575 => 'Mount Pleasant, TX',
1903577 => 'Mount Pleasant, TX',
1903581 => 'Tyler, TX',
1903583 => 'Bonham, TX',
1903586 => 'Jacksonville, TX',
1903587 => 'Leonard, TX',
1903589 => 'Jacksonville, TX',
1903592 => 'Tyler, TX',
1903593 => 'Tyler, TX',
1903595 => 'Tyler, TX',
1903596 => 'Tyler, TX',
1903597 => 'Tyler, TX',
1903614 => 'Texarkana, TX',
1903626 => 'Jewett, TX',
1903628 => 'New Boston, TX',
1903636 => 'Big Sandy, TX',
1903639 => 'Hughes Springs, TX',
1903640 => 'Bonham, TX',
1903641 => 'Corsicana, TX',
1903643 => 'Longview, TX',
1903645 => 'Daingerfield, TX',
1903654 => 'Corsicana, TX',
1903655 => 'Henderson, TX',
1903657 => 'Henderson, TX',
1903663 => 'Longview, TX',
1903665 => 'Jefferson, TX',
1903667 => 'De Kalb, TX',
1903668 => 'Hallsville, TX',
1903670 => 'Athens, TX',
1903675 => 'Athens, TX',
1903677 => 'Athens, TX',
1903683 => 'Rusk, TX',
1903687 => 'Waskom, TX',
1903693 => 'Carthage, TX',
1903694 => 'Carthage, TX',
1903723 => 'Palestine, TX',
1903729 => 'Palestine, TX',
1903731 => 'Palestine, TX',
1903734 => 'Gilmer, TX',
1903737 => 'Paris, TX',
1903739 => 'Paris, TX',
1903753 => 'Longview, TX',
1903756 => 'Linden, TX',
1903757 => 'Longview, TX',
1903758 => 'Longview, TX',
1903759 => 'Longview, TX',
1903763 => 'Quitman, TX',
1903769 => 'Hawkins, TX',
1903783 => 'Paris, TX',
1903784 => 'Paris, TX',
1903785 => 'Paris, TX',
1903786 => 'Pottsboro, TX',
1903791 => 'Texarkana, TX',
1903792 => 'Texarkana, TX',
1903793 => 'Texarkana, TX',
1903794 => 'Texarkana, TX',
1903796 => 'Atlanta, TX',
1903798 => 'Texarkana, TX',
1903799 => 'Atlanta, TX',
1903813 => 'Sherman, TX',
1903825 => 'Flint, TX',
1903831 => 'Texarkana, TX',
1903832 => 'Texarkana, TX',
1903834 => 'Overton, TX',
1903838 => 'Texarkana, TX',
1903839 => 'Whitehouse, TX',
1903842 => 'Troup, TX',
1903843 => 'Gilmer, TX',
1903845 => 'Gladewater, TX',
1903849 => 'Chandler, TX',
1903852 => 'Brownsboro, TX',
1903856 => 'Pittsburg, TX',
1903868 => 'Sherman, TX',
1903870 => 'Sherman, TX',
1903872 => 'Corsicana, TX',
1903873 => 'Wills Point, TX',
1903874 => 'Corsicana, TX',
1903875 => 'Corsicana, TX',
1903876 => 'Frankston, TX',
1903877 => 'Tyler, TX',
1903881 => 'Lindale, TX',
1903882 => 'Lindale, TX',
1903883 => 'Greenville, TX',
1903885 => 'Sulphur Springs, TX',
1903886 => 'Commerce, TX',
1903887 => 'Gun Barrel City, TX',
1903891 => 'Sherman, TX',
1903892 => 'Sherman, TX',
1903893 => 'Sherman, TX',
1903894 => 'Bullard, TX',
1903896 => 'Edgewood, TX',
1903923 => 'Marshall, TX',
1903927 => 'Marshall, TX',
1903934 => 'Marshall, TX',
1903935 => 'Marshall, TX',
1903938 => 'Marshall, TX',
1903939 => 'Tyler, TX',
1903947 => 'Tatum, TX',
1903962 => 'Grand Saline, TX',
1903963 => 'Van, TX',
1903965 => 'Bells, TX',
1903968 => 'Ore City, TX',
1903983 => 'Kilgore, TX',
1903984 => 'Kilgore, TX',
1903986 => 'Kilgore, TX',
1904 => 'Florida',
1904202 => 'Jacksonville, FL',
1904209 => 'St. Augustine, FL',
1904213 => 'Orange Park, FL',
1904215 => 'Orange Park, FL',
1904217 => 'St. Augustine, FL',
1904220 => 'Jacksonville, FL',
1904221 => 'Jacksonville, FL',
1904223 => 'Jacksonville, FL',
1904225 => 'Yulee, FL',
1904232 => 'Jacksonville, FL',
1904240 => 'Jacksonville, FL',
1904244 => 'Jacksonville, FL',
1904253 => 'Jacksonville, FL',
1904259 => 'Macclenny, FL',
1904260 => 'Jacksonville, FL',
1904261 => 'Fernandina Beach, FL',
1904262 => 'Jacksonville, FL',
1904264 => 'Orange Park, FL',
1904268 => 'Jacksonville, FL',
1904269 => 'Orange Park, FL',
1904272 => 'Orange Park, FL',
1904273 => 'Ponte Vedra Bch, FL',
1904276 => 'Orange Park, FL',
1904277 => 'Fernandina Beach, FL',
1904278 => 'Orange Park, FL',
1904280 => 'Ponte Vedra Bch, FL',
1904281 => 'Jacksonville, FL',
1904282 => 'Middleburg, FL',
1904284 => 'Green Cove Spgs, FL',
1904285 => 'Ponte Vedra Bch, FL',
1904288 => 'Jacksonville, FL',
1904291 => 'Middleburg, FL',
1904292 => 'Jacksonville, FL',
1904296 => 'Jacksonville, FL',
1904298 => 'Orange Park, FL',
1904306 => 'Jacksonville, FL',
1904308 => 'Jacksonville, FL',
1904310 => 'Fernandina Beach, FL',
1904317 => 'Jacksonville, FL',
1904321 => 'Fernandina Beach, FL',
1904329 => 'Jacksonville, FL',
1904332 => 'Jacksonville, FL',
1904338 => 'Jacksonville, FL',
1904342 => 'St. Augustine, FL',
1904346 => 'Jacksonville, FL',
1904347 => 'St. Augustine, FL',
1904348 => 'Jacksonville, FL',
190435 => 'Jacksonville, FL',
1904363 => 'Jacksonville, FL',
1904367 => 'Jacksonville, FL',
1904368 => 'Starke, FL',
1904371 => 'Jacksonville, FL',
1904374 => 'Jacksonville, FL',
1904375 => 'Orange Park, FL',
1904378 => 'Jacksonville, FL',
1904379 => 'Jacksonville, FL',
190438 => 'Jacksonville, FL',
1904394 => 'Jacksonville, FL',
1904396 => 'Jacksonville, FL',
1904398 => 'Jacksonville, FL',
1904399 => 'Jacksonville, FL',
1904406 => 'Middleburg, FL',
1904419 => 'Jacksonville, FL',
1904421 => 'Jacksonville, FL',
1904425 => 'Jacksonville, FL',
1904448 => 'Jacksonville, FL',
1904460 => 'St. Augustine, FL',
1904461 => 'St. Augustine, FL',
1904471 => 'St. Augustine, FL',
1904491 => 'Fernandina Beach, FL',
1904493 => 'Jacksonville, FL',
1904501 => 'St. Augustine, FL',
1904503 => 'Jacksonville, FL',
1904519 => 'Jacksonville, FL',
1904527 => 'Jacksonville, FL',
1904529 => 'Green Cove Spgs, FL',
1904538 => 'Jacksonville, FL',
1904540 => 'St. Augustine, FL',
1904541 => 'Orange Park, FL',
1904542 => 'Jacksonville, FL',
1904548 => 'Yulee, FL',
1904551 => 'Jacksonville, FL',
1904564 => 'Jacksonville, FL',
1904565 => 'Jacksonville, FL',
1904573 => 'Jacksonville, FL',
1904579 => 'Orange Park, FL',
1904598 => 'Jacksonville, FL',
1904619 => 'Jacksonville, FL',
1904620 => 'Jacksonville, FL',
1904630 => 'Jacksonville, FL',
1904632 => 'Jacksonville, FL',
1904633 => 'Jacksonville, FL',
1904634 => 'Jacksonville, FL',
1904636 => 'Jacksonville, FL',
1904641 => 'Jacksonville, FL',
1904642 => 'Jacksonville, FL',
1904644 => 'Orange Park, FL',
1904645 => 'Jacksonville, FL',
1904646 => 'Jacksonville, FL',
1904647 => 'Jacksonville, FL',
1904652 => 'Jacksonville, FL',
1904669 => 'St. Augustine, FL',
1904674 => 'Jacksonville, FL',
1904683 => 'Jacksonville, FL',
1904687 => 'St. Augustine, FL',
1904692 => 'Hastings, FL',
1904693 => 'Jacksonville, FL',
1904695 => 'Jacksonville, FL',
1904696 => 'Jacksonville, FL',
1904697 => 'Jacksonville, FL',
1904714 => 'Jacksonville, FL',
190472 => 'Jacksonville, FL',
190473 => 'Jacksonville, FL',
1904741 => 'Jacksonville, FL',
1904743 => 'Jacksonville, FL',
1904744 => 'Jacksonville, FL',
1904745 => 'Jacksonville, FL',
1904751 => 'Jacksonville, FL',
1904757 => 'Jacksonville, FL',
1904764 => 'Jacksonville, FL',
1904765 => 'Jacksonville, FL',
1904766 => 'Jacksonville, FL',
1904768 => 'Jacksonville, FL',
1904771 => 'Jacksonville, FL',
1904772 => 'Jacksonville, FL',
1904777 => 'Jacksonville, FL',
1904778 => 'Jacksonville, FL',
1904779 => 'Jacksonville, FL',
1904781 => 'Jacksonville, FL',
1904783 => 'Jacksonville, FL',
1904786 => 'Jacksonville, FL',
1904794 => 'St. Augustine, FL',
1904797 => 'St. Augustine, FL',
1904807 => 'Jacksonville, FL',
1904808 => 'St. Augustine, FL',
1904810 => 'St. Augustine, FL',
1904814 => 'St. Augustine, FL',
1904819 => 'St. Augustine, FL',
190482 => 'St. Augustine, FL',
1904821 => 'Jacksonville, FL',
1904845 => 'Hilliard, FL',
1904854 => 'Jacksonville, FL',
1904858 => 'Jacksonville, FL',
1904879 => 'Callahan, FL',
1904880 => 'Jacksonville, FL',
1904886 => 'Jacksonville, FL',
1904900 => 'Jacksonville, FL',
1904908 => 'Jacksonville, FL',
1904924 => 'Jacksonville, FL',
1904928 => 'Jacksonville, FL',
1904940 => 'St. Augustine, FL',
1904953 => 'Jacksonville, FL',
1904964 => 'Starke, FL',
1904992 => 'Jacksonville, FL',
1904996 => 'Jacksonville, FL',
1904997 => 'Jacksonville, FL',
1904998 => 'Jacksonville, FL',
19052 => 'Ontario',
1905201 => 'Markham, ON',
1905206 => 'Mississauga, ON',
1905209 => 'Markham, ON',
1905212 => 'Mississauga, ON',
1905216 => 'Brampton, ON',
1905227 => 'Thorold, ON',
1905230 => 'Brampton, ON',
1905231 => 'Ajax, ON',
1905232 => 'Mississauga, ON',
1905235 => 'Newmarket, ON',
1905237 => 'Richmond Hill, ON',
1905238 => 'Mississauga, ON',
1905239 => 'Ajax, ON',
1905240 => 'Oshawa, ON',
1905257 => 'Oakville, ON',
1905263 => 'Hampton, ON',
1905264 => 'Woodbridge, ON',
1905265 => 'Woodbridge, ON',
1905266 => 'Woodbridge, ON',
1905267 => 'Mississauga, ON',
1905268 => 'Mississauga, ON',
190527 => 'Mississauga, ON',
1905281 => 'Mississauga, ON',
1905282 => 'Mississauga, ON',
1905286 => 'Mississauga, ON',
1905290 => 'Mississauga, ON',
1905294 => 'Markham, ON',
1905295 => 'Niagara Falls, ON',
1905296 => 'Hamilton, ON',
1905297 => 'Hamilton, ON',
1905300 => 'Ontario',
1905301 => 'Ontario',
1905302 => 'Ontario',
1905303 => 'Maple, ON',
1905304 => 'Ancaster, ON',
1905305 => 'Markham, ON',
1905306 => 'Mississauga, ON',
1905307 => 'Ontario',
1905308 => 'Hamilton, ON',
1905309 => 'Grimsby, ON',
190531 => 'Ontario',
1905312 => 'Hamilton, ON',
1905315 => 'Burlington, ON',
1905318 => 'Hamilton, ON',
1905319 => 'Burlington, ON',
190532 => 'Ontario',
1905330 => 'Ontario',
1905331 => 'Burlington, ON',
1905332 => 'Burlington, ON',
1905333 => 'Burlington, ON',
1905334 => 'Ontario',
1905335 => 'Burlington, ON',
1905336 => 'Burlington, ON',
1905337 => 'Oakville, ON',
1905338 => 'Oakville, ON',
1905339 => 'Oakville, ON',
190534 => 'Ontario',
1905346 => 'St. Catharines, ON',
1905350 => 'Ontario',
1905351 => 'Ontario',
1905352 => 'Ontario',
1905353 => 'Niagara Falls, ON',
1905354 => 'Niagara Falls, ON',
1905355 => 'Colborne, ON',
1905356 => 'Niagara Falls, ON',
1905357 => 'Niagara Falls, ON',
1905358 => 'Niagara Falls, ON',
1905359 => 'Ontario',
190536 => 'Ontario',
1905362 => 'Mississauga, ON',
1905366 => 'Mississauga, ON',
1905370 => 'Ontario',
1905371 => 'Niagara Falls, ON',
1905372 => 'Cobourg, ON',
1905373 => 'Cobourg, ON',
1905374 => 'Niagara Falls, ON',
1905375 => 'Ontario',
1905376 => 'Ontario',
1905377 => 'Cobourg, ON',
1905378 => 'Ontario',
1905379 => 'Ontario',
1905380 => 'Ontario',
1905381 => 'Ontario',
1905382 => 'Stevensville, ON',
1905383 => 'Hamilton, ON',
1905384 => 'Ontario',
1905385 => 'Hamilton, ON',
1905386 => 'Ontario',
1905387 => 'Hamilton, ON',
1905388 => 'Hamilton, ON',
1905389 => 'Hamilton, ON',
190539 => 'Ontario',
1905397 => 'St. Catharines, ON',
190540 => 'Ontario',
1905403 => 'Mississauga, ON',
1905404 => 'Oshawa, ON',
1905405 => 'Mississauga, ON',
190541 => 'Ontario',
1905415 => 'Markham, ON',
1905417 => 'Maple, ON',
190542 => 'Ontario',
1905420 => 'Pickering, ON',
1905426 => 'Ajax, ON',
1905427 => 'Ajax, ON',
1905428 => 'Ajax, ON',
1905430 => 'Whitby, ON',
1905431 => 'Ontario',
1905432 => 'Oshawa, ON',
1905433 => 'Oshawa, ON',
1905434 => 'Oshawa, ON',
1905435 => 'Ontario',
1905436 => 'Oshawa, ON',
1905437 => 'Ontario',
1905438 => 'Oshawa, ON',
1905439 => 'Ontario',
190544 => 'Ontario',
1905448 => 'Oshawa, ON',
190545 => 'Brampton, ON',
1905460 => 'Brampton, ON',
1905461 => 'Mississauga, ON',
1905462 => 'Ontario',
1905463 => 'Brampton, ON',
1905464 => 'Ontario',
1905465 => 'Oakville, ON',
1905466 => 'Ontario',
1905467 => 'Ontario',
1905468 => 'Niagara-on-the-Lake, ON',
1905469 => 'Oakville, ON',
190547 => 'Markham, ON',
1905473 => 'Mount Albert, ON',
1905476 => 'Keswick, ON',
1905478 => 'Queensville, ON',
190548 => 'Ontario',
1905480 => 'Markham, ON',
1905487 => 'Brampton, ON',
1905488 => 'Brampton, ON',
1905489 => 'Markham, ON',
1905490 => 'Ontario',
1905491 => 'Ontario',
1905492 => 'Pickering, ON',
1905493 => 'Whitby, ON',
1905494 => 'Brampton, ON',
1905495 => 'Brampton, ON',
1905496 => 'Ontario',
1905497 => 'Brampton, ON',
1905498 => 'Ontario',
1905499 => 'Ontario',
1905500 => 'Ontario',
1905501 => 'Mississauga, ON',
1905502 => 'Mississauga, ON',
1905503 => 'Aurora, ON',
1905504 => 'Ontario',
1905505 => 'Ontario',
1905506 => 'Ontario',
1905507 => 'Mississauga, ON',
1905508 => 'Richmond Hill, ON',
1905509 => 'Pickering, ON',
190551 => 'Ontario',
1905513 => 'Markham, ON',
190552 => 'Hamilton, ON',
1905520 => 'Ontario',
190553 => 'Ontario',
1905538 => 'Hamilton, ON',
190554 => 'Hamilton, ON',
1905541 => 'Ontario',
1905542 => 'Mississauga, ON',
190555 => 'Ontario',
1905554 => 'Markham, ON',
190556 => 'Mississauga, ON',
1905560 => 'Hamilton, ON',
1905561 => 'Hamilton, ON',
1905562 => 'Vineland, ON',
1905563 => 'Beamsville, ON',
190557 => 'Hamilton, ON',
1905570 => 'Ontario',
1905571 => 'Oshawa, ON',
1905576 => 'Oshawa, ON',
1905579 => 'Oshawa, ON',
190558 => 'Ontario',
1905582 => 'Oakville, ON',
190559 => 'Ontario',
1905592 => 'Burlington, ON',
1905593 => 'Mississauga, ON',
1905595 => 'Brampton, ON',
1905600 => 'Ontario',
1905601 => 'Ontario',
1905602 => 'Mississauga, ON',
1905603 => 'Ontario',
1905604 => 'Markham, ON',
1905605 => 'Woodbridge, ON',
1905606 => 'Ontario',
1905607 => 'Mississauga, ON',
1905608 => 'Mississauga, ON',
1905609 => 'Ontario',
190561 => 'Ontario',
1905612 => 'Mississauga, ON',
1905614 => 'Mississauga, ON',
1905615 => 'Mississauga, ON',
1905619 => 'Ajax, ON',
1905620 => 'Ontario',
1905621 => 'Ontario',
1905622 => 'Ontario',
1905623 => 'Bowmanville, ON',
1905624 => 'Mississauga, ON',
1905625 => 'Mississauga, ON',
1905626 => 'Ontario',
1905627 => 'Dundas, ON',
1905628 => 'Dundas, ON',
1905629 => 'Mississauga, ON',
190563 => 'Burlington, ON',
1905630 => 'Ontario',
1905636 => 'Milton, ON',
1905638 => 'Ontario',
1905640 => 'Whitchurch-Stouffville, ON',
1905641 => 'St. Catharines, ON',
1905642 => 'Whitchurch-Stouffville, ON',
1905643 => 'Stoney Creek, ON',
1905644 => 'Ontario',
1905645 => 'Ontario',
1905646 => 'St. Catharines, ON',
1905647 => 'Ontario',
1905648 => 'Ancaster, ON',
1905649 => 'Claremont, ON',
190565 => 'Ontario',
1905655 => 'Brooklin, ON',
1905659 => 'Freelton, ON',
1905660 => 'Concord, ON',
1905661 => 'Ontario',
1905662 => 'Stoney Creek, ON',
1905663 => 'Ontario',
1905664 => 'Stoney Creek, ON',
1905665 => 'Whitby, ON',
1905666 => 'Whitby, ON',
1905667 => 'Hamilton, ON',
1905668 => 'Whitby, ON',
1905669 => 'Concord, ON',
190567 => 'Mississauga, ON',
1905674 => 'Ontario',
1905675 => 'Ontario',
1905679 => 'Mount Hope, ON',
1905680 => 'Ontario',
1905681 => 'Burlington, ON',
1905682 => 'St. Catharines, ON',
1905683 => 'Ajax, ON',
1905684 => 'St. Catharines, ON',
1905685 => 'St. Catharines, ON',
1905686 => 'Ajax, ON',
1905687 => 'St. Catharines, ON',
1905688 => 'St. Catharines, ON',
1905689 => 'Waterdown, ON',
1905690 => 'Waterdown, ON',
1905691 => 'Ontario',
1905692 => 'Binbrook, ON',
1905693 => 'Milton, ON',
1905694 => 'Ontario',
1905695 => 'Ontario',
1905696 => 'Mississauga, ON',
1905697 => 'Bowmanville, ON',
1905698 => 'Ontario',
1905699 => 'Ontario',
190570 => 'Ontario',
1905701 => 'Dunnville, ON',
1905702 => 'Georgetown, ON',
1905704 => 'St. Catharines, ON',
190571 => 'Ontario',
1905712 => 'Mississauga, ON',
1905713 => 'Aurora, ON',
1905714 => 'Welland, ON',
1905715 => 'Newmarket, ON',
1905720 => 'Oshawa, ON',
1905721 => 'Oshawa, ON',
1905722 => 'Sutton West, ON',
1905723 => 'Oshawa, ON',
1905724 => 'Ontario',
1905725 => 'Oshawa, ON',
1905726 => 'Aurora, ON',
1905727 => 'Aurora, ON',
1905728 => 'Oshawa, ON',
1905729 => 'Beeton, ON',
1905730 => 'Ontario',
1905731 => 'Thornhill, ON',
1905732 => 'Welland, ON',
1905733 => 'Ontario',
1905734 => 'Welland, ON',
1905735 => 'Welland, ON',
1905736 => 'Ontario',
1905737 => 'Richmond Hill, ON',
1905738 => 'Concord, ON',
1905739 => 'Ontario',
190574 => 'Ontario',
190575 => 'Ontario',
1905751 => 'Aurora, ON',
1905752 => 'Markham, ON',
190576 => 'Ontario',
1905760 => 'Concord, ON',
1905761 => 'Concord, ON',
1905765 => 'Caledonia, ON',
1905768 => 'Hagersville, ON',
1905770 => 'Richmond Hill, ON',
1905771 => 'Ontario',
1905772 => 'Cayuga, ON',
1905773 => 'Ontario',
1905774 => 'Dunnville, ON',
1905775 => 'Bradford, ON',
1905776 => 'Ontario',
1905777 => 'Hamilton, ON',
1905778 => 'Bradford, ON',
1905779 => 'Ontario',
1905780 => 'Richmond Hill, ON',
1905781 => 'Ontario',
1905782 => 'Ontario',
1905783 => 'Ontario',
1905784 => 'Ontario',
1905785 => 'Mississauga, ON',
1905786 => 'Ontario',
1905787 => 'Richmond Hill, ON',
1905788 => 'Welland, ON',
1905789 => 'Brampton, ON',
190579 => 'Brampton, ON',
1905794 => 'Castlemore, ON',
1905795 => 'Mississauga, ON',
1905797 => 'Ontario',
1905798 => 'Ontario',
190580 => 'Ontario',
1905803 => 'Mississauga, ON',
1905804 => 'Mississauga, ON',
1905810 => 'Ontario',
1905811 => 'Ontario',
1905812 => 'Mississauga, ON',
1905813 => 'Mississauga, ON',
1905814 => 'Mississauga, ON',
1905815 => 'Oakville, ON',
1905816 => 'Ontario',
1905817 => 'Mississauga, ON',
1905818 => 'Ontario',
1905819 => 'Mississauga, ON',
190582 => 'Mississauga, ON',
1905825 => 'Oakville, ON',
1905827 => 'Oakville, ON',
1905829 => 'Oakville, ON',
1905830 => 'Newmarket, ON',
1905831 => 'Pickering, ON',
1905832 => 'Maple, ON',
1905833 => 'King City, ON',
1905834 => 'Port Colborne, ON',
1905835 => 'Port Colborne, ON',
1905836 => 'Newmarket, ON',
1905837 => 'Pickering, ON',
1905838 => 'Ontario',
1905839 => 'Pickering, ON',
1905840 => 'Brampton, ON',
1905841 => 'Aurora, ON',
1905842 => 'Oakville, ON',
1905843 => 'Ontario',
1905844 => 'Oakville, ON',
1905845 => 'Oakville, ON',
1905846 => 'Brampton, ON',
1905847 => 'Oakville, ON',
1905848 => 'Mississauga, ON',
1905849 => 'Oakville, ON',
1905850 => 'Woodbridge, ON',
1905851 => 'Woodbridge, ON',
1905852 => 'Uxbridge, ON',
1905853 => 'Newmarket, ON',
1905854 => 'Campbellville, ON',
1905855 => 'Mississauga, ON',
1905856 => 'Woodbridge, ON',
1905857 => 'Bolton, ON',
1905858 => 'Mississauga, ON',
1905859 => 'Nobleton, ON',
190586 => 'Ontario',
1905862 => 'Uxbridge, ON',
1905864 => 'Milton, ON',
1905868 => 'Newmarket, ON',
1905870 => 'Ontario',
1905871 => 'Fort Erie, ON',
1905872 => 'Ontario',
1905873 => 'Georgetown, ON',
1905874 => 'Brampton, ON',
1905875 => 'Milton, ON',
1905876 => 'Milton, ON',
1905877 => 'Georgetown, ON',
1905878 => 'Milton, ON',
1905879 => 'Ontario',
1905880 => 'Ontario',
1905881 => 'Thornhill, ON',
1905882 => 'Ontario',
1905883 => 'Richmond Hill, ON',
1905884 => 'Richmond Hill, ON',
1905885 => 'Port Hope, ON',
1905886 => 'Ontario',
1905887 => 'Ontario',
1905888 => 'Bethesda, ON',
1905889 => 'Thornhill, ON',
1905890 => 'Mississauga, ON',
1905891 => 'Mississauga, ON',
1905892 => 'Ontario',
1905893 => 'Kleinburg, ON',
1905894 => 'Ridgeway, ON',
1905895 => 'Newmarket, ON',
1905896 => 'Mississauga, ON',
1905897 => 'Mississauga, ON',
1905898 => 'Newmarket, ON',
1905899 => 'Wainfleet, ON',
19059 => 'Ontario',
1905901 => 'Oakville, ON',
1905910 => 'Markham, ON',
1905913 => 'Castlemore, ON',
1905918 => 'Richmond Hill, ON',
1905934 => 'St. Catharines, ON',
1905935 => 'St. Catharines, ON',
1905936 => 'Tottenham, ON',
1905937 => 'St. Catharines, ON',
1905938 => 'St. Catharines, ON',
1905939 => 'Schomberg, ON',
190594 => 'Markham, ON',
1905945 => 'Grimsby, ON',
1905949 => 'Mississauga, ON',
1905951 => 'Bolton, ON',
1905953 => 'Newmarket, ON',
1905954 => 'Newmarket, ON',
1905957 => 'Smithville, ON',
1905967 => 'Newmarket, ON',
1905970 => 'Brampton, ON',
1905982 => 'Port Perry, ON',
1905983 => 'Orono, ON',
1905984 => 'St. Catharines, ON',
1905985 => 'Port Perry, ON',
1905987 => 'Newcastle, ON',
1905988 => 'St. Catharines, ON',
1905989 => 'Keswick, ON',
1905990 => 'Mississauga, ON',
1905994 => 'Fort Erie, ON',
1905997 => 'Mississauga, ON',
1906 => 'Michigan',
1906225 => 'Marquette, MI',
1906226 => 'Marquette, MI',
1906227 => 'Marquette, MI',
1906228 => 'Marquette, MI',
1906233 => 'Escanaba, MI',
1906248 => 'Brimley, MI',
1906249 => 'Marquette, MI',
1906253 => 'Sault Ste. Marie, MI',
1906265 => 'Iron River, MI',
1906293 => 'Newberry, MI',
1906296 => 'Lake Linden, MI',
1906337 => 'Calumet Township, MI',
1906341 => 'Manistique, MI',
1906346 => 'Gwinn, MI',
1906353 => 'Baraga, MI',
1906387 => 'Munising, MI',
1906428 => 'Gladstone, MI',
1906466 => 'Bark River, MI',
1906475 => 'Negaunee, MI',
1906484 => 'Cedarville, MI',
1906485 => 'Ishpeming, MI',
1906486 => 'Ishpeming, MI',
1906487 => 'Houghton, MI',
1906493 => 'Drummond, MI',
1906495 => 'Kincheloe, MI',
1906523 => 'Chassell, MI',
1906524 => 'L\'Anse, MI',
1906563 => 'Norway, MI',
1906632 => 'Sault Ste. Marie, MI',
1906635 => 'Sault Ste. Marie, MI',
1906643 => 'St. Ignace, MI',
1906647 => 'Pickford, MI',
1906753 => 'Stephenson, MI',
1906774 => 'Iron Mountain, MI',
1906776 => 'Iron Mountain, MI',
1906779 => 'Iron Mountain, MI',
1906786 => 'Escanaba, MI',
1906789 => 'Escanaba, MI',
1906847 => 'Mackinac Island, MI',
1906863 => 'Menominee, MI',
1906864 => 'Menominee, MI',
1906875 => 'Crystal Falls, MI',
1906884 => 'Ontonagon, MI',
1906932 => 'Ironwood, MI',
1907 => 'Alaska',
1907212 => 'Anchorage, AK',
1907222 => 'Anchorage, AK',
1907224 => 'Seward, AK',
1907225 => 'Ketchikan, AK',
1907228 => 'Ketchikan, AK',
1907235 => 'Homer, AK',
1907243 => 'Anchorage, AK',
1907245 => 'Anchorage, AK',
1907247 => 'Ketchikan, AK',
1907248 => 'Anchorage, AK',
1907257 => 'Anchorage, AK',
1907258 => 'Anchorage, AK',
1907260 => 'Soldotna, AK',
1907262 => 'Soldotna, AK',
1907264 => 'Anchorage, AK',
1907269 => 'Anchorage, AK',
190727 => 'Anchorage, AK',
1907283 => 'Kenai, AK',
190733 => 'Anchorage, AK',
1907335 => 'Kenai, AK',
1907343 => 'Anchorage, AK',
1907344 => 'Anchorage, AK',
1907345 => 'Anchorage, AK',
1907346 => 'Anchorage, AK',
1907349 => 'Anchorage, AK',
1907352 => 'Wasilla, AK',
1907357 => 'Wasilla, AK',
1907373 => 'Wasilla, AK',
1907374 => 'Fairbanks, AK',
1907376 => 'Wasilla, AK',
1907424 => 'Cordova, AK',
1907442 => 'Kotzebue, AK',
1907443 => 'Nome, AK',
190745 => 'Fairbanks, AK',
1907463 => 'Juneau, AK',
1907465 => 'Juneau, AK',
1907474 => 'Fairbanks, AK',
1907479 => 'Fairbanks, AK',
1907486 => 'Kodiak, AK',
1907487 => 'Kodiak, AK',
1907488 => 'North Pole, AK',
1907490 => 'North Pole, AK',
1907495 => 'Willow, AK',
1907522 => 'Anchorage, AK',
1907523 => 'Juneau, AK',
1907543 => 'Bethel, AK',
1907561 => 'Anchorage, AK',
1907562 => 'Anchorage, AK',
1907563 => 'Anchorage, AK',
1907567 => 'Ninilchik, AK',
1907569 => 'Anchorage, AK',
1907580 => 'Elmendorf Air Force Base, AK',
1907581 => 'Unalaska, AK',
1907586 => 'Juneau, AK',
1907622 => 'Eagle River, AK',
1907644 => 'Anchorage, AK',
1907646 => 'Anchorage, AK',
1907677 => 'Anchorage, AK',
1907683 => 'Healy, AK',
1907688 => 'Chugiak, AK',
1907694 => 'Eagle River, AK',
1907696 => 'Eagle River, AK',
1907714 => 'Soldotna, AK',
1907729 => 'Anchorage, AK',
1907733 => 'Talkeetna, AK',
1907742 => 'Anchorage, AK',
1907743 => 'Anchorage, AK',
1907745 => 'Palmer, AK',
1907746 => 'Palmer, AK',
1907747 => 'Sitka, AK',
1907766 => 'Haines, AK',
1907770 => 'Anchorage, AK',
1907772 => 'Petersburg, AK',
1907776 => 'Kenai, AK',
1907780 => 'Juneau, AK',
1907783 => 'Girdwood, AK',
1907789 => 'Juneau, AK',
1907790 => 'Juneau, AK',
1907822 => 'Glennallen, AK',
1907826 => 'Craig, AK',
1907835 => 'Valdez, AK',
1907842 => 'Dillingham, AK',
1907852 => 'Barrow, AK',
1907868 => 'Anchorage, AK',
1907874 => 'Wrangell, AK',
1907883 => 'Tok, AK',
1907895 => 'Delta Junction, AK',
1907929 => 'Anchorage, AK',
1907966 => 'Sitka, AK',
1907983 => 'Skagway, AK',
1908 => 'New Jersey',
1908206 => 'Union, NJ',
1908213 => 'Phillipsburg, NJ',
1908221 => 'Bernardsville, NJ',
1908232 => 'Westfield, NJ',
1908233 => 'Westfield, NJ',
1908236 => 'Lebanon, NJ',
1908237 => 'Flemington, NJ',
1908258 => 'Union, NJ',
1908272 => 'Cranford, NJ',
1908273 => 'Summit, NJ',
1908276 => 'Cranford, NJ',
1908277 => 'Summit, NJ',
1908281 => 'Hillsborough Township, NJ',
1908282 => 'Elizabeth, NJ',
1908284 => 'Flemington, NJ',
1908289 => 'Elizabeth, NJ',
1908317 => 'Westfield, NJ',
1908322 => 'Scotch Plains, NJ',
1908351 => 'Elizabeth, NJ',
1908352 => 'Elizabeth, NJ',
1908353 => 'Elizabeth, NJ',
1908354 => 'Elizabeth, NJ',
1908355 => 'Elizabeth, NJ',
1908359 => 'Hillsborough Township, NJ',
1908362 => 'Blairstown, NJ',
1908369 => 'Hillsborough Township, NJ',
1908387 => 'Phillipsburg, NJ',
1908431 => 'Hillsborough Township, NJ',
1908436 => 'Elizabeth, NJ',
1908453 => 'Oxford Township, NJ',
1908454 => 'Phillipsburg, NJ',
1908464 => 'Berkeley Heights, NJ',
1908469 => 'Elizabeth, NJ',
1908474 => 'Linden, NJ',
1908475 => 'Belvidere, NJ',
1908486 => 'Linden, NJ',
1908496 => 'Columbia, NJ',
1908497 => 'Cranford, NJ',
1908522 => 'Summit, NJ',
1908527 => 'Elizabeth, NJ',
1908558 => 'Elizabeth, NJ',
1908587 => 'Linden, NJ',
1908598 => 'Summit, NJ',
1908624 => 'Union, NJ',
1908637 => 'Great Meadows, NJ',
1908654 => 'Westfield, NJ',
1908684 => 'Hackettstown, NJ',
1908686 => 'Union, NJ',
1908687 => 'Union, NJ',
1908688 => 'Union, NJ',
1908689 => 'Washington, NJ',
1908709 => 'Cranford, NJ',
1908719 => 'Bedminster Township, NJ',
1908782 => 'Flemington, NJ',
1908788 => 'Flemington, NJ',
1908806 => 'Flemington, NJ',
1908810 => 'Union, NJ',
1908813 => 'Hackettstown, NJ',
1908820 => 'Elizabeth, NJ',
1908832 => 'Califon, NJ',
1908835 => 'Washington, NJ',
1908850 => 'Hackettstown, NJ',
1908851 => 'Union, NJ',
1908852 => 'Hackettstown, NJ',
1908859 => 'Phillipsburg, NJ',
1908862 => 'Linden, NJ',
1908874 => 'Hillsborough Township, NJ',
1908876 => 'Long Valley, NJ',
1908879 => 'Chester Borough, NJ',
1908904 => 'Hillsborough Township, NJ',
1908925 => 'Linden, NJ',
1908931 => 'Cranford, NJ',
1908964 => 'Union, NJ',
1908965 => 'Elizabeth, NJ',
1908979 => 'Hackettstown, NJ',
1908994 => 'Elizabeth, NJ',
1908995 => 'Milford, NJ',
1908996 => 'Frenchtown, NJ',
1909 => 'California',
1909305 => 'San Dimas, CA',
1909307 => 'Redlands, CA',
1909335 => 'Redlands, CA',
1909336 => 'Lake Arrowhead, CA',
1909337 => 'Lake Arrowhead, CA',
1909338 => 'Crestline, CA',
1909349 => 'Fontana, CA',
1909350 => 'Fontana, CA',
1909353 => 'Riverside, CA',
1909355 => 'Fontana, CA',
1909356 => 'Fontana, CA',
1909357 => 'Fontana, CA',
1909364 => 'Chino, CA',
1909370 => 'Colton, CA',
190938 => 'San Bernardino, CA',
1909390 => 'Ontario, CA',
1909391 => 'Ontario, CA',
1909392 => 'La Verne, CA',
1909393 => 'Chino Hills, CA',
1909394 => 'San Dimas, CA',
1909395 => 'Ontario, CA',
1909396 => 'Diamond Bar, CA',
1909397 => 'Pomona, CA',
1909421 => 'Rialto, CA',
1909422 => 'Colton, CA',
1909427 => 'Fontana, CA',
1909428 => 'Fontana, CA',
1909429 => 'Fontana, CA',
1909433 => 'Colton, CA',
1909444 => 'Walnut, CA',
1909460 => 'Ontario, CA',
1909464 => 'Chino, CA',
1909465 => 'Chino, CA',
1909466 => 'Rancho Cucamonga, CA',
1909467 => 'Ontario, CA',
1909468 => 'Walnut, CA',
1909469 => 'Pomona, CA',
1909473 => 'San Bernardino, CA',
1909475 => 'San Bernardino, CA',
1909476 => 'Rancho Cucamonga, CA',
1909477 => 'Rancho Cucamonga, CA',
1909478 => 'Loma Linda, CA',
1909481 => 'Rancho Cucamonga, CA',
1909483 => 'Rancho Cucamonga, CA',
1909484 => 'Rancho Cucamonga, CA',
1909517 => 'Chino, CA',
1909548 => 'Chino, CA',
1909558 => 'Loma Linda, CA',
1909574 => 'Fontana, CA',
1909579 => 'Upland, CA',
1909580 => 'Colton, CA',
1909581 => 'Rancho Cucamonga, CA',
1909584 => 'Big Bear, CA',
1909585 => 'Big Bear, CA',
1909590 => 'Chino, CA',
1909591 => 'Chino, CA',
1909592 => 'San Dimas, CA',
1909593 => 'La Verne, CA',
1909594 => 'Walnut, CA',
1909595 => 'Walnut, CA',
1909596 => 'La Verne, CA',
1909598 => 'Walnut, CA',
1909599 => 'San Dimas, CA',
1909605 => 'Ontario, CA',
1909606 => 'Chino Hills, CA',
1909608 => 'Upland, CA',
1909612 => 'Diamond Bar, CA',
1909613 => 'Chino, CA',
1909620 => 'Pomona, CA',
1909622 => 'Pomona, CA',
1909623 => 'Pomona, CA',
1909627 => 'Chino, CA',
1909628 => 'Chino, CA',
1909629 => 'Pomona, CA',
1909646 => 'Rancho Cucamonga, CA',
1909673 => 'Ontario, CA',
1909748 => 'Redlands, CA',
1909758 => 'Rancho Cucamonga, CA',
1909790 => 'Yucaipa, CA',
1909792 => 'Redlands, CA',
1909793 => 'Redlands, CA',
1909797 => 'Yucaipa, CA',
1909798 => 'Redlands, CA',
1909799 => 'Loma Linda, CA',
1909820 => 'Rialto, CA',
1909822 => 'Fontana, CA',
1909823 => 'Fontana, CA',
1909829 => 'Fontana, CA',
1909854 => 'Fontana, CA',
1909860 => 'Diamond Bar, CA',
1909861 => 'Diamond Bar, CA',
1909862 => 'Highland, CA',
1909863 => 'Highland, CA',
1909864 => 'Highland, CA',
1909865 => 'Pomona, CA',
1909866 => 'Big Bear Lake, CA',
1909867 => 'Running Springs, CA',
1909868 => 'Pomona, CA',
1909873 => 'Rialto, CA',
1909874 => 'Rialto, CA',
1909875 => 'Rialto, CA',
1909877 => 'Bloomington, CA',
1909878 => 'Big Bear Lake, CA',
190988 => 'San Bernardino, CA',
1909890 => 'San Bernardino, CA',
1909902 => 'Chino, CA',
1909920 => 'Upland, CA',
1909923 => 'Ontario, CA',
1909930 => 'Ontario, CA',
1909931 => 'Upland, CA',
1909937 => 'Ontario, CA',
1909941 => 'Rancho Cucamonga, CA',
1909944 => 'Rancho Cucamonga, CA',
1909945 => 'Rancho Cucamonga, CA',
1909946 => 'Upland, CA',
1909947 => 'Ontario, CA',
1909948 => 'Rancho Cucamonga, CA',
1909949 => 'Upland, CA',
1909980 => 'Rancho Cucamonga, CA',
1909981 => 'Upland, CA',
1909982 => 'Upland, CA',
1909983 => 'Ontario, CA',
1909984 => 'Ontario, CA',
1909985 => 'Upland, CA',
1909986 => 'Ontario, CA',
1909987 => 'Rancho Cucamonga, CA',
1909988 => 'Ontario, CA',
1909989 => 'Rancho Cucamonga, CA',
1910 => 'North Carolina',
1910215 => 'Pinehurst, NC',
1910219 => 'Jacksonville, NC',
1910223 => 'Fayetteville, NC',
1910228 => 'Wilmington, NC',
1910232 => 'Wilmington, NC',
1910235 => 'Pinehurst, NC',
1910245 => 'Vass, NC',
1910246 => 'Southern Pines, NC',
1910251 => 'Wilmington, NC',
1910253 => 'Bolivia, NC',
1910254 => 'Wilmington, NC',
1910256 => 'Wilmington, NC',
1910259 => 'Burgaw, NC',
1910262 => 'Wilmington, NC',
1910264 => 'Wilmington, NC',
1910267 => 'Faison, NC',
1910270 => 'Hampstead, NC',
1910272 => 'Lumberton, NC',
1910276 => 'Laurinburg, NC',
1910277 => 'Laurinburg, NC',
1910278 => 'Oak Island, NC',
1910285 => 'Wallace, NC',
1910289 => 'Rose Hill, NC',
1910293 => 'Warsaw, NC',
1910295 => 'Pinehurst, NC',
1910296 => 'Kenansville, NC',
1910297 => 'Wilmington, NC',
1910298 => 'Beulaville, NC',
1910299 => 'Clinton, NC',
1910313 => 'Wilmington, NC',
1910321 => 'Fayetteville, NC',
1910323 => 'Fayetteville, NC',
1910324 => 'Richlands, NC',
1910325 => 'Swansboro, NC',
1910326 => 'Swansboro, NC',
1910327 => 'Sneads Ferry, NC',
1910328 => 'Surf City, NC',
1910329 => 'Holly Ridge, NC',
1910332 => 'Wilmington, NC',
1910333 => 'Jacksonville, NC',
1910338 => 'Wilmington, NC',
1910339 => 'Fayetteville, NC',
1910341 => 'Wilmington, NC',
1910343 => 'Wilmington, NC',
1910346 => 'Jacksonville, NC',
1910347 => 'Jacksonville, NC',
1910350 => 'Wilmington, NC',
1910352 => 'Wilmington, NC',
1910353 => 'Jacksonville, NC',
1910355 => 'Jacksonville, NC',
1910362 => 'Wilmington, NC',
1910371 => 'Leland, NC',
1910383 => 'Leland, NC',
1910392 => 'Wilmington, NC',
1910395 => 'Wilmington, NC',
1910396 => 'Fort Bragg, NC',
1910397 => 'Wilmington, NC',
1910399 => 'Wilmington, NC',
1910417 => 'Rockingham, NC',
1910422 => 'Rowland, NC',
1910423 => 'Fayetteville, NC',
1910424 => 'Fayetteville, NC',
1910425 => 'Fayetteville, NC',
1910426 => 'Fayetteville, NC',
1910428 => 'Biscoe, NC',
1910429 => 'Fayetteville, NC',
1910433 => 'Fayetteville, NC',
1910436 => 'Spring Lake, NC',
1910439 => 'Mount Gilead, NC',
1910442 => 'Wilmington, NC',
1910450 => 'Camp Lejeune, NC',
1910451 => 'Camp Lejeune, NC',
1910452 => 'Wilmington, NC',
1910454 => 'Southport, NC',
1910455 => 'Jacksonville, NC',
1910457 => 'Southport, NC',
1910458 => 'Carolina Beach, NC',
191048 => 'Fayetteville, NC',
1910497 => 'Spring Lake, NC',
1910509 => 'Wilmington, NC',
1910520 => 'Wilmington, NC',
1910521 => 'Pembroke, NC',
1910522 => 'Pembroke, NC',
1910525 => 'Roseboro, NC',
1910538 => 'Wilmington, NC',
1910564 => 'Clinton, NC',
1910572 => 'Troy, NC',
1910576 => 'Troy, NC',
1910577 => 'Jacksonville, NC',
1910582 => 'Hamlet, NC',
1910590 => 'Clinton, NC',
1910592 => 'Clinton, NC',
1910594 => 'Newton Grove, NC',
1910609 => 'Fayetteville, NC',
1910615 => 'Fayetteville, NC',
1910616 => 'Wilmington, NC',
1910618 => 'Lumberton, NC',
1910620 => 'Wilmington, NC',
1910628 => 'Fairmont, NC',
1910630 => 'Fayetteville, NC',
1910640 => 'Whiteville, NC',
1910641 => 'Whiteville, NC',
1910642 => 'Whiteville, NC',
1910648 => 'Bladenboro, NC',
1910652 => 'Ellerbe, NC',
1910653 => 'Tabor City, NC',
1910654 => 'Chadbourn, NC',
1910671 => 'Lumberton, NC',
1910673 => 'West End, NC',
1910675 => 'Castle Hayne, NC',
1910678 => 'Fayetteville, NC',
1910686 => 'Wilmington, NC',
1910692 => 'Southern Pines, NC',
1910693 => 'Southern Pines, NC',
1910695 => 'Southern Pines, NC',
1910715 => 'Pinehurst, NC',
1910738 => 'Lumberton, NC',
1910739 => 'Lumberton, NC',
1910762 => 'Wilmington, NC',
1910763 => 'Wilmington, NC',
1910764 => 'Fayetteville, NC',
1910772 => 'Wilmington, NC',
1910777 => 'Wilmington, NC',
191079 => 'Wilmington, NC',
1910814 => 'Lillington, NC',
1910815 => 'Wilmington, NC',
1910822 => 'Fayetteville, NC',
1910826 => 'Fayetteville, NC',
1910842 => 'Supply, NC',
1910843 => 'Red Springs, NC',
1910844 => 'Maxton, NC',
1910848 => 'Raeford, NC',
1910860 => 'Fayetteville, NC',
1910862 => 'Elizabethtown, NC',
1910863 => 'Bladenboro, NC',
1910864 => 'Fayetteville, NC',
1910865 => 'St. Pauls, NC',
1910867 => 'Fayetteville, NC',
1910868 => 'Fayetteville, NC',
1910875 => 'Raeford, NC',
1910891 => 'Dunn, NC',
1910892 => 'Dunn, NC',
1910893 => 'Lillington, NC',
1910895 => 'Rockingham, NC',
1910904 => 'Raeford, NC',
1910907 => 'E. E. Smith, Fort Bragg, NC',
1910920 => 'Fayetteville, NC',
1910938 => 'Jacksonville, NC',
1910944 => 'Aberdeen, NC',
1910947 => 'Carthage, NC',
1910948 => 'Robbins, NC',
1910974 => 'Candor, NC',
1910997 => 'Rockingham, NC',
1912 => 'Georgia',
1912201 => 'Savannah, GA',
191223 => 'Savannah, GA',
1912261 => 'Brunswick, GA',
1912262 => 'Brunswick, GA',
1912264 => 'Brunswick, GA',
1912265 => 'Brunswick, GA',
1912267 => 'Brunswick, GA',
1912275 => 'Brunswick, GA',
1912280 => 'Brunswick, GA',
1912283 => 'Waycross, GA',
1912284 => 'Waycross, GA',
1912285 => 'Waycross, GA',
1912287 => 'Waycross, GA',
1912289 => 'Brunswick, GA',
1912303 => 'Savannah, GA',
1912330 => 'Pooler, GA',
1912335 => 'Savannah, GA',
1912342 => 'Brunswick, GA',
1912349 => 'Savannah, GA',
191235 => 'Savannah, GA',
1912359 => 'Broxton, GA',
1912366 => 'Baxley, GA',
1912367 => 'Baxley, GA',
1912368 => 'Hinesville, GA',
1912369 => 'Hinesville, GA',
1912375 => 'Hazlehurst, GA',
1912383 => 'Douglas, GA',
1912384 => 'Douglas, GA',
1912389 => 'Douglas, GA',
1912422 => 'Pearson, GA',
1912427 => 'Jesup, GA',
1912435 => 'Fort Stewart, GA',
1912437 => 'Darien, GA',
1912443 => 'Savannah, GA',
1912447 => 'Savannah, GA',
1912449 => 'Blackshear, GA',
1912459 => 'Richmond Hill, GA',
1912462 => 'Nahunta, GA',
1912466 => 'Brunswick, GA',
1912487 => 'Homerville, GA',
1912489 => 'Statesboro, GA',
1912496 => 'Folkston, GA',
1912526 => 'Lyons, GA',
1912529 => 'Soperton, GA',
1912530 => 'Jesup, GA',
1912537 => 'Vidalia, GA',
1912538 => 'Vidalia, GA',
1912545 => 'Ludowici, GA',
1912554 => 'Brunswick, GA',
1912557 => 'Reidsville, GA',
1912564 => 'Sylvania, GA',
1912583 => 'Mount Vernon, GA',
1912587 => 'Statesboro, GA',
1912588 => 'Jesup, GA',
1912598 => 'Savannah, GA',
1912629 => 'Savannah, GA',
1912632 => 'Alma, GA',
1912634 => 'Saint Simons Island, GA',
1912638 => 'Saint Simons Island, GA',
1912644 => 'Savannah, GA',
1912651 => 'Savannah, GA',
1912652 => 'Savannah, GA',
1912653 => 'Pembroke, GA',
1912654 => 'Glennville, GA',
1912673 => 'St. Marys, GA',
1912681 => 'Statesboro, GA',
1912685 => 'Metter, GA',
1912691 => 'Savannah, GA',
1912692 => 'Savannah, GA',
1912727 => 'Richmond Hill, GA',
1912729 => 'Kingsland, GA',
1912739 => 'Claxton, GA',
1912748 => 'Pooler, GA',
1912754 => 'Springfield, GA',
1912756 => 'Richmond Hill, GA',
1912764 => 'Statesboro, GA',
1912772 => 'Guyton, GA',
1912786 => 'Tybee Island, GA',
1912790 => 'Savannah, GA',
1912819 => 'Savannah, GA',
1912826 => 'Rincon, GA',
1912832 => 'Townsend, GA',
1912839 => 'Statesboro, GA',
1912842 => 'Brooklet, GA',
1912863 => 'Sylvania, GA',
1912865 => 'Portal, GA',
1912871 => 'Statesboro, GA',
1912876 => 'Hinesville, GA',
1912877 => 'Hinesville, GA',
1912882 => 'St. Marys, GA',
1912884 => 'Midway, GA',
1912897 => 'Savannah, GA',
1912898 => 'Savannah, GA',
1912920 => 'Savannah, GA',
1912921 => 'Savannah, GA',
1912925 => 'Savannah, GA',
1912927 => 'Savannah, GA',
1912961 => 'Savannah, GA',
1912964 => 'Savannah, GA',
1913 => 'Kansas',
1913233 => 'Kansas City, KS',
1913239 => 'Overland Park, KS',
1913248 => 'Shawnee, KS',
1913250 => 'Leavenworth, KS',
1913254 => 'Olathe, KS',
1913281 => 'Kansas City, KS',
1913287 => 'Kansas City, KS',
1913294 => 'Paola, KS',
1913299 => 'Kansas City, KS',
1913317 => 'Overland Park, KS',
1913321 => 'Kansas City, KS',
1913328 => 'Kansas City, KS',
1913334 => 'Kansas City, KS',
1913342 => 'Kansas City, KS',
1913352 => 'Pleasanton, KS',
1913367 => 'Atchison, KS',
1913371 => 'Kansas City, KS',
1913390 => 'Olathe, KS',
1913393 => 'Olathe, KS',
1913397 => 'Olathe, KS',
1913402 => 'Overland Park, KS',
1913498 => 'Overland Park, KS',
1913557 => 'Paola, KS',
1913573 => 'Kansas City, KS',
1913583 => 'De Soto, KS',
1913588 => 'Kansas City, KS',
1913592 => 'Spring Hill, KS',
1913596 => 'Kansas City, KS',
1913621 => 'Kansas City, KS',
1913651 => 'Leavenworth, KS',
1913680 => 'Leavenworth, KS',
1913681 => 'Overland Park, KS',
1913682 => 'Leavenworth, KS',
1913685 => 'Overland Park, KS',
1913696 => 'Leawood, KS',
1913715 => 'Olathe, KS',
1913721 => 'Kansas City, KS',
1913724 => 'Basehor, KS',
1913727 => 'Lansing, KS',
1913755 => 'Osawatomie, KS',
1913757 => 'LaCygne, KS',
1913758 => 'Leavenworth, KS',
1913764 => 'Olathe, KS',
1913768 => 'Olathe, KS',
1913780 => 'Olathe, KS',
1913782 => 'Olathe, KS',
1913788 => 'Kansas City, KS',
1913791 => 'Olathe, KS',
1913795 => 'Mound City, KS',
1913814 => 'Overland Park, KS',
1913829 => 'Olathe, KS',
1913837 => 'Louisburg, KS',
1913845 => 'Tonganoxie, KS',
1913851 => 'Overland Park, KS',
1913856 => 'Gardner, KS',
1913884 => 'Gardner, KS',
1913901 => 'Overland Park, KS',
1914 => 'New York',
1914207 => 'Yonkers, NY',
1914232 => 'Katonah, NY',
1914234 => 'Bedford, NY',
1914235 => 'New Rochelle, NY',
1914237 => 'Yonkers, NY',
1914238 => 'Chappaqua, NY',
1914241 => 'Mount Kisco, NY',
1914242 => 'Mount Kisco, NY',
1914243 => 'Yorktown Heights, NY',
1914244 => 'Mount Kisco, NY',
1914245 => 'Yorktown Heights, NY',
1914271 => 'Croton-on-Hudson, NY',
1914273 => 'Armonk, NY',
1914276 => 'Somers, NY',
1914277 => 'Somers, NY',
1914285 => 'White Plains, NY',
1914287 => 'White Plains, NY',
1914288 => 'White Plains, NY',
1914304 => 'White Plains, NY',
1914305 => 'Port Chester, NY',
1914328 => 'White Plains, NY',
1914332 => 'Tarrytown, NY',
1914333 => 'Tarrytown, NY',
1914345 => 'Elmsford, NY',
1914347 => 'Elmsford, NY',
1914355 => 'New Rochelle, NY',
1914358 => 'White Plains, NY',
1914366 => 'Sleepy Hollow, NY',
1914375 => 'Yonkers, NY',
1914376 => 'Yonkers, NY',
1914377 => 'Yonkers, NY',
1914378 => 'Yonkers, NY',
1914381 => 'Mamaroneck, NY',
1914421 => 'White Plains, NY',
1914422 => 'White Plains, NY',
1914423 => 'Yonkers, NY',
1914428 => 'White Plains, NY',
1914457 => 'Yonkers, NY',
1914472 => 'Scarsdale, NY',
1914476 => 'Yonkers, NY',
1914481 => 'Port Chester, NY',
1914493 => 'Valhalla, NY',
1914524 => 'Tarrytown, NY',
1914528 => 'Mohegan Lake, NY',
1914533 => 'South Salem, NY',
1914576 => 'New Rochelle, NY',
1914591 => 'Irvington, NY',
1914592 => 'Elmsford, NY',
1914631 => 'Tarrytown, NY',
1914632 => 'New Rochelle, NY',
1914633 => 'New Rochelle, NY',
1914636 => 'New Rochelle, NY',
1914637 => 'New Rochelle, NY',
1914654 => 'New Rochelle, NY',
1914663 => 'Mount Vernon, NY',
1914664 => 'Mount Vernon, NY',
1914665 => 'Mount Vernon, NY',
1914666 => 'Mount Kisco, NY',
1914667 => 'Mount Vernon, NY',
1914668 => 'Mount Vernon, NY',
1914669 => 'North Salem, NY',
1914681 => 'White Plains, NY',
1914682 => 'White Plains, NY',
1914683 => 'White Plains, NY',
1914684 => 'White Plains, NY',
1914686 => 'White Plains, NY',
1914698 => 'Mamaroneck, NY',
1914699 => 'Mount Vernon, NY',
1914713 => 'Scarsdale, NY',
1914722 => 'Scarsdale, NY',
1914723 => 'Scarsdale, NY',
1914725 => 'Scarsdale, NY',
1914734 => 'Peekskill, NY',
1914738 => 'Pelham, NY',
1914740 => 'New Rochelle, NY',
1914751 => 'Yonkers, NY',
1914761 => 'White Plains, NY',
1914764 => 'Pound Ridge, NY',
1914776 => 'Yonkers, NY',
1914777 => 'Mamaroneck, NY',
1914813 => 'New Rochelle, NY',
1914831 => 'White Plains, NY',
1914833 => 'Larchmont, NY',
1914834 => 'Larchmont, NY',
1914835 => 'Harrison, NY',
1914864 => 'Mount Kisco, NY',
1914921 => 'Rye, NY',
1914923 => 'Ossining, NY',
1914925 => 'Rye, NY',
1914930 => 'Peekskill, NY',
1914934 => 'Port Chester, NY',
1914935 => 'Port Chester, NY',
1914937 => 'Port Chester, NY',
1914939 => 'Port Chester, NY',
1914941 => 'Ossining, NY',
1914944 => 'Ossining, NY',
1914946 => 'White Plains, NY',
1914948 => 'White Plains, NY',
1914949 => 'White Plains, NY',
191496 => 'Yonkers, NY',
1914962 => 'Yorktown Heights, NY',
1914967 => 'Rye, NY',
1914993 => 'White Plains, NY',
1914997 => 'White Plains, NY',
1915 => 'Texas',
1915231 => 'El Paso, TX',
1915257 => 'El Paso, TX',
1915307 => 'El Paso, TX',
1915313 => 'El Paso, TX',
1915351 => 'El Paso, TX',
1915532 => 'El Paso, TX',
1915533 => 'El Paso, TX',
1915534 => 'El Paso, TX',
191554 => 'El Paso, TX',
1915562 => 'El Paso, TX',
1915564 => 'El Paso, TX',
1915565 => 'El Paso, TX',
1915566 => 'El Paso, TX',
1915569 => 'El Paso, TX',
1915577 => 'El Paso, TX',
1915581 => 'El Paso, TX',
1915584 => 'El Paso, TX',
1915585 => 'El Paso, TX',
1915587 => 'El Paso, TX',
191559 => 'El Paso, TX',
1915613 => 'El Paso, TX',
1915629 => 'El Paso, TX',
1915633 => 'El Paso, TX',
1915751 => 'El Paso, TX',
1915755 => 'El Paso, TX',
1915757 => 'El Paso, TX',
1915759 => 'El Paso, TX',
1915760 => 'El Paso, TX',
1915764 => 'Fabens, TX',
191577 => 'El Paso, TX',
1915781 => 'El Paso, TX',
1915790 => 'El Paso, TX',
1915821 => 'El Paso, TX',
1915833 => 'El Paso, TX',
1915838 => 'El Paso, TX',
1915842 => 'El Paso, TX',
1915843 => 'El Paso, TX',
1915845 => 'El Paso, TX',
1915849 => 'El Paso, TX',
191585 => 'El Paso, TX',
1915860 => 'El Paso, TX',
1915872 => 'El Paso, TX',
1915875 => 'El Paso, TX',
1915877 => 'Canutillo, TX',
1915881 => 'El Paso, TX',
1915886 => 'Anthony, TX',
1915921 => 'El Paso, TX',
1916 => 'California',
1916285 => 'Sacramento, CA',
1916294 => 'Folsom, CA',
1916315 => 'Rocklin, CA',
1916325 => 'Sacramento, CA',
1916333 => 'Sacramento, CA',
1916338 => 'Sacramento, CA',
1916351 => 'Folsom, CA',
1916353 => 'Folsom, CA',
1916354 => 'Rancho Murieta, CA',
1916355 => 'Folsom, CA',
1916358 => 'El Dorado Hills, CA',
191636 => 'Sacramento, CA',
191637 => 'West Sacramento, CA',
1916379 => 'Sacramento, CA',
1916381 => 'Sacramento, CA',
1916383 => 'Sacramento, CA',
1916386 => 'Sacramento, CA',
1916387 => 'Sacramento, CA',
1916388 => 'Sacramento, CA',
191639 => 'Sacramento, CA',
1916408 => 'Lincoln, CA',
1916419 => 'Sacramento, CA',
191642 => 'Sacramento, CA',
1916434 => 'Lincoln, CA',
1916435 => 'Rocklin, CA',
191644 => 'Sacramento, CA',
191645 => 'Sacramento, CA',
1916473 => 'Sacramento, CA',
1916476 => 'Sacramento, CA',
1916478 => 'Elk Grove, CA',
191648 => 'Sacramento, CA',
1916492 => 'Sacramento, CA',
1916498 => 'Sacramento, CA',
1916514 => 'Sacramento, CA',
1916515 => 'Sacramento, CA',
1916525 => 'Sacramento, CA',
1916537 => 'Carmichael, CA',
1916543 => 'Lincoln, CA',
1916550 => 'Sacramento, CA',
1916564 => 'Sacramento, CA',
1916565 => 'Sacramento, CA',
1916567 => 'Sacramento, CA',
1916568 => 'Sacramento, CA',
1916608 => 'Folsom, CA',
1916609 => 'Carmichael, CA',
1916614 => 'Sacramento, CA',
1916624 => 'Rocklin, CA',
1916625 => 'Rocklin, CA',
1916630 => 'Rocklin, CA',
1916631 => 'Rancho Cordova, CA',
1916632 => 'Rocklin, CA',
1916635 => 'Rancho Cordova, CA',
1916638 => 'Rancho Cordova, CA',
1916641 => 'Sacramento, CA',
1916645 => 'Lincoln, CA',
1916646 => 'Sacramento, CA',
1916648 => 'Sacramento, CA',
1916649 => 'Sacramento, CA',
1916652 => 'Loomis, CA',
1916660 => 'Loomis, CA',
1916663 => 'Newcastle, CA',
1916681 => 'Sacramento, CA',
1916682 => 'Sacramento, CA',
1916683 => 'Elk Grove, CA',
1916684 => 'Elk Grove, CA',
1916685 => 'Elk Grove, CA',
1916686 => 'Elk Grove, CA',
1916687 => 'Wilton, CA',
1916688 => 'Sacramento, CA',
1916689 => 'Sacramento, CA',
1916691 => 'Elk Grove, CA',
1916706 => 'Sacramento, CA',
1916714 => 'Elk Grove, CA',
191672 => 'Citrus Heights, CA',
191673 => 'Sacramento, CA',
1916771 => 'Roseville, CA',
1916772 => 'Roseville, CA',
1916773 => 'Roseville, CA',
1916774 => 'Roseville, CA',
1916776 => 'Walnut Grove, CA',
1916777 => 'Isleton, CA',
191678 => 'Roseville, CA',
1916808 => 'Sacramento, CA',
1916817 => 'Folsom, CA',
1916851 => 'Rancho Cordova, CA',
1916852 => 'Rancho Cordova, CA',
1916853 => 'Rancho Cordova, CA',
1916858 => 'Rancho Cordova, CA',
1916863 => 'Fair Oaks, CA',
1916874 => 'Sacramento, CA',
1916875 => 'Sacramento, CA',
191692 => 'Sacramento, CA',
1916930 => 'Sacramento, CA',
1916932 => 'Folsom, CA',
1916933 => 'El Dorado Hills, CA',
1916939 => 'El Dorado Hills, CA',
1916941 => 'El Dorado Hills, CA',
1916944 => 'Carmichael, CA',
1916962 => 'Fair Oaks, CA',
1916965 => 'Fair Oaks, CA',
1916966 => 'Fair Oaks, CA',
1916967 => 'Fair Oaks, CA',
1916972 => 'Sacramento, CA',
1916973 => 'Sacramento, CA',
1916978 => 'Sacramento, CA',
1916979 => 'Sacramento, CA',
1916983 => 'Folsom, CA',
1916984 => 'Folsom, CA',
1916985 => 'Folsom, CA',
1916987 => 'Orangevale, CA',
1916988 => 'Orangevale, CA',
1916989 => 'Orangevale, CA',
1916991 => 'Rio Linda, CA',
1916992 => 'Rio Linda, CA',
1917 => 'New York',
1918 => 'Oklahoma',
1918207 => 'Tahlequah, OK',
1918224 => 'Sapulpa, OK',
1918225 => 'Cushing, OK',
1918227 => 'Sapulpa, OK',
1918234 => 'Tulsa, OK',
1918241 => 'Sand Springs, OK',
1918245 => 'Sand Springs, OK',
1918246 => 'Sand Springs, OK',
1918249 => 'Tulsa, OK',
1918250 => 'Tulsa, OK',
1918251 => 'Broken Arrow, OK',
1918252 => 'Tulsa, OK',
1918253 => 'Jay, OK',
1918254 => 'Tulsa, OK',
1918256 => 'Vinita, OK',
1918257 => 'Afton, OK',
1918258 => 'Broken Arrow, OK',
1918259 => 'Broken Arrow, OK',
1918266 => 'Catoosa, OK',
1918267 => 'Beggs, OK',
1918270 => 'Tulsa, OK',
1918272 => 'Owasso, OK',
1918273 => 'Nowata, OK',
1918274 => 'Owasso, OK',
1918279 => 'Coweta, OK',
1918283 => 'Claremore, OK',
1918286 => 'Broken Arrow, OK',
1918287 => 'Pawhuska, OK',
1918289 => 'Tulsa, OK',
1918291 => 'Glenpool, OK',
1918293 => 'Tulsa, OK',
1918294 => 'Tulsa, OK',
1918295 => 'Tulsa, OK',
1918297 => 'Hartshorne, OK',
1918298 => 'Tulsa, OK',
1918302 => 'McAlester, OK',
1918307 => 'Tulsa, OK',
1918321 => 'Kiefer, OK',
1918331 => 'Bartlesville, OK',
1918333 => 'Bartlesville, OK',
1918335 => 'Bartlesville, OK',
1918336 => 'Bartlesville, OK',
1918337 => 'Bartlesville, OK',
1918341 => 'Claremore, OK',
1918342 => 'Claremore, OK',
1918343 => 'Claremore, OK',
1918352 => 'Drumright, OK',
1918355 => 'Broken Arrow, OK',
1918357 => 'Broken Arrow, OK',
1918358 => 'Cleveland, OK',
1918366 => 'Bixby, OK',
1918367 => 'Bristow, OK',
1918369 => 'Bixby, OK',
1918371 => 'Collinsville, OK',
1918376 => 'Owasso, OK',
1918382 => 'Tulsa, OK',
1918392 => 'Tulsa, OK',
1918394 => 'Tulsa, OK',
1918396 => 'Skiatook, OK',
1918398 => 'Tulsa, OK',
1918420 => 'McAlester, OK',
1918421 => 'McAlester, OK',
1918422 => 'Colcord, OK',
1918423 => 'McAlester, OK',
1918425 => 'Tulsa, OK',
1918426 => 'McAlester, OK',
1918427 => 'Muldrow, OK',
1918429 => 'McAlester, OK',
1918431 => 'Tahlequah, OK',
1918434 => 'Salina, OK',
1918436 => 'Pocola, OK',
1918437 => 'Tulsa, OK',
1918438 => 'Tulsa, OK',
1918439 => 'Tulsa, OK',
1918443 => 'Oologah, OK',
1918445 => 'Tulsa, OK',
1918446 => 'Tulsa, OK',
1918447 => 'Tulsa, OK',
1918449 => 'Broken Arrow, OK',
1918451 => 'Broken Arrow, OK',
1918453 => 'Tahlequah, OK',
1918455 => 'Broken Arrow, OK',
1918456 => 'Tahlequah, OK',
1918458 => 'Tahlequah, OK',
1918459 => 'Tulsa, OK',
1918461 => 'Tulsa, OK',
1918465 => 'Wilburton, OK',
1918473 => 'Checotah, OK',
1918476 => 'Chouteau, OK',
1918477 => 'Tulsa, OK',
1918478 => 'Fort Gibson, OK',
1918479 => 'Locust Grove, OK',
1918481 => 'Tulsa, OK',
1918482 => 'Haskell, OK',
1918485 => 'Wagoner, OK',
1918486 => 'Coweta, OK',
1918488 => 'Tulsa, OK',
191849 => 'Tulsa, OK',
1918502 => 'Tulsa, OK',
1918534 => 'Dewey, OK',
1918540 => 'Miami, OK',
1918542 => 'Miami, OK',
1918543 => 'Inola, OK',
1918567 => 'Talihina, OK',
1918569 => 'Clayton, OK',
1918574 => 'Tulsa, OK',
1918579 => 'Tulsa, OK',
191858 => 'Tulsa, OK',
1918591 => 'Tulsa, OK',
1918592 => 'Tulsa, OK',
1918594 => 'Tulsa, OK',
1918596 => 'Tulsa, OK',
1918599 => 'Tulsa, OK',
1918609 => 'Owasso, OK',
1918610 => 'Tulsa, OK',
1918619 => 'Tulsa, OK',
1918622 => 'Tulsa, OK',
1918623 => 'Okemah, OK',
1918627 => 'Tulsa, OK',
1918628 => 'Tulsa, OK',
1918647 => 'Poteau, OK',
1918649 => 'Poteau, OK',
1918652 => 'Henryetta, OK',
1918653 => 'Heavener, OK',
1918660 => 'Tulsa, OK',
1918663 => 'Tulsa, OK',
1918664 => 'Tulsa, OK',
1918665 => 'Tulsa, OK',
191868 => 'Muskogee, OK',
1918689 => 'Eufaula, OK',
1918696 => 'Stilwell, OK',
1918712 => 'Tulsa, OK',
1918723 => 'Westville, OK',
1918728 => 'Tulsa, OK',
191874 => 'Tulsa, OK',
1918756 => 'Okmulgee, OK',
1918758 => 'Okmulgee, OK',
1918762 => 'Pawnee, OK',
1918770 => 'Tulsa, OK',
1918773 => 'Vian, OK',
1918775 => 'Sallisaw, OK',
1918779 => 'Tulsa, OK',
1918786 => 'Grove, OK',
1918787 => 'Grove, OK',
1918789 => 'Chelsea, OK',
1918794 => 'Tulsa, OK',
1918806 => 'Broken Arrow, OK',
1918824 => 'Pryor Creek, OK',
1918825 => 'Pryor Creek, OK',
1918828 => 'Tulsa, OK',
1918832 => 'Tulsa, OK',
1918834 => 'Tulsa, OK',
1918835 => 'Tulsa, OK',
1918836 => 'Tulsa, OK',
1918838 => 'Tulsa, OK',
1918865 => 'Mannford, OK',
1918868 => 'Kansas, OK',
1918872 => 'Broken Arrow, OK',
1918877 => 'Tulsa, OK',
1918885 => 'Hominy, OK',
1918895 => 'Tulsa, OK',
1918933 => 'Tulsa, OK',
1918938 => 'Tulsa, OK',
1918949 => 'Tulsa, OK',
1918962 => 'Spiro, OK',
1918967 => 'Stigler, OK',
1918968 => 'Stroud, OK',
1919 => 'North Carolina',
1919207 => 'Benson, NC',
1919209 => 'Smithfield, NC',
1919212 => 'Raleigh, NC',
1919217 => 'Knightdale, NC',
1919220 => 'Durham, NC',
1919231 => 'Raleigh, NC',
1919232 => 'Raleigh, NC',
1919237 => 'Durham, NC',
1919240 => 'Chapel Hill, NC',
1919242 => 'Fremont, NC',
1919245 => 'Hillsborough, NC',
1919250 => 'Raleigh, NC',
1919251 => 'Durham, NC',
1919255 => 'Raleigh, NC',
1919256 => 'Raleigh, NC',
1919258 => 'Broadway, NC',
1919261 => 'Knightdale, NC',
1919266 => 'Knightdale, NC',
1919267 => 'Apex, NC',
1919269 => 'Zebulon, NC',
1919284 => 'Kenly, NC',
1919286 => 'Durham, NC',
1919303 => 'Apex, NC',
1919304 => 'Mebane, NC',
1919309 => 'Durham, NC',
1919313 => 'Durham, NC',
1919319 => 'Cary, NC',
1919331 => 'Angier, NC',
1919340 => 'Louisburg, NC',
1919350 => 'Raleigh, NC',
1919359 => 'Clayton, NC',
1919361 => 'Durham, NC',
1919362 => 'Apex, NC',
1919363 => 'Apex, NC',
1919365 => 'Wendell, NC',
1919366 => 'Wendell, NC',
1919367 => 'Apex, NC',
1919380 => 'Cary, NC',
1919381 => 'Durham, NC',
1919382 => 'Durham, NC',
1919383 => 'Durham, NC',
1919387 => 'Apex, NC',
1919388 => 'Cary, NC',
1919401 => 'Durham, NC',
1919402 => 'Durham, NC',
1919403 => 'Durham, NC',
1919404 => 'Zebulon, NC',
1919405 => 'Durham, NC',
1919416 => 'Durham, NC',
1919419 => 'Durham, NC',
1919420 => 'Raleigh, NC',
1919424 => 'Raleigh, NC',
1919453 => 'Wake Forest, NC',
191946 => 'Cary, NC',
1919470 => 'Durham, NC',
1919471 => 'Durham, NC',
1919477 => 'Durham, NC',
1919479 => 'Durham, NC',
1919481 => 'Cary, NC',
1919484 => 'Durham, NC',
1919489 => 'Durham, NC',
1919490 => 'Durham, NC',
1919493 => 'Durham, NC',
1919494 => 'Franklinton, NC',
1919496 => 'Louisburg, NC',
1919497 => 'Louisburg, NC',
1919499 => 'Sanford, NC',
1919510 => 'Raleigh, NC',
1919515 => 'Raleigh, NC',
1919518 => 'Raleigh, NC',
1919528 => 'Creedmoor, NC',
1919530 => 'Durham, NC',
1919542 => 'Pittsboro, NC',
1919544 => 'Durham, NC',
1919545 => 'Pittsboro, NC',
1919550 => 'Clayton, NC',
1919552 => 'Fuquay-Varina, NC',
1919553 => 'Clayton, NC',
1919554 => 'Wake Forest, NC',
1919556 => 'Wake Forest, NC',
1919557 => 'Fuquay-Varina, NC',
1919560 => 'Durham, NC',
1919562 => 'Wake Forest, NC',
1919563 => 'Mebane, NC',
1919567 => 'Fuquay-Varina, NC',
1919571 => 'Raleigh, NC',
1919572 => 'Durham, NC',
1919575 => 'Butner, NC',
1919577 => 'Fuquay-Varina, NC',
1919580 => 'Goldsboro, NC',
1919585 => 'Clayton, NC',
1919596 => 'Durham, NC',
1919598 => 'Durham, NC',
1919603 => 'Oxford, NC',
1919620 => 'Durham, NC',
1919639 => 'Angier, NC',
1919644 => 'Hillsborough, NC',
1919658 => 'Mount Olive, NC',
1919660 => 'Durham, NC',
1919661 => 'Garner, NC',
1919662 => 'Garner, NC',
1919663 => 'Siler City, NC',
1919668 => 'Durham, NC',
1919676 => 'Raleigh, NC',
1919677 => 'Cary, NC',
1919678 => 'Cary, NC',
191968 => 'Durham, NC',
1919689 => 'Goldsboro, NC',
1919690 => 'Oxford, NC',
1919693 => 'Oxford, NC',
1919708 => 'Sanford, NC',
1919718 => 'Sanford, NC',
1919731 => 'Goldsboro, NC',
1919732 => 'Hillsborough, NC',
1919733 => 'Raleigh, NC',
1919734 => 'Goldsboro, NC',
1919735 => 'Goldsboro, NC',
1919736 => 'Goldsboro, NC',
1919739 => 'Goldsboro, NC',
1919742 => 'Siler City, NC',
1919751 => 'Goldsboro, NC',
1919755 => 'Raleigh, NC',
1919772 => 'Garner, NC',
1919773 => 'Garner, NC',
1919774 => 'Sanford, NC',
1919775 => 'Sanford, NC',
1919776 => 'Sanford, NC',
1919777 => 'Sanford, NC',
1919778 => 'Goldsboro, NC',
1919779 => 'Garner, NC',
191978 => 'Raleigh, NC',
1919790 => 'Raleigh, NC',
1919791 => 'Raleigh, NC',
1919792 => 'Raleigh, NC',
1919803 => 'Raleigh, NC',
1919806 => 'Durham, NC',
1919821 => 'Raleigh, NC',
1919828 => 'Raleigh, NC',
1919829 => 'Raleigh, NC',
191983 => 'Raleigh, NC',
191984 => 'Raleigh, NC',
1919840 => 'Morrisville, NC',
1919843 => 'Chapel Hill, NC',
1919850 => 'Raleigh, NC',
1919855 => 'Raleigh, NC',
1919856 => 'Raleigh, NC',
1919861 => 'Raleigh, NC',
1919862 => 'Raleigh, NC',
1919863 => 'Raleigh, NC',
191987 => 'Raleigh, NC',
1919881 => 'Raleigh, NC',
1919890 => 'Raleigh, NC',
1919894 => 'Benson, NC',
1919896 => 'Raleigh, NC',
1919918 => 'Chapel Hill, NC',
1919928 => 'Chapel Hill, NC',
1919929 => 'Chapel Hill, NC',
1919932 => 'Chapel Hill, NC',
1919933 => 'Chapel Hill, NC',
1919934 => 'Smithfield, NC',
1919936 => 'Princeton, NC',
1919938 => 'Smithfield, NC',
1919941 => 'Durham, NC',
1919942 => 'Chapel Hill, NC',
1919954 => 'Raleigh, NC',
1919956 => 'Durham, NC',
1919957 => 'Durham, NC',
191996 => 'Chapel Hill, NC',
1919963 => 'Four Oaks, NC',
1919965 => 'Selma, NC',
1919981 => 'Raleigh, NC',
1919989 => 'Smithfield, NC',
1920 => 'Wisconsin',
1920206 => 'Watertown, WI',
1920208 => 'Sheboygan, WI',
1920223 => 'Oshkosh, WI',
192023 => 'Oshkosh, WI',
1920261 => 'Watertown, WI',
1920262 => 'Watertown, WI',
1920269 => 'Lomira, WI',
1920288 => 'Green Bay, WI',
1920294 => 'Green Lake, WI',
1920295 => 'Princeton, WI',
1920303 => 'Oshkosh, WI',
1920320 => 'Manitowoc, WI',
1920322 => 'Fond du Lac, WI',
1920324 => 'Waupun, WI',
1920326 => 'Randolph, WI',
1920330 => 'De Pere, WI',
1920336 => 'De Pere, WI',
1920337 => 'De Pere, WI',
1920338 => 'De Pere, WI',
1920339 => 'De Pere, WI',
1920347 => 'De Pere, WI',
1920356 => 'Beaver Dam, WI',
1920361 => 'Berlin, WI',
1920380 => 'Appleton, WI',
1920386 => 'Juneau, WI',
1920387 => 'Mayville, WI',
1920388 => 'Kewaunee, WI',
1920398 => 'Markesan, WI',
1920405 => 'Green Bay, WI',
1920406 => 'Green Bay, WI',
1920424 => 'Oshkosh, WI',
1920426 => 'Oshkosh, WI',
192043 => 'Green Bay, WI',
1920446 => 'Fremont, WI',
1920448 => 'Green Bay, WI',
1920451 => 'Sheboygan, WI',
1920452 => 'Sheboygan, WI',
1920457 => 'Sheboygan, WI',
1920458 => 'Sheboygan, WI',
1920459 => 'Sheboygan, WI',
1920465 => 'Green Bay, WI',
1920467 => 'Sheboygan Falls, WI',
1920468 => 'Green Bay, WI',
1920469 => 'Green Bay, WI',
1920478 => 'Waterloo, WI',
1920485 => 'Horicon, WI',
1920487 => 'Algoma, WI',
192049 => 'Green Bay, WI',
1920532 => 'Wrightstown, WI',
1920533 => 'Campbellsport, WI',
1920544 => 'Green Bay, WI',
1920563 => 'Fort Atkinson, WI',
1920564 => 'Oostburg, WI',
1920568 => 'Fort Atkinson, WI',
1920574 => 'Appleton, WI',
1920582 => 'Winneconne, WI',
1920593 => 'Green Bay, WI',
1920596 => 'Manawa, WI',
1920622 => 'Wild Rose, WI',
1920623 => 'Columbus, WI',
1920648 => 'Lake Mills, WI',
1920652 => 'Manitowoc, WI',
1920662 => 'Green Bay, WI',
1920668 => 'Cedar Grove, WI',
1920674 => 'Jefferson, WI',
1920682 => 'Manitowoc, WI',
1920683 => 'Manitowoc, WI',
1920684 => 'Manitowoc, WI',
1920685 => 'Omro, WI',
1920686 => 'Manitowoc, WI',
1920693 => 'Cleveland, WI',
1920699 => 'Johnson Creek, WI',
1920720 => 'Neenah, WI',
1920722 => 'Neenah, WI',
1920725 => 'Neenah, WI',
1920727 => 'Neenah, WI',
1920729 => 'Neenah, WI',
192073 => 'Appleton, WI',
1920743 => 'Sturgeon Bay, WI',
1920746 => 'Sturgeon Bay, WI',
1920748 => 'Ripon, WI',
1920749 => 'Appleton, WI',
1920751 => 'Neenah, WI',
1920755 => 'Mishicot, WI',
1920756 => 'Brillion, WI',
1920757 => 'Greenville, WI',
1920758 => 'Manitowoc, WI',
1920759 => 'Kaukauna, WI',
1920766 => 'Kaukauna, WI',
1920775 => 'Valders, WI',
1920779 => 'Hortonville, WI',
1920787 => 'Wautoma, WI',
1920793 => 'Two Rivers, WI',
1920794 => 'Two Rivers, WI',
1920803 => 'Sheboygan, WI',
1920822 => 'Pulaski, WI',
1920826 => 'Abrams, WI',
1920830 => 'Appleton, WI',
1920831 => 'Appleton, WI',
1920832 => 'Appleton, WI',
1920833 => 'Seymour, WI',
1920834 => 'Oconto, WI',
1920836 => 'Larsen, WI',
1920837 => 'Casco, WI',
1920839 => 'Baileys Harbor, WI',
1920842 => 'Suring, WI',
1920845 => 'Luxemburg, WI',
1920846 => 'Oconto Falls, WI',
1920849 => 'Chilton, WI',
1920853 => 'Hilbert, WI',
1920854 => 'Sister Bay, WI',
1920855 => 'Gillett, WI',
1920863 => 'Denmark, WI',
1920864 => 'Greenleaf, WI',
1920866 => 'New Franken, WI',
1920867 => 'Weyauwega, WI',
1920868 => 'Fish Creek, WI',
1920869 => 'Oneida, WI',
1920876 => 'Elkhart Lake, WI',
1920882 => 'Appleton, WI',
1920884 => 'Green Bay, WI',
1920885 => 'Beaver Dam, WI',
1920886 => 'Neenah, WI',
1920887 => 'Beaver Dam, WI',
1920892 => 'Plymouth, WI',
1920893 => 'Plymouth, WI',
1920894 => 'Kiel, WI',
1920897 => 'Coleman, WI',
1920898 => 'New Holstein, WI',
1920907 => 'Fond du Lac, WI',
192092 => 'Fond du Lac, WI',
1920928 => 'Fox Lake, WI',
1920933 => 'Fond du Lac, WI',
1920954 => 'Appleton, WI',
1920964 => 'De Pere, WI',
1920965 => 'Green Bay, WI',
1920968 => 'Appleton, WI',
1920969 => 'Neenah, WI',
1920982 => 'New London, WI',
1920983 => 'De Pere, WI',
1920984 => 'Black Creek, WI',
1920992 => 'Rio, WI',
1920993 => 'Appleton, WI',
1920994 => 'Random Lake, WI',
1920996 => 'Appleton, WI',
1920997 => 'Appleton, WI',
1925 => 'California',
1925210 => 'Walnut Creek, CA',
1925225 => 'Pleasanton, CA',
1925227 => 'Pleasanton, CA',
1925228 => 'Martinez, CA',
1925229 => 'Martinez, CA',
1925240 => 'Brentwood, CA',
1925242 => 'San Ramon, CA',
1925243 => 'Livermore, CA',
1925244 => 'San Ramon, CA',
1925245 => 'Livermore, CA',
1925249 => 'Pleasanton, CA',
1925251 => 'Pleasanton, CA',
1925252 => 'Pittsburg, CA',
1925253 => 'Orinda, CA',
1925254 => 'Orinda, CA',
1925256 => 'Walnut Creek, CA',
1925258 => 'Orinda, CA',
1925274 => 'Walnut Creek, CA',
1925275 => 'San Ramon, CA',
1925277 => 'San Ramon, CA',
1925280 => 'Walnut Creek, CA',
1925283 => 'Lafayette, CA',
1925284 => 'Lafayette, CA',
1925287 => 'Walnut Creek, CA',
1925288 => 'Concord, CA',
1925292 => 'Livermore, CA',
1925294 => 'Livermore, CA',
1925295 => 'Walnut Creek, CA',
1925296 => 'Walnut Creek, CA',
1925299 => 'Lafayette, CA',
1925308 => 'Brentwood, CA',
1925313 => 'Martinez, CA',
1925314 => 'Danville, CA',
1925335 => 'Martinez, CA',
1925355 => 'San Ramon, CA',
1925356 => 'Concord, CA',
1925363 => 'Concord, CA',
1925370 => 'Martinez, CA',
1925371 => 'Livermore, CA',
1925372 => 'Martinez, CA',
1925373 => 'Livermore, CA',
1925376 => 'Moraga, CA',
1925377 => 'Moraga, CA',
1925416 => 'Pleasanton, CA',
1925417 => 'Pleasanton, CA',
1925426 => 'Pleasanton, CA',
1925427 => 'Pittsburg, CA',
1925432 => 'Pittsburg, CA',
1925439 => 'Pittsburg, CA',
1925443 => 'Livermore, CA',
1925447 => 'Livermore, CA',
1925449 => 'Livermore, CA',
1925454 => 'Livermore, CA',
1925455 => 'Livermore, CA',
1925456 => 'Livermore, CA',
1925458 => 'Bay Point, CA',
1925460 => 'Pleasanton, CA',
1925461 => 'Pleasanton, CA',
1925462 => 'Pleasanton, CA',
1925463 => 'Pleasanton, CA',
1925469 => 'Pleasanton, CA',
1925472 => 'Walnut Creek, CA',
1925473 => 'Pittsburg, CA',
1925478 => 'Walnut Creek, CA',
1925484 => 'Pleasanton, CA',
1925485 => 'Pleasanton, CA',
1925513 => 'Brentwood, CA',
1925516 => 'Brentwood, CA',
1925521 => 'Concord, CA',
1925522 => 'Antioch, CA',
1925543 => 'San Ramon, CA',
1925551 => 'Dublin, CA',
1925556 => 'Dublin, CA',
1925560 => 'Dublin, CA',
1925600 => 'Pleasanton, CA',
1925603 => 'Concord, CA',
1925606 => 'Livermore, CA',
1925609 => 'Concord, CA',
1925625 => 'Oakley, CA',
1925631 => 'Moraga, CA',
1925634 => 'Brentwood, CA',
1925648 => 'Danville, CA',
1925671 => 'Concord, CA',
1925672 => 'Clayton, CA',
1925673 => 'Clayton, CA',
1925674 => 'Concord, CA',
1925676 => 'Concord, CA',
1925679 => 'Oakley, CA',
192568 => 'Concord, CA',
1925684 => 'Bethel Island, CA',
1925691 => 'Concord, CA',
1925706 => 'Antioch, CA',
1925734 => 'Pleasanton, CA',
1925735 => 'San Ramon, CA',
1925736 => 'Danville, CA',
1925743 => 'Danville, CA',
1925754 => 'Antioch, CA',
1925755 => 'Antioch, CA',
1925756 => 'Antioch, CA',
1925757 => 'Antioch, CA',
1925776 => 'Antioch, CA',
1925777 => 'Antioch, CA',
1925778 => 'Antioch, CA',
1925779 => 'Antioch, CA',
1925798 => 'Concord, CA',
1925803 => 'Dublin, CA',
1925813 => 'Antioch, CA',
1925820 => 'Danville, CA',
1925825 => 'Concord, CA',
1925827 => 'Concord, CA',
1925828 => 'Dublin, CA',
1925829 => 'Dublin, CA',
1925830 => 'San Ramon, CA',
1925833 => 'Dublin, CA',
1925837 => 'Danville, CA',
1925846 => 'Pleasanton, CA',
1925847 => 'Pleasanton, CA',
1925849 => 'Concord, CA',
1925866 => 'San Ramon, CA',
1925875 => 'Dublin, CA',
1925906 => 'Walnut Creek, CA',
1925924 => 'Pleasanton, CA',
192593 => 'Walnut Creek, CA',
1925931 => 'Pleasanton, CA',
1925943 => 'Walnut Creek, CA',
1925944 => 'Walnut Creek, CA',
1925945 => 'Walnut Creek, CA',
1925946 => 'Walnut Creek, CA',
1925947 => 'Walnut Creek, CA',
1925952 => 'Walnut Creek, CA',
1925954 => 'Walnut Creek, CA',
1925957 => 'Martinez, CA',
1925960 => 'Livermore, CA',
1925962 => 'Lafayette, CA',
1925969 => 'Concord, CA',
1925978 => 'Antioch, CA',
1925979 => 'Walnut Creek, CA',
1925988 => 'Walnut Creek, CA',
1928 => 'Arizona',
1928203 => 'Sedona, AZ',
1928204 => 'Sedona, AZ',
1928213 => 'Flagstaff, AZ',
1928214 => 'Flagstaff, AZ',
1928226 => 'Flagstaff, AZ',
1928237 => 'Prescott, AZ',
1928282 => 'Sedona, AZ',
1928283 => 'Tuba City, AZ',
1928284 => 'Sedona, AZ',
1928289 => 'Winslow, AZ',
1928314 => 'Yuma, AZ',
1928317 => 'Yuma, AZ',
1928329 => 'Yuma, AZ',
1928333 => 'Springerville, AZ',
1928337 => 'St. Johns, AZ',
1928338 => 'Whiteriver, AZ',
1928341 => 'Yuma, AZ',
1928342 => 'Yuma, AZ',
1928343 => 'Yuma, AZ',
1928344 => 'Yuma, AZ',
1928345 => 'Yuma, AZ',
1928348 => 'Safford, AZ',
1928367 => 'Pinetop, AZ',
1928368 => 'Lakeside, AZ',
1928373 => 'Yuma, AZ',
1928425 => 'Globe, AZ',
1928428 => 'Safford, AZ',
1928442 => 'Prescott, AZ',
1928443 => 'Prescott, AZ',
1928445 => 'Prescott, AZ',
1928453 => 'Lake Havasu City, AZ',
1928468 => 'Payson, AZ',
1928472 => 'Payson, AZ',
1928474 => 'Payson, AZ',
1928475 => 'San Carlos, AZ',
1928476 => 'Pine, AZ',
1928505 => 'Lake Havasu City, AZ',
1928522 => 'Flagstaff, AZ',
1928524 => 'Holbrook, AZ',
1928526 => 'Flagstaff, AZ',
1928527 => 'Flagstaff, AZ',
1928532 => 'Show Low, AZ',
1928536 => 'Snowflake, AZ',
1928537 => 'Show Low, AZ',
1928541 => 'Prescott, AZ',
1928556 => 'Flagstaff, AZ',
1928565 => 'Golden Valley, AZ',
1928567 => 'Camp Verde, AZ',
1928607 => 'Flagstaff, AZ',
1928634 => 'Cottonwood, AZ',
1928635 => 'Williams, AZ',
1928636 => 'Chino Valley, AZ',
1928638 => 'Grand Canyon Village, AZ',
1928639 => 'Cottonwood, AZ',
1928645 => 'Page, AZ',
1928649 => 'Cottonwood, AZ',
1928669 => 'Parker, AZ',
1928674 => 'Chinle, AZ',
1928680 => 'Lake Havasu City, AZ',
1928681 => 'Kingman, AZ',
1928684 => 'Wickenburg, AZ',
1928692 => 'Kingman, AZ',
1928697 => 'Kayenta, AZ',
1928699 => 'Flagstaff, AZ',
1928704 => 'Bullhead City, AZ',
1928708 => 'Prescott, AZ',
1928710 => 'Prescott, AZ',
1928714 => 'Flagstaff, AZ',
1928717 => 'Prescott, AZ',
1928718 => 'Kingman, AZ',
1928726 => 'Yuma, AZ',
1928729 => 'Fort Defiance, AZ',
1928753 => 'Kingman, AZ',
1928754 => 'Bullhead City, AZ',
1928757 => 'Kingman, AZ',
1928758 => 'Bullhead City, AZ',
1928759 => 'Prescott Valley, AZ',
1928763 => 'Bullhead City, AZ',
1928764 => 'Lake Havasu City, AZ',
1928771 => 'Prescott, AZ',
1928772 => 'Prescott Valley, AZ',
1928773 => 'Flagstaff, AZ',
1928774 => 'Flagstaff, AZ',
1928775 => 'Prescott Valley, AZ',
1928776 => 'Prescott, AZ',
1928777 => 'Prescott, AZ',
1928778 => 'Prescott, AZ',
1928779 => 'Flagstaff, AZ',
1928782 => 'Yuma, AZ',
1928783 => 'Yuma, AZ',
1928785 => 'Wellton, AZ',
1928788 => 'Fort Mohave, AZ',
1928853 => 'Flagstaff, AZ',
1928854 => 'Lake Havasu City, AZ',
1928855 => 'Lake Havasu City, AZ',
1928859 => 'Salome, AZ',
1928865 => 'Clifton, AZ',
1928871 => 'Window Rock, AZ',
1928899 => 'Prescott, AZ',
1928927 => 'Quartzsite, AZ',
1929 => 'New York',
1930 => 'Indiana',
1931 => 'Tennessee',
1931221 => 'Clarksville, TN',
1931223 => 'Columbia, TN',
1931232 => 'Dover, TN',
1931243 => 'Celina, TN',
1931245 => 'Clarksville, TN',
1931268 => 'Gainesboro, TN',
1931270 => 'Lewisburg, TN',
1931289 => 'Erin, TN',
1931296 => 'Waverly, TN',
1931320 => 'Clarksville, TN',
1931358 => 'Clarksville, TN',
1931359 => 'Lewisburg, TN',
1931363 => 'Pulaski, TN',
1931364 => 'Chapel Hill, TN',
1931372 => 'Cookeville, TN',
1931379 => 'Mount Pleasant, TN',
1931380 => 'Columbia, TN',
1931381 => 'Columbia, TN',
1931388 => 'Columbia, TN',
1931393 => 'Tullahoma, TN',
1931424 => 'Pulaski, TN',
1931427 => 'Ardmore, TN',
1931431 => 'Clarksville, TN',
1931432 => 'Cookeville, TN',
1931433 => 'Fayetteville, TN',
1931438 => 'Fayetteville, TN',
1931454 => 'Tullahoma, TN',
1931455 => 'Tullahoma, TN',
1931456 => 'Crossville, TN',
1931461 => 'Tullahoma, TN',
1931473 => 'McMinnville, TN',
1931474 => 'McMinnville, TN',
1931484 => 'Crossville, TN',
1931486 => 'Spring Hill, TN',
1931490 => 'Columbia, TN',
1931503 => 'Clarksville, TN',
1931507 => 'McMinnville, TN',
1931520 => 'Cookeville, TN',
1931525 => 'Cookeville, TN',
1931526 => 'Cookeville, TN',
1931528 => 'Cookeville, TN',
1931535 => 'New Johnsonville, TN',
1931537 => 'Cookeville, TN',
1931542 => 'Clarksville, TN',
1931551 => 'Clarksville, TN',
1931552 => 'Clarksville, TN',
1931553 => 'Clarksville, TN',
1931582 => 'McEwen, TN',
1931589 => 'Linden, TN',
1931592 => 'Tracy City, TN',
1931598 => 'Sewanee, TN',
1931645 => 'Clarksville, TN',
1931647 => 'Clarksville, TN',
1931648 => 'Clarksville, TN',
1931668 => 'McMinnville, TN',
1931670 => 'Lyles, TN',
1931680 => 'Shelbyville, TN',
1931684 => 'Shelbyville, TN',
1931685 => 'Shelbyville, TN',
1931686 => 'Rock Island, TN',
1931707 => 'Crossville, TN',
1931722 => 'Waynesboro, TN',
1931723 => 'Manchester, TN',
1931724 => 'Collinwood, TN',
1931728 => 'Manchester, TN',
1931729 => 'Centerville, TN',
1931738 => 'Sparta, TN',
1931759 => 'Lynchburg, TN',
1931761 => 'Sparta, TN',
1931762 => 'Lawrenceburg, TN',
1931766 => 'Lawrenceburg, TN',
1931779 => 'Gruetli-Laager, TN',
1931787 => 'Crossville, TN',
1931788 => 'Crossville, TN',
1931796 => 'Hohenwald, TN',
1931802 => 'Clarksville, TN',
1931815 => 'McMinnville, TN',
1931823 => 'Livingston, TN',
1931836 => 'Sparta, TN',
1931837 => 'Sparta, TN',
1931839 => 'Monterey, TN',
1931840 => 'Columbia, TN',
1931852 => 'Leoma, TN',
1931853 => 'Loretto, TN',
1931858 => 'Baxter, TN',
1931863 => 'Clarkrange, TN',
1931864 => 'Byrdstown, TN',
1931879 => 'Jamestown, TN',
1931905 => 'Clarksville, TN',
1931906 => 'Clarksville, TN',
1931920 => 'Clarksville, TN',
1931924 => 'Monteagle, TN',
1931946 => 'Spencer, TN',
1931962 => 'Winchester, TN',
1931967 => 'Winchester, TN',
1934 => 'New York, NY',
1936 => 'Texas',
1936231 => 'Conroe, TX',
1936254 => 'Timpson, TX',
1936257 => 'Dayton, TX',
1936258 => 'Dayton, TX',
1936264 => 'Conroe, TX',
1936269 => 'Joaquin, TX',
1936271 => 'Conroe, TX',
1936273 => 'Conroe, TX',
1936275 => 'San Augustine, TX',
1936291 => 'Huntsville, TX',
1936293 => 'Huntsville, TX',
1936294 => 'Huntsville, TX',
1936295 => 'Huntsville, TX',
1936327 => 'Livingston, TX',
1936328 => 'Livingston, TX',
1936334 => 'Liberty, TX',
1936336 => 'Liberty, TX',
1936344 => 'New Waverly, TX',
1936348 => 'Madisonville, TX',
1936372 => 'Waller, TX',
1936398 => 'Corrigan, TX',
1936435 => 'Huntsville, TX',
1936436 => 'Huntsville, TX',
1936439 => 'Huntsville, TX',
1936441 => 'Conroe, TX',
1936448 => 'Montgomery, TX',
1936449 => 'Montgomery, TX',
1936462 => 'Nacogdoches, TX',
1936494 => 'Conroe, TX',
1936522 => 'Conroe, TX',
1936539 => 'Conroe, TX',
1936544 => 'Crockett, TX',
1936559 => 'Nacogdoches, TX',
1936560 => 'Nacogdoches, TX',
1936564 => 'Nacogdoches, TX',
1936569 => 'Nacogdoches, TX',
1936582 => 'Montgomery, TX',
1936588 => 'Montgomery, TX',
1936590 => 'Center, TX',
1936591 => 'Center, TX',
1936594 => 'Trinity, TX',
1936597 => 'Montgomery, TX',
1936598 => 'Center, TX',
1936628 => 'Shepherd, TX',
1936632 => 'Lufkin, TX',
1936633 => 'Lufkin, TX',
1936634 => 'Lufkin, TX',
1936637 => 'Lufkin, TX',
1936639 => 'Lufkin, TX',
1936642 => 'Groveton, TX',
1936646 => 'Onalaska, TX',
1936647 => 'Conroe, TX',
1936653 => 'Coldspring, TX',
1936687 => 'Grapeland, TX',
1936699 => 'Lufkin, TX',
1936756 => 'Conroe, TX',
1936760 => 'Conroe, TX',
1936788 => 'Conroe, TX',
1936825 => 'Navasota, TX',
1936829 => 'Diboll, TX',
1936856 => 'Willis, TX',
1936858 => 'Alto, TX',
1936875 => 'Lufkin, TX',
1936890 => 'Willis, TX',
1936931 => 'Waller, TX',
1936967 => 'Livingston, TX',
1937 => 'Ohio',
1937208 => 'Dayton, OH',
193722 => 'Dayton, OH',
1937233 => 'Dayton, OH',
1937235 => 'Dayton, OH',
1937236 => 'Dayton, OH',
1937237 => 'Dayton, OH',
193725 => 'Dayton, OH',
1937262 => 'Dayton, OH',
1937263 => 'Dayton, OH',
1937264 => 'Dayton, OH',
1937268 => 'Dayton, OH',
193727 => 'Dayton, OH',
193729 => 'Dayton, OH',
1937292 => 'Bellefontaine, OH',
1937295 => 'Fort Loramie, OH',
1937312 => 'Dayton, OH',
1937320 => 'Beavercreek, OH',
1937322 => 'Springfield, OH',
1937323 => 'Springfield, OH',
1937324 => 'Springfield, OH',
1937325 => 'Springfield, OH',
1937328 => 'Springfield, OH',
1937332 => 'Troy, OH',
1937333 => 'Dayton, OH',
1937335 => 'Troy, OH',
1937339 => 'Troy, OH',
1937342 => 'Springfield, OH',
1937352 => 'Xenia, OH',
1937364 => 'Lynchburg, OH',
1937372 => 'Xenia, OH',
1937374 => 'Xenia, OH',
1937376 => 'Xenia, OH',
1937378 => 'Georgetown, OH',
1937382 => 'Wilmington, OH',
1937383 => 'Wilmington, OH',
1937384 => 'Miamisburg, OH',
1937386 => 'Seaman, OH',
1937390 => 'Springfield, OH',
1937392 => 'Ripley, OH',
1937393 => 'Hillsboro, OH',
1937399 => 'Springfield, OH',
1937415 => 'Dayton, OH',
1937424 => 'Dayton, OH',
1937426 => 'Beavercreek, OH',
1937427 => 'Beavercreek, OH',
1937428 => 'Dayton, OH',
1937429 => 'Beavercreek, OH',
193743 => 'Dayton, OH',
1937431 => 'Beavercreek, OH',
1937437 => 'New Paris, OH',
1937440 => 'Troy, OH',
1937443 => 'Dayton, OH',
1937444 => 'Mount Orab, OH',
1937446 => 'Sardinia, OH',
1937452 => 'Camden, OH',
1937454 => 'Dayton, OH',
1937456 => 'Eaton, OH',
1937461 => 'Dayton, OH',
1937465 => 'West Liberty, OH',
1937473 => 'Covington, OH',
1937484 => 'Urbana, OH',
1937492 => 'Sidney, OH',
1937496 => 'Dayton, OH',
1937497 => 'Sidney, OH',
1937498 => 'Sidney, OH',
1937525 => 'Springfield, OH',
1937526 => 'Versailles, OH',
1937544 => 'West Union, OH',
1937547 => 'Greenville, OH',
1937548 => 'Greenville, OH',
1937549 => 'Manchester, OH',
1937558 => 'Dayton, OH',
1937578 => 'Marysville, OH',
1937584 => 'Sabina, OH',
1937585 => 'De Graff, OH',
1937587 => 'Peebles, OH',
1937592 => 'Bellefontaine, OH',
1937593 => 'Bellefontaine, OH',
1937596 => 'Jackson Center, OH',
1937599 => 'Bellefontaine, OH',
1937610 => 'Dayton, OH',
1937615 => 'Piqua, OH',
1937641 => 'Dayton, OH',
1937642 => 'Marysville, OH',
1937644 => 'Marysville, OH',
1937652 => 'Urbana, OH',
1937653 => 'Urbana, OH',
1937660 => 'Dayton, OH',
1937663 => 'St. Paris, OH',
1937667 => 'Tipp City, OH',
1937669 => 'Tipp City, OH',
1937675 => 'Jamestown, OH',
1937687 => 'New Lebanon, OH',
1937692 => 'Arcanum, OH',
1937698 => 'West Milton, OH',
1937723 => 'Dayton, OH',
1937743 => 'Franklin, OH',
1937746 => 'Franklin, OH',
1937748 => 'Springboro, OH',
1937754 => 'Fairborn, OH',
1937766 => 'Cedarville, OH',
1937767 => 'Yellow Springs, OH',
1937773 => 'Piqua, OH',
1937778 => 'Piqua, OH',
1937780 => 'Leesburg, OH',
1937783 => 'Blanchester, OH',
1937833 => 'Brookville, OH',
1937834 => 'Mechanicsburg, OH',
1937836 => 'Englewood, OH',
1937839 => 'West Alexandria, OH',
1937845 => 'New Carlisle, OH',
1937847 => 'Miamisburg, OH',
1937848 => 'Bellbrook, OH',
1937849 => 'New Carlisle, OH',
1937855 => 'Germantown, OH',
1937864 => 'Enon, OH',
1937865 => 'Miamisburg, OH',
1937866 => 'Miamisburg, OH',
1937878 => 'Fairborn, OH',
1937879 => 'Fairborn, OH',
1937890 => 'Dayton, OH',
1937898 => 'Vandalia, OH',
1937912 => 'Beavercreek, OH',
1937938 => 'Dayton, OH',
1937962 => 'Lewisburg, OH',
1937964 => 'Springfield, OH',
1937981 => 'Greenfield, OH',
1938 => 'Alabama',
1940 => 'Texas',
1940228 => 'Wichita Falls, TX',
1940243 => 'Denton, TX',
1940320 => 'Denton, TX',
1940322 => 'Wichita Falls, TX',
1940323 => 'Denton, TX',
1940325 => 'Mineral Wells, TX',
1940328 => 'Mineral Wells, TX',
1940349 => 'Denton, TX',
1940365 => 'Aubrey, TX',
194038 => 'Denton, TX',
1940397 => 'Wichita Falls, TX',
1940433 => 'Boyd, TX',
1940442 => 'Denton, TX',
1940458 => 'Sanger, TX',
1940464 => 'Argyle, TX',
1940479 => 'Ponder, TX',
1940482 => 'Krum, TX',
1940484 => 'Denton, TX',
1940495 => 'Electra, TX',
1940521 => 'Graham, TX',
1940538 => 'Henrietta, TX',
1940549 => 'Graham, TX',
1940552 => 'Vernon, TX',
1940553 => 'Vernon, TX',
1940564 => 'Olney, TX',
1940565 => 'Denton, TX',
1940566 => 'Denton, TX',
1940567 => 'Jacksboro, TX',
1940569 => 'Burkburnett, TX',
1940574 => 'Archer City, TX',
1940591 => 'Denton, TX',
1940592 => 'Iowa Park, TX',
1940612 => 'Gainesville, TX',
1940626 => 'Decatur, TX',
1940627 => 'Decatur, TX',
1940644 => 'Chico, TX',
1940648 => 'Justin, TX',
1940663 => 'Quanah, TX',
1940665 => 'Gainesville, TX',
1940668 => 'Gainesville, TX',
1940676 => 'Sheppard AFB, Wichita Falls, TX',
1940683 => 'Bridgeport, TX',
1940686 => 'Pilot Point, TX',
1940687 => 'Wichita Falls, TX',
1940689 => 'Wichita Falls, TX',
1940691 => 'Wichita Falls, TX',
1940692 => 'Wichita Falls, TX',
1940696 => 'Wichita Falls, TX',
1940716 => 'Wichita Falls, TX',
1940723 => 'Wichita Falls, TX',
1940759 => 'Muenster, TX',
1940761 => 'Wichita Falls, TX',
1940766 => 'Wichita Falls, TX',
1940767 => 'Wichita Falls, TX',
1940779 => 'Graford, TX',
1940825 => 'Nocona, TX',
1940851 => 'Wichita Falls, TX',
1940855 => 'Wichita Falls, TX',
1940864 => 'Haskell, TX',
1940872 => 'Bowie, TX',
1940889 => 'Seymour, TX',
1940891 => 'Denton, TX',
1940898 => 'Denton, TX',
1940937 => 'Childress, TX',
1941 => 'Florida',
1941205 => 'Punta Gorda, FL',
1941235 => 'Port Charlotte, FL',
1941240 => 'North Port, FL',
1941244 => 'Venice, FL',
1941255 => 'Port Charlotte, FL',
1941284 => 'Sarasota, FL',
1941302 => 'Sarasota, FL',
1941306 => 'Sarasota, FL',
1941308 => 'Sarasota, FL',
1941312 => 'Sarasota, FL',
1941316 => 'Sarasota, FL',
1941320 => 'Sarasota, FL',
1941321 => 'Sarasota, FL',
1941322 => 'Myakka City, FL',
1941330 => 'Sarasota, FL',
1941342 => 'Sarasota, FL',
1941343 => 'Sarasota, FL',
1941346 => 'Sarasota, FL',
1941347 => 'Punta Gorda, FL',
1941349 => 'Sarasota, FL',
1941350 => 'Sarasota, FL',
1941351 => 'Sarasota, FL',
1941355 => 'Sarasota, FL',
1941358 => 'Sarasota, FL',
1941359 => 'Sarasota, FL',
194136 => 'Sarasota, FL',
1941371 => 'Sarasota, FL',
1941373 => 'Sarasota, FL',
1941377 => 'Sarasota, FL',
1941378 => 'Sarasota, FL',
1941379 => 'Sarasota, FL',
1941383 => 'Longboat Key, FL',
1941387 => 'Longboat Key, FL',
1941388 => 'Sarasota, FL',
1941391 => 'Port Charlotte, FL',
1941400 => 'Sarasota, FL',
1941408 => 'Venice, FL',
1941412 => 'Venice, FL',
1941423 => 'North Port, FL',
1941426 => 'North Port, FL',
1941429 => 'North Port, FL',
1941444 => 'Sarasota, FL',
1941460 => 'Englewood, FL',
1941473 => 'Englewood, FL',
1941474 => 'Englewood, FL',
1941475 => 'Englewood, FL',
194148 => 'Venice, FL',
1941487 => 'Sarasota, FL',
1941492 => 'Venice, FL',
1941493 => 'Venice, FL',
1941496 => 'Venice, FL',
1941497 => 'Venice, FL',
1941505 => 'Punta Gorda, FL',
1941544 => 'Sarasota, FL',
1941552 => 'Sarasota, FL',
1941554 => 'Sarasota, FL',
1941556 => 'Sarasota, FL',
1941564 => 'North Port, FL',
1941567 => 'Bradenton, FL',
1941575 => 'Punta Gorda, FL',
1941586 => 'Sarasota, FL',
1941613 => 'Port Charlotte, FL',
1941623 => 'Port Charlotte, FL',
1941624 => 'Port Charlotte, FL',
1941625 => 'Port Charlotte, FL',
1941627 => 'Port Charlotte, FL',
1941629 => 'Port Charlotte, FL',
1941637 => 'Punta Gorda, FL',
1941639 => 'Punta Gorda, FL',
1941706 => 'Sarasota, FL',
1941708 => 'Bradenton, FL',
1941721 => 'Palmetto, FL',
1941722 => 'Palmetto, FL',
1941723 => 'Palmetto, FL',
1941727 => 'Bradenton, FL',
1941729 => 'Palmetto, FL',
1941739 => 'Bradenton, FL',
194174 => 'Bradenton, FL',
1941743 => 'Port Charlotte, FL',
194175 => 'Bradenton, FL',
1941761 => 'Bradenton, FL',
1941764 => 'Port Charlotte, FL',
1941766 => 'Port Charlotte, FL',
1941776 => 'Parrish, FL',
1941782 => 'Bradenton, FL',
1941792 => 'Bradenton, FL',
1941794 => 'Bradenton, FL',
1941795 => 'Bradenton, FL',
1941798 => 'Bradenton, FL',
1941809 => 'Sarasota, FL',
1941822 => 'Sarasota, FL',
1941833 => 'Punta Gorda, FL',
1941861 => 'Sarasota, FL',
1941870 => 'Sarasota, FL',
1941894 => 'Sarasota, FL',
1941896 => 'Bradenton, FL',
1941906 => 'Sarasota, FL',
1941917 => 'Sarasota, FL',
194192 => 'Sarasota, FL',
1941932 => 'Bradenton, FL',
194195 => 'Sarasota, FL',
1941964 => 'Boca Grande, FL',
1941979 => 'Port Charlotte, FL',
1945 => 'Texas',
1947 => 'Michigan',
1949 => 'California',
1949221 => 'Irvine, CA',
1949249 => 'Laguna Niguel, CA',
1949253 => 'Irvine, CA',
1949258 => 'Newport Beach, CA',
1949260 => 'Irvine, CA',
1949262 => 'Irvine, CA',
1949333 => 'Irvine, CA',
1949336 => 'Irvine, CA',
1949341 => 'Irvine, CA',
1949347 => 'Mission Viejo, CA',
1949361 => 'San Clemente, CA',
1949363 => 'Laguna Niguel, CA',
1949364 => 'Mission Viejo, CA',
1949366 => 'San Clemente, CA',
1949369 => 'San Clemente, CA',
1949376 => 'Laguna Beach, CA',
1949387 => 'Irvine, CA',
1949425 => 'Aliso Viejo, CA',
1949428 => 'Irvine, CA',
1949442 => 'Irvine, CA',
1949450 => 'Irvine, CA',
1949452 => 'Laguna Hills, CA',
1949453 => 'Irvine, CA',
1949474 => 'Irvine, CA',
1949477 => 'Irvine, CA',
1949492 => 'San Clemente, CA',
1949494 => 'Laguna Beach, CA',
1949495 => 'Laguna Niguel, CA',
1949497 => 'Laguna Beach, CA',
1949498 => 'San Clemente, CA',
1949499 => 'Laguna Beach, CA',
1949502 => 'Irvine, CA',
1949509 => 'Irvine, CA',
1949515 => 'Costa Mesa, CA',
1949548 => 'Costa Mesa, CA',
1949551 => 'Irvine, CA',
1949552 => 'Irvine, CA',
1949553 => 'Irvine, CA',
1949559 => 'Irvine, CA',
1949585 => 'Irvine, CA',
1949622 => 'Irvine, CA',
1949631 => 'Costa Mesa, CA',
1949640 => 'Newport Beach, CA',
1949642 => 'Costa Mesa, CA',
1949644 => 'Newport Beach, CA',
1949645 => 'Costa Mesa, CA',
1949646 => 'Costa Mesa, CA',
1949650 => 'Costa Mesa, CA',
1949651 => 'Irvine, CA',
1949653 => 'Irvine, CA',
1949654 => 'Irvine, CA',
1949660 => 'Irvine, CA',
1949673 => 'Newport Beach, CA',
1949675 => 'Newport Beach, CA',
1949679 => 'Irvine, CA',
1949706 => 'Newport Beach, CA',
1949715 => 'Laguna Beach, CA',
1949717 => 'Newport Beach, CA',
1949718 => 'Newport Beach, CA',
1949719 => 'Newport Beach, CA',
1949720 => 'Newport Beach, CA',
1949721 => 'Newport Beach, CA',
1949722 => 'Costa Mesa, CA',
1949723 => 'Newport Beach, CA',
1949724 => 'Irvine, CA',
1949725 => 'Irvine, CA',
1949726 => 'Irvine, CA',
1949727 => 'Irvine, CA',
1949733 => 'Irvine, CA',
1949748 => 'Irvine, CA',
1949753 => 'Irvine, CA',
1949757 => 'Irvine, CA',
1949759 => 'Newport Beach, CA',
1949760 => 'Newport Beach, CA',
1949764 => 'Newport Beach, CA',
1949769 => 'Irvine, CA',
1949786 => 'Irvine, CA',
1949788 => 'Irvine, CA',
1949824 => 'Irvine, CA',
1949854 => 'Irvine, CA',
1949857 => 'Irvine, CA',
1949861 => 'Irvine, CA',
1949940 => 'San Clemente, CA',
1951 => 'California',
1951222 => 'Riverside, CA',
1951225 => 'Temecula, CA',
1951242 => 'Moreno Valley, CA',
1951243 => 'Moreno Valley, CA',
1951244 => 'Canyon Lake, CA',
1951245 => 'Lake Elsinore, CA',
1951247 => 'Moreno Valley, CA',
1951248 => 'Riverside, CA',
195127 => 'Corona, CA',
1951274 => 'Riverside, CA',
1951275 => 'Riverside, CA',
1951276 => 'Riverside, CA',
1951280 => 'Corona, CA',
1951296 => 'Temecula, CA',
1951302 => 'Temecula, CA',
1951303 => 'Temecula, CA',
1951304 => 'Murrieta, CA',
1951308 => 'Temecula, CA',
1951328 => 'Riverside, CA',
1951340 => 'Corona, CA',
1951343 => 'Riverside, CA',
195135 => 'Riverside, CA',
1951369 => 'Riverside, CA',
1951371 => 'Corona, CA',
1951372 => 'Corona, CA',
1951413 => 'Moreno Valley, CA',
1951443 => 'Perris, CA',
1951445 => 'Murrieta, CA',
1951461 => 'Murrieta, CA',
1951471 => 'Lake Elsinore, CA',
1951485 => 'Moreno Valley, CA',
1951486 => 'Moreno Valley, CA',
1951487 => 'San Jacinto, CA',
1951491 => 'Temecula, CA',
1951506 => 'Temecula, CA',
1951509 => 'Riverside, CA',
1951520 => 'Corona, CA',
1951549 => 'Corona, CA',
1951571 => 'Moreno Valley, CA',
1951582 => 'Corona, CA',
1951587 => 'Temecula, CA',
1951600 => 'Murrieta, CA',
1951601 => 'Moreno Valley, CA',
1951609 => 'Wildomar, CA',
1951637 => 'Riverside, CA',
1951652 => 'Hemet, CA',
1951653 => 'Moreno Valley, CA',
1951654 => 'San Jacinto, CA',
1951657 => 'Perris, CA',
1951658 => 'Hemet, CA',
1951659 => 'Idyllwild-Pine Cove, CA',
1951674 => 'Lake Elsinore, CA',
1951676 => 'Temecula, CA',
1951677 => 'Murrieta, CA',
195168 => 'Riverside, CA',
1951693 => 'Temecula, CA',
1951694 => 'Temecula, CA',
1951695 => 'Temecula, CA',
1951696 => 'Murrieta, CA',
1951698 => 'Murrieta, CA',
1951699 => 'Temecula, CA',
1951719 => 'Temecula, CA',
195173 => 'Corona, CA',
1951763 => 'Anza, CA',
1951765 => 'Hemet, CA',
1951766 => 'Hemet, CA',
1951769 => 'Beaumont, CA',
1951776 => 'Riverside, CA',
1951779 => 'Riverside, CA',
195178 => 'Riverside, CA',
1951808 => 'Corona, CA',
1951817 => 'Corona, CA',
1951845 => 'Beaumont, CA',
1951849 => 'Banning, CA',
1951894 => 'Murrieta, CA',
1951898 => 'Corona, CA',
1951922 => 'Banning, CA',
1951924 => 'Moreno Valley, CA',
1951925 => 'Hemet, CA',
1951927 => 'Hemet, CA',
1951929 => 'Hemet, CA',
1951940 => 'Perris, CA',
1951943 => 'Perris, CA',
1951955 => 'Riverside, CA',
1951977 => 'Riverside, CA',
1952 => 'Minnesota',
1952233 => 'Shakopee, MN',
1952361 => 'Chaska, MN',
1952368 => 'Chaska, MN',
1952403 => 'Shakopee, MN',
1952423 => 'Apple Valley, MN',
1952432 => 'Apple Valley, MN',
1952435 => 'Burnsville, MN',
1952440 => 'Prior Lake, MN',
1952442 => 'Waconia, MN',
1952443 => 'Victoria, MN',
1952445 => 'Shakopee, MN',
1952446 => 'St. Bonifacius, MN',
1952447 => 'Prior Lake, MN',
1952448 => 'Chaska, MN',
1952466 => 'Cologne, MN',
1952469 => 'Lakeville, MN',
1952472 => 'Mound, MN',
1952473 => 'Wayzata, MN',
1952474 => 'Excelsior, MN',
1952475 => 'Wayzata, MN',
1952476 => 'Wayzata, MN',
1952492 => 'Jordan, MN',
1952496 => 'Shakopee, MN',
1952556 => 'Chaska, MN',
1952707 => 'Burnsville, MN',
1952736 => 'Burnsville, MN',
1952758 => 'New Prague, MN',
1952808 => 'Burnsville, MN',
1952829 => 'Eden Prairie, MN',
1952848 => 'Edina, MN',
1952854 => 'Bloomington, MN',
1952858 => 'Bloomington, MN',
1952873 => 'Belle Plaine, MN',
1952882 => 'Burnsville, MN',
1952883 => 'Minneapolis, MN',
1952885 => 'East Bloomington, Bloomington, MN',
1952890 => 'Burnsville, MN',
1952892 => 'Burnsville, MN',
1952894 => 'Burnsville, MN',
1952895 => 'Burnsville, MN',
1952924 => 'Minneapolis, MN',
1952934 => 'Eden Prairie, MN',
1952937 => 'Eden Prairie, MN',
1952941 => 'Eden Prairie, MN',
1952942 => 'Eden Prairie, MN',
1952944 => 'Eden Prairie, MN',
1952949 => 'Eden Prairie, MN',
1952955 => 'Watertown, MN',
1952975 => 'Eden Prairie, MN',
1952985 => 'Lakeville, MN',
1954 => 'Florida',
1954202 => 'Fort Lauderdale, FL',
1954217 => 'Weston, FL',
1954227 => 'Coral Springs, FL',
1954229 => 'Fort Lauderdale, FL',
1954255 => 'Coral Springs, FL',
1954262 => 'Davie, FL',
1954265 => 'Hollywood, FL',
1954267 => 'Fort Lauderdale, FL',
1954332 => 'Fort Lauderdale, FL',
1954340 => 'Coral Springs, FL',
1954341 => 'Coral Springs, FL',
1954344 => 'Coral Springs, FL',
1954345 => 'Coral Springs, FL',
1954346 => 'Coral Springs, FL',
1954349 => 'Weston, FL',
1954351 => 'Fort Lauderdale, FL',
1954355 => 'Fort Lauderdale, FL',
1954359 => 'Fort Lauderdale, FL',
1954360 => 'Deerfield Beach, FL',
1954384 => 'Weston, FL',
1954385 => 'Weston, FL',
1954389 => 'Weston, FL',
1954396 => 'Fort Lauderdale, FL',
1954418 => 'Deerfield Beach, FL',
195442 => 'Deerfield Beach, FL',
195443 => 'Pembroke Pines, FL',
1954441 => 'Pembroke Pines, FL',
1954442 => 'Pembroke Pines, FL',
1954443 => 'Pembroke Pines, FL',
1954450 => 'Pembroke Pines, FL',
1954454 => 'Hallandale Beach, FL',
1954455 => 'Hallandale Beach, FL',
1954456 => 'Hallandale Beach, FL',
1954457 => 'Hallandale Beach, FL',
1954458 => 'Hallandale Beach, FL',
1954462 => 'Fort Lauderdale, FL',
1954463 => 'Fort Lauderdale, FL',
1954467 => 'Fort Lauderdale, FL',
1954468 => 'Fort Lauderdale, FL',
1954473 => 'Plantation, FL',
1954480 => 'Deerfield Beach, FL',
1954481 => 'Deerfield Beach, FL',
1954489 => 'Fort Lauderdale, FL',
1954491 => 'Fort Lauderdale, FL',
1954492 => 'Fort Lauderdale, FL',
1954493 => 'Fort Lauderdale, FL',
1954509 => 'Coral Springs, FL',
1954510 => 'Coral Springs, FL',
1954522 => 'Fort Lauderdale, FL',
1954523 => 'Fort Lauderdale, FL',
1954524 => 'Fort Lauderdale, FL',
1954525 => 'Fort Lauderdale, FL',
1954527 => 'Fort Lauderdale, FL',
1954531 => 'Deerfield Beach, FL',
1954532 => 'Pompano Beach, FL',
1954537 => 'Fort Lauderdale, FL',
1954545 => 'Pompano Beach, FL',
1954563 => 'Fort Lauderdale, FL',
1954564 => 'Fort Lauderdale, FL',
1954565 => 'Fort Lauderdale, FL',
1954566 => 'Fort Lauderdale, FL',
1954568 => 'Fort Lauderdale, FL',
1954570 => 'Deerfield Beach, FL',
1954571 => 'Deerfield Beach, FL',
1954572 => 'Sunrise, FL',
1954575 => 'Coral Springs, FL',
1954578 => 'Sunrise, FL',
1954580 => 'Pompano Beach, FL',
1954596 => 'Deerfield Beach, FL',
1954597 => 'Tamarac, FL',
1954659 => 'Weston, FL',
1954693 => 'Plantation, FL',
1954698 => 'Deerfield Beach, FL',
1954704 => 'Pembroke Pines, FL',
1954712 => 'Fort Lauderdale, FL',
1954718 => 'Tamarac, FL',
1954720 => 'Tamarac, FL',
1954721 => 'Tamarac, FL',
1954722 => 'Tamarac, FL',
1954724 => 'Tamarac, FL',
1954725 => 'Deerfield Beach, FL',
1954726 => 'Tamarac, FL',
1954728 => 'Fort Lauderdale, FL',
195474 => 'Sunrise, FL',
1954752 => 'Coral Springs, FL',
1954753 => 'Coral Springs, FL',
1954755 => 'Coral Springs, FL',
1954757 => 'Coral Springs, FL',
1954759 => 'Fort Lauderdale, FL',
195476 => 'Fort Lauderdale, FL',
1954771 => 'Fort Lauderdale, FL',
1954772 => 'Fort Lauderdale, FL',
1954776 => 'Fort Lauderdale, FL',
1954779 => 'Fort Lauderdale, FL',
195478 => 'Pompano Beach, FL',
1954796 => 'Coral Springs, FL',
1954828 => 'Fort Lauderdale, FL',
1954831 => 'Fort Lauderdale, FL',
1954835 => 'Sunrise, FL',
1954838 => 'Sunrise, FL',
1954845 => 'Sunrise, FL',
1954846 => 'Sunrise, FL',
1954851 => 'Sunrise, FL',
1954894 => 'Hollywood, FL',
195492 => 'Hollywood, FL',
1954933 => 'Pompano Beach, FL',
1954938 => 'Fort Lauderdale, FL',
1954941 => 'Pompano Beach, FL',
1954942 => 'Pompano Beach, FL',
1954943 => 'Pompano Beach, FL',
1954946 => 'Pompano Beach, FL',
1954958 => 'Fort Lauderdale, FL',
195496 => 'Hollywood, FL',
1954960 => 'Pompano Beach, FL',
195498 => 'Hollywood, FL',
1956 => 'Texas',
1956213 => 'McAllen, TX',
1956233 => 'Los Fresnos, TX',
1956283 => 'Pharr, TX',
1956287 => 'Edinburg, TX',
1956289 => 'Edinburg, TX',
1956316 => 'Edinburg, TX',
1956318 => 'Edinburg, TX',
1956350 => 'Brownsville, TX',
1956361 => 'San Benito, TX',
1956364 => 'Harlingen, TX',
1956365 => 'Harlingen, TX',
1956380 => 'Edinburg, TX',
1956381 => 'Edinburg, TX',
1956383 => 'Edinburg, TX',
1956386 => 'Edinburg, TX',
1956389 => 'Harlingen, TX',
1956399 => 'San Benito, TX',
1956412 => 'Harlingen, TX',
1956421 => 'Harlingen, TX',
1956423 => 'Harlingen, TX',
1956424 => 'Mission, TX',
1956425 => 'Harlingen, TX',
1956428 => 'Harlingen, TX',
1956440 => 'Harlingen, TX',
1956447 => 'Weslaco, TX',
1956461 => 'Donna, TX',
1956464 => 'Donna, TX',
1956465 => 'Brownsville, TX',
1956487 => 'Rio Grande City, TX',
1956488 => 'Rio Grande City, TX',
1956504 => 'Brownsville, TX',
1956514 => 'Mercedes, TX',
1956519 => 'Mission, TX',
1956523 => 'Laredo, TX',
1956541 => 'Brownsville, TX',
1956542 => 'Brownsville, TX',
1956544 => 'Brownsville, TX',
1956546 => 'Brownsville, TX',
1956548 => 'Brownsville, TX',
1956550 => 'Brownsville, TX',
1956554 => 'Brownsville, TX',
1956565 => 'Mercedes, TX',
1956568 => 'Laredo, TX',
1956574 => 'Brownsville, TX',
1956580 => 'Mission, TX',
1956581 => 'Mission, TX',
1956583 => 'Mission, TX',
1956584 => 'Mission, TX',
1956585 => 'Mission, TX',
1956618 => 'McAllen, TX',
1956621 => 'Brownsville, TX',
1956627 => 'McAllen, TX',
1956630 => 'McAllen, TX',
1956631 => 'McAllen, TX',
1956661 => 'McAllen, TX',
1956664 => 'McAllen, TX',
1956668 => 'McAllen, TX',
1956682 => 'McAllen, TX',
1956683 => 'McAllen, TX',
1956686 => 'McAllen, TX',
1956687 => 'McAllen, TX',
1956688 => 'McAllen, TX',
1956689 => 'Raymondville, TX',
1956702 => 'Pharr, TX',
1956712 => 'Laredo, TX',
1956717 => 'Laredo, TX',
1956718 => 'Laredo, TX',
195672 => 'Laredo, TX',
1956748 => 'Rio Hondo, TX',
1956753 => 'Laredo, TX',
1956765 => 'Zapata, TX',
1956781 => 'Pharr, TX',
1956782 => 'Pharr, TX',
1956783 => 'Pharr, TX',
1956787 => 'Pharr, TX',
1956791 => 'Laredo, TX',
1956795 => 'Laredo, TX',
1956796 => 'Laredo, TX',
1956797 => 'La Feria, TX',
1956825 => 'Mercedes, TX',
1956831 => 'Brownsville, TX',
1956838 => 'Brownsville, TX',
1956843 => 'Hidalgo, TX',
1956849 => 'Roma, TX',
1956928 => 'McAllen, TX',
1956943 => 'Port Isabel, TX',
1956968 => 'Weslaco, TX',
1956969 => 'Weslaco, TX',
1956971 => 'McAllen, TX',
1956972 => 'McAllen, TX',
1956973 => 'Weslaco, TX',
1956982 => 'Brownsville, TX',
1956992 => 'McAllen, TX',
1956994 => 'McAllen, TX',
1959 => 'Connecticut',
1970 => 'Colorado',
1970203 => 'Loveland, CO',
1970204 => 'Fort Collins, CO',
1970206 => 'Fort Collins, CO',
1970207 => 'Fort Collins, CO',
197022 => 'Fort Collins, CO',
1970232 => 'Fort Collins, CO',
197024 => 'Grand Junction, CO',
1970240 => 'Montrose, CO',
1970247 => 'Durango, CO',
1970249 => 'Montrose, CO',
1970250 => 'Grand Junction, CO',
1970252 => 'Montrose, CO',
1970254 => 'Grand Junction, CO',
1970255 => 'Grand Junction, CO',
1970256 => 'Grand Junction, CO',
1970257 => 'Grand Junction, CO',
1970259 => 'Durango, CO',
1970261 => 'Grand Junction, CO',
1970263 => 'Grand Junction, CO',
1970264 => 'Pagosa Springs, CO',
1970266 => 'Fort Collins, CO',
1970276 => 'Hayden, CO',
1970278 => 'Loveland, CO',
1970282 => 'Fort Collins, CO',
1970284 => 'La Salle, CO',
1970285 => 'Parachute, CO',
1970298 => 'Grand Junction, CO',
1970304 => 'Greeley, CO',
1970323 => 'Olathe, CO',
1970325 => 'Ouray, CO',
1970327 => 'Norwood, CO',
1970328 => 'Eagle, CO',
1970330 => 'Greeley, CO',
1970332 => 'Wray, CO',
1970336 => 'Greeley, CO',
1970339 => 'Greeley, CO',
1970345 => 'Akron, CO',
1970346 => 'Greeley, CO',
1970347 => 'Greeley, CO',
1970349 => 'Crested Butte, CO',
1970350 => 'Greeley, CO',
1970351 => 'Greeley, CO',
1970352 => 'Greeley, CO',
1970353 => 'Greeley, CO',
1970356 => 'Greeley, CO',
1970375 => 'Durango, CO',
1970377 => 'Fort Collins, CO',
1970378 => 'Greeley, CO',
1970382 => 'Durango, CO',
1970384 => 'Glenwood Springs, CO',
1970385 => 'Durango, CO',
1970387 => 'Silverton, CO',
1970392 => 'Greeley, CO',
1970396 => 'Greeley, CO',
1970403 => 'Durango, CO',
1970407 => 'Fort Collins, CO',
1970416 => 'Fort Collins, CO',
1970424 => 'Grand Junction, CO',
1970429 => 'Aspen, CO',
1970449 => 'Fort Collins, CO',
1970453 => 'Breckenridge, CO',
1970454 => 'Eaton, CO',
1970461 => 'Loveland, CO',
1970464 => 'Palisade, CO',
1970472 => 'Fort Collins, CO',
1970474 => 'Julesburg, CO',
1970476 => 'Vail, CO',
1970479 => 'Vail, CO',
1970482 => 'Fort Collins, CO',
1970483 => 'Wiggins, CO',
1970484 => 'Fort Collins, CO',
197049 => 'Fort Collins, CO',
1970506 => 'Greeley, CO',
1970521 => 'Sterling, CO',
1970522 => 'Sterling, CO',
1970523 => 'Grand Junction, CO',
1970524 => 'Gypsum, CO',
1970527 => 'Paonia, CO',
1970532 => 'Berthoud, CO',
1970533 => 'Mancos, CO',
1970542 => 'Fort Morgan, CO',
1970544 => 'Aspen, CO',
1970547 => 'Breckenridge, CO',
1970563 => 'Ignacio, CO',
1970564 => 'Cortez, CO',
1970565 => 'Cortez, CO',
1970568 => 'Wellington, CO',
1970569 => 'Edwards, CO',
1970577 => 'Estes Park, CO',
1970586 => 'Estes Park, CO',
1970587 => 'Johnstown, CO',
1970593 => 'Loveland, CO',
1970613 => 'Loveland, CO',
1970619 => 'Loveland, CO',
1970622 => 'Loveland, CO',
1970625 => 'Rifle, CO',
1970626 => 'Ridgway, CO',
1970627 => 'Grand Lake, CO',
1970631 => 'Fort Collins, CO',
1970635 => 'Loveland, CO',
1970641 => 'Gunnison, CO',
1970663 => 'Loveland, CO',
1970667 => 'Loveland, CO',
1970668 => 'Frisco, CO',
1970669 => 'Loveland, CO',
1970672 => 'Fort Collins, CO',
1970673 => 'Greeley, CO',
1970674 => 'Windsor, CO',
1970675 => 'Rangely, CO',
1970677 => 'Dove Creek, CO',
1970682 => 'Fort Collins, CO',
1970686 => 'Windsor, CO',
1970689 => 'Fort Collins, CO',
1970704 => 'Carbondale, CO',
1970723 => 'Walden, CO',
1970724 => 'Kremmling, CO',
1970728 => 'Telluride, CO',
1970731 => 'Pagosa Springs, CO',
1970739 => 'Cortez, CO',
1970748 => 'Avon, CO',
1970749 => 'Durango, CO',
1970759 => 'Durango, CO',
1970764 => 'Durango, CO',
1970769 => 'Durango, CO',
1970774 => 'Haxtun, CO',
1970776 => 'Loveland, CO',
1970785 => 'Platteville, CO',
1970799 => 'Durango, CO',
1970824 => 'Craig, CO',
1970827 => 'Minturn, CO',
1970834 => 'Ault, CO',
1970842 => 'Brush, CO',
1970845 => 'Avon, CO',
1970848 => 'Yuma, CO',
1970854 => 'Holyoke, CO',
1970856 => 'Cedaredge, CO',
1970858 => 'Fruita, CO',
1970864 => 'Nucla, CO',
1970867 => 'Fort Morgan, CO',
1970870 => 'Steamboat Spgs, CO',
1970871 => 'Steamboat Spgs, CO',
1970872 => 'Hotchkiss, CO',
1970874 => 'Delta, CO',
1970876 => 'Silt, CO',
1970878 => 'Meeker, CO',
1970879 => 'Steamboat Spgs, CO',
1970882 => 'Dolores, CO',
1970884 => 'Bayfield, CO',
1970887 => 'Granby, CO',
1970903 => 'Durango, CO',
1970920 => 'Aspen, CO',
1970923 => 'Snowmass Village, CO',
1970925 => 'Aspen, CO',
1970926 => 'Edwards, CO',
1970927 => 'Basalt, CO',
1970928 => 'Glenwood Springs, CO',
1970944 => 'Lake City, CO',
1970945 => 'Glenwood Springs, CO',
1970946 => 'Durango, CO',
1970947 => 'Glenwood Springs, CO',
1970949 => 'Avon, CO',
1970962 => 'Loveland, CO',
1970963 => 'Carbondale, CO',
1970984 => 'New Castle, CO',
1971 => 'Oregon',
1971255 => 'Portland, OR',
1971279 => 'Portland, OR',
1972 => 'Texas',
1972202 => 'Plano, TX',
1972205 => 'Garland, TX',
1972206 => 'Grand Prairie, TX',
1972208 => 'Plano, TX',
1972216 => 'Mesquite, TX',
1972218 => 'Lancaster, TX',
1972219 => 'Lewisville, TX',
1972221 => 'Lewisville, TX',
1972222 => 'Mesquite, TX',
1972223 => 'DeSoto, TX',
1972225 => 'Hutchins, TX',
1972227 => 'Lancaster, TX',
1972230 => 'DeSoto, TX',
1972231 => 'Richardson, TX',
1972233 => 'Dallas, TX',
1972234 => 'Richardson, TX',
1972235 => 'Richardson, TX',
1972237 => 'Grand Prairie, TX',
1972238 => 'Richardson, TX',
1972239 => 'Dallas, TX',
1972240 => 'Garland, TX',
1972241 => 'Dallas, TX',
1972242 => 'Carrollton, TX',
1972243 => 'Dallas, TX',
1972245 => 'Carrollton, TX',
1972247 => 'Dallas, TX',
1972248 => 'Dallas, TX',
197225 => 'Irving, TX',
1972262 => 'Grand Prairie, TX',
1972263 => 'Grand Prairie, TX',
1972264 => 'Grand Prairie, TX',
1972266 => 'Grand Prairie, TX',
1972270 => 'Mesquite, TX',
1972271 => 'Garland, TX',
1972272 => 'Garland, TX',
1972274 => 'DeSoto, TX',
1972276 => 'Garland, TX',
1972278 => 'Garland, TX',
1972279 => 'Mesquite, TX',
1972285 => 'Mesquite, TX',
1972287 => 'Seagoville, TX',
1972288 => 'Mesquite, TX',
1972289 => 'Mesquite, TX',
1972291 => 'Cedar Hill, TX',
1972293 => 'Cedar Hill, TX',
1972296 => 'Duncanville, TX',
1972298 => 'Duncanville, TX',
1972299 => 'Cedar Hill, TX',
1972303 => 'Garland, TX',
1972304 => 'Coppell, TX',
1972312 => 'Plano, TX',
1972313 => 'Irving, TX',
1972315 => 'Lewisville, TX',
1972316 => 'Lewisville, TX',
1972317 => 'Lewisville, TX',
1972323 => 'Carrollton, TX',
1972329 => 'Mesquite, TX',
1972335 => 'Frisco, TX',
1972346 => 'Prosper, TX',
1972347 => 'Prosper, TX',
1972352 => 'Grand Prairie, TX',
1972353 => 'Lewisville, TX',
1972355 => 'Flower Mound, TX',
1972359 => 'Allen, TX',
1972369 => 'McKinney, TX',
1972370 => 'The Colony, TX',
1972377 => 'Frisco, TX',
1972378 => 'Plano, TX',
1972382 => 'Celina, TX',
1972385 => 'Dallas, TX',
1972386 => 'Dallas, TX',
1972387 => 'Dallas, TX',
1972390 => 'Allen, TX',
1972392 => 'Dallas, TX',
1972393 => 'Coppell, TX',
1972394 => 'Carrollton, TX',
1972395 => 'Carrollton, TX',
1972396 => 'Allen, TX',
1972398 => 'Plano, TX',
1972401 => 'Irving, TX',
1972402 => 'Irving, TX',
1972403 => 'Plano, TX',
1972404 => 'Dallas, TX',
1972406 => 'Dallas, TX',
1972407 => 'Dallas, TX',
1972409 => 'Irving, TX',
1972412 => 'Rowlett, TX',
1972414 => 'Garland, TX',
1972416 => 'Carrollton, TX',
1972417 => 'Carrollton, TX',
1972418 => 'Carrollton, TX',
1972419 => 'Dallas, TX',
1972420 => 'Lewisville, TX',
1972422 => 'Plano, TX',
1972423 => 'Plano, TX',
1972424 => 'Plano, TX',
1972429 => 'Wylie, TX',
1972434 => 'Lewisville, TX',
1972436 => 'Lewisville, TX',
1972437 => 'Richardson, TX',
1972438 => 'Irving, TX',
1972442 => 'Wylie, TX',
1972445 => 'Irving, TX',
1972446 => 'Carrollton, TX',
1972450 => 'Dallas, TX',
1972456 => 'Dallas, TX',
1972458 => 'Dallas, TX',
1972459 => 'Lewisville, TX',
1972462 => 'Coppell, TX',
1972463 => 'Rowlett, TX',
1972466 => 'Carrollton, TX',
1972470 => 'Richardson, TX',
1972473 => 'Plano, TX',
1972475 => 'Rowlett, TX',
1972478 => 'Carrollton, TX',
1972479 => 'Richardson, TX',
1972481 => 'Dallas, TX',
1972484 => 'Dallas, TX',
1972485 => 'Garland, TX',
1972487 => 'Garland, TX',
1972488 => 'Dallas, TX',
1972490 => 'Dallas, TX',
1972491 => 'Plano, TX',
1972492 => 'Carrollton, TX',
1972494 => 'Garland, TX',
1972495 => 'Garland, TX',
1972496 => 'Garland, TX',
1972501 => 'Irving, TX',
1972503 => 'Dallas, TX',
1972509 => 'Plano, TX',
1972516 => 'Plano, TX',
1972517 => 'Plano, TX',
1972519 => 'Plano, TX',
1972522 => 'Grand Prairie, TX',
1972524 => 'Terrell, TX',
1972527 => 'Plano, TX',
1972529 => 'McKinney, TX',
1972530 => 'Garland, TX',
1972539 => 'Flower Mound, TX',
1972540 => 'McKinney, TX',
1972542 => 'McKinney, TX',
1972544 => 'Ferris, TX',
1972547 => 'McKinney, TX',
1972548 => 'McKinney, TX',
1972550 => 'Irving, TX',
1972551 => 'Terrell, TX',
1972552 => 'Forney, TX',
1972554 => 'Irving, TX',
1972562 => 'McKinney, TX',
1972563 => 'Terrell, TX',
1972564 => 'Forney, TX',
1972566 => 'Dallas, TX',
1972569 => 'McKinney, TX',
1972570 => 'Irving, TX',
1972574 => 'Dallas, TX',
1972576 => 'Red Oak, TX',
1972578 => 'Plano, TX',
1972579 => 'Irving, TX',
1972580 => 'Irving, TX',
1972594 => 'Irving, TX',
1972596 => 'Plano, TX',
1972599 => 'Plano, TX',
1972600 => 'Irving, TX',
1972602 => 'Grand Prairie, TX',
1972606 => 'Grand Prairie, TX',
1972608 => 'Plano, TX',
1972612 => 'Plano, TX',
1972613 => 'Mesquite, TX',
1972617 => 'Red Oak, TX',
1972618 => 'Plano, TX',
1972620 => 'Dallas, TX',
1972623 => 'Grand Prairie, TX',
1972625 => 'The Colony, TX',
1972633 => 'Plano, TX',
1972635 => 'Royse City, TX',
1972636 => 'Royse City, TX',
1972641 => 'Grand Prairie, TX',
1972642 => 'Grand Prairie, TX',
1972644 => 'Richardson, TX',
1972647 => 'Grand Prairie, TX',
1972660 => 'Grand Prairie, TX',
1972661 => 'Dallas, TX',
1972663 => 'Dallas, TX',
1972664 => 'Richardson, TX',
1972665 => 'Plano, TX',
1972668 => 'Frisco, TX',
1972669 => 'Richardson, TX',
1972671 => 'Richardson, TX',
1972675 => 'Garland, TX',
1972678 => 'Allen, TX',
1972680 => 'Richardson, TX',
1972681 => 'Mesquite, TX',
1972682 => 'Mesquite, TX',
1972686 => 'Mesquite, TX',
1972690 => 'Richardson, TX',
1972691 => 'Flower Mound, TX',
1972698 => 'Mesquite, TX',
1972699 => 'Richardson, TX',
1972701 => 'Dallas, TX',
1972702 => 'Dallas, TX',
1972712 => 'Frisco, TX',
1972717 => 'Irving, TX',
1972719 => 'Irving, TX',
1972721 => 'Irving, TX',
1972722 => 'Rockwall, TX',
1972723 => 'Midlothian, TX',
1972724 => 'Flower Mound, TX',
1972726 => 'Dallas, TX',
1972727 => 'Allen, TX',
1972732 => 'Dallas, TX',
1972733 => 'Dallas, TX',
1972736 => 'Princeton, TX',
1972744 => 'Richardson, TX',
1972745 => 'Coppell, TX',
1972747 => 'Allen, TX',
1972758 => 'Plano, TX',
1972769 => 'Plano, TX',
1972770 => 'Dallas, TX',
1972771 => 'Rockwall, TX',
1972772 => 'Rockwall, TX',
1972774 => 'Dallas, TX',
1972775 => 'Midlothian, TX',
1972780 => 'Duncanville, TX',
1972781 => 'Plano, TX',
1972782 => 'Farmersville, TX',
1972783 => 'Richardson, TX',
1972784 => 'Farmersville, TX',
1972788 => 'Dallas, TX',
1972789 => 'Dallas, TX',
1972790 => 'Irving, TX',
1972801 => 'Plano, TX',
1972837 => 'Melissa, TX',
1972840 => 'Garland, TX',
1972851 => 'Dallas, TX',
1972855 => 'Dallas, TX',
1972864 => 'Garland, TX',
1972867 => 'Plano, TX',
1972870 => 'Irving, TX',
1972871 => 'Irving, TX',
1972874 => 'Flower Mound, TX',
1972875 => 'Ennis, TX',
1972878 => 'Ennis, TX',
1972881 => 'Plano, TX',
1972889 => 'Richardson, TX',
1972906 => 'Lewisville, TX',
1972907 => 'Richardson, TX',
1972910 => 'Irving, TX',
1972918 => 'Richardson, TX',
1972923 => 'Waxahachie, TX',
1972924 => 'Anna, TX',
1972926 => 'Garland, TX',
1972929 => 'Irving, TX',
1972932 => 'Kaufman, TX',
1972934 => 'Dallas, TX',
1972935 => 'Waxahachie, TX',
1972937 => 'Waxahachie, TX',
1972938 => 'Waxahachie, TX',
1972939 => 'Carrollton, TX',
1972941 => 'Plano, TX',
1972943 => 'Plano, TX',
1972960 => 'Dallas, TX',
1972961 => 'Rockwall, TX',
1972962 => 'Kaufman, TX',
1972964 => 'Plano, TX',
1972980 => 'Dallas, TX',
1972981 => 'Plano, TX',
1972984 => 'McKinney, TX',
1972985 => 'Plano, TX',
1972986 => 'Irving, TX',
1972988 => 'Grand Prairie, TX',
1972991 => 'Dallas, TX',
1973 => 'New Jersey',
1973227 => 'Fairfield, NJ',
1973230 => 'Newark, NJ',
1973233 => 'Montclair, NJ',
1973235 => 'Nutley, NJ',
1973239 => 'Verona, NJ',
1973242 => 'Newark, NJ',
1973243 => 'West Orange, NJ',
1973244 => 'Fairfield, NJ',
1973247 => 'Paterson, NJ',
1973253 => 'Clifton, NJ',
1973259 => 'Bloomfield, NJ',
1973266 => 'East Orange, NJ',
1973267 => 'Morristown, NJ',
1973268 => 'Newark, NJ',
1973273 => 'Newark, NJ',
1973274 => 'Newark, NJ',
1973276 => 'Fairfield, NJ',
1973278 => 'Paterson, NJ',
1973279 => 'Paterson, NJ',
1973284 => 'Nutley, NJ',
1973285 => 'Morristown, NJ',
1973292 => 'Morristown, NJ',
1973293 => 'Montague Township, NJ',
1973300 => 'Newton, NJ',
1973301 => 'Florham Park, NJ',
1973305 => 'Wayne, NJ',
1973321 => 'Paterson, NJ',
1973322 => 'Livingston, NJ',
1973324 => 'West Orange, NJ',
1973325 => 'West Orange, NJ',
1973326 => 'Morristown, NJ',
1973333 => 'Paterson, NJ',
1973338 => 'Bloomfield, NJ',
1973340 => 'Clifton, NJ',
1973341 => 'Paterson, NJ',
1973344 => 'Newark, NJ',
1973345 => 'Paterson, NJ',
1973350 => 'Newark, NJ',
1973353 => 'Newark, NJ',
1973357 => 'Paterson, NJ',
1973365 => 'Passaic, NJ',
1973371 => 'Irvington, NJ',
1973372 => 'Irvington, NJ',
1973373 => 'Irvington, NJ',
1973374 => 'Irvington, NJ',
1973375 => 'Irvington, NJ',
1973383 => 'Newton, NJ',
1973395 => 'East Orange, NJ',
1973399 => 'Irvington, NJ',
1973414 => 'East Orange, NJ',
1973416 => 'Irvington, NJ',
1973422 => 'Livingston, NJ',
1973423 => 'Hawthorne, NJ',
1973425 => 'Morristown, NJ',
1973427 => 'Hawthorne, NJ',
1973429 => 'Bloomfield, NJ',
1973439 => 'Fairfield, NJ',
1973450 => 'Belleville, NJ',
1973455 => 'Morristown, NJ',
1973465 => 'Newark, NJ',
1973466 => 'Newark, NJ',
1973481 => 'Newark, NJ',
1973482 => 'Newark, NJ',
1973483 => 'Newark, NJ',
1973484 => 'Newark, NJ',
1973485 => 'Newark, NJ',
1973491 => 'Newark, NJ',
1973509 => 'Montclair, NJ',
1973522 => 'Newark, NJ',
1973523 => 'Paterson, NJ',
1973533 => 'Livingston, NJ',
1973535 => 'Livingston, NJ',
1973538 => 'Morristown, NJ',
1973539 => 'Morristown, NJ',
1973540 => 'Morristown, NJ',
1973542 => 'Nutley, NJ',
1973543 => 'Mendham, NJ',
1973546 => 'Clifton, NJ',
1973569 => 'Paterson, NJ',
1973575 => 'Fairfield, NJ',
1973579 => 'Newton, NJ',
1973589 => 'Newark, NJ',
1973593 => 'Madison, NJ',
1973594 => 'Clifton, NJ',
1973596 => 'Newark, NJ',
1973597 => 'Livingston, NJ',
1973605 => 'Morristown, NJ',
1973621 => 'Newark, NJ',
1973622 => 'Newark, NJ',
1973623 => 'Newark, NJ',
1973624 => 'Newark, NJ',
1973625 => 'Denville, NJ',
1973628 => 'Wayne, NJ',
1973633 => 'Wayne, NJ',
1973635 => 'Chatham, NJ',
1973642 => 'Newark, NJ',
1973643 => 'Newark, NJ',
1973644 => 'Morristown, NJ',
1973645 => 'Newark, NJ',
1973648 => 'Newark, NJ',
1973653 => 'Paterson, NJ',
1973655 => 'Montclair, NJ',
1973656 => 'Morristown, NJ',
1973660 => 'Florham Park, NJ',
1973661 => 'Nutley, NJ',
1973663 => 'Lake Hopatcong, NJ',
1973667 => 'Nutley, NJ',
1973669 => 'West Orange, NJ',
197367 => 'East Orange, NJ',
1973680 => 'Bloomfield, NJ',
1973684 => 'Paterson, NJ',
1973686 => 'Wayne, NJ',
1973689 => 'Paterson, NJ',
1973694 => 'Wayne, NJ',
1973696 => 'Wayne, NJ',
1973701 => 'Chatham, NJ',
1973702 => 'Sussex, NJ',
1973706 => 'Wayne, NJ',
1973726 => 'Sparta Township, NJ',
1973728 => 'West Milford, NJ',
1973729 => 'Sparta Township, NJ',
1973731 => 'West Orange, NJ',
1973732 => 'Newark, NJ',
1973733 => 'Newark, NJ',
1973736 => 'West Orange, NJ',
1973740 => 'Livingston, NJ',
1973742 => 'Paterson, NJ',
1973743 => 'Bloomfield, NJ',
1973744 => 'Montclair, NJ',
1973746 => 'Montclair, NJ',
1973748 => 'Bloomfield, NJ',
1973751 => 'Belleville, NJ',
1973754 => 'Paterson, NJ',
1973759 => 'Belleville, NJ',
1973761 => 'Maplewood, NJ',
1973764 => 'Vernon Township, NJ',
1973772 => 'Clifton, NJ',
1973782 => 'Paterson, NJ',
1973783 => 'Montclair, NJ',
1973786 => 'Andover, NJ',
1973808 => 'Fairfield, NJ',
1973817 => 'Newark, NJ',
1973824 => 'Newark, NJ',
1973829 => 'Morristown, NJ',
1973844 => 'Belleville, NJ',
1973853 => 'Hewitt, NJ',
1973857 => 'Verona, NJ',
1973872 => 'Wayne, NJ',
1973875 => 'Sussex, NJ',
1973877 => 'Newark, NJ',
1973881 => 'Paterson, NJ',
1973882 => 'Fairfield, NJ',
1973889 => 'Morristown, NJ',
1973895 => 'Randolph, NJ',
1973898 => 'Morristown, NJ',
1973923 => 'Newark, NJ',
1973925 => 'Paterson, NJ',
1973926 => 'Newark, NJ',
1973940 => 'Newton, NJ',
1973948 => 'Branchville, NJ',
1973962 => 'Ringwood, NJ',
1973971 => 'Morristown, NJ',
1973972 => 'Newark, NJ',
1973977 => 'Paterson, NJ',
1973984 => 'Morristown, NJ',
1973991 => 'Newark, NJ',
1973992 => 'Livingston, NJ',
1973993 => 'Morristown, NJ',
1973994 => 'Livingston, NJ',
1978 => 'Massachusetts',
1978208 => 'Lawrence, MA',
1978232 => 'Beverly, MA',
1978244 => 'Chelmsford, MA',
1978249 => 'Athol, MA',
1978250 => 'Chelmsford, MA',
1978251 => 'North Chelmsford, MA',
1978256 => 'Chelmsford, MA',
1978258 => 'Lawrence, MA',
1978263 => 'Acton, MA',
1978264 => 'Acton, MA',
1978266 => 'Acton, MA',
1978275 => 'Lowell, MA',
1978276 => 'North Reading, MA',
1978281 => 'Gloucester, MA',
1978282 => 'Gloucester, MA',
1978283 => 'Gloucester, MA',
1978287 => 'Concord, MA',
1978297 => 'Winchendon, MA',
1978318 => 'Concord, MA',
1978327 => 'Lawrence, MA',
1978342 => 'Fitchburg, MA',
1978343 => 'Fitchburg, MA',
1978345 => 'Fitchburg, MA',
1978346 => 'Merrimac, MA',
1978352 => 'Georgetown, MA',
1978354 => 'Salem, MA',
1978355 => 'Barre, MA',
1978356 => 'Ipswich, MA',
1978363 => 'West Newbury, MA',
1978365 => 'Clinton, MA',
1978368 => 'Clinton, MA',
1978369 => 'Concord, MA',
1978371 => 'Concord, MA',
1978372 => 'Haverhill, MA',
1978373 => 'Haverhill, MA',
1978374 => 'Haverhill, MA',
1978386 => 'Ashby, MA',
1978388 => 'Amesbury, MA',
1978392 => 'Westford, MA',
1978422 => 'Sterling, MA',
1978425 => 'Shirley, MA',
1978433 => 'Pepperell, MA',
1978440 => 'Sudbury, MA',
1978441 => 'Lowell, MA',
1978443 => 'Sudbury, MA',
1978446 => 'Lowell, MA',
1978448 => 'Groton, MA',
1978452 => 'Lowell, MA',
1978453 => 'Lowell, MA',
1978454 => 'Lowell, MA',
1978456 => 'Harvard, MA',
1978458 => 'Lowell, MA',
1978459 => 'Lowell, MA',
1978461 => 'Maynard, MA',
1978462 => 'Newburyport, MA',
1978463 => 'Newburyport, MA',
1978464 => 'Princeton, MA',
1978465 => 'Newburyport, MA',
1978466 => 'Leominster, MA',
1978468 => 'South Hamilton, MA',
1978470 => 'Andover, MA',
1978474 => 'Andover, MA',
1978475 => 'Andover, MA',
1978486 => 'Littleton, MA',
1978499 => 'Newburyport, MA',
1978521 => 'Haverhill, MA',
1978524 => 'Beverly, MA',
1978525 => 'Gloucester, MA',
1978526 => 'Manchester, MA',
1978531 => 'Peabody, MA',
1978532 => 'Peabody, MA',
1978534 => 'Leominster, MA',
1978535 => 'Peabody, MA',
1978536 => 'Peabody, MA',
1978537 => 'Leominster, MA',
1978538 => 'Peabody, MA',
1978544 => 'Orange, MA',
1978546 => 'Rockport, MA',
1978556 => 'Haverhill, MA',
1978557 => 'Lawrence, MA',
1978562 => 'Hudson, MA',
1978567 => 'Hudson, MA',
1978568 => 'Hudson, MA',
1978582 => 'Lunenburg, MA',
1978594 => 'Salem, MA',
1978597 => 'Townsend, MA',
1978630 => 'Gardner, MA',
1978632 => 'Gardner, MA',
1978635 => 'Acton, MA',
1978640 => 'Tewksbury, MA',
1978646 => 'Danvers, MA',
1978649 => 'Tyngsborough, MA',
1978657 => 'Wilmington, MA',
1978658 => 'Wilmington, MA',
1978663 => 'Billerica, MA',
1978664 => 'North Reading, MA',
1978667 => 'Billerica, MA',
1978670 => 'Billerica, MA',
1978671 => 'Billerica, MA',
1978692 => 'Westford, MA',
1978735 => 'Lowell, MA',
1978739 => 'Danvers, MA',
1978740 => 'Salem, MA',
1978741 => 'Salem, MA',
1978744 => 'Salem, MA',
1978745 => 'Salem, MA',
1978749 => 'Andover, MA',
1978750 => 'Danvers, MA',
1978762 => 'Danvers, MA',
1978768 => 'Essex, MA',
1978772 => 'Ayer, MA',
1978774 => 'Danvers, MA',
1978777 => 'Danvers, MA',
1978779 => 'Bolton, MA',
1978827 => 'Ashburnham, MA',
1978834 => 'Amesbury, MA',
1978838 => 'Berlin, MA',
1978840 => 'Leominster, MA',
1978851 => 'Tewksbury, MA',
1978858 => 'Tewksbury, MA',
1978874 => 'Westminster, MA',
1978887 => 'Topsfield, MA',
1978897 => 'Maynard, MA',
1978921 => 'Beverly, MA',
1978922 => 'Beverly, MA',
1978927 => 'Beverly, MA',
1978928 => 'Hubbardston, MA',
1978934 => 'Lowell, MA',
1978937 => 'Lowell, MA',
1978939 => 'Templeton, MA',
1978948 => 'Rowley, MA',
1978952 => 'Littleton, MA',
1978957 => 'Dracut, MA',
1978969 => 'Beverly, MA',
1978970 => 'Lowell, MA',
1978977 => 'Peabody, MA',
1978988 => 'Wilmington, MA',
1979 => 'Texas',
1979209 => 'Bryan, TX',
1979233 => 'Freeport, TX',
1979234 => 'Eagle Lake, TX',
1979239 => 'Freeport, TX',
1979242 => 'La Grange, TX',
1979244 => 'Bay City, TX',
1979245 => 'Bay City, TX',
1979251 => 'Brenham, TX',
1979265 => 'Clute, TX',
1979272 => 'Caldwell, TX',
1979277 => 'Brenham, TX',
1979279 => 'Hearne, TX',
1979282 => 'Wharton, TX',
1979285 => 'Lake Jackson, TX',
1979297 => 'Lake Jackson, TX',
1979299 => 'Lake Jackson, TX',
1979323 => 'Bay City, TX',
1979335 => 'East Bernard, TX',
1979345 => 'West Columbia, TX',
1979421 => 'Brenham, TX',
1979480 => 'Lake Jackson, TX',
1979532 => 'Wharton, TX',
1979542 => 'Giddings, TX',
1979543 => 'El Campo, TX',
1979548 => 'Sweeny, TX',
1979567 => 'Caldwell, TX',
1979578 => 'El Campo, TX',
1979596 => 'Somerville, TX',
197969 => 'College Station, TX',
1979703 => 'Bryan, TX',
1979725 => 'Weimar, TX',
1979731 => 'Bryan, TX',
1979732 => 'Columbus, TX',
1979733 => 'Columbus, TX',
1979743 => 'Schulenburg, TX',
1979764 => 'College Station, TX',
1979773 => 'Lexington, TX',
1979774 => 'Bryan, TX',
1979775 => 'Bryan, TX',
1979776 => 'Bryan, TX',
1979778 => 'Bryan, TX',
1979779 => 'Bryan, TX',
1979793 => 'Needville, TX',
1979798 => 'Brazoria, TX',
1979822 => 'Bryan, TX',
1979823 => 'Bryan, TX',
1979826 => 'Hempstead, TX',
1979828 => 'Franklin, TX',
1979830 => 'Brenham, TX',
1979836 => 'Brenham, TX',
1979845 => 'College Station, TX',
1979848 => 'Angleton, TX',
1979849 => 'Angleton, TX',
1979864 => 'Angleton, TX',
1979865 => 'Bellville, TX',
1979885 => 'Sealy, TX',
1979968 => 'La Grange, TX',
1980 => 'North Carolina',
1980207 => 'Charlotte, NC',
1980224 => 'Charlotte, NC',
1980343 => 'Charlotte, NC',
1980487 => 'Shelby, NC',
1980819 => 'Charlotte, NC',
1984 => 'North Carolina',
1985 => 'Louisiana',
1985223 => 'Houma, LA',
1985229 => 'Kentwood, LA',
1985230 => 'Hammond, LA',
1985246 => 'Covington, LA',
1985249 => 'Covington, LA',
1985252 => 'Pierre Part, LA',
1985262 => 'Houma, LA',
1985288 => 'Slidell, LA',
1985325 => 'Cut Off, LA',
1985327 => 'Covington, LA',
1985331 => 'Luling, LA',
1985340 => 'Hammond, LA',
1985345 => 'Hammond, LA',
1985359 => 'LaPlace, LA',
1985369 => 'Napoleonville, LA',
1985370 => 'Ponchatoula, LA',
1985384 => 'Morgan City, LA',
1985385 => 'Morgan City, LA',
1985386 => 'Ponchatoula, LA',
1985395 => 'Patterson, LA',
1985396 => 'Golden Meadow, LA',
1985419 => 'Hammond, LA',
1985429 => 'Hammond, LA',
1985446 => 'Thibodaux, LA',
1985447 => 'Thibodaux, LA',
1985448 => 'Thibodaux, LA',
1985449 => 'Thibodaux, LA',
1985475 => 'Golden Meadow, LA',
1985493 => 'Thibodaux, LA',
1985532 => 'Lockport, LA',
1985536 => 'Reserve, LA',
1985537 => 'Raceland, LA',
1985542 => 'Hammond, LA',
1985543 => 'Hammond, LA',
1985580 => 'Houma, LA',
1985624 => 'Mandeville, LA',
1985626 => 'Mandeville, LA',
1985632 => 'Cut Off, LA',
1985639 => 'Slidell, LA',
1985641 => 'Slidell, LA',
1985643 => 'Slidell, LA',
1985645 => 'Slidell, LA',
1985646 => 'Slidell, LA',
1985649 => 'Slidell, LA',
1985651 => 'LaPlace, LA',
1985652 => 'LaPlace, LA',
1985662 => 'Hammond, LA',
1985674 => 'Mandeville, LA',
1985690 => 'Slidell, LA',
1985693 => 'Larose, LA',
1985727 => 'Mandeville, LA',
1985732 => 'Bogalusa, LA',
1985735 => 'Bogalusa, LA',
1985747 => 'Amite City, LA',
1985748 => 'Amite City, LA',
1985764 => 'Destrehan, LA',
1985778 => 'Mandeville, LA',
1985781 => 'Slidell, LA',
1985783 => 'Hahnville, LA',
1985785 => 'Luling, LA',
1985792 => 'Madisonville, LA',
1985795 => 'Franklinton, LA',
1985796 => 'Folsom, LA',
1985809 => 'Covington, LA',
1985839 => 'Franklinton, LA',
1985845 => 'Madisonville, LA',
1985847 => 'Slidell, LA',
1985851 => 'Houma, LA',
1985853 => 'Houma, LA',
1985857 => 'Houma, LA',
1985863 => 'Pearl River, LA',
1985867 => 'Covington, LA',
1985868 => 'Houma, LA',
1985871 => 'Covington, LA',
1985872 => 'Houma, LA',
1985873 => 'Houma, LA',
1985875 => 'Covington, LA',
1985876 => 'Houma, LA',
1985878 => 'Independence, LA',
1985879 => 'Houma, LA',
1985882 => 'Lacombe, LA',
1985892 => 'Covington, LA',
1985893 => 'Covington, LA',
1985898 => 'Covington, LA',
1986 => 'Idaho',
1989 => 'Michigan',
1989224 => 'St. Johns, MI',
1989227 => 'St. Johns, MI',
1989246 => 'Gladwin, MI',
1989249 => 'Saginaw, MI',
1989269 => 'Bad Axe, MI',
1989275 => 'Roscommon, MI',
1989288 => 'Durand, MI',
1989317 => 'Mount Pleasant, MI',
1989343 => 'West Branch, MI',
1989345 => 'West Branch, MI',
1989348 => 'Grayling, MI',
1989352 => 'Lakeview, MI',
1989354 => 'Alpena, MI',
1989356 => 'Alpena, MI',
1989358 => 'Alpena, MI',
1989362 => 'Tawas City, MI',
1989366 => 'Houghton Lake, MI',
1989386 => 'Clare, MI',
1989389 => 'Saint Helen, MI',
1989401 => 'Saginaw, MI',
1989422 => 'Houghton Lake, MI',
1989426 => 'Gladwin, MI',
1989427 => 'Edmore, MI',
1989435 => 'Beaverton, MI',
1989453 => 'Pigeon, MI',
1989463 => 'Alma, MI',
1989465 => 'Coleman, MI',
1989466 => 'Alma, MI',
1989471 => 'Ossineke, MI',
1989479 => 'Harbor Beach, MI',
1989486 => 'Midland, MI',
1989496 => 'Midland, MI',
1989497 => 'Saginaw, MI',
1989539 => 'Harrison, MI',
1989583 => 'Saginaw, MI',
1989584 => 'Carson City, MI',
1989588 => 'Farwell, MI',
1989593 => 'Fowler, MI',
1989624 => 'Birch Run, MI',
1989631 => 'Midland, MI',
1989633 => 'Midland, MI',
1989635 => 'Marlette, MI',
1989642 => 'Hemlock, MI',
1989643 => 'Merrill, MI',
1989644 => 'Weidman, MI',
1989652 => 'Frankenmuth, MI',
1989658 => 'Ubly, MI',
1989662 => 'Auburn, MI',
1989667 => 'Bay City, MI',
1989671 => 'Bay City, MI',
1989672 => 'Caro, MI',
1989673 => 'Caro, MI',
1989681 => 'St. Louis, MI',
1989684 => 'Bay City, MI',
1989685 => 'Rose City, MI',
1989686 => 'Bay City, MI',
1989687 => 'Sanford, MI',
1989695 => 'Freeland, MI',
1989697 => 'Linwood, MI',
1989705 => 'Gaylord, MI',
1989723 => 'Owosso, MI',
1989724 => 'Harrisville, MI',
1989725 => 'Owosso, MI',
1989727 => 'Hubbard Lake, MI',
1989728 => 'Hale, MI',
1989729 => 'Owosso, MI',
1989731 => 'Gaylord, MI',
1989732 => 'Gaylord, MI',
1989733 => 'Onaway, MI',
1989734 => 'Rogers City, MI',
1989736 => 'Lincoln, MI',
1989738 => 'Port Austin, MI',
1989739 => 'Oscoda, MI',
1989742 => 'Hillman, MI',
1989743 => 'Corunna, MI',
1989752 => 'Saginaw, MI',
1989753 => 'Saginaw, MI',
1989754 => 'Saginaw, MI',
1989755 => 'Saginaw, MI',
1989759 => 'Saginaw, MI',
1989772 => 'Mount Pleasant, MI',
1989773 => 'Mount Pleasant, MI',
1989775 => 'Mount Pleasant, MI',
1989779 => 'Mount Pleasant, MI',
1989781 => 'Saginaw, MI',
1989785 => 'Atlanta, MI',
1989786 => 'Lewiston, MI',
198979 => 'Saginaw, MI',
1989821 => 'Roscommon, MI',
1989823 => 'Vassar, MI',
1989826 => 'Mio, MI',
1989828 => 'Shepherd, MI',
1989831 => 'Stanton, MI',
1989832 => 'Midland, MI',
1989834 => 'Ovid, MI',
1989835 => 'Midland, MI',
1989837 => 'Midland, MI',
1989839 => 'Midland, MI',
1989842 => 'Breckenridge, MI',
1989843 => 'Mayville, MI',
1989845 => 'Chesaning, MI',
1989846 => 'Standish, MI',
1989848 => 'Fairview, MI',
1989856 => 'Caseville, MI',
1989862 => 'Elsie, MI',
1989865 => 'St. Charles, MI',
1989868 => 'Reese, MI',
1989871 => 'Millington, MI',
1989872 => 'Cass City, MI',
1989873 => 'Prescott, MI',
1989875 => 'Ithaca, MI',
1989876 => 'Au Gres, MI',
1989879 => 'Pinconning, MI',
1989883 => 'Sebewaing, MI',
1989891 => 'Bay City, MI',
1989892 => 'Bay City, MI',
1989893 => 'Bay City, MI',
1989894 => 'Bay City, MI',
1989895 => 'Bay City, MI',
);
| giggsey/libphonenumber-for-php | src/geocoding/data/en/19.php | PHP | apache-2.0 | 134,060 |
/*
* 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.druid.tests.indexer;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.apache.druid.indexer.partitions.DynamicPartitionsSpec;
import org.apache.druid.java.util.common.Pair;
import org.apache.druid.java.util.common.StringUtils;
import org.testng.annotations.DataProvider;
import java.io.Closeable;
import java.util.List;
import java.util.UUID;
import java.util.function.Function;
public abstract class AbstractS3InputSourceParallelIndexTest extends AbstractITBatchIndexTest
{
private static final String INDEX_TASK = "/indexer/wikipedia_cloud_index_task.json";
private static final String INDEX_QUERIES_RESOURCE = "/indexer/wikipedia_index_queries.json";
private static final String INDEX_DATASOURCE = "wikipedia_index_test_" + UUID.randomUUID();
private static final String INPUT_SOURCE_URIS_KEY = "uris";
private static final String INPUT_SOURCE_PREFIXES_KEY = "prefixes";
private static final String INPUT_SOURCE_OBJECTS_KEY = "objects";
private static final String WIKIPEDIA_DATA_1 = "wikipedia_index_data1.json";
private static final String WIKIPEDIA_DATA_2 = "wikipedia_index_data2.json";
private static final String WIKIPEDIA_DATA_3 = "wikipedia_index_data3.json";
@DataProvider
public static Object[][] resources()
{
return new Object[][]{
{new Pair<>(INPUT_SOURCE_URIS_KEY,
ImmutableList.of(
"s3://%%BUCKET%%/%%PATH%%" + WIKIPEDIA_DATA_1,
"s3://%%BUCKET%%/%%PATH%%" + WIKIPEDIA_DATA_2,
"s3://%%BUCKET%%/%%PATH%%" + WIKIPEDIA_DATA_3
)
)},
{new Pair<>(INPUT_SOURCE_PREFIXES_KEY,
ImmutableList.of(
"s3://%%BUCKET%%/%%PATH%%"
)
)},
{new Pair<>(INPUT_SOURCE_OBJECTS_KEY,
ImmutableList.of(
ImmutableMap.of("bucket", "%%BUCKET%%", "path", "%%PATH%%" + WIKIPEDIA_DATA_1),
ImmutableMap.of("bucket", "%%BUCKET%%", "path", "%%PATH%%" + WIKIPEDIA_DATA_2),
ImmutableMap.of("bucket", "%%BUCKET%%", "path", "%%PATH%%" + WIKIPEDIA_DATA_3)
)
)}
};
}
void doTest(Pair<String, List> s3InputSource) throws Exception
{
try (
final Closeable ignored1 = unloader(INDEX_DATASOURCE + config.getExtraDatasourceNameSuffix());
) {
final Function<String, String> s3PropsTransform = spec -> {
try {
String inputSourceValue = jsonMapper.writeValueAsString(s3InputSource.rhs);
inputSourceValue = StringUtils.replace(
inputSourceValue,
"%%BUCKET%%",
config.getCloudBucket()
);
inputSourceValue = StringUtils.replace(
inputSourceValue,
"%%PATH%%",
config.getCloudPath()
);
spec = StringUtils.replace(
spec,
"%%PARTITIONS_SPEC%%",
jsonMapper.writeValueAsString(new DynamicPartitionsSpec(null, null))
);
spec = StringUtils.replace(
spec,
"%%INPUT_SOURCE_TYPE%%",
"s3"
);
spec = StringUtils.replace(
spec,
"%%INPUT_SOURCE_PROPERTY_KEY%%",
s3InputSource.lhs
);
return StringUtils.replace(
spec,
"%%INPUT_SOURCE_PROPERTY_VALUE%%",
inputSourceValue
);
}
catch (Exception e) {
throw new RuntimeException(e);
}
};
doIndexTest(
INDEX_DATASOURCE,
INDEX_TASK,
s3PropsTransform,
INDEX_QUERIES_RESOURCE,
false,
true,
true
);
}
}
}
| implydata/druid | integration-tests/src/test/java/org/apache/druid/tests/indexer/AbstractS3InputSourceParallelIndexTest.java | Java | apache-2.0 | 4,697 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProtoCore;
using ProtoCore.Utils;
namespace GraphToDSCompiler
{
public class AstCodeBlockTraverse
{
//private AST.AssociativeAST.BinaryExpressionNode ben;
/// <summary>
/// This is used during ProtoAST generation to connect BinaryExpressionNode's
/// generated from Block nodes to its child AST tree - pratapa
/// </summary>
protected ProtoCore.AST.AssociativeAST.BinaryExpressionNode ChildTree { get; set; }
public AstCodeBlockTraverse(List<ProtoCore.AST.AssociativeAST.AssociativeNode> astList)
//: base(astList)
{ }
public AstCodeBlockTraverse(ProtoCore.AST.AssociativeAST.BinaryExpressionNode bNode)
{
ChildTree = bNode;
}
protected void EmitIdentifierNode(ref ProtoCore.AST.AssociativeAST.AssociativeNode identNode)
{
ProtoCore.AST.AssociativeAST.IdentifierNode iNode = ChildTree.LeftNode as ProtoCore.AST.AssociativeAST.IdentifierNode;
Validity.Assert(iNode != null);
if ((identNode as ProtoCore.AST.AssociativeAST.IdentifierNode).Value == iNode.Value)
{
//ProtoCore.AST.AssociativeAST.ArrayNode temp = (identNode as ProtoCore.AST.AssociativeAST.IdentifierNode).ArrayDimensions;
identNode = ChildTree;
//if ((identNode as ProtoCore.AST.AssociativeAST.BinaryExpressionNode).LeftNode is ProtoCore.AST.AssociativeAST.IdentifierNode)
// ((identNode as ProtoCore.AST.AssociativeAST.BinaryExpressionNode).LeftNode
// as AST.AssociativeAST.IdentifierNode).ArrayDimensions = temp;
}
}
public void DFSTraverse(ref ProtoCore.AST.AssociativeAST.AssociativeNode node)
{
if (node is ProtoCore.AST.AssociativeAST.IdentifierNode)
EmitIdentifierNode(ref node);
else if (node is ProtoCore.AST.AssociativeAST.IdentifierListNode)
{
ProtoCore.AST.AssociativeAST.IdentifierListNode identList = node as ProtoCore.AST.AssociativeAST.IdentifierListNode;
EmitIdentifierListNode(ref identList);
}
else if (node is ProtoCore.AST.AssociativeAST.IntNode)
{
ProtoCore.AST.AssociativeAST.IntNode intNode = node as ProtoCore.AST.AssociativeAST.IntNode;
EmitIntNode(ref intNode);
}
else if (node is ProtoCore.AST.AssociativeAST.DoubleNode)
{
ProtoCore.AST.AssociativeAST.DoubleNode doubleNode = node as ProtoCore.AST.AssociativeAST.DoubleNode;
EmitDoubleNode(ref doubleNode);
}
else if (node is ProtoCore.AST.AssociativeAST.FunctionCallNode)
{
ProtoCore.AST.AssociativeAST.FunctionCallNode funcCallNode = node as ProtoCore.AST.AssociativeAST.FunctionCallNode;
EmitFunctionCallNode(ref funcCallNode);
}
else if (node is ProtoCore.AST.AssociativeAST.FunctionDotCallNode)
{
ProtoCore.AST.AssociativeAST.FunctionDotCallNode funcDotCall = node as ProtoCore.AST.AssociativeAST.FunctionDotCallNode;
EmitFunctionDotCallNode(ref funcDotCall);
}
else if (node is ProtoCore.AST.AssociativeAST.BinaryExpressionNode)
{
ProtoCore.AST.AssociativeAST.BinaryExpressionNode binaryExpr = node as ProtoCore.AST.AssociativeAST.BinaryExpressionNode;
if (binaryExpr.Optr != ProtoCore.DSASM.Operator.assign);
EmitBinaryNode(ref binaryExpr);
if (binaryExpr.Optr == ProtoCore.DSASM.Operator.assign)
{
}
if (binaryExpr.Optr != ProtoCore.DSASM.Operator.assign);
}
else if (node is ProtoCore.AST.AssociativeAST.FunctionDefinitionNode)
{
ProtoCore.AST.AssociativeAST.FunctionDefinitionNode funcDefNode = node as ProtoCore.AST.AssociativeAST.FunctionDefinitionNode;
EmitFunctionDefNode(ref funcDefNode);
}
else if (node is ProtoCore.AST.AssociativeAST.ClassDeclNode)
{
ProtoCore.AST.AssociativeAST.ClassDeclNode classDeclNode = node as ProtoCore.AST.AssociativeAST.ClassDeclNode;
EmitClassDeclNode(ref classDeclNode);
}
else if (node is ProtoCore.AST.AssociativeAST.NullNode)
{
ProtoCore.AST.AssociativeAST.NullNode nullNode = node as ProtoCore.AST.AssociativeAST.NullNode;
EmitNullNode(ref nullNode);
}
else if (node is ProtoCore.AST.AssociativeAST.ArrayIndexerNode)
{
ProtoCore.AST.AssociativeAST.ArrayIndexerNode arrIdxNode = node as ProtoCore.AST.AssociativeAST.ArrayIndexerNode;
EmitArrayIndexerNode(ref arrIdxNode);
}
else if (node is ProtoCore.AST.AssociativeAST.ExprListNode)
{
ProtoCore.AST.AssociativeAST.ExprListNode exprListNode = node as ProtoCore.AST.AssociativeAST.ExprListNode;
EmitExprListNode(ref exprListNode);
}
}
//=======================
/// <summary>
/// Depth first traversal of an AST node
/// </summary>
/// <param name="node"></param>
/// <summary>
/// These functions emit the DesignScript code on the destination stream
/// </summary>
/// <param name="identNode"></param>
#region ASTNODE_CODE_EMITTERS
private void EmitArrayIndexerNode(ref ProtoCore.AST.AssociativeAST.ArrayIndexerNode arrIdxNode)
{
if (arrIdxNode.Array is ProtoCore.AST.AssociativeAST.IdentifierNode)
EmitIdentifierNode(ref arrIdxNode.Array);
else if (arrIdxNode.Array is ProtoCore.AST.AssociativeAST.BinaryExpressionNode)
{
ProtoCore.AST.AssociativeAST.AssociativeNode ben = (arrIdxNode.Array as ProtoCore.AST.AssociativeAST.BinaryExpressionNode).LeftNode;
EmitIdentifierNode(ref ben);
ProtoCore.AST.AssociativeAST.AssociativeNode rightNode = (arrIdxNode.Array as ProtoCore.AST.AssociativeAST.BinaryExpressionNode).RightNode;
DFSTraverse(ref rightNode);
}
}
private void EmitExprListNode(ref ProtoCore.AST.AssociativeAST.ExprListNode exprListNode)
{
for (int i = 0; i < exprListNode.list.Count; i++)
{
ProtoCore.AST.AssociativeAST.AssociativeNode node = exprListNode.list[i];
DFSTraverse(ref node);
exprListNode.list[i] = node;
}
}
protected virtual void EmitImportNode(ProtoCore.AST.AssociativeAST.ImportNode importNode)
{
}
protected virtual void EmitIdentifierListNode(ref ProtoCore.AST.AssociativeAST.IdentifierListNode identList)
{
Validity.Assert(null != identList);
ProtoCore.AST.AssociativeAST.AssociativeNode left = identList.LeftNode;
DFSTraverse(ref left);
ProtoCore.AST.AssociativeAST.AssociativeNode right = identList.RightNode;
DFSTraverse(ref right);
}
protected virtual void EmitIntNode(ref ProtoCore.AST.AssociativeAST.IntNode intNode)
{
Validity.Assert(null != intNode);
}
protected virtual void EmitDoubleNode(ref ProtoCore.AST.AssociativeAST.DoubleNode doubleNode)
{
Validity.Assert(null != doubleNode);
}
protected virtual void EmitFunctionCallNode(ref ProtoCore.AST.AssociativeAST.FunctionCallNode funcCallNode)
{
Validity.Assert(null != funcCallNode);
Validity.Assert(funcCallNode.Function is ProtoCore.AST.AssociativeAST.IdentifierNode);
string functionName = (funcCallNode.Function as ProtoCore.AST.AssociativeAST.IdentifierNode).Value;
Validity.Assert(!string.IsNullOrEmpty(functionName));
for (int n = 0; n < funcCallNode.FormalArguments.Count; ++n)
{
ProtoCore.AST.AssociativeAST.AssociativeNode argNode = funcCallNode.FormalArguments[n];
DFSTraverse(ref argNode);
funcCallNode.FormalArguments[n] = argNode;
if (n + 1 < funcCallNode.FormalArguments.Count)
{
}
}
}
protected virtual void EmitFunctionDotCallNode(ref ProtoCore.AST.AssociativeAST.FunctionDotCallNode dotCall)
{
Validity.Assert(null != dotCall);
ProtoCore.AST.AssociativeAST.AssociativeNode identNode = dotCall.DotCall.FormalArguments[0];
if (identNode is ProtoCore.AST.AssociativeAST.BinaryExpressionNode)
{
ProtoCore.AST.AssociativeAST.AssociativeNode idNode = (identNode as ProtoCore.AST.AssociativeAST.BinaryExpressionNode).LeftNode;
EmitIdentifierNode(ref idNode);
(identNode as ProtoCore.AST.AssociativeAST.BinaryExpressionNode).LeftNode = idNode;
}
else
EmitIdentifierNode(ref identNode);
dotCall.DotCall.FormalArguments[0] = identNode;
ProtoCore.AST.AssociativeAST.FunctionCallNode funcDotCall = dotCall.FunctionCall;
EmitFunctionCallNode(ref funcDotCall);
}
protected virtual void EmitBinaryNode(ref ProtoCore.AST.AssociativeAST.BinaryExpressionNode binaryExprNode)
{
Validity.Assert(null != binaryExprNode);
ProtoCore.AST.AssociativeAST.AssociativeNode leftNode = binaryExprNode.LeftNode;
DFSTraverse(ref leftNode);
ProtoCore.AST.AssociativeAST.AssociativeNode rightNode = binaryExprNode.RightNode;
DFSTraverse(ref rightNode);
}
protected virtual void EmitFunctionDefNode(ref ProtoCore.AST.AssociativeAST.FunctionDefinitionNode funcDefNode)
{
if (funcDefNode.ReturnType.UID != ProtoCore.DSASM.Constants.kInvalidIndex)
{
}
if (funcDefNode.Singnature != null)
{
}
else
{
}
if (null != funcDefNode.FunctionBody)
{
List<ProtoCore.AST.AssociativeAST.AssociativeNode> funcBody = funcDefNode.FunctionBody.Body;
//EmitCode("{\n");
foreach (ProtoCore.AST.AssociativeAST.AssociativeNode bodyNode in funcBody)
{
if (bodyNode is ProtoCore.AST.AssociativeAST.BinaryExpressionNode)
{
ProtoCore.AST.AssociativeAST.BinaryExpressionNode binaryEpr = bodyNode as ProtoCore.AST.AssociativeAST.BinaryExpressionNode;
EmitBinaryNode(ref binaryEpr);
}
if (bodyNode is ProtoCore.AST.AssociativeAST.ReturnNode)
{
ProtoCore.AST.AssociativeAST.ReturnNode returnNode = bodyNode as ProtoCore.AST.AssociativeAST.ReturnNode;
EmitReturnNode(ref returnNode);
}
}
}
}
protected virtual void EmitReturnNode(ref ProtoCore.AST.AssociativeAST.ReturnNode returnNode)
{
ProtoCore.AST.AssociativeAST.AssociativeNode rightNode = returnNode.ReturnExpr;
DFSTraverse(ref rightNode);
}
protected virtual void EmitVarDeclNode(ref ProtoCore.AST.AssociativeAST.VarDeclNode varDeclNode)
{
}
protected virtual void EmitClassDeclNode(ref ProtoCore.AST.AssociativeAST.ClassDeclNode classDeclNode)
{
List<ProtoCore.AST.AssociativeAST.AssociativeNode> varList = classDeclNode.varlist;
foreach (ProtoCore.AST.AssociativeAST.AssociativeNode varMember in varList)
{
//how is var member stored?
if (varMember is ProtoCore.AST.AssociativeAST.VarDeclNode)
{
ProtoCore.AST.AssociativeAST.VarDeclNode varDecl = varMember as ProtoCore.AST.AssociativeAST.VarDeclNode;
EmitVarDeclNode(ref varDecl);
}
}
List<ProtoCore.AST.AssociativeAST.AssociativeNode> funcList = classDeclNode.funclist;
foreach (ProtoCore.AST.AssociativeAST.AssociativeNode funcMember in funcList)
{
if (funcMember is ProtoCore.AST.AssociativeAST.FunctionDefinitionNode)
{
ProtoCore.AST.AssociativeAST.FunctionDefinitionNode funcDefNode = funcMember as ProtoCore.AST.AssociativeAST.FunctionDefinitionNode;
EmitFunctionDefNode(ref funcDefNode);
}
}
}
protected virtual void EmitNullNode(ref ProtoCore.AST.AssociativeAST.NullNode nullNode)
{
Validity.Assert(null != nullNode);
}
#endregion
}
}
| DynamoDS/designscript-archive | Core/GraphToDSCompiler/AstCodeBlockTraverse.cs | C# | apache-2.0 | 13,253 |
/**
* 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.apache.aurora.common.net.http.handlers;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.inject.name.Named;
/**
* A servlet that provides a way to remotely signal the process to initiate a clean shutdown
* sequence.
*/
@Path("/quitquitquit")
public class QuitHandler {
private static final Logger LOG = Logger.getLogger(QuitHandler.class.getName());
/**
* A {@literal @Named} binding key for the QuitHandler listener.
*/
public static final String QUIT_HANDLER_KEY =
"com.twitter.common.net.http.handlers.QuitHandler.listener";
private final Runnable quitListener;
/**
* Constructs a new QuitHandler that will notify the given {@code quitListener} when the servlet
* is accessed. It is the responsibility of the listener to initiate a clean shutdown of the
* process.
*
* @param quitListener Runnable to notify when the servlet is accessed.
*/
@Inject
public QuitHandler(@Named(QUIT_HANDLER_KEY) Runnable quitListener) {
this.quitListener = Preconditions.checkNotNull(quitListener);
}
@POST
@Produces(MediaType.TEXT_PLAIN)
public String quit(@Context HttpServletRequest req) {
LOG.info(String.format("Received quit HTTP signal from %s (%s)",
req.getRemoteAddr(), req.getRemoteHost()));
new Thread(quitListener).start();
return "Notifying quit listener.";
}
}
| mschenck/aurora | commons/src/main/java/org/apache/aurora/common/net/http/handlers/QuitHandler.java | Java | apache-2.0 | 2,198 |
/**
* 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.camel.api.management.mbean;
public interface RouteError {
enum Phase {
START,
STOP,
SUSPEND,
RESUME,
SHUTDOWN,
REMOVE
}
/**
* Gets the phase associated with the error.
*
* @return the phase.
*/
Phase getPhase();
/**
* Gets the error.
*
* @return the error.
*/
Throwable getException();
}
| punkhorn/camel-upstream | core/camel-management-api/src/main/java/org/apache/camel/api/management/mbean/RouteError.java | Java | apache-2.0 | 1,226 |
package org.apache.cassandra.io.sstable;
/*
*
* 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 static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.apache.cassandra.CleanupHelper;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.filter.IFilter;
import org.apache.cassandra.db.columniterator.IdentityQueryFilter;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.io.util.DataOutputBuffer;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.thrift.IndexClause;
import org.apache.cassandra.thrift.IndexExpression;
import org.apache.cassandra.thrift.IndexOperator;
import org.apache.cassandra.utils.FBUtilities;
import org.junit.Test;
public class SSTableWriterTest extends CleanupHelper {
@Test
public void testRecoverAndOpen() throws IOException, ExecutionException, InterruptedException
{
RowMutation rm;
rm = new RowMutation("Keyspace1", "k1".getBytes());
rm.add(new QueryPath("Indexed1", null, "birthdate".getBytes("UTF8")), FBUtilities.toByteArray(1L), new TimestampClock(0));
rm.apply();
ColumnFamily cf = ColumnFamily.create("Keyspace1", "Indexed1");
cf.addColumn(new Column("birthdate".getBytes(), FBUtilities.toByteArray(1L), new TimestampClock(0)));
cf.addColumn(new Column("anydate".getBytes(), FBUtilities.toByteArray(1L), new TimestampClock(0)));
Map<byte[], byte[]> entries = new HashMap<byte[], byte[]>();
DataOutputBuffer buffer = new DataOutputBuffer();
ColumnFamily.serializer().serializeWithIndexes(cf, buffer);
entries.put("k2".getBytes(), Arrays.copyOf(buffer.getData(), buffer.getLength()));
cf.clear();
cf.addColumn(new Column("anydate".getBytes(), FBUtilities.toByteArray(1L), new TimestampClock(0)));
buffer = new DataOutputBuffer();
ColumnFamily.serializer().serializeWithIndexes(cf, buffer);
entries.put("k3".getBytes(), Arrays.copyOf(buffer.getData(), buffer.getLength()));
SSTableReader orig = SSTableUtils.writeRawSSTable("Keyspace1", "Indexed1", entries);
// whack the index to trigger the recover
FileUtils.deleteWithConfirm(orig.desc.filenameFor(Component.PRIMARY_INDEX));
FileUtils.deleteWithConfirm(orig.desc.filenameFor(Component.FILTER));
SSTableReader sstr = CompactionManager.instance.submitSSTableBuild(orig.desc).get();
ColumnFamilyStore cfs = Table.open("Keyspace1").getColumnFamilyStore("Indexed1");
cfs.addSSTable(sstr);
cfs.buildSecondaryIndexes(cfs.getSSTables(), cfs.getIndexedColumns());
IndexExpression expr = new IndexExpression("birthdate".getBytes("UTF8"), IndexOperator.EQ, FBUtilities.toByteArray(1L));
IndexClause clause = new IndexClause(Arrays.asList(expr), "".getBytes(), 100);
IFilter filter = new IdentityQueryFilter();
IPartitioner p = StorageService.getPartitioner();
Range range = new Range(p.getMinimumToken(), p.getMinimumToken());
List<Row> rows = cfs.scan(clause, range, filter);
assertEquals("IndexExpression should return two rows on recoverAndOpen", 2, rows.size());
assertTrue("First result should be 'k1'",Arrays.equals("k1".getBytes(), rows.get(0).key.key));
}
}
| lvasselt/cassandra-shawn | test/unit/org/apache/cassandra/io/sstable/SSTableWriterTest.java | Java | apache-2.0 | 4,468 |
/*
* 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 tachyon;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link UnderFileSystem}
*/
public final class UnderFileSystemTest {
@Test
public void parseTest() {
Pair<String, String> result = UnderFileSystem.parse("/path");
Assert.assertEquals(result.getFirst(), "/");
Assert.assertEquals(result.getSecond(), "/path");
result = UnderFileSystem.parse("file:///path");
Assert.assertEquals(result.getFirst(), "/");
Assert.assertEquals(result.getSecond(), "/path");
result = UnderFileSystem.parse("tachyon://localhost:19998");
Assert.assertEquals(result.getFirst(), "tachyon://localhost:19998");
Assert.assertEquals(result.getSecond(), "/");
result = UnderFileSystem.parse("tachyon://localhost:19998/");
Assert.assertEquals(result.getFirst(), "tachyon://localhost:19998");
Assert.assertEquals(result.getSecond(), "/");
result = UnderFileSystem.parse("tachyon://localhost:19998/path");
Assert.assertEquals(result.getFirst(), "tachyon://localhost:19998");
Assert.assertEquals(result.getSecond(), "/path");
result = UnderFileSystem.parse("tachyon-ft://localhost:19998/path");
Assert.assertEquals(result.getFirst(), "tachyon-ft://localhost:19998");
Assert.assertEquals(result.getSecond(), "/path");
result = UnderFileSystem.parse("hdfs://localhost:19998/path");
Assert.assertEquals(result.getFirst(), "hdfs://localhost:19998");
Assert.assertEquals(result.getSecond(), "/path");
result = UnderFileSystem.parse("s3://localhost:19998/path");
Assert.assertEquals(result.getFirst(), "s3://localhost:19998");
Assert.assertEquals(result.getSecond(), "/path");
result = UnderFileSystem.parse("s3n://localhost:19998/path");
Assert.assertEquals(result.getFirst(), "s3n://localhost:19998");
Assert.assertEquals(result.getSecond(), "/path");
Assert.assertEquals(UnderFileSystem.parse(null), null);
Assert.assertEquals(UnderFileSystem.parse(""), null);
Assert.assertEquals(UnderFileSystem.parse("anythingElse"), null);
}
}
| gsoundar/mambo-ec2-deploy | packages/tachyon-0.5.0/core/src/test/java/tachyon/UnderFileSystemTest.java | Java | apache-2.0 | 2,856 |
.example {
position: relative;
padding: 20px;
border-style: solid;
background-color: #fff;
border: 1px solid #ddd;
outline: none;
transition: all 0.3s;
height: 75px;
}
.pad0 {
padding: 0;
}
.description {
padding: 15px 18px 25px;
}
| ljh50/thinkphp-agile-dev | Addons/Report/_static/css/report.css | CSS | apache-2.0 | 252 |
package javasmmr.zoowsome.models.animals;
public class Dolphin extends Aquatic {
public Dolphin(Integer nrOfLegs, String name,Integer avgSwimDepth, Water waterType) {
setNrOfLegs(nrOfLegs);
setName(name);
setAvgSwimDepth(avgSwimDepth);
setWaterType(waterType);
}
public Dolphin() {
this(new Integer(0),"dolphin", new Integer(100), Water.SALTWATER);
}
}
| JavaSummer/JavaMainRepo | Students/Pop P. Roxana/assignment3.1/src/javasmmr/zoowsome/models/animals/Dolphin.java | Java | apache-2.0 | 372 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_09) on Wed Aug 01 14:02:17 EEST 2007 -->
<TITLE>
datechooser.beans.customizer.edit (DateChooser javadoc)
</TITLE>
<META NAME="keywords" CONTENT="datechooser.beans.customizer.edit package">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameTitleFont">
<A HREF="../../../../datechooser/beans/customizer/edit/package-summary.html" target="classFrame">datechooser.beans.customizer.edit</A></FONT>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Classes</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="PropertyCellEditor.html" title="class in datechooser.beans.customizer.edit" target="classFrame">PropertyCellEditor</A>
<BR>
<A HREF="TextChangeListener.html" title="class in datechooser.beans.customizer.edit" target="classFrame">TextChangeListener</A></FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
| AndresJMM/Proyecto | Proyecto/librerias/jdatechooser_bin_doc_1_1_1/javadoc/datechooser/beans/customizer/edit/package-frame.html | HTML | apache-2.0 | 1,163 |
/*
* 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 privileges and
* limitations under the License.
*/
package org.apache.ambari.server.controller.internal;
import org.apache.ambari.server.controller.spi.Predicate;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.orm.dao.ClusterDAO;
import org.apache.ambari.server.orm.entities.ClusterEntity;
import org.apache.ambari.server.orm.entities.GroupEntity;
import org.apache.ambari.server.orm.entities.PermissionEntity;
import org.apache.ambari.server.orm.entities.PrivilegeEntity;
import org.apache.ambari.server.orm.entities.ResourceEntity;
import org.apache.ambari.server.orm.entities.ResourceTypeEntity;
import org.apache.ambari.server.orm.entities.UserEntity;
import org.apache.ambari.server.orm.entities.ViewEntity;
import org.apache.ambari.server.orm.entities.ViewInstanceEntity;
import org.apache.ambari.server.security.authorization.ResourceType;
import org.apache.ambari.server.security.authorization.RoleAuthorization;
import org.apache.ambari.server.view.ViewRegistry;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.apache.ambari.server.controller.internal.ClusterPrivilegeResourceProvider.PRIVILEGE_CLUSTER_NAME_PROPERTY_ID;
import static org.apache.ambari.server.controller.internal.ViewPrivilegeResourceProvider.PRIVILEGE_INSTANCE_NAME_PROPERTY_ID;
import static org.apache.ambari.server.controller.internal.ViewPrivilegeResourceProvider.PRIVILEGE_VIEW_NAME_PROPERTY_ID;
import static org.apache.ambari.server.controller.internal.ViewPrivilegeResourceProvider.PRIVILEGE_VIEW_VERSION_PROPERTY_ID;
/**
* Resource provider for Ambari privileges.
*/
public class AmbariPrivilegeResourceProvider extends PrivilegeResourceProvider<Object> {
public static final String PRIVILEGE_TYPE_PROPERTY_ID = "PrivilegeInfo/type";
/**
* Data access object used to obtain privilege entities.
*/
protected static ClusterDAO clusterDAO;
/**
* The property ids for an Ambari privilege resource.
*/
private static Set<String> propertyIds = new HashSet<String>();
static {
propertyIds.add(PRIVILEGE_ID_PROPERTY_ID);
propertyIds.add(PERMISSION_NAME_PROPERTY_ID);
propertyIds.add(PERMISSION_LABEL_PROPERTY_ID);
propertyIds.add(PRINCIPAL_NAME_PROPERTY_ID);
propertyIds.add(PRINCIPAL_TYPE_PROPERTY_ID);
propertyIds.add(PRIVILEGE_VIEW_NAME_PROPERTY_ID);
propertyIds.add(PRIVILEGE_VIEW_VERSION_PROPERTY_ID);
propertyIds.add(PRIVILEGE_INSTANCE_NAME_PROPERTY_ID);
propertyIds.add(PRIVILEGE_CLUSTER_NAME_PROPERTY_ID);
propertyIds.add(PRIVILEGE_TYPE_PROPERTY_ID);
}
/**
* The key property ids for a privilege resource.
*/
private static Map<Resource.Type, String> keyPropertyIds = new HashMap<Resource.Type, String>();
static {
keyPropertyIds.put(Resource.Type.AmbariPrivilege, PRIVILEGE_ID_PROPERTY_ID);
}
// ----- Constructors ------------------------------------------------------
/**
* Construct an AmbariPrivilegeResourceProvider.
*/
public AmbariPrivilegeResourceProvider() {
super(propertyIds, keyPropertyIds, Resource.Type.AmbariPrivilege);
EnumSet<RoleAuthorization> requiredAuthorizations = EnumSet.of(RoleAuthorization.AMBARI_ASSIGN_ROLES);
setRequiredCreateAuthorizations(requiredAuthorizations);
setRequiredDeleteAuthorizations(requiredAuthorizations);
setRequiredGetAuthorizations(requiredAuthorizations);
setRequiredUpdateAuthorizations(requiredAuthorizations);
}
// ----- AmbariPrivilegeResourceProvider ---------------------------------
/**
* Static initialization.
*
* @param clusterDao the cluster data access object
*/
public static void init(ClusterDAO clusterDao) {
clusterDAO = clusterDao;
}
// ----- AbstractResourceProvider ------------------------------------------
@Override
public Map<Resource.Type, String> getKeyPropertyIds() {
return keyPropertyIds;
}
// ----- PrivilegeResourceProvider -----------------------------------------
@Override
public Map<Long, Object> getResourceEntities(Map<String, Object> properties) {
Map<Long, Object> resourceEntities = new HashMap<Long, Object>();
resourceEntities.put(ResourceEntity.AMBARI_RESOURCE_ID, null);
// add cluster entities
List<ClusterEntity> clusterEntities = clusterDAO.findAll();
if (clusterEntities != null) {
for (ClusterEntity clusterEntity : clusterEntities) {
resourceEntities.put(clusterEntity.getResource().getId(), clusterEntity);
}
}
//add view entities
ViewRegistry viewRegistry = ViewRegistry.getInstance();
for (ViewEntity viewEntity : viewRegistry.getDefinitions()) {
if (viewEntity.isDeployed()) {
for (ViewInstanceEntity viewInstanceEntity : viewEntity.getInstances()) {
resourceEntities.put(viewInstanceEntity.getResource().getId(), viewInstanceEntity);
}
}
}
return resourceEntities;
}
@Override
protected Resource toResource(PrivilegeEntity privilegeEntity,
Map<Long, UserEntity> userEntities,
Map<Long, GroupEntity> groupEntities,
Map<Long, PermissionEntity> roleEntities,
Map<Long, Object> resourceEntities,
Set<String> requestedIds) {
Resource resource = super.toResource(privilegeEntity, userEntities, groupEntities, roleEntities, resourceEntities, requestedIds);
if (resource != null) {
ResourceEntity resourceEntity = privilegeEntity.getResource();
ResourceTypeEntity type = resourceEntity.getResourceType();
String typeName = type.getName();
ResourceType resourceType = ResourceType.translate(typeName);
if(resourceType != null) {
switch (resourceType) {
case AMBARI:
// there is nothing special to add for this case
break;
case CLUSTER:
ClusterEntity clusterEntity = (ClusterEntity) resourceEntities.get(resourceEntity.getId());
setResourceProperty(resource, PRIVILEGE_CLUSTER_NAME_PROPERTY_ID, clusterEntity.getClusterName(), requestedIds);
break;
case VIEW:
ViewInstanceEntity viewInstanceEntity = (ViewInstanceEntity) resourceEntities.get(resourceEntity.getId());
ViewEntity viewEntity = viewInstanceEntity.getViewEntity();
setResourceProperty(resource, PRIVILEGE_VIEW_NAME_PROPERTY_ID, viewEntity.getCommonName(), requestedIds);
setResourceProperty(resource, PRIVILEGE_VIEW_VERSION_PROPERTY_ID, viewEntity.getVersion(), requestedIds);
setResourceProperty(resource, PRIVILEGE_INSTANCE_NAME_PROPERTY_ID, viewInstanceEntity.getName(), requestedIds);
break;
}
setResourceProperty(resource, PRIVILEGE_TYPE_PROPERTY_ID, resourceType.name(), requestedIds);
}
}
return resource;
}
@Override
public Long getResourceEntityId(Predicate predicate) {
return ResourceEntity.AMBARI_RESOURCE_ID;
}
}
| arenadata/ambari | ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariPrivilegeResourceProvider.java | Java | apache-2.0 | 7,894 |
#
# %CopyrightBegin%
#
# Copyright Ericsson AB 2009. All Rights Reserved.
#
# The contents of this file are subject to the Erlang Public License,
# Version 1.1, (the "License"); you may not use this file except in
# compliance with the License. You should have received a copy of the
# Erlang Public License along with this software. If not, it can be
# retrieved online at http://www.erlang.org/.
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
# the License for the specific language governing rights and limitations
# under the License.
#
# %CopyrightEnd%
#
include ../../vsn.mk
include ../../config.mk
TOPDIR = ../..
SRC = .
BIN = .
ERLINC = $(TOPDIR)/include
ERLC = erlc
TESTMODS = \
demo \
demo_html_tagger \
ex_aui \
ex_button \
ex_canvas \
ex_canvas_paint \
ex_choices \
ex_cursor \
ex_dialogs \
ex_frame_utils \
ex_gauge \
ex_gl \
ex_grid \
ex_htmlWindow \
ex_listCtrl \
ex_notebook \
ex_pickers \
ex_popupMenu \
ex_radioBox \
ex_sashWindow \
ex_sizers \
ex_slider \
ex_splitterWindow \
ex_static \
ex_textCtrl \
ex_treeCtrl \
ex_graphicsContext
TESTTARGETS = $(TESTMODS:%=%.beam)
TESTSRC = $(TESTMODS:%=%.erl)
# Targets
opt debug: $(TESTTARGETS)
clean:
rm -f $(TESTTARGETS)
rm -f *~ core erl_crash.dump
docs:
run: opt
erl -smp -detached -pa $(TOPDIR)/ebin -s demo
ifneq ($(INSIDE_ERLSRC),true)
%.beam: %.erl
$(ERLC) -W -I$(ERLINC) -bbeam -o$(BIN) $<
else
EXRELSYSDIR = $(RELSYSDIR)/examples/demo
include $(ERL_TOP)/make/otp_release_targets.mk
docs:
release_spec:
$(INSTALL_DIR) $(EXRELSYSDIR)
$(INSTALL_DATA) $(TESTSRC) $(EXRELSYSDIR)
$(INSTALL_DATA) $(TESTTARGETS) $(EXRELSYSDIR)
$(INSTALL_DATA) image.jpg erlang.png ex_htmlWindow.html $(EXRELSYSDIR)
release_tests_spec:
release_docs_spec:
endif
| jtimberman/omnibus | source/otp_src_R14B02/lib/wx/examples/demo/Makefile | Makefile | apache-2.0 | 1,868 |
<?php declare(strict_types=1);
/*.
require_module 'standard';
.*/
/**
* @OA\Get(
* tags={"registration"},
* path="/registration/open/{event}",
* summary="Returns if event registration is open or not..",
* @OA\Parameter(
* description="Event ID",
* in="path",
* name="event",
* required=true,
* @OA\Schema(type="integer")
* ),
* @OA\Response(
* response=200,
* description="Event registration open status",
* @OA\JsonContent(
* @OA\Property(
* property="type",
* type="string",
* enum={"registration"}
* ),
* @OA\Property(
* property="event",
* type="integer",
* description="event Id"
* ),
* @OA\Property(
* property="open",
* type="boolean",
* description="Is registration open"
* )
* )
* ),
* @OA\Response(
* response=404,
* ref="#/components/responses/event_not_found"
* )
* )
*
* @OA\Get(
* tags={"registration"},
* path="/registration/open",
* summary="Returns if current event registration is open or not..",
* @OA\Response(
* response=200,
* description="Event registration open status",
* @OA\JsonContent(
* @OA\Property(
* property="type",
* type="string",
* enum={"registration"}
* ),
* @OA\Property(
* property="event",
* type="integer",
* description="event Id"
* ),
* @OA\Property(
* property="open",
* type="boolean",
* description="Is registration open"
* )
* )
* )
* )
**/
namespace App\Modules\registration\Controller;
use Slim\Http\Request;
use Slim\Http\Response;
use Atlas\Query\Select;
use App\Controller\NotFoundException;
class GetOpen extends BaseRegistration
{
use \App\Controller\TraitConfiguration;
public function buildResource(Request $request, Response $response, $args): array
{
if (array_key_exists('event', $args)) {
$event = $args['event'];
} else {
$event = 'current';
}
$event = $this->getEvent($event)['id'];
if (!$event) {
throw new NotFoundException('Event not found');
}
$data = Select::new($this->container->db)
->columns('*')
->from('Events')
->whereEquals(['EventID' => $event])
->fetchOne();
if (empty($data)) {
throw new NotFoundException('Event not found');
}
$now = strtotime('now');
$opentime = strtotime($data['DateFrom']);
$closetime = strtotime($data['DateTo']);
$open = (($opentime <= $now) && ($now <= $closetime));
if ($open != false) {
$data = $this->getConfiguration([], 'Registration_Configuration');
$config = [];
foreach ($data as $entry) {
$config[$entry['field']] = $entry['value'];
}
$today = intval(date("H"));
$open = ($config['ForceOpen']) || (
($config['RegistrationOpen'] <= $today) &&
($today < $config['RegistrationClose']));
}
$result = ['type' => 'registration',
'event' => $event,
'open' => $open];
return [
\App\Controller\BaseController::RESOURCE_TYPE,
$result];
}
/* end GetOpen */
}
| CON-In-A-Box/ConComSignIn | api/src/Modules/registration/Controller/GetOpen.php | PHP | apache-2.0 | 3,828 |
-- @author prabhd
-- @created 2014-04-01 12:00:00
-- @modified 2012-04-01 12:00:00
-- @tags dml MPP-21090 ORCA
-- @optimizer_mode on
-- @description Tests for MPP-21090
\echo --start_ignore
set gp_enable_column_oriented_table=on;
\echo --end_ignore
DROP TABLE IF EXISTS mpp21090_drop_lastcol_dml_timestamptz;
CREATE TABLE mpp21090_drop_lastcol_dml_timestamptz(
col1 int,
col2 decimal,
col3 char,
col4 date,
col5 timestamptz
) with (appendonly= true) DISTRIBUTED by(col3);
INSERT INTO mpp21090_drop_lastcol_dml_timestamptz VALUES(0,0.00,'a','2014-01-01','2013-12-31 12:00:00 PST');
SELECT * FROM mpp21090_drop_lastcol_dml_timestamptz ORDER BY 1,2,3,4;
ALTER TABLE mpp21090_drop_lastcol_dml_timestamptz DROP COLUMN col5;
INSERT INTO mpp21090_drop_lastcol_dml_timestamptz SELECT 1,1.00,'b','2014-01-02';
SELECT * FROM mpp21090_drop_lastcol_dml_timestamptz ORDER BY 1,2,3,4;
UPDATE mpp21090_drop_lastcol_dml_timestamptz SET col3='c' WHERE col3 = 'b' AND col1 = 1;
SELECT * FROM mpp21090_drop_lastcol_dml_timestamptz ORDER BY 1,2,3,4;
DELETE FROM mpp21090_drop_lastcol_dml_timestamptz WHERE col3='c';
SELECT * FROM mpp21090_drop_lastcol_dml_timestamptz ORDER BY 1,2,3,4;
| lintzc/gpdb | src/test/tinc/tincrepo/dml/functional/sql_partition/mpp21090_drop_lastcol_dml_timestamptz_ao.sql | SQL | apache-2.0 | 1,170 |
/* $NetBSD: atomic_and_16_cas.c,v 1.3 2014/06/23 21:53:45 joerg Exp $ */
/*-
* Copyright (c) 2007 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Jason R. Thorpe.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "atomic_op_namespace.h"
#include <sys/atomic.h>
uint16_t fetch_and_and_2(volatile uint16_t *, uint16_t, ...)
asm("__sync_fetch_and_and_2");
uint16_t
fetch_and_and_2(volatile uint16_t *addr, uint16_t val, ...)
{
uint16_t old, new;
do {
old = *addr;
new = old & val;
} while (atomic_cas_16(addr, old, new) != old);
return old;
}
__strong_alias(__atomic_fetch_and_2,__sync_fetch_and_and_2)
| execunix/vinos | common/lib/libc/atomic/atomic_and_16_cas.c | C | apache-2.0 | 1,979 |
package org.xtuml.bp.mc.java;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.xtuml.bp.core.CorePlugin;
import org.xtuml.bp.core.Ooaofooa;
import org.xtuml.bp.core.Package_c;
import org.xtuml.bp.core.PackageableElement_c;
import org.xtuml.bp.core.SystemModel_c;
import org.xtuml.bp.core.activity.errors.ActivityError;
import org.xtuml.bp.core.common.ClassQueryInterface_c;
import org.xtuml.bp.core.common.NonRootModelElement;
import org.xtuml.bp.core.ui.preferences.BridgePointProjectReferencesPreferences;
import org.xtuml.bp.io.core.CoreExport;
import org.xtuml.bp.io.mdl.ExportModelStream;
import org.xtuml.bp.mc.AbstractActivator;
import org.xtuml.bp.mc.AbstractExportBuilder;
import org.xtuml.bp.utilities.ui.ProjectUtilities;
public class McJavaBuilder extends AbstractExportBuilder {
// The shared instance
private static McJavaBuilder singleton = null;
private IRunnableWithProgress m_exporter;
private File m_outputFile;
private ByteArrayOutputStream m_outStream;
private List<NonRootModelElement> m_elements;
private List<SystemModel_c> m_exportedSystems;
private String m_sourceProject = "";
private String m_rootPkgName = "";
private String[] m_splitPoints = new String[0];
private List<String> m_dontParse = new ArrayList<String>();
private List<String> m_parseOnly = new ArrayList<String>();
private List<ActivityError> activityErrors = new ArrayList<>();
public McJavaBuilder() {
m_elements = new ArrayList<NonRootModelElement>();
m_exportedSystems = new ArrayList<SystemModel_c>();
}
/**
* Returns the shared instance. Creates if it has not yet been created
*
* @return the shared instance
*/
public static McJavaBuilder getDefault() {
if (McJavaBuilder.singleton == null) {
McJavaBuilder.singleton = new McJavaBuilder();
}
return McJavaBuilder.singleton;
}
// The eclipse infrastructure calls this function in response to
// direct request by the user for a build or because auto building
// is turned on.
protected IProject[] build(int kind, Map<String, String> args, IProgressMonitor monitor) throws CoreException {
setArgs(args);
IPath destPath = getCodeGenFolderPath(getProject());
if (!destPath.toFile().exists()) {
destPath.toFile().mkdir();
}
SystemModel_c sys = SystemModel_c.SystemModelInstance(Ooaofooa.getDefaultInstance(), new ClassQueryInterface_c() {
public boolean evaluate(Object candidate) {
return ((SystemModel_c) candidate).getName().equals(getProject().getName());
}
});
exportSystem(sys, destPath.toOSString(), monitor, false, "", false);
return new IProject[0];
}
/**
* This routine sets all variables that come from the .project file
*
* @param args
* This is the list of arguments that were read from the the
* project's .project file
*
* @throws CoreException
*/
public void setArgs(Map<String, String> args) throws CoreException {
// This is used when the project bring built is not the same as the one being
// exported. This is only currently used by the bp.als build.
if (args.containsKey("SourceProject")) {
m_sourceProject = args.get("SourceProject");
}
if (args.containsKey("RootPackageName")) {
m_rootPkgName = args.get("RootPackageName");
} else {
String errorMsg = "No RootPackageName in .project java_export_builder section.";
IStatus status = new Status(IStatus.ERROR, AbstractExportBuilder.class.getPackage().getName(),
IStatus.ERROR, errorMsg, null);
throw new CoreException(status);
}
if (args.containsKey("SplitAtPackage")) {
m_splitPoints = args.get("SplitAtPackage").split(",");
}
if (args.containsKey("DontParse")) {
String[] excluding = args.get("DontParse").toString().split(",");
for (String exclusion : excluding) {
m_dontParse.add(exclusion);
}
}
if (args.containsKey("ParseOnly")) {
String[] including = args.get("ParseOnly").toString().split(",");
for (String inclusion : including) {
m_parseOnly.add(inclusion);
}
}
}
@Override
public List<SystemModel_c> exportSystem(SystemModel_c system, String destDir, final IProgressMonitor monitor,
boolean append, String originalSystem, boolean doNotParse) throws CoreException {
return exportSystem(system, destDir, monitor, append, originalSystem);
}
public List<SystemModel_c> exportSystem(SystemModel_c system, String destDir, final IProgressMonitor monitor,
boolean append, String originalSystem) throws CoreException {
boolean exportNeeded = readyBuildArea(monitor);
// if export is not needed do not perform this step
if (!exportNeeded) {
return new ArrayList<SystemModel_c>();
}
String errorMsg = "Unable to export to destination file.";
boolean exportSucceeded = false;
Exception exception = null;
if (!m_sourceProject.isEmpty()) {
system = SystemModel_c.SystemModelInstance(Ooaofooa.getDefaultInstance(), new ClassQueryInterface_c() {
public boolean evaluate(Object candidate) {
return ((SystemModel_c) candidate).getName().equals(m_sourceProject);
}
});
}
try {
FileOutputStream fos;
m_elements.clear();
if (originalSystem.isEmpty()) {
originalSystem = system.getName();
}
Package_c[] topLevelPkgs = Package_c.getManyEP_PKGsOnR1401(system);
for (Package_c pkg : topLevelPkgs) {
if (pkg.getName().equals(m_rootPkgName)) {
m_elements.add(pkg);
}
}
// Add any loaded global elements
if (CorePlugin.getLoadedGlobals() != null && system.getUseglobals() && !append) {
m_elements.addAll(Arrays.asList(CorePlugin.getLoadedGlobals()));
}
m_outStream = new ByteArrayOutputStream();
m_exporter = org.xtuml.bp.core.CorePlugin.getStreamExportFactory().create(
new SingleQuoteFilterOutputStream(m_outStream),
m_elements.toArray(new NonRootModelElement[m_elements.size()]), true, true);
if (m_exporter instanceof CoreExport) {
CoreExport exporter = (CoreExport) m_exporter;
// collect activity errors
exporter.setErrorCollector(error -> {
activityErrors.add(error);
});
exporter.setExportOAL(CoreExport.YES);
exporter.setExportGraphics(CoreExport.NO);
// Perform a parse-all to assure the model is up to date
List<NonRootModelElement> etps = exporter
.getElementsToParse(m_elements.toArray(new NonRootModelElement[0]));
List<NonRootModelElement> etpsPass1 = new ArrayList<NonRootModelElement>();
List<ArrayList<NonRootModelElement>> etpsSubsequentPasses = new ArrayList<ArrayList<NonRootModelElement>>();
for (NonRootModelElement etp : etps) {
if (etp instanceof Package_c && ((Package_c) etp).getName().equals(m_rootPkgName)) {
organizePasses(etpsPass1, etpsSubsequentPasses, (Package_c) etp);
}
}
String postFix = ".sql";
if (!etpsSubsequentPasses.isEmpty()) {
postFix = "-1.sql";
}
// Pass1
int passNumber = 1;
// Make sure the code generation folder exists
IProject proj = (IProject) system.getAdapter(org.eclipse.core.resources.IProject.class);
IFolder genFolder = proj.getFolder(AbstractActivator.GEN_FOLDER_NAME);
if (!genFolder.exists()) {
genFolder.create(true, true, new NullProgressMonitor());
}
IFolder codeFolder = genFolder.getFolder(getCodeGenFolderPath(proj).lastSegment());
if (!codeFolder.exists()) {
codeFolder.create(true, true, new NullProgressMonitor());
}
String destFileName = destDir + m_rootPkgName + postFix;
// System.out.println("ExportBuilder.java::exportSystem() - Creating filename: "
// + destFileName);
m_outputFile = new File(destFileName);
if (m_outputFile.exists() && !append) {
m_outputFile.delete();
}
exporter.parseAllForExport(etpsPass1.toArray(new NonRootModelElement[etpsPass1.size()]), monitor);
m_exporter.run(monitor);
m_outputFile.createNewFile();
fos = new FileOutputStream(m_outputFile, append);
fos.write(m_outStream.toByteArray());
fos.close();
// Subsequent passes
for (ArrayList<NonRootModelElement> etpsSubsequentPass : etpsSubsequentPasses) {
passNumber++;
m_outStream = new ByteArrayOutputStream();
m_exporter = org.xtuml.bp.core.CorePlugin.getStreamExportFactory().create(
new SingleQuoteFilterOutputStream(m_outStream),
m_elements.toArray(new NonRootModelElement[m_elements.size()]), true, true);
if (m_exporter instanceof CoreExport) {
exporter = (CoreExport) m_exporter;
exporter.setExportOAL(CoreExport.YES);
exporter.setExportGraphics(CoreExport.NO);
}
m_outputFile = new File(destDir + m_rootPkgName + "-" + passNumber + ".sql");
if (m_outputFile.exists() && !append) {
m_outputFile.delete();
}
exporter.parseAllForExport(
etpsSubsequentPass.toArray(new NonRootModelElement[etpsSubsequentPass.size()]), monitor);
m_exporter.run(monitor);
m_outputFile.createNewFile();
fos = new FileOutputStream(m_outputFile, append);
fos.write(m_outStream.toByteArray());
fos.close();
}
exportSucceeded = true;
// Check to see if the user has set the preferences to
// export RTO data for this project.
// Their project setting overrides the workspace setting. If
// they've never set the value
// for the project, the workspace setting is used as the
// default.
boolean doEmitRTOs = BridgePointProjectReferencesPreferences.getProjectBoolean(
BridgePointProjectReferencesPreferences.BP_PROJECT_EMITRTODATA_ID, originalSystem);
if (doEmitRTOs) {
Set<String> rtoSystems = ((ExportModelStream) m_exporter).getSavedRTOSystems();
m_elements.clear();
for (String rtoSystem : rtoSystems) {
// Maintain a list of already exported systems -
// only export if we haven't already.
SystemModel_c referredToSystem = ProjectUtilities.getSystemModel(rtoSystem);
if ((referredToSystem != null) && !m_exportedSystems.contains(referredToSystem)) {
// Now that we have a referred to system in
// hand, export it and append
// the data to our original system's file. Note
// that this will cause a parse
// on the referredToSystem.
m_exportedSystems.add(referredToSystem);
exportSystem(referredToSystem, destDir, monitor, true, originalSystem);
}
}
}
} else {
throw new RuntimeException("Failed to obtain a CoreExport instance.");
}
} catch (FileNotFoundException e) {
exception = e;
CorePlugin.logError(errorMsg, e);
} catch (IOException e) {
exception = e;
CorePlugin.logError(errorMsg, e);
if (m_outputFile.exists())
m_outputFile.delete();
} catch (InvocationTargetException e) {
exception = e;
CorePlugin.logError(errorMsg, e);
} catch (InterruptedException e) {
exception = e;
CorePlugin.logError(errorMsg, e);
if (m_outputFile.exists())
m_outputFile.delete();
} catch (RuntimeException e) {
exception = e;
errorMsg += " " + e.getMessage();
CorePlugin.logError(errorMsg, e);
}
m_elements.clear();
// If the export failed we do not want to proceed with the
// model compiler build.
if (!exportSucceeded) {
IStatus status = new Status(IStatus.ERROR, AbstractExportBuilder.class.getPackage().getName(),
IStatus.ERROR, errorMsg, exception);
throw new CoreException(status);
}
return m_exportedSystems;
}
private void organizePasses(List<NonRootModelElement> etpsPass1,
List<ArrayList<NonRootModelElement>> etpsSubsequentPasses, Package_c etp) {
// Some packages need to be processed in the first pass and others need
// to be deferred to the last package
String firstPass_pkgs = "External Entities";
String deferred_pkgs = "Functions";
List<NonRootModelElement> deferred = new ArrayList<NonRootModelElement>();
int splitPointsFound = 0;
Package_c[] subPackages = Package_c.getManyEP_PKGsOnR8001(PackageableElement_c.getManyPE_PEsOnR8000(etp));
for (Package_c pkg : subPackages) {
// Split point is effective even if packages are excluded
for (String splitPoint : m_splitPoints) {
if (pkg.getName().equals(splitPoint)) {
splitPointsFound++;
etpsSubsequentPasses.add(new ArrayList<NonRootModelElement>());
}
}
if (m_parseOnly.isEmpty() || m_parseOnly.contains(pkg.getName())) {
if (!m_dontParse.contains(pkg.getName())) {
if (deferred_pkgs.contains(pkg.getName())) {
deferred.add(pkg);
} else {
if (splitPointsFound == 0 || firstPass_pkgs.contains(pkg.getName())) {
etpsPass1.add(pkg);
} else {
etpsSubsequentPasses.get(splitPointsFound - 1).add(pkg);
}
}
}
}
}
if (splitPointsFound == 0) {
etpsPass1.addAll(deferred);
} else {
etpsSubsequentPasses.get(splitPointsFound - 1).addAll(deferred);
}
}
public List<ActivityError> getActivityErrors() {
return activityErrors;
}
}
| cortlandstarrett/bridgepoint | src/org.xtuml.bp.mc.java/src/org/xtuml/bp/mc/java/McJavaBuilder.java | Java | apache-2.0 | 16,498 |
/*
* Copyright 2013 - 2020 Outworkers Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.outworkers.phantom.builder.query.engine
import com.outworkers.phantom.builder.syntax.CQLSyntax
import com.outworkers.phantom.builder.syntax.CQLSyntax.Symbols
import com.outworkers.phantom.connectors.KeySpaceCQLQuery
import scala.collection.compat._
case class CQLQuery(override val queryString: String) extends KeySpaceCQLQuery {
val defaultSep = ", "
def instance(st: String): CQLQuery = CQLQuery(st)
def nonEmpty: Boolean = queryString.nonEmpty
def append(st: String): CQLQuery = instance(queryString + st)
def append(st: CQLQuery): CQLQuery = append(st.queryString)
def append[M[X] <: IterableOnce[X]](list: M[String], sep: String = defaultSep): CQLQuery = {
instance(queryString + list.iterator.mkString(sep))
}
def appendEscape(st: String): CQLQuery = append(escape(st))
def appendEscape(st: CQLQuery): CQLQuery = appendEscape(st.queryString)
def terminate: CQLQuery = appendIfAbsent(CQLSyntax.Symbols.semicolon)
def appendSingleQuote(st: String): CQLQuery = append(singleQuote(st))
def appendSingleQuote(st: CQLQuery): CQLQuery = append(singleQuote(st.queryString))
def appendIfAbsent(st: String): CQLQuery = if (queryString.endsWith(st)) instance(queryString) else append(st)
def appendIfAbsent(st: CQLQuery): CQLQuery = appendIfAbsent(st.queryString)
def prepend(st: String): CQLQuery = instance(st + queryString)
def prepend(st: CQLQuery): CQLQuery = prepend(st.queryString)
def prependIfAbsent(st: String): CQLQuery = if (queryString.startsWith(st)) instance(queryString) else prepend(st)
def prependIfAbsent(st: CQLQuery): CQLQuery = prependIfAbsent(st.queryString)
def escape(st: String): String = "`" + st + "`"
def singleQuote(st: String): String = "'" + st.replaceAll("'", "''") + "'"
def spaced: Boolean = queryString.endsWith(" ")
def pad: CQLQuery = if (spaced) this.asInstanceOf[CQLQuery] else instance(queryString + " ")
def bpad: CQLQuery = prependIfAbsent(" ")
def forcePad: CQLQuery = instance(queryString + " ")
def trim: CQLQuery = instance(queryString.trim)
def wrapn(str: String): CQLQuery = append(Symbols.`(`).append(str).append(Symbols.`)`)
def wrapn(query: CQLQuery): CQLQuery = wrapn(query.queryString)
def wrap(str: String): CQLQuery = pad.wrapn(str)
def wrap(query: CQLQuery): CQLQuery = wrap(query.queryString)
def wrapn[M[X] <: IterableOnce[X]](
col: M[String],
sep: String = defaultSep
): CQLQuery = wrapn(col.iterator mkString sep)
def wrap[M[X] <: IterableOnce[X]](
col: M[String],
sep: String = defaultSep
): CQLQuery = wrap(col.iterator mkString sep)
override def toString: String = queryString
}
object CQLQuery {
def empty: CQLQuery = CQLQuery("")
def escape(str: String): String = "'" + str.replaceAll("'", "''") + "'"
def apply(collection: IterableOnce[String]): CQLQuery = CQLQuery(collection.iterator.mkString(", "))
}
| outworkers/phantom | phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/engine/CQLQuery.scala | Scala | apache-2.0 | 3,502 |
/*
* Copyright 2014 Peter Heisig
*
* 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 de.psdev.licensesdialog.licenses;
import android.content.Context;
import de.psdev.licensesdialog.R;
public class CreativeCommonsAttributionShareAlike30Unported extends License {
private static final long serialVersionUID = -1221518691431383957L;
@Override
public String getName() {
return "Creative Commons Attribution-Share Alike 3.0 Unported";
}
@Override
public String readSummaryTextFromResources(final Context context) {
return getContent(context, R.raw.ccbysa_30_summary);
}
@Override
public String readFullTextFromResources(final Context context) {
return getContent(context, R.raw.ccbysa_30_full);
}
@Override
public String getVersion() {
return "3.0";
}
@Override
public String getUrl() {
return "http://creativecommons.org/licenses/by-sa/3.0/";
}
}
| dpint/LicensesDialog | library/src/main/java/de/psdev/licensesdialog/licenses/CreativeCommonsAttributionShareAlike30Unported.java | Java | apache-2.0 | 1,505 |
require File.expand_path('../boot', __FILE__)
#require 'rails/all'
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "rails/test_unit/railtie"
require "sprockets/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require *Rails.groups(:assets => %w(development test))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module PopHealth
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
config.autoload_paths += %W(#{Rails.root}/lib/hds)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
config.relative_url_root = ""
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# add devise views
# config.paths["app/views/devise"]
config.paths["app/views"] << "app/views/devise"
require 'will_paginate/array'
end
end
| smc-ssiddiqui/pophealthv2 | config/application.rb | Ruby | apache-2.0 | 2,451 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.