repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
google-research/weakly_supervised_control | weakly_supervised_control/vae/path_collector.py | 1712 | # Copyright 2020 The Weakly-Supervised Control 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.
from rlkit.envs.vae_wrapper import VAEWrappedEnv
from rlkit.samplers.data_collector import GoalConditionedPathCollector
class VAEWrappedEnvPathCollector(GoalConditionedPathCollector):
def __init__(
self,
goal_sampling_mode,
env: VAEWrappedEnv,
policy,
decode_goals=False,
**kwargs
):
super().__init__(env, policy, **kwargs)
self._goal_sampling_mode = goal_sampling_mode
self._decode_goals = decode_goals
def collect_new_paths(self, *args, **kwargs):
self._env.goal_sampling_mode = self._goal_sampling_mode
self._env.decode_goals = self._decode_goals
return super().collect_new_paths(*args, **kwargs)
def get_snapshot(self):
return dict(
env=self._env,
policy=self._policy,
observation_key=self._observation_key,
desired_goal_key=self._desired_goal_key,
# epoch_paths=self._epoch_paths,
# num_steps_total=self._num_steps_total,
# num_paths_total=self._num_paths_total,
)
| apache-2.0 |
shangsony/fabric_sdk_golang | core/chaincode/shim/crypto/ecdsa/ecdsa.go | 1777 | /*
Copyright IBM Corp. 2016 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ecdsa
import (
"crypto/ecdsa"
"encoding/asn1"
"math/big"
"github.com/fabric_sdk_golang/core/chaincode/shim/crypto"
)
type x509ECDSASignatureVerifierImpl struct {
}
// ECDSASignature represents an ECDSA signature
type ECDSASignature struct {
R, S *big.Int
}
func (sv *x509ECDSASignatureVerifierImpl) Verify(certificate, signature, message []byte) (bool, error) {
// Interpret vk as an x509 certificate
cert, err := derToX509Certificate(certificate)
if err != nil {
return false, err
}
// TODO: verify certificate
// Interpret signature as an ECDSA signature
vk := cert.PublicKey.(*ecdsa.PublicKey)
return sv.verifyImpl(vk, signature, message)
}
func (sv *x509ECDSASignatureVerifierImpl) verifyImpl(vk *ecdsa.PublicKey, signature, message []byte) (bool, error) {
ecdsaSignature := new(ECDSASignature)
_, err := asn1.Unmarshal(signature, ecdsaSignature)
if err != nil {
return false, err
}
h, err := computeHash(message, vk.Params().BitSize)
if err != nil {
return false, err
}
return ecdsa.Verify(vk, h, ecdsaSignature.R, ecdsaSignature.S), nil
}
func NewX509ECDSASignatureVerifier() crypto.SignatureVerifier {
return &x509ECDSASignatureVerifierImpl{}
}
| apache-2.0 |
elliotli02/xxland | src/main/java/xxland/framework/io/impl/KnowLedgeFileControllerImpl.java | 3158 | package xxland.framework.io.impl;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import xxland.com.domain.model.KnowLedge;
import xxland.framework.ComConstant;
import xxland.framework.io.IFileController;
public class KnowLedgeFileControllerImpl extends FileControllerImpl implements IFileController{
public KnowLedgeFileControllerImpl() {
// TODO 自動生成されたコンストラクター・スタブ
}
public KnowLedgeFileControllerImpl(String fileAbsolutePath) {
// TODO 自動生成されたコンストラクター・スタブ
// super.mFileAbsolutePath = fileAbsolutePath;
super(fileAbsolutePath);
}
public List<KnowLedge> FindKnowLedge(String mainKey){
try {
// String path = "C:\\XXLAND\\knowledge";
FileSearch search = new FileSearch();
File[] files = search.listFiles(ComConstant.KNOWLEDGE_PASS, mainKey+".txt");
KnowLedge knowLedge ;
List<KnowLedge> knowLedgeList = new ArrayList<KnowLedge>();
for (int i = 0; i < files.length; i++) {
File file = files[i];
BufferedReader br;
br = new BufferedReader(new FileReader(file));
String str;
while((str = br.readLine()) != null){
// str = br.readLine();
String[] fruit = str.split(",", -1);
knowLedge = new KnowLedge();
knowLedge.setMainKey(fruit[0]);
knowLedge.setSubKey1(fruit[1]);
knowLedge.setSubKey2(fruit[2]);
knowLedge.setSubKey3(fruit[3]);
knowLedge.setSubKey4(fruit[4]);
knowLedge.setSubKey5(fruit[5]);
knowLedgeList.add(knowLedge);
}
br.close();
}
return knowLedgeList;
} catch (FileNotFoundException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
return null;
}
public boolean AddKnowLedge(KnowLedge addknowLedge){
// String path = "C:\\XXLAND\\knowledge";
// FileSearch search = new FileSearch();
// File[] files = search.listFiles(ComConstant.KNOWLEDGE_PASS, mainKey+".txt");
KnowLedge knowLedge = new KnowLedge();
knowLedge.setMainKey(addknowLedge.getSubMainKey());
knowLedge.setSubKey1(addknowLedge.getSubSubKey1());
knowLedge.setSubKey2(addknowLedge.getSubSubKey1());
knowLedge.setSubKey3(addknowLedge.getSubSubKey1());
knowLedge.setSubKey4(addknowLedge.getSubSubKey1());
knowLedge.setSubKey5(addknowLedge.getSubSubKey1());
String newLine = addknowLedge.getSubMainKey() + "," + addknowLedge.getSubSubKey1() + "," +
addknowLedge.getSubSubKey2() + "," + addknowLedge.getSubSubKey3() + "," +
addknowLedge.getSubSubKey4() + "," + addknowLedge.getSubSubKey5() ;
String fileName = ComConstant.KNOWLEDGE_PASS + addknowLedge.getSubMainKey() + ".txt";
WriteFile(newLine,true);
return true;
}
}
| apache-2.0 |
tsugiproject/tsugi | vendor/google/apiclient-services/src/Google/Service/PostmasterTools/IpReputation.php | 1402 | <?php
/*
* Copyright 2014 Google 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.
*/
class Google_Service_PostmasterTools_IpReputation extends Google_Collection
{
protected $collection_key = 'sampleIps';
public $ipCount;
public $numIps;
public $reputation;
public $sampleIps;
public function setIpCount($ipCount)
{
$this->ipCount = $ipCount;
}
public function getIpCount()
{
return $this->ipCount;
}
public function setNumIps($numIps)
{
$this->numIps = $numIps;
}
public function getNumIps()
{
return $this->numIps;
}
public function setReputation($reputation)
{
$this->reputation = $reputation;
}
public function getReputation()
{
return $this->reputation;
}
public function setSampleIps($sampleIps)
{
$this->sampleIps = $sampleIps;
}
public function getSampleIps()
{
return $this->sampleIps;
}
}
| apache-2.0 |
nickbabcock/dropwizard | dropwizard-jersey/src/test/java/io/dropwizard/jersey/optional/OptionalHeaderParamResourceTest.java | 3934 | package io.dropwizard.jersey.optional;
import io.dropwizard.jersey.AbstractJerseyTest;
import io.dropwizard.jersey.DropwizardResourceConfig;
import io.dropwizard.jersey.MyMessage;
import io.dropwizard.jersey.MyMessageParamConverterProvider;
import io.dropwizard.jersey.params.UUIDParam;
import org.junit.Test;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
public class OptionalHeaderParamResourceTest extends AbstractJerseyTest {
@Override
protected Application configure() {
return DropwizardResourceConfig.forTesting()
.register(OptionalHeaderParamResource.class)
.register(MyMessageParamConverterProvider.class);
}
@Test
public void shouldReturnDefaultMessageWhenMessageIsNotPresent() {
String defaultMessage = "Default Message";
String response = target("/optional/message").request().get(String.class);
assertThat(response).isEqualTo(defaultMessage);
}
@Test
public void shouldReturnMessageWhenMessageIsBlank() {
String response = target("/optional/message").request().header("message", "").get(String.class);
assertThat(response).isEqualTo("");
}
@Test
public void shouldReturnMessageWhenMessageIsPresent() {
String customMessage = "Custom Message";
String response = target("/optional/message").request().header("message", customMessage).get(String.class);
assertThat(response).isEqualTo(customMessage);
}
@Test
public void shouldReturnDefaultMessageWhenMyMessageIsNotPresent() {
String defaultMessage = "My Default Message";
String response = target("/optional/my-message").request().get(String.class);
assertThat(response).isEqualTo(defaultMessage);
}
@Test
public void shouldReturnMyMessageWhenMyMessageIsPresent() {
String myMessage = "My Message";
String response = target("/optional/my-message").request().header("mymessage", myMessage).get(String.class);
assertThat(response).isEqualTo(myMessage);
}
@Test
public void shouldThrowBadRequestExceptionWhenInvalidUUIDIsPresent() {
String invalidUUID = "invalid-uuid";
assertThatExceptionOfType(BadRequestException.class).isThrownBy(() ->
target("/optional/uuid").request().header("uuid", invalidUUID).get(String.class));
}
@Test
public void shouldReturnDefaultUUIDWhenUUIDIsNotPresent() {
String defaultUUID = "d5672fa8-326b-40f6-bf71-d9dacf44bcdc";
String response = target("/optional/uuid").request().get(String.class);
assertThat(response).isEqualTo(defaultUUID);
}
@Test
public void shouldReturnUUIDWhenValidUUIDIsPresent() {
String uuid = "fd94b00d-bd50-46b3-b42f-905a9c9e7d78";
String response = target("/optional/uuid").request().header("uuid", uuid).get(String.class);
assertThat(response).isEqualTo(uuid);
}
@Path("/optional")
public static class OptionalHeaderParamResource {
@GET
@Path("/message")
public String getMessage(@HeaderParam("message") Optional<String> message) {
return message.orElse("Default Message");
}
@GET
@Path("/my-message")
public String getMyMessage(@HeaderParam("mymessage") Optional<MyMessage> myMessage) {
return myMessage.orElse(new MyMessage("My Default Message")).getMessage();
}
@GET
@Path("/uuid")
public String getUUID(@HeaderParam("uuid") Optional<UUIDParam> uuid) {
return uuid.orElse(new UUIDParam("d5672fa8-326b-40f6-bf71-d9dacf44bcdc")).get().toString();
}
}
}
| apache-2.0 |
FelipeAdorno/fixture-factory | src/main/java/br/com/six2six/fixturefactory/ObjectFactory.java | 9581 | package br.com.six2six.fixturefactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import br.com.six2six.fixturefactory.util.PropertySorter;
import org.apache.commons.lang.StringUtils;
import br.com.six2six.fixturefactory.processor.Processor;
import br.com.six2six.fixturefactory.transformer.CalendarTransformer;
import br.com.six2six.fixturefactory.transformer.ParameterPlaceholderTransformer;
import br.com.six2six.fixturefactory.transformer.PrimitiveTransformer;
import br.com.six2six.fixturefactory.transformer.PropertyPlaceholderTransformer;
import br.com.six2six.fixturefactory.transformer.SetTransformer;
import br.com.six2six.fixturefactory.transformer.Transformer;
import br.com.six2six.fixturefactory.transformer.TransformerChain;
import br.com.six2six.fixturefactory.transformer.WrapperTransformer;
import br.com.six2six.fixturefactory.util.ReflectionUtils;
import static br.com.six2six.fixturefactory.util.ReflectionUtils.hasDefaultConstructor;
import static br.com.six2six.fixturefactory.util.ReflectionUtils.newInstance;
public class ObjectFactory {
private static final String NO_SUCH_LABEL_MESSAGE = "%s-> No such label: %s";
private static final String LABELS_AMOUNT_DOES_NOT_MATCH = "%s-> labels amount does not match asked quantity (%s)";
private TemplateHolder templateHolder;
private Object owner;
private Processor processor;
public ObjectFactory(TemplateHolder templateHolder) {
this.templateHolder = templateHolder;
}
public ObjectFactory(TemplateHolder templateHolder, Object owner) {
this(templateHolder);
this.owner = owner;
}
public ObjectFactory(TemplateHolder templateHolder, Processor processor) {
this(templateHolder);
this.processor = processor;
}
public ObjectFactory uses(Processor processor) {
this.processor = processor;
return this;
}
@SuppressWarnings("unchecked")
public <T> T gimme(String label) {
Rule rule = findRule(label);
return (T) this.createObject(rule);
}
@SuppressWarnings("unchecked")
public <T> T gimme(String label, Rule propertiesToOverride) {
Rule rule = findRule(label);
return (T) this.createObject(new Rule(rule, propertiesToOverride));
}
public <T> List<T> gimme(Integer quantity, String label) {
Rule rule = findRule(label);
return this.createObjects(quantity, rule);
}
public <T> List<T> gimme(Integer quantity, String... labels) {
return gimme(quantity, Arrays.asList(labels));
}
public <T> List<T> gimme(Integer quantity, List<String> labels) {
if(labels.size() != quantity) throw new IllegalArgumentException(String.format(LABELS_AMOUNT_DOES_NOT_MATCH, templateHolder.getClazz().getName(), StringUtils.join(labels, ",")));
List<Rule> rules = findRules(labels);
return createObjects(quantity, rules);
}
public <T> List<T> gimme(int quantity, String label, Rule propertiesToOverride) {
Rule rule = findRule(label);
return this.createObjects(quantity, new Rule(rule, propertiesToOverride));
}
protected Object createObject(Rule rule) {
Map<String, Property> constructorArguments = new HashMap<String, Property>();
List<Property> deferredProperties = new ArrayList<Property>();
Class<?> clazz = templateHolder.getClazz();
Set<Property> properties = new PropertySorter(rule.getProperties()).sort();
List<String> parameterNames = !hasDefaultConstructor(clazz) ?
lookupConstructorParameterNames(clazz, properties) : new ArrayList<String>();
for (Property property : properties) {
if(parameterNames.contains(property.getRootAttribute())) {
constructorArguments.put(property.getName(), property);
} else {
deferredProperties.add(property);
}
}
Object result = newInstance(clazz, processConstructorArguments(parameterNames, constructorArguments));
Set<Property> propertiesNotUsedInConstructor = getPropertiesNotUsedInConstructor(constructorArguments, parameterNames);
if(propertiesNotUsedInConstructor.size() > 0) {
deferredProperties.addAll(propertiesNotUsedInConstructor);
}
for (Property property : deferredProperties) {
ReflectionUtils.invokeRecursiveSetter(result, property.getName(), processPropertyValue(result, property));
}
if (processor != null) {
processor.execute(result);
}
return result;
}
private Set<Property> getPropertiesNotUsedInConstructor(Map<String, Property> constructorArguments, List<String> parameterNames) {
Map<String, Property> propertiesNotUsedInConstructor = new HashMap<String, Property>(constructorArguments);
for(String parameterName : parameterNames) {
propertiesNotUsedInConstructor.remove(parameterName);
}
return new HashSet<Property>(propertiesNotUsedInConstructor.values());
}
@SuppressWarnings("unchecked")
protected <T> List<T> createObjects(int quantity, Rule rule) {
List<T> results = new ArrayList<T>(quantity);
for (int i = 0; i < quantity; i++) {
results.add((T) this.createObject(rule));
}
return results;
}
@SuppressWarnings("unchecked")
protected <T> List<T> createObjects(int quantity, List<Rule> rules) {
List<T> results = new ArrayList<T>(quantity);
for (int i = 0; i < quantity; i++) {
results.add((T) this.createObject(rules.get(i)));
}
return results;
}
private Rule findRule(String label) {
Rule rule = templateHolder.getRules().get(label);
if (rule == null) {
throw new IllegalArgumentException(String.format(NO_SUCH_LABEL_MESSAGE, templateHolder.getClazz().getName(), label));
}
return rule;
}
private List<Rule> findRules(List<String> labels) {
List<Rule> rules = new ArrayList<Rule>();
for(String label : labels) {
Rule rule = templateHolder.getRules().get(label);
if(rule == null) throw new IllegalArgumentException(String.format(NO_SUCH_LABEL_MESSAGE, templateHolder.getClazz().getName(), label));
rules.add(rule);
}
return rules;
}
private Object generateConstructorParamValue(Property property) {
if (property.hasRelationFunction() && processor != null) {
return property.getValue(processor);
} else {
return property.getValue();
}
}
protected List<Object> processConstructorArguments(List<String> parameterNames, Map<String, Property> arguments) {
List<Object> values = new ArrayList<Object>();
Map<String, Object> processedArguments = processArguments(arguments);
if (owner != null && ReflectionUtils.isInnerClass(templateHolder.getClazz())) {
values.add(owner);
}
TransformerChain transformerChain = buildTransformerChain(new ParameterPlaceholderTransformer(processedArguments));
for (String parameterName : parameterNames) {
Class<?> fieldType = ReflectionUtils.invokeRecursiveType(templateHolder.getClazz(), parameterName);
Object result = processedArguments.get(parameterName);
if (result == null) {
result = processChainedProperty(parameterName, fieldType, processedArguments);
}
values.add(transformerChain.transform(result, fieldType));
}
return values;
}
private Map<String, Object> processArguments(Map<String, Property> arguments) {
Map<String, Object> processedArguments = new HashMap<String, Object>();
for(Entry<String, Property> entry : arguments.entrySet()) {
processedArguments.put(entry.getKey(), generateConstructorParamValue(entry.getValue()));
}
return processedArguments;
}
protected Object processChainedProperty(String parameterName, Class<?> fieldType, Map<String, Object> arguments) {
Rule rule = new Rule();
for (final String argument : arguments.keySet()) {
int index = argument.indexOf(".");
if (index > 0 && argument.substring(0, index).equals(parameterName)) {
rule.add(argument.substring(index+1), arguments.get(argument));
}
}
return new ObjectFactory(new TemplateHolder(fieldType), processor).createObject(rule);
}
protected Object processPropertyValue(Object object, Property property) {
Class<?> fieldType = ReflectionUtils.invokeRecursiveType(object.getClass(), property.getName());
Object value = null;
if (property.hasRelationFunction() || ReflectionUtils.isInnerClass(fieldType)) {
value = processor != null ? property.getValue(object, processor) : property.getValue(object);
} else {
value = property.getValue();
}
TransformerChain transformerChain = buildTransformerChain(new PropertyPlaceholderTransformer(object));
return transformerChain.transform(value, fieldType);
}
protected <T> List<String> lookupConstructorParameterNames(Class<T> target, Set<Property> properties) {
Collection<String> propertyNames = ReflectionUtils.map(properties, "rootAttribute");
return ReflectionUtils.filterConstructorParameters(target, propertyNames);
}
protected TransformerChain buildTransformerChain(Transformer transformer) {
TransformerChain transformerChain = new TransformerChain(transformer);
transformerChain.add(new CalendarTransformer());
transformerChain.add(new SetTransformer());
transformerChain.add(new PrimitiveTransformer());
transformerChain.add(new WrapperTransformer());
return transformerChain;
}
}
| apache-2.0 |
vitessio/vitess | go/pools/resource_pool.go | 13117 | /*
Copyright 2019 The Vitess 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 pools provides functionality to manage and reuse resources
// like connections.
package pools
import (
"errors"
"fmt"
"sync"
"time"
"vitess.io/vitess/go/vt/log"
"context"
"vitess.io/vitess/go/sync2"
"vitess.io/vitess/go/timer"
"vitess.io/vitess/go/trace"
"vitess.io/vitess/go/vt/vterrors"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
)
var (
// ErrClosed is returned if ResourcePool is used when it's closed.
ErrClosed = errors.New("resource pool is closed")
// ErrTimeout is returned if a resource get times out.
ErrTimeout = vterrors.New(vtrpcpb.Code_DEADLINE_EXCEEDED, "resource pool timed out")
// ErrCtxTimeout is returned if a ctx is already expired by the time the resource pool is used
ErrCtxTimeout = vterrors.New(vtrpcpb.Code_DEADLINE_EXCEEDED, "resource pool context already expired")
prefillTimeout = 30 * time.Second
)
// Factory is a function that can be used to create a resource.
type Factory func(context.Context) (Resource, error)
// RefreshCheck is a function used to determine if a resource pool should be
// refreshed (i.e. closed and reopened)
type RefreshCheck func() (bool, error)
// Resource defines the interface that every resource must provide.
// Thread synchronization between Close() and IsClosed()
// is the responsibility of the caller.
type Resource interface {
Close()
}
// ResourcePool allows you to use a pool of resources.
type ResourcePool struct {
// stats. Atomic fields must remain at the top in order to prevent panics on certain architectures.
available sync2.AtomicInt64
active sync2.AtomicInt64
inUse sync2.AtomicInt64
waitCount sync2.AtomicInt64
waitTime sync2.AtomicDuration
idleClosed sync2.AtomicInt64
exhausted sync2.AtomicInt64
capacity sync2.AtomicInt64
idleTimeout sync2.AtomicDuration
resources chan resourceWrapper
factory Factory
idleTimer *timer.Timer
logWait func(time.Time)
refreshCheck RefreshCheck
refreshInterval time.Duration
refreshStop chan struct{}
refreshTicker *time.Ticker
refreshWg sync.WaitGroup
reopenMutex sync.Mutex
}
type resourceWrapper struct {
resource Resource
timeUsed time.Time
}
// NewResourcePool creates a new ResourcePool pool.
// capacity is the number of possible resources in the pool:
// there can be up to 'capacity' of these at a given time.
// maxCap specifies the extent to which the pool can be resized
// in the future through the SetCapacity function.
// You cannot resize the pool beyond maxCap.
// If a resource is unused beyond idleTimeout, it's replaced
// with a new one.
// An idleTimeout of 0 means that there is no timeout.
// A non-zero value of prefillParallelism causes the pool to be pre-filled.
// The value specifies how many resources can be opened in parallel.
// refreshCheck is a function we consult at refreshInterval
// intervals to determine if the pool should be drained and reopened
func NewResourcePool(factory Factory, capacity, maxCap int, idleTimeout time.Duration, prefillParallelism int, logWait func(time.Time), refreshCheck RefreshCheck, refreshInterval time.Duration) *ResourcePool {
if capacity <= 0 || maxCap <= 0 || capacity > maxCap {
panic(errors.New("invalid/out of range capacity"))
}
rp := &ResourcePool{
resources: make(chan resourceWrapper, maxCap),
factory: factory,
available: sync2.NewAtomicInt64(int64(capacity)),
capacity: sync2.NewAtomicInt64(int64(capacity)),
idleTimeout: sync2.NewAtomicDuration(idleTimeout),
logWait: logWait,
}
for i := 0; i < capacity; i++ {
rp.resources <- resourceWrapper{}
}
ctx, cancel := context.WithTimeout(context.TODO(), prefillTimeout)
defer cancel()
if prefillParallelism != 0 {
sem := sync2.NewSemaphore(prefillParallelism, 0 /* timeout */)
var wg sync.WaitGroup
for i := 0; i < capacity; i++ {
wg.Add(1)
go func() {
defer wg.Done()
_ = sem.Acquire()
defer sem.Release()
// If context has expired, give up.
select {
case <-ctx.Done():
return
default:
}
r, err := rp.Get(ctx)
if err != nil {
return
}
rp.Put(r)
}()
}
wg.Wait()
}
if idleTimeout != 0 {
rp.idleTimer = timer.NewTimer(idleTimeout / 10)
rp.idleTimer.Start(rp.closeIdleResources)
}
if refreshCheck != nil && refreshInterval > 0 {
rp.refreshInterval = refreshInterval
rp.refreshCheck = refreshCheck
rp.startRefreshTicker()
}
return rp
}
func (rp *ResourcePool) startRefreshTicker() {
rp.refreshTicker = time.NewTicker(rp.refreshInterval)
rp.refreshStop = make(chan struct{})
rp.refreshWg.Add(1)
go func() {
defer rp.refreshWg.Done()
for {
select {
case <-rp.refreshTicker.C:
val, err := rp.refreshCheck()
if err != nil {
log.Info(err)
}
if val {
go rp.reopen()
return
}
case <-rp.refreshStop:
return
}
}
}()
}
// Close empties the pool calling Close on all its resources.
// You can call Close while there are outstanding resources.
// It waits for all resources to be returned (Put).
// After a Close, Get is not allowed.
func (rp *ResourcePool) Close() {
if rp.idleTimer != nil {
rp.idleTimer.Stop()
}
if rp.refreshTicker != nil {
rp.refreshTicker.Stop()
close(rp.refreshStop)
rp.refreshWg.Wait()
}
_ = rp.SetCapacity(0)
}
// IsClosed returns true if the resource pool is closed.
func (rp *ResourcePool) IsClosed() (closed bool) {
return rp.capacity.Get() == 0
}
// closeIdleResources scans the pool for idle resources
func (rp *ResourcePool) closeIdleResources() {
available := int(rp.Available())
idleTimeout := rp.IdleTimeout()
for i := 0; i < available; i++ {
var wrapper resourceWrapper
select {
case wrapper = <-rp.resources:
default:
// stop early if we don't get anything new from the pool
return
}
func() {
defer func() { rp.resources <- wrapper }()
if wrapper.resource != nil && idleTimeout > 0 && time.Until(wrapper.timeUsed.Add(idleTimeout)) < 0 {
wrapper.resource.Close()
rp.idleClosed.Add(1)
rp.reopenResource(&wrapper)
}
}()
}
}
// reopen drains and reopens the connection pool
func (rp *ResourcePool) reopen() {
rp.reopenMutex.Lock() // Avoid race, since we can refresh asynchronously
defer rp.reopenMutex.Unlock()
capacity := int(rp.capacity.Get())
log.Infof("Draining and reopening resource pool with capacity %d by request", capacity)
rp.Close()
_ = rp.SetCapacity(capacity)
if rp.idleTimer != nil {
rp.idleTimer.Start(rp.closeIdleResources)
}
if rp.refreshCheck != nil {
rp.startRefreshTicker()
}
}
// Get will return the next available resource. If capacity
// has not been reached, it will create a new one using the factory. Otherwise,
// it will wait till the next resource becomes available or a timeout.
// A timeout of 0 is an indefinite wait.
func (rp *ResourcePool) Get(ctx context.Context) (resource Resource, err error) {
span, ctx := trace.NewSpan(ctx, "ResourcePool.Get")
span.Annotate("capacity", rp.capacity.Get())
span.Annotate("in_use", rp.inUse.Get())
span.Annotate("available", rp.available.Get())
span.Annotate("active", rp.active.Get())
defer span.Finish()
return rp.get(ctx)
}
func (rp *ResourcePool) get(ctx context.Context) (resource Resource, err error) {
// If ctx has already expired, avoid racing with rp's resource channel.
select {
case <-ctx.Done():
return nil, ErrCtxTimeout
default:
}
// Fetch
var wrapper resourceWrapper
var ok bool
select {
case wrapper, ok = <-rp.resources:
default:
startTime := time.Now()
select {
case wrapper, ok = <-rp.resources:
case <-ctx.Done():
return nil, ErrTimeout
}
rp.recordWait(startTime)
}
if !ok {
return nil, ErrClosed
}
// Unwrap
if wrapper.resource == nil {
span, _ := trace.NewSpan(ctx, "ResourcePool.factory")
wrapper.resource, err = rp.factory(ctx)
span.Finish()
if err != nil {
rp.resources <- resourceWrapper{}
return nil, err
}
rp.active.Add(1)
}
if rp.available.Add(-1) <= 0 {
rp.exhausted.Add(1)
}
rp.inUse.Add(1)
return wrapper.resource, err
}
// Put will return a resource to the pool. For every successful Get,
// a corresponding Put is required. If you no longer need a resource,
// you will need to call Put(nil) instead of returning the closed resource.
// This will cause a new resource to be created in its place.
func (rp *ResourcePool) Put(resource Resource) {
var wrapper resourceWrapper
if resource != nil {
wrapper = resourceWrapper{
resource: resource,
timeUsed: time.Now(),
}
} else {
rp.reopenResource(&wrapper)
}
select {
case rp.resources <- wrapper:
default:
panic(errors.New("attempt to Put into a full ResourcePool"))
}
rp.inUse.Add(-1)
rp.available.Add(1)
}
func (rp *ResourcePool) reopenResource(wrapper *resourceWrapper) {
if r, err := rp.factory(context.TODO()); err == nil {
wrapper.resource = r
wrapper.timeUsed = time.Now()
} else {
wrapper.resource = nil
rp.active.Add(-1)
}
}
// SetCapacity changes the capacity of the pool.
// You can use it to shrink or expand, but not beyond
// the max capacity. If the change requires the pool
// to be shrunk, SetCapacity waits till the necessary
// number of resources are returned to the pool.
// A SetCapacity of 0 is equivalent to closing the ResourcePool.
func (rp *ResourcePool) SetCapacity(capacity int) error {
if capacity < 0 || capacity > cap(rp.resources) {
return fmt.Errorf("capacity %d is out of range", capacity)
}
// Atomically swap new capacity with old
var oldcap int
for {
oldcap = int(rp.capacity.Get())
if oldcap == 0 && capacity > 0 {
// Closed this before, re-open the channel
rp.resources = make(chan resourceWrapper, cap(rp.resources))
}
if oldcap == capacity {
return nil
}
if rp.capacity.CompareAndSwap(int64(oldcap), int64(capacity)) {
break
}
}
if capacity < oldcap {
for i := 0; i < oldcap-capacity; i++ {
wrapper := <-rp.resources
if wrapper.resource != nil {
wrapper.resource.Close()
rp.active.Add(-1)
}
rp.available.Add(-1)
}
} else {
for i := 0; i < capacity-oldcap; i++ {
rp.resources <- resourceWrapper{}
rp.available.Add(1)
}
}
if capacity == 0 {
close(rp.resources)
}
return nil
}
func (rp *ResourcePool) recordWait(start time.Time) {
rp.waitCount.Add(1)
rp.waitTime.Add(time.Since(start))
if rp.logWait != nil {
rp.logWait(start)
}
}
// SetIdleTimeout sets the idle timeout. It can only be used if there was an
// idle timeout set when the pool was created.
func (rp *ResourcePool) SetIdleTimeout(idleTimeout time.Duration) {
if rp.idleTimer == nil {
panic("SetIdleTimeout called when timer not initialized")
}
rp.idleTimeout.Set(idleTimeout)
rp.idleTimer.SetInterval(idleTimeout / 10)
}
// StatsJSON returns the stats in JSON format.
func (rp *ResourcePool) StatsJSON() string {
return fmt.Sprintf(`{"Capacity": %v, "Available": %v, "Active": %v, "InUse": %v, "MaxCapacity": %v, "WaitCount": %v, "WaitTime": %v, "IdleTimeout": %v, "IdleClosed": %v, "Exhausted": %v}`,
rp.Capacity(),
rp.Available(),
rp.Active(),
rp.InUse(),
rp.MaxCap(),
rp.WaitCount(),
rp.WaitTime().Nanoseconds(),
rp.IdleTimeout().Nanoseconds(),
rp.IdleClosed(),
rp.Exhausted(),
)
}
// Capacity returns the capacity.
func (rp *ResourcePool) Capacity() int64 {
return rp.capacity.Get()
}
// Available returns the number of currently unused and available resources.
func (rp *ResourcePool) Available() int64 {
return rp.available.Get()
}
// Active returns the number of active (i.e. non-nil) resources either in the
// pool or claimed for use
func (rp *ResourcePool) Active() int64 {
return rp.active.Get()
}
// InUse returns the number of claimed resources from the pool
func (rp *ResourcePool) InUse() int64 {
return rp.inUse.Get()
}
// MaxCap returns the max capacity.
func (rp *ResourcePool) MaxCap() int64 {
return int64(cap(rp.resources))
}
// WaitCount returns the total number of waits.
func (rp *ResourcePool) WaitCount() int64 {
return rp.waitCount.Get()
}
// WaitTime returns the total wait time.
func (rp *ResourcePool) WaitTime() time.Duration {
return rp.waitTime.Get()
}
// IdleTimeout returns the idle timeout.
func (rp *ResourcePool) IdleTimeout() time.Duration {
return rp.idleTimeout.Get()
}
// IdleClosed returns the count of resources closed due to idle timeout.
func (rp *ResourcePool) IdleClosed() int64 {
return rp.idleClosed.Get()
}
// Exhausted returns the number of times Available dropped below 1
func (rp *ResourcePool) Exhausted() int64 {
return rp.exhausted.Get()
}
| apache-2.0 |
m3z/HT | openstack_dashboard/test/settings.py | 2276 | import os
from django.utils.translation import ugettext_lazy as _
from horizon.test.settings import *
from horizon.utils.secret_key import generate_or_read_from_file
from openstack_dashboard.exceptions import UNAUTHORIZED, RECOVERABLE, NOT_FOUND
TEST_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_PATH = os.path.abspath(os.path.join(TEST_DIR, ".."))
SECRET_KEY = generate_or_read_from_file(os.path.join(TEST_DIR,
'.secret_key_store'))
ROOT_URLCONF = 'openstack_dashboard.urls'
TEMPLATE_DIRS = (
os.path.join(TEST_DIR, 'templates'),
)
TEMPLATE_CONTEXT_PROCESSORS += (
'openstack_dashboard.context_processors.openstack',
)
INSTALLED_APPS = (
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.messages',
'django.contrib.humanize',
'django_nose',
'openstack_auth',
'compressor',
'horizon',
'openstack_dashboard',
'openstack_dashboard.dashboards.project',
'openstack_dashboard.dashboards.admin',
'openstack_dashboard.dashboards.settings',
)
AUTHENTICATION_BACKENDS = ('openstack_auth.backend.KeystoneBackend',)
SITE_BRANDING = 'OpenStack'
HORIZON_CONFIG = {
'dashboards': ('project', 'admin', 'settings'),
'default_dashboard': 'project',
"password_validator": {
"regex": '^.{8,18}$',
"help_text": _("Password must be between 8 and 18 characters.")
},
'user_home': None,
'help_url': "http://docs.openstack.org",
'exceptions': {'recoverable': RECOVERABLE,
'not_found': NOT_FOUND,
'unauthorized': UNAUTHORIZED},
}
AVAILABLE_REGIONS = [
('http://localhost:5000/v2.0', 'local'),
('http://remote:5000/v2.0', 'remote'),
]
OPENSTACK_KEYSTONE_URL = "http://localhost:5000/v2.0"
OPENSTACK_KEYSTONE_DEFAULT_ROLE = "Member"
OPENSTACK_KEYSTONE_BACKEND = {
'name': 'native',
'can_edit_user': True
}
OPENSTACK_HYPERVISOR_FEATURES = {
'can_set_mount_point': True
}
LOGGING['loggers']['openstack_dashboard'] = {
'handlers': ['test'],
'propagate': False,
}
NOSE_ARGS = ['--nocapture',
'--nologcapture',
'--cover-package=openstack_dashboard',
'--cover-inclusive',
'--all-modules']
| apache-2.0 |
NuPattern/NuPattern | Src/Runtime/Source/Runtime.Guidance/UI/GuidanceBrowser.cs | 4116 | using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using NuPattern.Reflection;
namespace NuPattern.Runtime.Guidance.UI
{
internal class GuidanceBrowser : UserControl
{
public static readonly DependencyProperty SourceProperty =
DependencyProperty.Register(Reflector<GuidanceBrowser>.GetPropertyName(x => x.Source), typeof(Uri), typeof(GuidanceBrowser), new UIPropertyMetadata(OnSourceChanged));
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register(Reflector<GuidanceBrowser>.GetPropertyName(x => x.Command), typeof(System.Windows.Input.ICommand), typeof(GuidanceBrowser));
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.Register(Reflector<GuidanceBrowser>.GetPropertyName(x => x.CommandParameter), typeof(object), typeof(GuidanceBrowser));
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "It is immutable")]
public static readonly DependencyPropertyKey CurrentLinkPropertyKey =
DependencyProperty.RegisterReadOnly(Reflector<GuidanceBrowser>.GetPropertyName(x => x.CurrentLink), typeof(Uri), typeof(GuidanceBrowser), new UIPropertyMetadata(null));
private WebBrowser webBrowser;
public GuidanceBrowser()
{
this.webBrowser = new WebBrowser();
this.webBrowser.Navigating += this.OnNavigating;
this.Content = this.webBrowser;
GuidanceCallContext.Current.GuidanceBrowserControl = this;
}
public System.Windows.Input.ICommand Command
{
get { return (System.Windows.Input.ICommand)this.GetValue(CommandProperty); }
set { this.SetValue(CommandProperty, value); }
}
public object CommandParameter
{
get { return this.GetValue(CommandParameterProperty); }
set { this.SetValue(CommandParameterProperty, value); }
}
public Uri CurrentLink
{
get { return (Uri)this.GetValue(CurrentLinkPropertyKey.DependencyProperty); }
set { this.SetValue(CurrentLinkPropertyKey, value); }
}
public Uri Source
{
get { return (Uri)this.GetValue(SourceProperty); }
set { this.SetValue(SourceProperty, value); }
}
public Uri HREF
{
set { this.webBrowser.Navigate(value); }
}
private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = (GuidanceBrowser)d;
control.webBrowser.Source = (Uri)e.NewValue;
}
private void OnNavigating(object sender, NavigatingCancelEventArgs e)
{
this.CurrentLink = e.Uri;
if (this.Source != e.Uri && this.Command != null)
{
e.Cancel = true;
// Not sure how this could ever happen, since the value is supposed to be set in the
// constructor of this class, but perhaps Current is being re-evaluated somewhere?
//
// Anyway, we must make sure this is set before the call to Execute
//
if (GuidanceCallContext.Current != null &&
GuidanceCallContext.Current.GuidanceBrowserControl == null)
GuidanceCallContext.Current.GuidanceBrowserControl = this;
this.Command.Execute(this.CommandParameter);
}
}
//private void webBrowser_Navigated(object sender, NavigationEventArgs e)
//{
// var document = (dynamic)this.webBrowser.Document;
// var links = document.Links;
// foreach (var link in links)
// {
// link.onclick += new EventHandler(this.ClickLink2);
// }
//}
//private void ClickLink2(object sender, EventArgs e)
//{
//}
}
} | apache-2.0 |
pulibrary/plum | spec/views/records/edit_fields/_geo_subject.html.erb_spec.rb | 1807 | require 'rails_helper'
include SimpleForm::ActionViewExtensions::FormHelper
RSpec.describe 'records/edit_fields/_geo_subject.html.erb' do
let(:project) { FactoryGirl.create :ephemera_project }
let(:box) { FactoryGirl.create :ephemera_box, ephemera_project: [project.id] }
let(:vocabulary_label) { "Geo subject" }
before do
allow(view).to receive(:f).and_return(simple_form_for(form))
allow(view).to receive(:key).and_return(:geo_subject)
allow(view).to receive(:params).and_return(parent_id: box.id)
Qa::Authorities::Local.registry.instance_variable_get(:@hash).delete(vocabulary_label)
end
after do
Qa::Authorities::Local.registry.instance_variable_get(:@hash).delete(vocabulary_label)
end
context 'with an ephemera folder' do
let(:folder) { FactoryGirl.build(:ephemera_folder, member_of_collections: [box]) }
let(:form) { Hyrax::EphemeraFolderForm.new(folder, nil, nil) }
let(:vocabulary) do
Vocabulary.create!(label: vocabulary_label).tap do |vocab|
VocabularyTerm.create!(vocabulary: vocab, label: "Ireland")
VocabularyTerm.create!(vocabulary: vocab, label: "Japan")
end
end
let(:form) { Hyrax::EphemeraFolderForm.new(folder, nil, nil) }
context "when there is no geo_subject vocabulary" do
before do
render
end
it "doesn't create a select box" do
expect(rendered).not_to have_selector "select"
end
end
context "when there is a geo_subject vocabulary" do
before do
EphemeraField.create! name: "EphemeraFolder.geo_subject", ephemera_project: project, vocabulary: vocabulary
render
end
it "creates a select box" do
expect(rendered).to have_select("Geo subject", options: ['', 'Ireland', 'Japan'])
end
end
end
end
| apache-2.0 |
hufsm/PocketHub | app/src/main/java/com/github/pockethub/ui/SingleChoiceDialogFragment.java | 2145 | /*
* Copyright (c) 2015 PocketHub
*
* 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.github.pockethub.ui;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* Helper to display a single choice dialog
*/
public class SingleChoiceDialogFragment extends DialogFragmentHelper implements
OnClickListener {
/**
* Arguments key for the selected item
*/
public static final String ARG_SELECTED = "selected";
/**
* Choices arguments
*/
protected static final String ARG_CHOICES = "choices";
/**
* Selected choice argument
*/
protected static final String ARG_SELECTED_CHOICE = "selectedChoice";
/**
* Tag
*/
protected static final String TAG = "single_choice_dialog";
/**
* Confirm message and deliver callback to given activity
*
* @param activity
* @param requestCode
* @param title
* @param message
* @param choices
* @param selectedChoice
* @param helper
*/
protected static void show(final DialogFragmentActivity activity,
final int requestCode, final String title, final String message,
ArrayList<? extends Parcelable> choices, final int selectedChoice,
final DialogFragmentHelper helper) {
Bundle arguments = createArguments(title, message, requestCode);
arguments.putParcelableArrayList(ARG_CHOICES, choices);
arguments.putInt(ARG_SELECTED_CHOICE, selectedChoice);
show(activity, helper, arguments, TAG);
}
}
| apache-2.0 |
whiteley/jetty8 | jetty-continuation/src/main/java/org/eclipse/jetty/continuation/ContinuationListener.java | 2046 | //
// ========================================================================
// Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.continuation;
import java.util.EventListener;
import javax.servlet.ServletRequestListener;
/* ------------------------------------------------------------ */
/** A Continuation Listener
* <p>
* A ContinuationListener may be registered with a call to
* {@link Continuation#addContinuationListener(ContinuationListener)}.
*
*/
public interface ContinuationListener extends EventListener
{
/* ------------------------------------------------------------ */
/**
* Called when a continuation life cycle is complete and after
* any calls to {@link ServletRequestListener#requestDestroyed(javax.servlet.ServletRequestEvent)}
* The response may still be written to during the call.
*
* @param continuation
*/
public void onComplete(Continuation continuation);
/* ------------------------------------------------------------ */
/**
* Called when a suspended continuation has timed out.
* The response may be written to and the methods
* {@link Continuation#resume()} or {@link Continuation#complete()}
* may be called by a onTimeout implementation,
* @param continuation
*/
public void onTimeout(Continuation continuation);
}
| apache-2.0 |
vespa-engine/vespa | jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilter.java | 5578 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.http.filter.security.rule;
import com.google.inject.Inject;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
import com.yahoo.jdisc.http.filter.security.base.JsonSecurityRequestFilterBase;
import com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.Rule.Action;
import com.yahoo.restapi.Path;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* Security request filter that filters requests based on host, method and uri path.
*
* @author bjorncs
*/
public class RuleBasedRequestFilter extends JsonSecurityRequestFilterBase {
private static final Logger log = Logger.getLogger(RuleBasedRequestFilter.class.getName());
private final Metric metric;
private final boolean dryrun;
private final List<Rule> rules;
private final ErrorResponse defaultResponse;
@Inject
public RuleBasedRequestFilter(Metric metric, RuleBasedFilterConfig config) {
this.metric = metric;
this.dryrun = config.dryrun();
this.rules = Rule.fromConfig(config.rule());
this.defaultResponse = createDefaultResponse(config.defaultRule());
}
@Override
protected Optional<ErrorResponse> filter(DiscFilterRequest request) {
String method = request.getMethod();
URI uri = request.getUri();
for (Rule rule : rules) {
if (rule.matches(method, uri)) {
log.log(Level.FINE, () ->
String.format("Request '%h' with method '%s' and uri '%s' matched rule '%s'", request, method, uri, rule.name));
return responseFor(request, rule.name, rule.response);
}
}
return responseFor(request, "default", defaultResponse);
}
private static ErrorResponse createDefaultResponse(RuleBasedFilterConfig.DefaultRule defaultRule) {
switch (defaultRule.action()) {
case ALLOW: return null;
case BLOCK: {
Response response = new Response(defaultRule.blockResponseCode());
defaultRule.blockResponseHeaders().forEach(h -> response.headers().add(h.name(), h.value()));
return new ErrorResponse(response, defaultRule.blockResponseMessage());
}
default: throw new IllegalArgumentException(defaultRule.action().name());
}
}
private Optional<ErrorResponse> responseFor(DiscFilterRequest request, String ruleName, ErrorResponse response) {
int statusCode = response != null ? response.getResponse().getStatus() : 0;
Metric.Context metricContext = metric.createContext(Map.of(
"rule", ruleName,
"dryrun", Boolean.toString(dryrun),
"statusCode", Integer.toString(statusCode)));
if (response != null) {
metric.add("jdisc.http.filter.rule.blocked_requests", 1L, metricContext);
log.log(Level.FINE, () -> String.format(
"Blocking request '%h' with status code '%d' using rule '%s' (dryrun=%b)", request, statusCode, ruleName, dryrun));
return dryrun ? Optional.empty() : Optional.of(response);
} else {
metric.add("jdisc.http.filter.rule.allowed_requests", 1L, metricContext);
log.log(Level.FINE, () -> String.format("Allowing request '%h' using rule '%s' (dryrun=%b)", request, ruleName, dryrun));
return Optional.empty();
}
}
private static class Rule {
final String name;
final Set<String> hostnames;
final Set<String> methods;
final Set<String> pathGlobExpressions;
final ErrorResponse response;
static List<Rule> fromConfig(List<RuleBasedFilterConfig.Rule> config) {
return config.stream()
.map(Rule::new)
.collect(Collectors.toList());
}
Rule(RuleBasedFilterConfig.Rule config) {
this.name = config.name();
this.hostnames = Set.copyOf(config.hostNames());
this.methods = config.methods().stream()
.map(m -> m.name().toUpperCase())
.collect(Collectors.toSet());
this.pathGlobExpressions = Set.copyOf(config.pathExpressions());
this.response = config.action() == Action.Enum.BLOCK ? createResponse(config) : null;
}
private static ErrorResponse createResponse(RuleBasedFilterConfig.Rule config) {
Response response = new Response(config.blockResponseCode());
config.blockResponseHeaders().forEach(h -> response.headers().add(h.name(), h.value()));
return new ErrorResponse(response, config.blockResponseMessage());
}
boolean matches(String method, URI uri) {
boolean methodMatches = methods.isEmpty() || methods.contains(method.toUpperCase());
String host = uri.getHost();
boolean hostnameMatches = hostnames.isEmpty() || (host != null && hostnames.contains(host));
Path pathMatcher = new Path(uri);
boolean pathMatches = pathGlobExpressions.isEmpty() || pathGlobExpressions.stream().anyMatch(pathMatcher::matches);
return methodMatches && hostnameMatches && pathMatches;
}
}
}
| apache-2.0 |
davidtsadler/ebay-sdk-php | src/Trading/Types/StorePreferencesType.php | 1501 | <?php
/**
* DO NOT EDIT THIS FILE!
*
* This file was automatically generated from external sources.
*
* Any manual change here will be lost the next time the SDK
* is updated. You've been warned!
*/
namespace DTS\eBaySDK\Trading\Types;
/**
*
* @property \DTS\eBaySDK\Trading\Types\StoreVacationPreferencesType $VacationPreferences
*/
class StorePreferencesType extends \DTS\eBaySDK\Types\BaseType
{
/**
* @var array Properties belonging to objects of this class.
*/
private static $propertyTypes = [
'VacationPreferences' => [
'type' => 'DTS\eBaySDK\Trading\Types\StoreVacationPreferencesType',
'repeatable' => false,
'attribute' => false,
'elementName' => 'VacationPreferences'
]
];
/**
* @param array $values Optional properties and values to assign to the object.
*/
public function __construct(array $values = [])
{
list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);
parent::__construct($parentValues);
if (!array_key_exists(__CLASS__, self::$properties)) {
self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
}
if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
self::$xmlNamespaces[__CLASS__] = 'xmlns="urn:ebay:apis:eBLBaseComponents"';
}
$this->setValues(__CLASS__, $childValues);
}
}
| apache-2.0 |
petabridge/NBench | src/NBench.Tests/CommandLineSpecs.cs | 529 | using FluentAssertions;
using Xunit;
namespace NBench.Tests
{
public class CommandLineSpecs
{
[Fact(DisplayName = "CommandLine: Should still parse NBench v1.2 commands")]
public void Should_parse_NBench_10_command_styles()
{
var command = new string[] { $"{NBenchCommands.OutputKey}", "D:\\NBench\\PerfResults\\netcoreapp1.0" };
var dict = NBenchCommands.ParseValues(command);
dict.ContainsKey(NBenchCommands.OutputKey).Should().BeTrue();
}
}
}
| apache-2.0 |
nafae/developer | modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201406/cm/CampaignCriterionServiceInterfacegetResponse.java | 1607 |
package com.google.api.ads.adwords.jaxws.v201406.cm;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for getResponse element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="getResponse">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="rval" type="{https://adwords.google.com/api/adwords/cm/v201406}CampaignCriterionPage" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"rval"
})
@XmlRootElement(name = "getResponse")
public class CampaignCriterionServiceInterfacegetResponse {
protected CampaignCriterionPage rval;
/**
* Gets the value of the rval property.
*
* @return
* possible object is
* {@link CampaignCriterionPage }
*
*/
public CampaignCriterionPage getRval() {
return rval;
}
/**
* Sets the value of the rval property.
*
* @param value
* allowed object is
* {@link CampaignCriterionPage }
*
*/
public void setRval(CampaignCriterionPage value) {
this.rval = value;
}
}
| apache-2.0 |
JeremyAiYt/MyApp | app/src/main/java/com/shaojun/myapp/widget/ultra/indicator/PtrTensionIndicator.java | 3716 | package com.shaojun.myapp.widget.ultra.indicator;
public class PtrTensionIndicator extends PtrIndicator {
private float DRAG_RATE = 0.5f;
private float mDownY;
private float mDownPos;
private float mOneHeight = 0;
private float mCurrentDragPercent;
private int mReleasePos;
private float mReleasePercent = -1;
@Override
public void onPressDown(float x, float y) {
super.onPressDown(x, y);
mDownY = y;
mDownPos = getCurrentPosY();
}
@Override
public void onRelease() {
super.onRelease();
mReleasePos = getCurrentPosY();
mReleasePercent = mCurrentDragPercent;
}
@Override
public void onUIRefreshComplete() {
mReleasePos = getCurrentPosY();
mReleasePercent = getOverDragPercent();
}
@Override
public void setHeaderHeight(int height) {
super.setHeaderHeight(height);
mOneHeight = height * 4f / 5;
}
@Override
protected void processOnMove(float currentX, float currentY, float offsetX, float offsetY) {
if (currentY < mDownY) {
super.processOnMove(currentX, currentY, offsetX, offsetY);
return;
}
// distance from top
final float scrollTop = (currentY - mDownY) * DRAG_RATE + mDownPos;
final float currentDragPercent = scrollTop / mOneHeight;
if (currentDragPercent < 0) {
setOffset(offsetX, 0);
return;
}
mCurrentDragPercent = currentDragPercent;
// 0 ~ 1
float boundedDragPercent = Math.min(1f, Math.abs(currentDragPercent));
float extraOS = scrollTop - mOneHeight;
// 0 ~ 2
// if extraOS lower than 0, which means scrollTop lower than onHeight, tensionSlingshotPercent will be 0.
float tensionSlingshotPercent = Math.max(0, Math.min(extraOS, mOneHeight * 2) / mOneHeight);
float tensionPercent = (float) ((tensionSlingshotPercent / 4) - Math.pow((tensionSlingshotPercent / 4), 2)) * 2f;
float extraMove = (mOneHeight) * tensionPercent / 2;
int targetY = (int) ((mOneHeight * boundedDragPercent) + extraMove);
int change = targetY - getCurrentPosY();
setOffset(currentX, change);
}
private float offsetToTarget(float scrollTop) {
// distance from top
final float currentDragPercent = scrollTop / mOneHeight;
mCurrentDragPercent = currentDragPercent;
// 0 ~ 1
float boundedDragPercent = Math.min(1f, Math.abs(currentDragPercent));
float extraOS = scrollTop - mOneHeight;
// 0 ~ 2
// if extraOS lower than 0, which means scrollTop lower than mOneHeight, tensionSlingshotPercent will be 0.
float tensionSlingshotPercent = Math.max(0, Math.min(extraOS, mOneHeight * 2) / mOneHeight);
float tensionPercent = (float) ((tensionSlingshotPercent / 4) - Math.pow((tensionSlingshotPercent / 4), 2)) * 2f;
float extraMove = (mOneHeight) * tensionPercent / 2;
int targetY = (int) ((mOneHeight * boundedDragPercent) + extraMove);
return 0;
}
@Override
public int getOffsetToKeepHeaderWhileLoading() {
return getOffsetToRefresh();
}
@Override
public int getOffsetToRefresh() {
return (int) mOneHeight;
}
public float getOverDragPercent() {
if (isUnderTouch()) {
return mCurrentDragPercent;
} else {
if (mReleasePercent <= 0) {
return 1.0f * getCurrentPosY() / getOffsetToKeepHeaderWhileLoading();
}
// after release
return mReleasePercent * getCurrentPosY() / mReleasePos;
}
}
}
| apache-2.0 |
MaximTar/satellite | src/main/resources/libs/JAT/jat/demo/vr/attitude/attitude.java | 3233 | /* JAT: Java Astrodynamics Toolkit
*
* Copyright (c) 2002 The JAT Project and the Center for Space Research (CSR),
* The University of Texas at Austin. All rights reserved.
*
* This file is part of JAT. JAT is free software; you can
* redistribute it and/or modify it under the terms of the
* NASA Open Source Agreement, version 1.3 or later.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* NASA Open Source Agreement for more details.
*
* You should have received a copy of the NASA Open Source Agreement
* along with this program; if not, write to the NASA Goddard
* Space Flight Center at opensource@gsfc.nasa.gov.
*
*/
package jat.demo.vr.attitude;
import jat.vr.*;
import jat.util.*;
import java.awt.*;
import java.applet.Applet;
import javax.media.j3d.*;
import javax.vecmath.*;
import com.sun.j3d.utils.applet.MainFrame;
public class attitude extends Applet
{
BranchGroup BG_root;
BranchGroup BG_vp;
TransformGroup TG_scene;
LightWaveObject shuttle;
ColorCube3D spacecraft;
Point3d origin = new Point3d(0.0f, 0.0f, 0.0f);
BoundingSphere bounds = new BoundingSphere(origin, 1.e10); //100000000.0
ControlPanel panel;
public CapturingCanvas3D c;
public attitude()
{
// Get path of this class, frames will be saved in subdirectory frames
String b = FileUtil.getClassFilePath("jat.demo.vr.attitude", "attitude");
System.out.println(b);
//Applet window
setLayout(new BorderLayout());
c = createCanvas(b + "frames/");
add("Center", c);
panel = new ControlPanel(BG_root);
add("South", panel);
// 3D Objects
BG_root = new BranchGroup();
BG_root.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
BG_root.setBounds(bounds);
TG_scene = new TransformGroup();
//TG_scene.addChild(shuttle = new LightWaveObject(this, "SpaceShuttle.lws", 1.f));
TG_scene.addChild(spacecraft = new ColorCube3D(10000.f));
BG_root.addChild(TG_scene);
BG_root.addChild(new Axis(20000.0f));
// Lights
BG_root.addChild(jat_light.DirectionalLight(bounds));
jat_light.setDirection(0.f, -100.f, -100.f);
// View
BG_vp = jat_view.view(-180000, 0., -1.e4, c);
// Behaviors
jat_behavior.behavior(BG_root, BG_vp, bounds);
// Animation
SimulationClock SimClock = new SimulationClock(this, 40, panel);
SimClock.setSchedulingBounds(bounds);
BG_vp.addChild(SimClock);
VirtualUniverse universe = new VirtualUniverse();
Locale locale = new Locale(universe);
locale.addBranchGraph(BG_root);
locale.addBranchGraph(BG_vp);
// Have Java 3D perform optimizations on this scene graph.
//BG_root.compile();
}
//private Canvas3D createCanvas()
private CapturingCanvas3D createCanvas(String frames_path)
{
GraphicsConfigTemplate3D template = new GraphicsConfigTemplate3D();
GraphicsConfiguration gc1 =
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getBestConfiguration(template);
return new CapturingCanvas3D(gc1, frames_path);
}
public void init()
{
}
public static void main(String[] args)
{
attitude at = new attitude(); // Applet
new MainFrame(at, 800, 600);
}
}
| apache-2.0 |
icemagno/mclm | src/main/webapp/app/view/trabalho/TrabalhoTree.js | 4885 | Ext.define('MCLM.view.trabalho.TrabalhoTree', {
extend: 'Ext.tree.TreePanel',
requires: [
'MCLM.view.trabalho.TrabalhoTreeController'
],
xtype: 'view.trabalhoTree',
id: 'trabalhoTree',
store: 'store.trabalhoTree',
rootVisible: true,
animate: false,
controller: 'trabalho',
scrollable: true,
scroll: 'both',
useArrows: true,
border: false,
frame: false,
viewConfig: {
markDirty: false,
id: 'trabalhoTreeView',
plugins: {
ptype: 'treeviewdragdrop'
},
listeners: {
drop: 'afterDropNode',
beforedrop: 'onBeforeDrop'
}
},
plugins: [{
ptype: 'cellediting',
clicksToEdit: 2,
listeners: {
// TODO: alterar texto do nó levando em consideração o ícone de anexo
beforeedit: (editor, context, eOpts) => {
((context.record.data.text = context.record.data.text.replace("<img src='img/attachment.svg' style='width:10px;height:auto'/>", "")) && false) || MCLM.Globals.isSceneryOwner() || MCLM.Globals.isAdmin()
}
}
}],
columns: [{
xtype: 'treecolumn',
dataIndex: 'text',
flex: 1,
editor: {
xtype: 'textfield'
}
}],
dockedItems: [{
xtype: 'toolbar',
items: [
// {
// iconCls: 'export-icon',
// id: 'exportMapBtn',
// tooltip: '<b>Exportar Cenário / Mapa atual.</b>',
// handler: 'exportMap'
// },
{
iconCls: 'reload-icon',
id: 'reloadWsBtn',
handler: 'reloadScenery',
tooltip: '<b>Recarregar cenário</b>',
disabled: true
},
{
iconCls: 'new-scenery-icon',
id: 'clrWsBtn',
handler: 'onRemoveSceneryBtnClick',
tooltip: '<b>Limpar cenário (modificações não gravadas no cenário atual serão perdidas)</b>'
},
{
iconCls: 'save-icon',
id: 'svWsBtn',
handler: 'saveScenery',
tooltip: '<b>Salvar/sobrescrever cenário</b>'
},
{xtype: 'tbseparator'},
{
iconCls: 'troca-icon',
tooltip: '<b>Troca rápida de cenário</b>' +
'<p>Exibe a lista de troca rápida de cenários (modificações não gravadas no cenário atual serão perdidas).</p>',
listeners: {
click: 'onQuickScenerySwitchBtnClick'
}
},
{xtype: 'tbfill'},
{
iconCls: 'layers-icon',
id: 'layerStackBtn',
handler: 'showLayerStack',
tooltip: '<b>Controle de camadas</b>' +
'<p>Controla a visualização das camadas ativas no cenário.</p>'
},
{
iconCls: 'group-icon',
tooltip: '<b>Gerenciar Grupos</b>',
cls: 'adminBtn',
handler: 'onGroupManageBtnClick'
},
{
iconCls: 'setting-icon',
id: 'mngCenaryBtn',
handler: 'loadSceneries',
tooltip: '<b>Gerenciar cenários</b>'
}
]
},
{
bbar: [
{
iconCls: 'properties-icon',
id: 'newLegendBtn',
handler: 'addLegend',
tooltip: '<b>Adicionar Legenda</b>'
},
{
iconCls: 'show-icon',
itemId: 'show_legend_btn',
tooltip: '<b>Exibir Legenda</b>',
handler: "showLegend",
hidden: true
},
{
iconCls: 'hide-icon',
itemId: 'hide_legend_btn',
tooltip: '<b>Esconder Legenda</b>',
handler: "hideLegend",
hidden: true
},
{
iconCls: 'lampada',
id: 'btndark',
hidden: true,
handler: 'onDarkMode',
tooltip: '<b>Modo Escuro</b>'
},
{
iconCls: 'draw-icon',
hidden: true,
id: 'btnEditLegend',
handler: 'onEditMode',
tooltip: '<b>Modo de Edição</b>'
}
]
}
],
listeners: {
checkchange: 'onLayerTreeCheckChange',
itemcontextmenu: 'onContextMenu'
}
});
| apache-2.0 |
vczhou/inductive | questions/migrations/0004_auto_20171021_2152.py | 463 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-21 21:52
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('questions', '0003_auto_20171021_2040'),
]
operations = [
migrations.AlterField(
model_name='question',
name='question_text',
field=models.TextField(max_length=400),
),
]
| apache-2.0 |
liliangali/qudao | vue1/src/components/Modules/Demo/Article/index.js | 118 | module.exports = {
Edit: require('./Edit/'),
Discount: require('./Discount/'),
List: require('./List/')
}; | apache-2.0 |
hheg/jitstatic | source/src/main/java/io/jitstatic/auth/constraints/HasPassword.java | 1265 | package io.jitstatic.auth.constraints;
/*-
* #%L
* jitstatic
* %%
* Copyright (C) 2017 - 2019 H.Hegardt
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Constraint(validatedBy = HasPasswordValidator.class)
@Documented
@Retention(RUNTIME)
@Target(TYPE)
public @interface HasPassword {
String message() default "Missing valid password";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
| apache-2.0 |
cping/RipplePower | eclipse/RipplePower/src/org/ripple/power/i18n/message/annotations/Handler.java | 517 | package org.ripple.power.i18n.message.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.ripple.power.i18n.message.MessageHandler;
import org.ripple.power.i18n.message.handlers.StringFormatMessageHandler;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Handler {
Class<? extends MessageHandler> value() default StringFormatMessageHandler.class;
}
| apache-2.0 |
zhangjunfang/jstorm-0.9.6.3- | jstorm-client/src/main/java/backtype/storm/task/IErrorReporter.java | 102 | package backtype.storm.task;
public interface IErrorReporter {
void reportError(Throwable error);
}
| apache-2.0 |
boyan-velinov/cf-mta-deploy-service | com.sap.cloud.lm.sl.cf.web/src/main/java/com/sap/cloud/lm/sl/cf/web/app/CFApplication.java | 1181 | package com.sap.cloud.lm.sl.cf.web.app;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
import com.sap.cloud.lm.sl.cf.web.resources.AdminResource;
import com.sap.cloud.lm.sl.cf.web.resources.CFExceptionMapper;
import com.sap.cloud.lm.sl.cf.web.resources.ConfigurationEntriesResource;
import com.sap.cloud.lm.sl.cf.web.resources.ConfigurationSubscriptionsResource;
import com.sap.cloud.lm.sl.cf.web.resources.CsrfTokenResource;
import com.sap.cloud.lm.sl.cf.web.resources.ApplicationShutdownResource;
public class CFApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<>();
classes.add(ConfigurationEntriesResource.class);
classes.add(ConfigurationSubscriptionsResource.class);
classes.add(CFExceptionMapper.class);
classes.add(CsrfTokenResource.class);
return classes;
}
@Override
public Set<Object> getSingletons() {
Set<Object> singletons = new HashSet<>();
singletons.add(new AdminResource());
singletons.add(new ApplicationShutdownResource());
return singletons;
}
}
| apache-2.0 |
OpsLabJPL/earthkit-cli | pool/userdata.go | 1885 | package pool
const UserData = `#!/bin/bash
# install docker
curl "__DOCKER_URL__" | bash
# fetch docker conf
wget "__DOCKER_CONF_URL__" -O /etc/init/docker.conf
# rerun docker with new config
service docker restart
mkdir -p /cescre/logs/
mkdir /cescre/bin/
mkdir /etc/ekit/
mkdir /etc/etcd/
mkdir /cescre/etcd_data
# Download and install etcd
wget https://github.com/coreos/etcd/releases/download/v0.3.0/etcd-v0.3.0-linux-amd64.tar.gz
tar xzvf etcd-v0.3.0-linux-amd64.tar.gz -C /cescre/
rm etcd-v0.3.0-linux-amd64.tar.gz
# setup ekit conf
cat << EOF > /etc/ekit/earthkitrc
aws_access_key = __AWS_ACCESS_KEY__
aws_secret_key = __AWS_SECRET_KEY__
s3bucket = __S3_BUCKET__
s3keyprefix = .earthkit
EOF
# setup etcd conf
pub_addr=` + "`" + `curl -s http://169.254.169.254/latest/meta-data/public-ipv4` + "`" + `
addr=` + "`" + `curl http://169.254.169.254/latest/meta-data/local-ipv4` + "`" + `
discovery=__DISCOVERY_URL__
name=` + "`" + `curl http://169.254.169.254/latest/meta-data/local-hostname` + "`" + `
cat << EOF > /etc/etcd/etcd.conf
discovery = "$discovery"
addr = "$pub_addr:4001"
data_dir = "/cescre/etcd_data"
name = "$name"
[peer]
addr = "$addr:7001"
EOF
# start etcd, using conf defined in /etc/etcd/etcd.conf
/cescre/etcd-v0.3.0-linux-amd64/etcd >> /cescre/logs/etcd.log 2>&1 &
# Download etcq daemon worker
wget "__ETCDQ_URL__" -O /cescre/bin/etcdq
chmod a+x /cescre/bin/etcdq
# mount ebs volume
# TODO: Remove hardcode of device name and mount dir
sudo mkfs -t ext4 /dev/xvdf1
sudo mkdir /mnt/data
sudo mount /dev/xvdf1 /mnt/data
sudo mkdir /mnt/data/earthkit
sudo chmod 1777 /mnt/data/earthkit
sleep 5
DATA_DIR=__DATA_DIR__ EARTHKIT_IMG=__EARTHKIT_IMG__ AWS_ACCESS_KEY=__AWS_ACCESS_KEY__ AWS_SECRET_KEY=__AWS_SECRET_KEY__ AWS_REGION=__AWS_REGION__ S3_BUCKET=__S3_BUCKET__ WORKSPACE=__WORK_SPACE__ /cescre/bin/etcdq >> /cescre/logs/etcdq.log 2>&1 &
`
| apache-2.0 |
inbloom/secure-data-service | tools/csv2xml/src/org/slc/sli/sample/entitiesR1/StudentSchoolAssociation.java | 11519 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.12.05 at 01:12:38 PM EST
//
package org.slc.sli.sample.entitiesR1;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* This association represents the school to which a student is enrolled.
*
* <p>Java class for StudentSchoolAssociation complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="StudentSchoolAssociation">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="StudentReference" type="{http://ed-fi.org/0100}StudentReferenceType"/>
* <element name="SchoolReference" type="{http://ed-fi.org/0100}EducationalOrgReferenceType"/>
* <element name="SchoolYear" type="{http://ed-fi.org/0100}SchoolYearType" minOccurs="0"/>
* <element name="EntryDate" type="{http://www.w3.org/2001/XMLSchema}date"/>
* <element name="EntryGradeLevel" type="{http://ed-fi.org/0100}GradeLevelType"/>
* <element name="EntryType" type="{http://ed-fi.org/0100}EntryType" minOccurs="0"/>
* <element name="RepeatGradeIndicator" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="ClassOf" type="{http://ed-fi.org/0100}SchoolYearType" minOccurs="0"/>
* <element name="SchoolChoiceTransfer" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="ExitWithdrawDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
* <element name="ExitWithdrawType" type="{http://ed-fi.org/0100}ExitWithdrawType" minOccurs="0"/>
* <element name="EducationalPlans" type="{http://ed-fi.org/0100}EducationalPlansType" minOccurs="0"/>
* <element name="GraduationPlanReference" type="{http://ed-fi.org/0100}ReferenceType" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "StudentSchoolAssociation", propOrder = {
"studentReference",
"schoolReference",
"schoolYear",
"entryDate",
"entryGradeLevel",
"entryType",
"repeatGradeIndicator",
"classOf",
"schoolChoiceTransfer",
"exitWithdrawDate",
"exitWithdrawType",
"educationalPlans",
"graduationPlanReference"
})
public class StudentSchoolAssociation {
@XmlElement(name = "StudentReference", required = true)
protected StudentReferenceType studentReference;
@XmlElement(name = "SchoolReference", required = true)
protected EducationalOrgReferenceType schoolReference;
@XmlElement(name = "SchoolYear")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String schoolYear;
@XmlElement(name = "EntryDate", required = true)
@XmlSchemaType(name = "date")
protected XMLGregorianCalendar entryDate;
@XmlElement(name = "EntryGradeLevel", required = true)
protected GradeLevelType entryGradeLevel;
@XmlElement(name = "EntryType")
protected EntryType entryType;
@XmlElement(name = "RepeatGradeIndicator")
protected Boolean repeatGradeIndicator;
@XmlElement(name = "ClassOf")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String classOf;
@XmlElement(name = "SchoolChoiceTransfer")
protected Boolean schoolChoiceTransfer;
@XmlElement(name = "ExitWithdrawDate")
@XmlSchemaType(name = "date")
protected XMLGregorianCalendar exitWithdrawDate;
@XmlElement(name = "ExitWithdrawType")
protected ExitWithdrawType exitWithdrawType;
@XmlElement(name = "EducationalPlans")
protected EducationalPlansType educationalPlans;
@XmlElement(name = "GraduationPlanReference")
protected ReferenceType graduationPlanReference;
/**
* Gets the value of the studentReference property.
*
* @return
* possible object is
* {@link StudentReferenceType }
*
*/
public StudentReferenceType getStudentReference() {
return studentReference;
}
/**
* Sets the value of the studentReference property.
*
* @param value
* allowed object is
* {@link StudentReferenceType }
*
*/
public void setStudentReference(StudentReferenceType value) {
this.studentReference = value;
}
/**
* Gets the value of the schoolReference property.
*
* @return
* possible object is
* {@link EducationalOrgReferenceType }
*
*/
public EducationalOrgReferenceType getSchoolReference() {
return schoolReference;
}
/**
* Sets the value of the schoolReference property.
*
* @param value
* allowed object is
* {@link EducationalOrgReferenceType }
*
*/
public void setSchoolReference(EducationalOrgReferenceType value) {
this.schoolReference = value;
}
/**
* Gets the value of the schoolYear property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSchoolYear() {
return schoolYear;
}
/**
* Sets the value of the schoolYear property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSchoolYear(String value) {
this.schoolYear = value;
}
/**
* Gets the value of the entryDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getEntryDate() {
return entryDate;
}
/**
* Sets the value of the entryDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setEntryDate(XMLGregorianCalendar value) {
this.entryDate = value;
}
/**
* Gets the value of the entryGradeLevel property.
*
* @return
* possible object is
* {@link GradeLevelType }
*
*/
public GradeLevelType getEntryGradeLevel() {
return entryGradeLevel;
}
/**
* Sets the value of the entryGradeLevel property.
*
* @param value
* allowed object is
* {@link GradeLevelType }
*
*/
public void setEntryGradeLevel(GradeLevelType value) {
this.entryGradeLevel = value;
}
/**
* Gets the value of the entryType property.
*
* @return
* possible object is
* {@link EntryType }
*
*/
public EntryType getEntryType() {
return entryType;
}
/**
* Sets the value of the entryType property.
*
* @param value
* allowed object is
* {@link EntryType }
*
*/
public void setEntryType(EntryType value) {
this.entryType = value;
}
/**
* Gets the value of the repeatGradeIndicator property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isRepeatGradeIndicator() {
return repeatGradeIndicator;
}
/**
* Sets the value of the repeatGradeIndicator property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setRepeatGradeIndicator(Boolean value) {
this.repeatGradeIndicator = value;
}
/**
* Gets the value of the classOf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClassOf() {
return classOf;
}
/**
* Sets the value of the classOf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClassOf(String value) {
this.classOf = value;
}
/**
* Gets the value of the schoolChoiceTransfer property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isSchoolChoiceTransfer() {
return schoolChoiceTransfer;
}
/**
* Sets the value of the schoolChoiceTransfer property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setSchoolChoiceTransfer(Boolean value) {
this.schoolChoiceTransfer = value;
}
/**
* Gets the value of the exitWithdrawDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getExitWithdrawDate() {
return exitWithdrawDate;
}
/**
* Sets the value of the exitWithdrawDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setExitWithdrawDate(XMLGregorianCalendar value) {
this.exitWithdrawDate = value;
}
/**
* Gets the value of the exitWithdrawType property.
*
* @return
* possible object is
* {@link ExitWithdrawType }
*
*/
public ExitWithdrawType getExitWithdrawType() {
return exitWithdrawType;
}
/**
* Sets the value of the exitWithdrawType property.
*
* @param value
* allowed object is
* {@link ExitWithdrawType }
*
*/
public void setExitWithdrawType(ExitWithdrawType value) {
this.exitWithdrawType = value;
}
/**
* Gets the value of the educationalPlans property.
*
* @return
* possible object is
* {@link EducationalPlansType }
*
*/
public EducationalPlansType getEducationalPlans() {
return educationalPlans;
}
/**
* Sets the value of the educationalPlans property.
*
* @param value
* allowed object is
* {@link EducationalPlansType }
*
*/
public void setEducationalPlans(EducationalPlansType value) {
this.educationalPlans = value;
}
/**
* Gets the value of the graduationPlanReference property.
*
* @return
* possible object is
* {@link ReferenceType }
*
*/
public ReferenceType getGraduationPlanReference() {
return graduationPlanReference;
}
/**
* Sets the value of the graduationPlanReference property.
*
* @param value
* allowed object is
* {@link ReferenceType }
*
*/
public void setGraduationPlanReference(ReferenceType value) {
this.graduationPlanReference = value;
}
}
| apache-2.0 |
Bismarrck/tensorflow | tensorflow/compiler/xla/reference_util.cc | 30380 | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/reference_util.h"
#include <array>
#include <utility>
#include "absl/memory/memory.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/service/hlo_evaluator.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/shape_inference.h"
#include "tensorflow/compiler/xla/window_util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/math/math_util.h"
#include "tensorflow/core/platform/logging.h"
namespace xla {
/* static */ std::unique_ptr<Array2D<Eigen::half>> ReferenceUtil::MatmulArray2D(
const Array2D<Eigen::half>& lhs, const Array2D<Eigen::half>& rhs) {
return HloEvaluator::MatmulArray2D(lhs, rhs);
}
/* static */ std::unique_ptr<Array2D<float>> ReferenceUtil::MatmulArray2D(
const Array2D<float>& lhs, const Array2D<float>& rhs) {
return HloEvaluator::MatmulArray2D(lhs, rhs);
}
/* static */ std::unique_ptr<Array2D<double>> ReferenceUtil::MatmulArray2D(
const Array2D<double>& lhs, const Array2D<double>& rhs) {
return HloEvaluator::MatmulArray2D(lhs, rhs);
}
/* static */ std::unique_ptr<Array2D<double>> ReferenceUtil::Array2DF32ToF64(
const Array2D<float>& input) {
auto result =
absl::make_unique<Array2D<double>>(input.height(), input.width());
for (int64 rowno = 0; rowno < input.height(); ++rowno) {
for (int64 colno = 0; colno < input.height(); ++colno) {
(*result)(rowno, colno) = input(rowno, colno);
}
}
return result;
}
/* static */ std::unique_ptr<Array3D<float>> ReferenceUtil::ConvArray3D(
const Array3D<float>& lhs, const Array3D<float>& rhs, int64 kernel_stride,
Padding padding) {
return ConvArray3DGeneralDimensionsDilated(
lhs, rhs, kernel_stride, padding, 1, 1,
XlaBuilder::CreateDefaultConvDimensionNumbers(1));
}
/*static*/ std::unique_ptr<Array3D<float>>
ReferenceUtil::ConvArray3DGeneralDimensionsDilated(
const Array3D<float>& lhs, const Array3D<float>& rhs, int64 kernel_stride,
Padding padding, int64 lhs_dilation, int64 rhs_dilation,
const ConvolutionDimensionNumbers& dnums) {
CHECK_EQ(dnums.input_spatial_dimensions_size(), 1);
CHECK_EQ(dnums.kernel_spatial_dimensions_size(), 1);
CHECK_EQ(dnums.output_spatial_dimensions_size(), 1);
// Reuse the code for Array4D-convolution by extending the 3D input into a 4D
// array by adding a fourth dummy dimension of size 1 without stride, padding
// and dilation.
Array4D<float> a4dlhs(lhs.n1(), lhs.n2(), lhs.n3(), 1);
a4dlhs.Each([&](absl::Span<const int64> indices, float* value_ptr) {
CHECK_EQ(indices[3], 0);
*value_ptr = lhs.operator()(indices[0], indices[1], indices[2]);
});
Array4D<float> a4drhs(rhs.n1(), rhs.n2(), rhs.n3(), 1);
a4drhs.Each([&](absl::Span<const int64> indices, float* value_ptr) {
CHECK_EQ(indices[3], 0);
*value_ptr = rhs.operator()(indices[0], indices[1], indices[2]);
});
// Add a second dummy spatial dimensions.
ConvolutionDimensionNumbers dnums2d = dnums;
dnums2d.add_input_spatial_dimensions(3);
dnums2d.add_kernel_spatial_dimensions(3);
dnums2d.add_output_spatial_dimensions(3);
std::unique_ptr<Array4D<float>> convr4 = ConvArray4DGeneralDimensionsDilated(
a4dlhs, a4drhs, {kernel_stride, 1}, padding, {lhs_dilation, 1},
{rhs_dilation, 1}, dnums2d);
auto convr3 = absl::make_unique<Array3D<float>>(
convr4->planes(), convr4->depth(), convr4->height());
convr4->Each([&](absl::Span<const int64> indices, float* value_ptr) {
CHECK_EQ(indices[3], 0);
convr3->operator()(indices[0], indices[1], indices[2]) = *value_ptr;
});
return convr3;
}
/* static */ std::unique_ptr<Array4D<float>> ReferenceUtil::ConvArray4D(
const Array4D<float>& lhs, const Array4D<float>& rhs,
std::pair<int64, int64> kernel_stride, Padding padding) {
return ConvArray4DGeneralDimensions(
lhs, rhs, kernel_stride, padding,
XlaBuilder::CreateDefaultConvDimensionNumbers());
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::SeparableConvArray4D(const Array4D<float>& input,
const Array4D<float>& depthwise_weights,
const Array4D<float>& pointwise_weights,
std::pair<int64, int64> kernel_stride,
Padding padding) {
const int64 depth_multiplier = depthwise_weights.planes();
CHECK_EQ(pointwise_weights.depth(), input.depth() * depth_multiplier);
// Combine the two weights by reducing the depth_multiplier, so that we can
// apply a single convolution on the combined weights.
Array4D<float> weights(pointwise_weights.planes(), input.depth(),
depthwise_weights.height(), depthwise_weights.width());
for (int64 kx = 0; kx < depthwise_weights.width(); ++kx) {
for (int64 ky = 0; ky < depthwise_weights.height(); ++ky) {
for (int64 kz = 0; kz < input.depth(); ++kz) {
for (int64 out = 0; out < pointwise_weights.planes(); ++out) {
float weight = 0.0;
for (int64 depth = 0; depth < depth_multiplier; ++depth) {
weight +=
depthwise_weights(depth, kz, ky, kx) *
pointwise_weights(out, depth + kz * depth_multiplier, 0, 0);
}
weights(out, kz, ky, kx) = weight;
}
}
}
}
return ConvArray4D(input, weights, kernel_stride, padding);
}
/* static */ int64 ReferenceUtil::WindowCount(int64 unpadded_width,
int64 window_len, int64 stride,
Padding padding) {
if (padding == Padding::kValid) {
return window_util::StridedBound(unpadded_width, window_len, stride);
}
return tensorflow::MathUtil::CeilOfRatio(unpadded_width, stride);
}
/* static */ std::unique_ptr<std::vector<float>>
ReferenceUtil::ReduceWindow1DGeneric(
absl::Span<const float> operand, float init,
const std::function<float(float, float)>& reduce_func,
absl::Span<const int64> window, absl::Span<const int64> stride,
absl::Span<const std::pair<int64, int64>> padding) {
std::vector<int64> dim_lengths{static_cast<int64>(operand.size())};
std::vector<int64> window_counts(window.size(), 0);
std::vector<int64> pad_low(window.size(), 0);
for (int64 i = 0; i < window.size(); ++i) {
int64 padded_width = padding[i].first + dim_lengths[i] + padding[i].second;
window_counts[i] =
window_util::StridedBound(padded_width, window[i], stride[i]);
pad_low[i] = padding[i].first;
}
auto result = absl::make_unique<std::vector<float>>(window_counts[0]);
// Do a full 1D reduce window.
for (int64 i0 = 0; i0 < window_counts[0]; ++i0) {
int64 i0_base = i0 * stride[0] - pad_low[0];
float val = init;
for (int64 i0_win = 0; i0_win < window[0]; ++i0_win) {
if (i0_base + i0_win >= 0 && i0_base + i0_win < dim_lengths[0]) {
val = reduce_func(val, operand[i0_base + i0_win]);
}
}
(*result)[i0] = val;
}
return result;
}
/* static */ std::unique_ptr<std::vector<float>>
ReferenceUtil::ReduceWindow1DAdd(absl::Span<const float> operand, float init,
absl::Span<const int64> window,
absl::Span<const int64> stride,
Padding padding) {
const auto add_reduce = [](float arg1, float arg2) { return arg1 + arg2; };
std::vector<int64> dim_lengths{static_cast<int64>(operand.size())};
return ReduceWindow1DGeneric(
operand, init, add_reduce, window, stride,
xla::MakePadding(dim_lengths, window, stride, padding));
}
/* static */ std::unique_ptr<Array2D<float>>
ReferenceUtil::ReduceWindow2DGeneric(
const Array2D<float>& operand, float init,
const std::function<float(float, float)>& reduce_func,
absl::Span<const int64> window, absl::Span<const int64> stride,
absl::Span<const std::pair<int64, int64>> padding) {
std::vector<int64> dim_lengths{operand.height(), operand.width()};
std::vector<int64> window_counts(window.size(), 0);
std::vector<int64> pad_low(window.size(), 0);
for (int64 i = 0; i < window.size(); ++i) {
int64 padded_width = padding[i].first + dim_lengths[i] + padding[i].second;
window_counts[i] =
window_util::StridedBound(padded_width, window[i], stride[i]);
pad_low[i] = padding[i].first;
}
auto result =
absl::make_unique<Array2D<float>>(window_counts[0], window_counts[1]);
// Do a full 2D reduce window.
for (int64 i0 = 0; i0 < window_counts[0]; ++i0) {
for (int64 i1 = 0; i1 < window_counts[1]; ++i1) {
int64 i0_base = i0 * stride[0] - pad_low[0];
int64 i1_base = i1 * stride[1] - pad_low[1];
float val = init;
for (int64 i0_win = 0; i0_win < window[0]; ++i0_win) {
for (int64 i1_win = 0; i1_win < window[1]; ++i1_win) {
if (i0_base + i0_win >= 0 && i1_base + i1_win >= 0 &&
i0_base + i0_win < operand.n1() &&
i1_base + i1_win < operand.n2()) {
val = reduce_func(val, operand(i0_base + i0_win, i1_base + i1_win));
}
}
}
(*result)(i0, i1) = val;
}
}
return result;
}
/* static */ std::unique_ptr<Array2D<float>> ReferenceUtil::ReduceWindow2DAdd(
const Array2D<float>& operand, float init, absl::Span<const int64> window,
absl::Span<const int64> stride, Padding padding) {
const auto add_reduce = [](float arg1, float arg2) { return arg1 + arg2; };
std::vector<int64> dim_lengths{operand.height(), operand.width()};
return ReduceWindow2DGeneric(
operand, init, add_reduce, window, stride,
xla::MakePadding(dim_lengths, window, stride, padding));
}
/* static */ std::unique_ptr<Array3D<float>> ReferenceUtil::ReduceWindow3DAdd(
const Array3D<float>& operand, float init, absl::Span<const int64> window,
absl::Span<const int64> stride, Padding padding) {
std::vector<int64> dim_lengths{operand.n1(), operand.n2(), operand.n3()};
auto padding_both = xla::MakePadding(dim_lengths, window, stride, padding);
std::vector<int64> window_counts(window.size(), 0);
std::vector<int64> pad_low(window.size(), 0);
for (int64 i = 0; i < window.size(); ++i) {
window_counts[i] =
WindowCount(dim_lengths[i], window[i], stride[i], padding);
pad_low[i] = padding_both[i].first;
}
auto result = absl::make_unique<Array3D<float>>(
window_counts[0], window_counts[1], window_counts[2]);
for (int64 i0 = 0; i0 < window_counts[0]; ++i0) {
for (int64 i1 = 0; i1 < window_counts[1]; ++i1) {
for (int64 i2 = 0; i2 < window_counts[2]; ++i2) {
int64 i0_base = i0 * stride[0] - pad_low[0];
int64 i1_base = i1 * stride[1] - pad_low[1];
int64 i2_base = i2 * stride[2] - pad_low[2];
float val = init;
for (int64 i0_win = 0; i0_win < window[0]; ++i0_win) {
for (int64 i1_win = 0; i1_win < window[1]; ++i1_win) {
for (int64 i2_win = 0; i2_win < window[2]; ++i2_win) {
if (i0_base + i0_win >= 0 && i1_base + i1_win >= 0 &&
i2_base + i2_win >= 0 && i0_base + i0_win < operand.n1() &&
i1_base + i1_win < operand.n2() &&
i2_base + i2_win < operand.n3()) {
val += operand(i0_base + i0_win, i1_base + i1_win,
i2_base + i2_win);
}
}
}
}
(*result)(i0, i1, i2) = val;
}
}
}
return result;
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::ReduceWindow4DGeneric(
const Array4D<float>& operand, float init,
const std::function<float(float, float)>& reduce_func,
absl::Span<const int64> window, absl::Span<const int64> stride,
Padding padding) {
std::vector<int64> dim_lengths{operand.n1(), operand.n2(), operand.n3(),
operand.n4()};
return ReduceWindow4DGeneric(
operand, init, reduce_func, window, stride,
xla::MakePadding(dim_lengths, window, stride, padding));
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::ReduceWindow4DGeneric(
const Array4D<float>& operand, float init,
const std::function<float(float, float)>& reduce_func,
absl::Span<const int64> window, absl::Span<const int64> stride,
absl::Span<const std::pair<int64, int64>> padding) {
std::vector<int64> dim_lengths{operand.n1(), operand.n2(), operand.n3(),
operand.n4()};
std::vector<int64> window_counts(window.size(), 0);
std::vector<int64> pad_low(window.size(), 0);
for (int64 i = 0; i < window.size(); ++i) {
int64 padded_width = padding[i].first + dim_lengths[i] + padding[i].second;
window_counts[i] =
window_util::StridedBound(padded_width, window[i], stride[i]);
pad_low[i] = padding[i].first;
}
auto result = absl::make_unique<Array4D<float>>(
window_counts[0], window_counts[1], window_counts[2], window_counts[3]);
// Do a full 4D reduce window.
for (int64 i0 = 0; i0 < window_counts[0]; ++i0) {
for (int64 i1 = 0; i1 < window_counts[1]; ++i1) {
for (int64 i2 = 0; i2 < window_counts[2]; ++i2) {
for (int64 i3 = 0; i3 < window_counts[3]; ++i3) {
int64 i0_base = i0 * stride[0] - pad_low[0];
int64 i1_base = i1 * stride[1] - pad_low[1];
int64 i2_base = i2 * stride[2] - pad_low[2];
int64 i3_base = i3 * stride[3] - pad_low[3];
float val = init;
for (int64 i0_win = 0; i0_win < window[0]; ++i0_win) {
for (int64 i1_win = 0; i1_win < window[1]; ++i1_win) {
for (int64 i2_win = 0; i2_win < window[2]; ++i2_win) {
for (int64 i3_win = 0; i3_win < window[3]; ++i3_win) {
if (i0_base + i0_win >= 0 && i1_base + i1_win >= 0 &&
i2_base + i2_win >= 0 && i3_base + i3_win >= 0 &&
i0_base + i0_win < operand.n1() &&
i1_base + i1_win < operand.n2() &&
i2_base + i2_win < operand.n3() &&
i3_base + i3_win < operand.n4()) {
val = reduce_func(
val, operand(i0_base + i0_win, i1_base + i1_win,
i2_base + i2_win, i3_base + i3_win));
}
}
}
}
}
(*result)(i0, i1, i2, i3) = val;
}
}
}
}
return result;
}
/* static */ std::unique_ptr<Array4D<float>> ReferenceUtil::ReduceWindow4DAdd(
const Array4D<float>& operand, float init, absl::Span<const int64> window,
absl::Span<const int64> stride, Padding padding) {
const auto add_reduce = [](float arg1, float arg2) { return arg1 + arg2; };
return ReduceWindow4DGeneric(operand, init, add_reduce, window, stride,
padding);
}
/* static */ std::unique_ptr<Array4D<float>> ReferenceUtil::BatchNorm4D(
const Array4D<float>& input, const Array4D<float>& mean,
const Array4D<float>& var, const Array4D<float>& scale,
const Array4D<float>& offset, float epsilon) {
auto normalized =
*MapArray4D(input, mean, [](float a, float b) { return a - b; });
normalized = *MapArray4D(normalized, var, [&](float a, float b) {
return a / std::sqrt(b + epsilon);
});
normalized =
*MapArray4D(normalized, scale, [](float a, float b) { return a * b; });
return MapArray4D(normalized, offset, [](float a, float b) { return a + b; });
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::SelectAndScatter4DGePlus(const Array4D<float>& operand,
const Array4D<float>& source,
float init,
absl::Span<const int64> window,
absl::Span<const int64> stride,
bool same_padding) {
Padding padding = same_padding ? Padding::kSame : Padding::kValid;
auto result = absl::make_unique<Array4D<float>>(operand.n1(), operand.n2(),
operand.n3(), operand.n4());
std::vector<int64> dim_lengths{operand.n1(), operand.n2(), operand.n3(),
operand.n4()};
auto padding_both = xla::MakePadding(dim_lengths, window, stride, padding);
// Fill the output, with the initial value.
result->Fill(init);
std::vector<int64> window_counts(window.size(), 0);
std::vector<int64> pad_low(window.size(), 0);
for (int64 i = 0; i < window.size(); ++i) {
window_counts[i] =
WindowCount(dim_lengths[i], window[i], stride[i], padding);
pad_low[i] = padding_both[i].first;
}
CHECK_EQ(window_counts[0], source.n1());
CHECK_EQ(window_counts[1], source.n2());
CHECK_EQ(window_counts[2], source.n3());
CHECK_EQ(window_counts[3], source.n4());
// Do a full 4D select and Scatter.
for (int64 i0 = 0; i0 < window_counts[0]; ++i0) {
for (int64 i1 = 0; i1 < window_counts[1]; ++i1) {
for (int64 i2 = 0; i2 < window_counts[2]; ++i2) {
for (int64 i3 = 0; i3 < window_counts[3]; ++i3) {
// Now we are inside a window and need to find the max and the argmax.
int64 i0_base = i0 * stride[0] - pad_low[0];
int64 i1_base = i1 * stride[1] - pad_low[1];
int64 i2_base = i2 * stride[2] - pad_low[2];
int64 i3_base = i3 * stride[3] - pad_low[3];
int64 scatter_0 = (i0_base >= 0) ? i0_base : 0;
int64 scatter_1 = (i1_base >= 0) ? i1_base : 0;
int64 scatter_2 = (i2_base >= 0) ? i2_base : 0;
int64 scatter_3 = (i3_base >= 0) ? i3_base : 0;
float val = operand(scatter_0, scatter_1, scatter_2, scatter_3);
for (int64 i0_win = 0; i0_win < window[0]; ++i0_win) {
for (int64 i1_win = 0; i1_win < window[1]; ++i1_win) {
for (int64 i2_win = 0; i2_win < window[2]; ++i2_win) {
for (int64 i3_win = 0; i3_win < window[3]; ++i3_win) {
if (i0_base + i0_win >= 0 && i1_base + i1_win >= 0 &&
i2_base + i2_win >= 0 && i3_base + i3_win >= 0 &&
i0_base + i0_win < operand.n1() &&
i1_base + i1_win < operand.n2() &&
i2_base + i2_win < operand.n3() &&
i3_base + i3_win < operand.n4()) {
float tmp = operand(i0_base + i0_win, i1_base + i1_win,
i2_base + i2_win, i3_base + i3_win);
if (tmp > val) {
val = tmp;
scatter_0 = i0_base + i0_win;
scatter_1 = i1_base + i1_win;
scatter_2 = i2_base + i2_win;
scatter_3 = i3_base + i3_win;
}
}
}
}
}
}
(*result)(scatter_0, scatter_1, scatter_2, scatter_3) +=
source(i0, i1, i2, i3);
}
}
}
}
return result;
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::ConvArray4DGeneralDimensions(
const Array4D<float>& lhs, const Array4D<float>& rhs,
std::pair<int64, int64> kernel_stride, Padding padding,
ConvolutionDimensionNumbers dimension_numbers) {
return ConvArray4DGeneralDimensionsDilated(lhs, rhs, kernel_stride, padding,
{1, 1}, {1, 1},
std::move(dimension_numbers));
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::ConvArray4DGeneralDimensionsDilated(
const Array4D<float>& lhs, const Array4D<float>& rhs,
std::pair<int64, int64> kernel_stride, Padding padding,
std::pair<int64, int64> lhs_dilation, std::pair<int64, int64> rhs_dilation,
ConvolutionDimensionNumbers dnums) {
HloComputation::Builder b("ConvArray4DGeneralDimensionDilated");
auto lhs_literal = LiteralUtil::CreateR4FromArray4D<float>(lhs);
auto rhs_literal = LiteralUtil::CreateR4FromArray4D<float>(rhs);
std::array<int64, 2> ordered_kernel_strides;
std::array<int64, 2> ordered_input_dimensions;
std::array<int64, 2> ordered_kernel_dimensions;
if (dnums.kernel_spatial_dimensions(0) > dnums.kernel_spatial_dimensions(1)) {
ordered_kernel_strides[0] = kernel_stride.second;
ordered_kernel_strides[1] = kernel_stride.first;
} else {
ordered_kernel_strides[0] = kernel_stride.first;
ordered_kernel_strides[1] = kernel_stride.second;
}
ordered_input_dimensions[0] =
lhs_literal.shape().dimensions(dnums.input_spatial_dimensions(0));
ordered_input_dimensions[1] =
lhs_literal.shape().dimensions(dnums.input_spatial_dimensions(1));
ordered_kernel_dimensions[0] =
rhs_literal.shape().dimensions(dnums.kernel_spatial_dimensions(0));
ordered_kernel_dimensions[1] =
rhs_literal.shape().dimensions(dnums.kernel_spatial_dimensions(1));
std::vector<std::pair<int64, int64>> paddings =
MakePadding(ordered_input_dimensions, ordered_kernel_dimensions,
ordered_kernel_strides, padding);
CHECK_EQ(paddings.size(), 2);
Window window;
WindowDimension dim;
dim.set_size(
rhs_literal.shape().dimensions(dnums.kernel_spatial_dimensions(0)));
dim.set_stride(kernel_stride.first);
dim.set_padding_low(paddings[0].first);
dim.set_padding_high(paddings[0].second);
dim.set_window_dilation(rhs_dilation.first);
dim.set_base_dilation(lhs_dilation.first);
*window.add_dimensions() = dim;
WindowDimension dim2;
dim2.set_size(
rhs_literal.shape().dimensions(dnums.kernel_spatial_dimensions(1)));
dim2.set_stride(kernel_stride.second);
dim2.set_padding_low(paddings[1].first);
dim2.set_padding_high(paddings[1].second);
dim2.set_window_dilation(rhs_dilation.second);
dim2.set_base_dilation(lhs_dilation.second);
*window.add_dimensions() = dim2;
const Shape& shape =
ShapeInference::InferConvolveShape(
lhs_literal.shape(), rhs_literal.shape(),
/*feature_group_count=*/1, /*batch_group_count=*/1, window, dnums)
.ConsumeValueOrDie();
HloInstruction* lhs_instruction =
b.AddInstruction(HloInstruction::CreateConstant(std::move(lhs_literal)));
HloInstruction* rhs_instruction =
b.AddInstruction(HloInstruction::CreateConstant(std::move(rhs_literal)));
PrecisionConfig precision_config;
precision_config.mutable_operand_precision()->Resize(
/*new_size=*/2, PrecisionConfig::DEFAULT);
b.AddInstruction(HloInstruction::CreateConvolve(
shape, lhs_instruction, rhs_instruction, /*feature_group_count=*/1,
/*batch_group_count=*/1, window, dnums, precision_config));
HloModuleConfig config;
HloModule module("ReferenceUtil", config);
auto computation = module.AddEntryComputation(b.Build());
HloEvaluator evaluator;
Literal result_literal =
evaluator.Evaluate<const Literal*>(*computation, {}).ConsumeValueOrDie();
CHECK_EQ(ShapeUtil::Rank(result_literal.shape()), 4);
auto result =
absl::make_unique<Array4D<float>>(result_literal.shape().dimensions(0),
result_literal.shape().dimensions(1),
result_literal.shape().dimensions(2),
result_literal.shape().dimensions(3));
result->Each([&](absl::Span<const int64> indices, float* value) {
*value = result_literal.Get<float>(indices);
});
return result;
}
/* static */ std::unique_ptr<std::vector<float>>
ReferenceUtil::ReduceToColArray2D(
const Array2D<float>& matrix, float init,
const std::function<float(float, float)>& reduce_function) {
int64 rows = matrix.height();
int64 cols = matrix.width();
auto result = absl::make_unique<std::vector<float>>();
for (int64 i = 0; i < rows; ++i) {
float acc = init;
for (int64 j = 0; j < cols; ++j) {
acc = reduce_function(acc, matrix(i, j));
}
result->push_back(acc);
}
return result;
}
/* static */ std::unique_ptr<std::vector<float>>
ReferenceUtil::ReduceToRowArray2D(
const Array2D<float>& matrix, float init,
const std::function<float(float, float)>& reduce_function) {
int64 rows = matrix.height();
int64 cols = matrix.width();
auto result = absl::make_unique<std::vector<float>>();
for (int64 i = 0; i < cols; ++i) {
float acc = init;
for (int64 j = 0; j < rows; ++j) {
acc = reduce_function(acc, matrix(j, i));
}
result->push_back(acc);
}
return result;
}
/*static*/ std::vector<float> ReferenceUtil::Reduce4DTo1D(
const Array4D<float>& array, float init, absl::Span<const int64> dims,
const std::function<float(float, float)>& reduce_function) {
std::vector<float> result;
CHECK_EQ(dims.size(), 3);
const std::set<int64> dim_set(dims.begin(), dims.end());
CHECK_EQ(dim_set.size(), 3);
for (int64 a0 = 0; a0 == 0 || (!dim_set.count(0) && a0 < array.n1()); ++a0) {
for (int64 a1 = 0; a1 == 0 || (!dim_set.count(1) && a1 < array.n2());
++a1) {
for (int64 a2 = 0; a2 == 0 || (!dim_set.count(2) && a2 < array.n3());
++a2) {
for (int64 a3 = 0; a3 == 0 || (!dim_set.count(3) && a3 < array.n4());
++a3) {
float accumulator = init;
for (int64 i0 = 0; i0 == 0 || (dim_set.count(0) && i0 < array.n1());
++i0) {
for (int64 i1 = 0; i1 == 0 || (dim_set.count(1) && i1 < array.n2());
++i1) {
for (int64 i2 = 0;
i2 == 0 || (dim_set.count(2) && i2 < array.n3()); ++i2) {
for (int64 i3 = 0;
i3 == 0 || (dim_set.count(3) && i3 < array.n4()); ++i3) {
// Handle zero-sized arrays.
if (array.n1() > 0 && array.n2() > 0 && array.n3() > 0 &&
array.n4() > 0) {
accumulator = reduce_function(
accumulator, array(a0 + i0, a1 + i1, a2 + i2, a3 + i3));
}
}
}
}
}
result.push_back(accumulator);
}
}
}
}
return result;
}
/* static */ std::unique_ptr<Array4D<float>> ReferenceUtil::Broadcast1DTo4D(
const std::vector<float>& array, const std::vector<int64>& bounds,
int64 broadcast_from_dim) {
auto result = absl::make_unique<Array4D<float>>(bounds[0], bounds[1],
bounds[2], bounds[3]);
for (int64 i = 0; i < result->n1(); ++i) {
for (int64 j = 0; j < result->n2(); ++j) {
for (int64 k = 0; k < result->n3(); ++k) {
for (int64 l = 0; l < result->n4(); ++l) {
switch (broadcast_from_dim) {
case 0:
(*result)(i, j, k, l) = array[i];
break;
case 1:
(*result)(i, j, k, l) = array[j];
break;
case 2:
(*result)(i, j, k, l) = array[k];
break;
case 3:
(*result)(i, j, k, l) = array[l];
break;
default:
break;
}
}
}
}
}
return result;
}
/* static */ std::unique_ptr<Array2D<float>> ReferenceUtil::Reduce3DTo2D(
const Array3D<float>& array, float init, absl::Span<const int64> dims,
const std::function<float(float, float)>& reduce_function) {
CHECK_EQ(dims.size(), 1);
int64 rows = dims[0] == 0 ? array.n2() : array.n1();
int64 cols = dims[0] == 2 ? array.n2() : array.n3();
auto result = absl::make_unique<Array2D<float>>(rows, cols);
result->Fill(init);
for (int i0 = 0; i0 < array.n1(); ++i0) {
for (int i1 = 0; i1 < array.n2(); ++i1) {
for (int i2 = 0; i2 < array.n3(); ++i2) {
int64 row = dims[0] == 0 ? i1 : i0;
int64 col = dims[0] == 2 ? i1 : i2;
(*result)(row, col) =
reduce_function((*result)(row, col), array(i0, i1, i2));
}
}
}
return result;
}
/* static */ std::unique_ptr<Array2D<float>> ReferenceUtil::MapArray2D(
const Array2D<float>& matrix,
const std::function<float(float)>& map_function) {
int64 rows = matrix.height();
int64 cols = matrix.width();
auto result = absl::make_unique<Array2D<float>>(rows, cols);
for (int64 i = 0; i < rows; ++i) {
for (int64 j = 0; j < cols; ++j) {
(*result)(i, j) = map_function(matrix(i, j));
}
}
return result;
}
/* static */ std::unique_ptr<Array2D<float>> ReferenceUtil::MapArray2D(
const Array2D<float>& lhs, const Array2D<float>& rhs,
const std::function<float(float, float)>& map_function) {
CHECK_EQ(lhs.height(), rhs.height());
CHECK_EQ(lhs.width(), rhs.width());
int64 rows = lhs.height();
int64 cols = rhs.width();
auto result = absl::make_unique<Array2D<float>>(rows, cols);
for (int64 i = 0; i < rows; ++i) {
for (int64 j = 0; j < cols; ++j) {
(*result)(i, j) = map_function(lhs(i, j), rhs(i, j));
}
}
return result;
}
/* static */ std::unique_ptr<Array2D<float>> ReferenceUtil::MapWithIndexArray2D(
const Array2D<float>& matrix,
const std::function<float(float, int64, int64)>& map_function) {
int64 rows = matrix.height();
int64 cols = matrix.width();
auto result = absl::make_unique<Array2D<float>>(rows, cols);
for (int64 i = 0; i < rows; ++i) {
for (int64 j = 0; j < cols; ++j) {
(*result)(i, j) = map_function(matrix(i, j), i, j);
}
}
return result;
}
} // namespace xla
| apache-2.0 |
BBVA-CIB/APIRestGenerator | core/src/test/java/com/bbva/kltt/apirest/core/parsed_info/parameters/ParameterFormDataTest.java | 2731 | package com.bbva.kltt.apirest.core.parsed_info.parameters;
import org.junit.Test;
import com.bbva.kltt.apirest.core.parsed_info.common.ItemTest;
import com.bbva.kltt.apirest.core.util.APIRestGeneratorException;
import com.bbva.kltt.apirest.core.util.ConstantsCommon;
import com.bbva.kltt.apirest.core.util.ConstantsTest;
/**
* ------------------------------------------------
* @author Francisco Manuel Benitez Chico
* ------------------------------------------------
*/
public class ParameterFormDataTest
{
@Test
public void fullTest() throws APIRestGeneratorException
{
final ParameterFormData parameterFormData = ParameterFormDataTest.generateDummyParameterFormData() ;
parameterFormData.getAlias() ;
parameterFormData.getClassName() ;
parameterFormData.getDescription() ;
parameterFormData.getItem() ;
parameterFormData.getName() ;
parameterFormData.getType() ;
parameterFormData.isAutoInjected() ;
}
@Test(expected = APIRestGeneratorException.class)
public void invalidParameterTypeNull() throws APIRestGeneratorException
{
final ParameterFormData parameterFormData = new ParameterFormData(ConstantsTest.NAME,
ConstantsTest.ALIAS,
ConstantsTest.DESCRIPTION,
ConstantsTest.REQUIRED,
null,
ConstantsTest.CONSUMES_MULTIPAR,
ConstantsTest.AUTO_INJECTED) ;
parameterFormData.validate() ;
}
@Test(expected = APIRestGeneratorException.class)
public void invalidParameterAutoInjectedTrue() throws APIRestGeneratorException
{
final ParameterFormData parameterFormData = new ParameterFormData(ConstantsTest.NAME,
ConstantsTest.ALIAS,
ConstantsTest.DESCRIPTION,
ConstantsTest.REQUIRED,
ConstantsCommon.TYPE_FILE,
ConstantsTest.CONSUMES_MULTIPAR,
"true") ;
parameterFormData.validate() ;
}
/**
* @return a dummy parameter formData
* @throws APIRestGeneratorException with an occurred exception
*/
public static ParameterFormData generateDummyParameterFormData() throws APIRestGeneratorException
{
final ParameterFormData parameterFormData = new ParameterFormData(ConstantsTest.NAME,
ConstantsTest.ALIAS,
ConstantsTest.DESCRIPTION,
ConstantsTest.REQUIRED,
ConstantsCommon.TYPE_FILE,
ConstantsTest.CONSUMES_MULTIPAR,
ConstantsTest.AUTO_INJECTED) ;
parameterFormData.setItem(ItemTest.generateDummyItem()) ;
return parameterFormData ;
}
}
| apache-2.0 |
pub007/dstruct | email_list/clsEmailList.php | 5385 | <?php
/**
* EmailList class
*/
/**
* Email Lists.
*
* Email Lists to which people subscribe.
* @package email_list
* @author David Lidstone
*/
class EmailList {
private $data = [
'Name'=>null,
'EmailAddress'=>null,
'IMAPHost'=>null,
'Username'=>null,
'Password'=>null,
'Host'=>null,
'Port'=>null,
'AdministratorEmail'=>null,
'ProcessedDir'=>null,
];
private $cs = null; // list subscribers object
private $id = null;
/**
* Class constructor.
* @param array $row Information to populate object.
*/
public function __construct($row = false) {
if ($row != false) {
$this->id = $row['EmailListID'];
unset($row['EmailListID']);
$this->data = $row;
}
}
public function __toString() {
$this->data['id'] = $this->id;
return print_r($this->data, true);
}
public function deleteSubscriber(ListSubscriber &$subscriber) {
$watcher = ObjWatcher::instance();
$watcher->remove($subscriber);
ListSubscriberDataManager::delete($subscriber->getID());
$this->removeActiveSubscriber($subscriber);
unset($subscriber);
}
// TODO: Test this function
// Why is this in own method?
protected function removeActiveSubscriber(ListSubscriber $subscriber) {
$this->cs['activesubscribers']->remove($subscriber);
}
public function getAdministratorEmail() {
return $this->data['AdministratorEmail'];
}
public function getActiveSubscribers() {
$this->loadActiveSubscribers();
return $this->cs['ActiveSubscribers'];
}
public function getEmailAddress() {
return $this->data['EmailAddress'];
}
public function getHost() {
return $this->data['Host'];
}
public function getID() {
return (isset($this->id))? $this->id : false;
}
public function getIMAPHost($raw = false) {
return $raw? $this->data['IMAPHost'] : Format::hsc($this->data['IMAPHost']);
}
public function getName($raw = false) {
return $raw? $this->data['Name'] : Format::hsc($this->data['Name']);
}
public function getPassword($raw = false) {
//$password = Generate::decrypt($this->data['Password']); // temp disabled due to mcrypt
$password = $this->data['Password'];
return $raw? $password : Format::hsc($password);
}
public function getPort() {
return $this->data['Port'];
}
public function getProcessedDir($raw = false) {
return $raw? $this->data['ProcessedDir'] : Format::hsc($this->data['ProcessedDir']);
}
public function getSubscribers() {
$this->loadSubscribers();
return $this->cs['subscribers'];
}
public function getUsername ($raw = false) {
return $raw? $this->data['Username'] : Format::hsc($this->data['Username']);
}
private function insert() {
$this->id = EmailListDataManager::insert($this->data);
}
private function loadActiveSubscribers() {
if (!$this->cs['activesubscribers']) {
$this->cs['activesubscribers'] = new ListSubscribers();
$this->cs['activesubscribers']->loadActiveByList($this);
}
}
/**
* Load the list by its ID.
*
* @param integer $id
* @param array $row Data to populate object
* @return false|Tree False if can't find list with that ID
*/
public static function loadByID($id, $row = false) {
// check numeric, as MySQL will cast the variable to a ?double? and so variables such as
// '1stdsf' will cast to 1 and return a record rather than false!!
if (!is_numeric($id)) {return false;}
if ($class = ObjWatcher::exists(__CLASS__, $id)) {return $class;}
if (!$row) {
$rs = EmailListDataManager::load($id);
if ($rs->count() == 0) {return false;}
foreach ($rs as $record) {$row = $record;}
}
$class = new self($row);
ObjWatcher::add($class);
return $class;
}
private function loadSubscribers() {
if (!$this->cs['subscribers']) {
$this->cs['subscribers'] = new ListSubscribers();
$this->cs['subscribers']->loadByList($this);
}
}
/**
* Save the object in the database.
*/
public function save() {
($this->id)? $this->update() : $this->insert();
}
public function setAdministratorEmail($administratoremail) {
$this->data['AdministratorEmail'] = $administratoremail;
}
public function setEmailAddress($address) {
$this->data['EmailAddress'] = $address;
}
public function setHost($host) {
$this->data['Host'] = $host;
}
/**
* Set string for connecting to IMAP
* e.g. {imap.zoho.com:993/imap/ssl}INBOX
* @param string $imaphost
*/
public function setIMAPHost($imaphost) {
$this->data['IMAPHost'] = $imaphost;
}
/**
* Set the name of the list
* @param string $name
*/
public function setName($name) {
$this->data['Name'] = $name;
}
public function setUsername($username) {
$this->data['Username'] = $username;
}
public function setPassword($password) {
//$this->data['Password'] = Generate::encypt($password); temp disabled due to mcrypt
$this->data['Password'] = $password;
}
public function setPort($port) {
$this->data['Port'] = $port;
}
/**
* Set the directory for the email to be moved to once processed
*
* e.g. [Gmail]/Trash
*
* @param string $processedDir
*/
public function setProcessedDir($processedDir) {
$this->data['ProcessedDir'] = $processedDir;
}
/**
* Update in the database.
*/
private function update() {
EmailListDataManager::update($this->data, $this->id);
}
} | apache-2.0 |
vjanmey/EpicMudfia | com/planet_ink/coffee_mud/Items/ShipTech/GenCompEnviroSystem.java | 3392 | package com.planet_ink.coffee_mud.Items.ShipTech;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.Technical.TechType;
import com.planet_ink.coffee_mud.Libraries.interfaces.GenericBuilder;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2014 Bo Zimmerman
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.
*/
public class GenCompEnviroSystem extends GenElecCompItem
{
@Override public String ID(){ return "GenCompEnviroSystem";}
protected final static int ENVIRO_TICKS=7;
protected int tickDown=ENVIRO_TICKS;
protected int airResource=RawMaterial.RESOURCE_AIR;
public GenCompEnviroSystem()
{
super();
setName("a generic environment system");
setDisplayText("a generic environment system sits here.");
setDescription("");
}
@Override public TechType getTechType() { return TechType.SHIP_ENVIRO_CONTROL; }
@Override
public void executeMsg(Environmental myHost, CMMsg msg)
{
super.executeMsg(myHost, msg);
if(msg.amITarget(this))
{
switch(msg.targetMinor())
{
case CMMsg.TYP_LOOK:
if(CMLib.flags().canBeSeenBy(this, msg.source()))
msg.source().tell(_("@x1 is currently @x2",name(),(activated()?"delivering power.\n\r":"deactivated/disconnected.\n\r")));
return;
case CMMsg.TYP_POWERCURRENT:
if(activated())
{
if(--tickDown <=0)
{
tickDown=ENVIRO_TICKS;
final SpaceObject obj=CMLib.map().getSpaceObject(this, true);
if(obj instanceof SpaceShip)
{
final SpaceShip ship=(SpaceShip)obj;
final Area A=ship.getShipArea();
double pct= Math.min(super.getInstalledFactor(),1.0)
* Math.min(super.getFinalManufacturer().getReliabilityPct(),1.0);
if(subjectToWearAndTear())
pct=pct*CMath.div(usesRemaining(),100);
final String code=Technical.TechCommand.AIRREFRESH.makeCommand(Double.valueOf(pct),Integer.valueOf(airResource));
final CMMsg msg2=CMClass.getMsg(msg.source(), ship, me, CMMsg.NO_EFFECT, null, CMMsg.MSG_ACTIVATE|CMMsg.MASK_CNTRLMSG, code, CMMsg.NO_EFFECT,null);
if(A.okMessage(msg2.source(), msg))
A.executeMsg(msg2.source(), msg);
}
}
}
break;
}
}
}
}
| apache-2.0 |
cloudfoundry/cli | command/translatableerror/droplet_file_error.go | 335 | package translatableerror
type DropletFileError struct {
Err error
}
func (DropletFileError) Error() string {
return "Error creating droplet file: {{.Error}}"
}
func (e DropletFileError) Translate(translate func(string, ...interface{}) string) string {
return translate(e.Error(), map[string]interface{}{
"Error": e.Err,
})
}
| apache-2.0 |
nesfit/NetfoxDetective | Framework/ApplicationRecognizers/AppIdent/Features/Bases/SYNPacketsBase.cs | 2882 | // Copyright (c) 2017 Jan Pluskal
//
//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 System.Collections.Generic;
using System.Linq;
using Netfox.AppIdent.Metrics;
using Netfox.AppIdent.Misc;
using Netfox.Core.Enums;
using Netfox.Framework.Models;
using Netfox.Framework.Models.PmLib.Frames;
namespace Netfox.AppIdent.Features.Bases
{
public class SYNPacketsBase : FeatureBase
{
public SYNPacketsBase() { }
public SYNPacketsBase(L7Conversation l7Conversation, DaRFlowDirection flowDirection) : base(l7Conversation, flowDirection) { }
public SYNPacketsBase(double featureValue) : base(featureValue) { }
public override FeatureKind FeatureKind { get; } = FeatureKind.Continous;
public override double ComputeDistanceToProtocolModel(FeatureBase sampleFeature)
{
return Math.Abs(this.Normalize(this.FeatureValue) - this.Normalize(sampleFeature.FeatureValue));
}
public override double ComputeFeature(L7Conversation l7Conversation, DaRFlowDirection flowDirection)
{
IEnumerable<PmFrameBase> frames;
switch(flowDirection)
{
case DaRFlowDirection.up:
frames = l7Conversation.UpFlowFrames;
break;
case DaRFlowDirection.down:
frames = l7Conversation.DownFlowFrames;
break;
case DaRFlowDirection.non:
frames = l7Conversation.UpFlowFrames.Concat(l7Conversation.DownFlowFrames);
break;
default: throw new ArgumentOutOfRangeException(nameof(flowDirection), flowDirection, null);
}
var pmFrameBases = frames as PmFrameBase[] ?? frames.ToArray();
if(!pmFrameBases.Any()) { return -1; }
return pmFrameBases.Count(count => count.TcpFSyn);
}
public override void ComputeFeatureForProtocolModel(IFeatureCollectionWrapper<FeatureBase> featureValues)
{
this.FeatureValue = FeatureMetrics.FeatureMetricAverage(featureValues);
if(this.FeatureValue != 1 && this.FeatureValue > 0) { this.Weight = 1; }
else if(this.FeatureValue == 1) { this.Weight = 0; }
else { this.Weight = WeightMetrics.WeightUsingNormEntropy(featureValues); }
}
}
} | apache-2.0 |
kulinski/myfaces | impl/src/main/java/org/apache/myfaces/context/servlet/InitParameterMap.java | 2399 | /*
* 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.myfaces.context.servlet;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.myfaces.util.AbstractAttributeMap;
/**
* ServletContext init parameters as Map.
*
* @author Anton Koinov (latest modification by $Author: bommel $)
* @version $Revision: 1187701 $ $Date: 2011-10-22 07:21:54 -0500 (Sat, 22 Oct 2011) $
*/
public final class InitParameterMap extends AbstractAttributeMap<String>
{
private final ServletContext _servletContext;
InitParameterMap(final ServletContext servletContext)
{
_servletContext = servletContext;
}
@Override
protected String getAttribute(final String key)
{
return _servletContext.getInitParameter(key);
}
@Override
protected void setAttribute(final String key, final String value)
{
throw new UnsupportedOperationException(
"Cannot set ServletContext InitParameter");
}
@Override
protected void removeAttribute(final String key)
{
throw new UnsupportedOperationException(
"Cannot remove ServletContext InitParameter");
}
@Override
@SuppressWarnings("unchecked")
protected Enumeration<String> getAttributeNames()
{
return _servletContext.getInitParameterNames();
}
@Override
public void putAll(final Map<? extends String, ? extends String> t)
{
throw new UnsupportedOperationException();
}
@Override
public void clear()
{
throw new UnsupportedOperationException();
}
}
| apache-2.0 |
xtofs/tiny-time | src/main/scala/net/xtof/time/InstantWriter.scala | 1723 | package net.xtof.time
trait InstantWriter {
def write(dateTime: Instant): String
}
object InstantWriter {
private val fmt = "%04d-%02d-%02d"
val date: InstantWriter = BaseInstantWriter(dt => {
val (y, m, d) = Calendar.dateParts(dt.millisSinceEpoch)
fmt.format(y, m, d)
})
val time: InstantWriter = Sequence(
part(InstantField.HourOfDay),
const(":"),
part(InstantField.MinuteOfHour),
ifNotNull(InstantField.SecondOfMinute,
const(":"),
part(InstantField.SecondOfMinute)),
// TODO: fix: if Second is 0 then the output is HH:MM.zzz
ifNotNull(InstantField.MillisecondsOfSecond,
const("."),
part(InstantField.MillisecondsOfSecond, 3))
)
val readable: InstantWriter = Sequence(date, const(" "), time)
private final case class BaseInstantWriter(f: Instant => String) extends InstantWriter {
def write(dateTime: Instant): String = f(dateTime)
}
private final case class Sequence(fmts: InstantWriter*) extends InstantWriter {
def write(dateTime: Instant): String =
fmts.map(fmt => fmt.write(dateTime)).mkString
}
def part(dtp: InstantField, n: Int = 2): InstantWriter =
format(dtp, "%0" + n.toString + "d")
def format(dtp: InstantField, format: String): InstantWriter =
BaseInstantWriter(dt => format.format(dtp.extract(dt)))
def const(str: String): InstantWriter =
BaseInstantWriter(_ => str)
def ifNotNull(dateTimePart: InstantField, fmts: InstantWriter*): InstantWriter =
cond(dt => dateTimePart.extract(dt) != 0, fmts: _*)
def cond(predicate: Instant => Boolean, fmts: InstantWriter*): InstantWriter =
BaseInstantWriter(dt => if (predicate(dt)) fmts.map(f => f.write(dt)).mkString else "")
} | apache-2.0 |
eBay/mTracker | core/src/main/java/com/ccoe/build/service/config/BuildServiceConfigBean.java | 1297 | /*
Copyright [2013-2014] eBay Software Foundation
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.ccoe.build.service.config;
public class BuildServiceConfigBean {
private boolean globalSwitch;
private String statusCode;
private String contacts;
private String site;
public boolean isGlobalSwitch() {
return globalSwitch;
}
public void setGlobalSwitch(boolean globalSwitch) {
this.globalSwitch = globalSwitch;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getContacts() {
return contacts;
}
public void setContacts(String contacts) {
this.contacts = contacts;
}
public String getSite() {
return site;
}
public void setSite(String site) {
this.site = site;
}
}
| apache-2.0 |
stringbean/elastic4s | elastic4s-core/src/main/scala/com/sksamuel/elastic4s/requests/searches/queries/compound/DisMaxQueryBodyFn.scala | 818 | package com.sksamuel.elastic4s.requests.searches.queries.compound
import com.sksamuel.elastic4s.json.{XContentBuilder, XContentFactory}
import com.sksamuel.elastic4s.requests.searches.queries.{DisMaxQuery, QueryBuilderFn}
object DisMaxQueryBodyFn {
def apply(q: DisMaxQuery): XContentBuilder = {
val builder = XContentFactory.jsonBuilder()
builder.startObject("dis_max")
q.tieBreaker.foreach(builder.field("tie_breaker", _))
q.boost.foreach(builder.field("boost", _))
q.queryName.foreach(builder.field("_name", _))
builder.startArray("queries")
// Workaround for bug where separator is not added with rawValues
q.queries.map(QueryBuilderFn.apply).foreach { query =>
builder.rawValue(query)
}
builder.endArray()
builder.endObject()
builder.endObject()
}
}
| apache-2.0 |
urvaksh/puffer | puffer/src/test/java/com/codeaspect/puffer/cache/MapCacheTest.java | 566 | package com.codeaspect.puffer.cache;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.Assert.*;
public class MapCacheTest {
private Cache<String,String> cache;
@Before
public void setup(){
cache = new MapCache<String,String>();
cache.put("Key", "Value");
}
@Test
public void testContains(){
assertTrue(cache.contains("Key"));
}
@Test
public void testGet(){
assertEquals("Value",cache.get("Key"));
}
@Test
public void testPut(){
cache.put("Key2", "Some Value");
assertTrue(cache.contains("Key2"));
}
}
| apache-2.0 |
j123b567/j2mod | src/main/java/com/ghgande/j2mod/modbus/msg/ReadMultipleRegistersRequest.java | 5179 | /*
* Copyright 2002-2016 jamod & j2mod development teams
*
* 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.ghgande.j2mod.modbus.msg;
import com.ghgande.j2mod.modbus.Modbus;
import com.ghgande.j2mod.modbus.net.AbstractModbusListener;
import com.ghgande.j2mod.modbus.procimg.IllegalAddressException;
import com.ghgande.j2mod.modbus.procimg.ProcessImage;
import com.ghgande.j2mod.modbus.procimg.Register;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* Class implementing a <tt>ReadMultipleRegistersRequest</tt>. The
* implementation directly correlates with the class 0 function <i>read multiple
* registers (FC 3)</i>. It encapsulates the corresponding request message.
*
* @author Dieter Wimberger
* @author Steve O'Hara (4energy)
* @version 2.0 (March 2016)
*/
public final class ReadMultipleRegistersRequest extends ModbusRequest {
// instance attributes
private int reference;
private int wordCount;
/**
* Constructs a new <tt>ReadMultipleRegistersRequest</tt> instance.
*/
public ReadMultipleRegistersRequest() {
super();
setFunctionCode(Modbus.READ_MULTIPLE_REGISTERS);
setDataLength(4);
}
/**
* Constructs a new <tt>ReadMultipleRegistersRequest</tt> instance with a
* given reference and count of words to be read. This message reads
* from holding (r/w) registers.
*
* @param ref the reference number of the register to read from.
* @param count the number of words to be read.
*
* @see ReadInputRegistersRequest
*/
public ReadMultipleRegistersRequest(int ref, int count) {
super();
setFunctionCode(Modbus.READ_MULTIPLE_REGISTERS);
setDataLength(4);
setReference(ref);
setWordCount(count);
}
@Override
public ModbusResponse getResponse() {
ReadMultipleRegistersResponse response;
response = new ReadMultipleRegistersResponse();
response.setUnitID(getUnitID());
response.setHeadless(isHeadless());
if (!isHeadless()) {
response.setProtocolID(getProtocolID());
response.setTransactionID(getTransactionID());
}
return response;
}
@Override
public ModbusResponse createResponse(AbstractModbusListener listener) {
ReadMultipleRegistersResponse response;
Register[] regs;
// 1. get process image
ProcessImage procimg = listener.getProcessImage(getUnitID());
// 2. get input registers range
try {
regs = procimg.getRegisterRange(getReference(), getWordCount());
}
catch (IllegalAddressException e) {
return createExceptionResponse(Modbus.ILLEGAL_ADDRESS_EXCEPTION);
}
response = (ReadMultipleRegistersResponse)getResponse();
response.setRegisters(regs);
return response;
}
/**
* Returns the reference of the register to to start reading from with this
* <tt>ReadMultipleRegistersRequest</tt>.
* <p>
*
* @return the reference of the register to start reading from as
* <tt>int</tt>.
*/
public int getReference() {
return reference;
}
/**
* Sets the reference of the register to start reading from with this
* <tt>ReadMultipleRegistersRequest</tt>.
* <p>
*
* @param ref the reference of the register to start reading from.
*/
public void setReference(int ref) {
reference = ref;
}
/**
* Returns the number of words to be read with this
* <tt>ReadMultipleRegistersRequest</tt>.
* <p>
*
* @return the number of words to be read as <tt>int</tt>.
*/
public int getWordCount() {
return wordCount;
}
/**
* Sets the number of words to be read with this
* <tt>ReadMultipleRegistersRequest</tt>.
* <p>
*
* @param count the number of words to be read.
*/
public void setWordCount(int count) {
wordCount = count;
}
public void writeData(DataOutput dout) throws IOException {
dout.writeShort(reference);
dout.writeShort(wordCount);
}
public void readData(DataInput din) throws IOException {
reference = din.readUnsignedShort();
wordCount = din.readUnsignedShort();
}
public byte[] getMessage() {
byte result[] = new byte[4];
result[0] = (byte)((reference >> 8) & 0xff);
result[1] = (byte)(reference & 0xff);
result[2] = (byte)((wordCount >> 8) & 0xff);
result[3] = (byte)(wordCount & 0xff);
return result;
}
}
| apache-2.0 |
Sutikshan/forecast-server | src/middlewares/response_formatter.js | 351 | const formatter = (req, res) => {
res.format({
'text/plain': () => {
res.send(JSON.stringify(res.locals.data));
},
'text/html': () => {
res.render(res.locals.view || 'index', res.locals.data);
},
'application/json': () => {
res.send(res.locals.data);
},
});
res.end();
};
module.exports = formatter;
| apache-2.0 |
oehme/analysing-gradle-performance | my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p442/Production8852.java | 1891 | package org.gradle.test.performance.mediummonolithicjavaproject.p442;
public class Production8852 {
private String property0;
public String getProperty0() {
return property0;
}
public void setProperty0(String value) {
property0 = value;
}
private String property1;
public String getProperty1() {
return property1;
}
public void setProperty1(String value) {
property1 = value;
}
private String property2;
public String getProperty2() {
return property2;
}
public void setProperty2(String value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
} | apache-2.0 |
kevenli/scrapydd | tests/handlers/test_rest.py | 8986 | """
Tests for rest api handlers
"""
# pylint: disable=missing-module-docstring
# pylint: disable=missing-class-docstring
# pylint: disable=missing-function-docstring
from os import path
from six.moves.urllib.parse import urlencode
from tornado.concurrent import Future
from scrapydd.poster.encode import multipart_encode, ensure_binary
from scrapydd.models import Project, session_scope
from scrapydd.main import make_app
from scrapydd.schedule import SchedulerManager
from scrapydd.nodes import NodeManager
from scrapydd.webhook import WebhookDaemon
from scrapydd.settting import SpiderSettingLoader
from scrapydd.config import Config
from scrapydd.exceptions import InvalidProjectEgg, ProcessFailed
from tests.base import AppTest, TestRunnerStub, TestRunnerFactoryStub
BASE_DIR = path.join(path.dirname(path.dirname(__file__)))
TEST_EGG_FILE = path.join(BASE_DIR, 'test_project-1.0-py2.7.egg')
class AddVersionHandlerTest(AppTest):
def test_post(self):
project_name = 'test_project'
post_data = {}
post_data['egg'] = open(TEST_EGG_FILE, 'rb')
post_data['project'] = project_name
post_data['version'] = '1.0'
post_data['_xsrf'] = 'dummy'
datagen, headers = multipart_encode(post_data)
databuffer = b''.join([ensure_binary(x) for x in datagen])
headers['Cookie'] = "_xsrf=dummy"
response = self.fetch('/addversion.json',
method='POST', headers=headers, body=databuffer)
self.assertEqual(200, response.code)
with session_scope() as session:
project = session.query(Project)\
.filter_by(name=project_name).first()
self.assertIsNotNone(project)
self.assertEqual(project.name, project_name)
def test_post_create(self):
project_name = 'test_project'
postdata = {'project': project_name}
response = self.fetch('/delproject.json',
method='POST', body=urlencode(postdata))
self.assertIn(response.code, [404, 200])
post_data = {}
post_data['egg'] = open(TEST_EGG_FILE, 'rb')
post_data['project'] = project_name
post_data['version'] = '1.0'
post_data['_xsrf'] = 'dummy'
datagen, headers = multipart_encode(post_data)
databuffer = b''.join([ensure_binary(x) for x in datagen])
headers['Cookie'] = "_xsrf=dummy"
response = self.fetch('/addversion.json', method='POST',
headers=headers, body=databuffer)
self.assertEqual(200, response.code)
with session_scope() as session:
project = session.query(Project)\
.filter_by(name=project_name).first()
self.assertIsNotNone(project)
self.assertEqual(project.name, project_name)
class AddVersionHandlerTestInvalidProjectEgg(AppTest):
class InvalidProjectWorkspaceStub(TestRunnerStub):
def list(self):
future = Future()
future.set_exception(InvalidProjectEgg())
return future
def test_post(self):
project_name = 'test_project'
post_data = {}
post_data['egg'] = open(TEST_EGG_FILE, 'rb')
post_data['project'] = project_name
post_data['version'] = '1.0'
post_data['_xsrf'] = 'dummy'
datagen, headers = multipart_encode(post_data)
databuffer = b''.join([ensure_binary(x) for x in datagen])
headers['Cookie'] = "_xsrf=dummy"
response = self.fetch('/addversion.json', method='POST',
headers=headers, body=databuffer)
self.assertEqual(400, response.code)
def get_app(self):
config = Config()
scheduler_manager = SchedulerManager(config=config)
scheduler_manager.init()
node_manager = NodeManager(scheduler_manager)
node_manager.init()
webhook_daemon = WebhookDaemon(config, SpiderSettingLoader(), scheduler_manager)
webhook_daemon.init()
runner_cls = AddVersionHandlerTestInvalidProjectEgg.\
InvalidProjectWorkspaceStub
runner_factory = TestRunnerFactoryStub(runner_cls)
return make_app(scheduler_manager, node_manager,
webhook_daemon, secret_key='123',
project_storage_dir='./test_data',
runner_factory=runner_factory)
class AddVersionHandlerTestProcessFail(AppTest):
class ProcessFailProjectWorkspaceStub(TestRunnerStub):
def list(self):
future = Future()
future.set_exception(ProcessFailed())
return future
def test_post(self):
project_name = 'test_project'
post_data = {}
post_data['egg'] = open(TEST_EGG_FILE, 'rb')
post_data['project'] = project_name
post_data['version'] = '1.0'
post_data['_xsrf'] = 'dummy'
datagen, headers = multipart_encode(post_data)
databuffer = b''.join([ensure_binary(x) for x in datagen])
headers['Cookie'] = "_xsrf=dummy"
response = self.fetch('/addversion.json', method='POST',
headers=headers, body=databuffer)
self.assertEqual(400, response.code)
def get_app(self):
config = Config()
scheduler_manager = SchedulerManager(config=config)
scheduler_manager.init()
node_manager = NodeManager(scheduler_manager)
node_manager.init()
webhook_daemon = WebhookDaemon(config, SpiderSettingLoader(), scheduler_manager)
webhook_daemon.init()
runner_cls = AddVersionHandlerTestProcessFail.ProcessFailProjectWorkspaceStub
runner_factory = TestRunnerFactoryStub(runner_cls)
return make_app(scheduler_manager, node_manager, webhook_daemon,
secret_key='123',
project_storage_dir='./test_data',
runner_factory=runner_factory)
class DeleteProjectHandlerTest(AppTest):
def test_post(self):
# TODO: create a project and then delete it.
project_name = 'DeleteProjectHandlerTest'
postdata = {'project': project_name}
response = self.fetch('/delproject.json', method='POST',
body=urlencode(postdata))
self.assertIn(response.code, [404, 200])
with session_scope() as session:
project = session.query(Project)\
.filter_by(name=project_name).first()
self.assertIsNone(project)
class AddScheduleHandlerTest(AppTest):
def test_post(self):
project_name = 'test_project'
spider = 'success_spider'
cron = '* * * * *'
post_data = {
'project': project_name,
'spider': spider,
'cron': cron,
'_xsrf': 'dummy',
}
response = self.fetch('/add_schedule.json', method='POST',
body=urlencode(post_data),
headers={"Cookie": "_xsrf=dummy"})
self.assertEqual(200, response.code)
self.assertIn(b'ok', response.body)
def test_project_not_found(self):
project_name = 'test_project_NOT_EXIST'
spider = 'success_spider'
cron = '* * * * *'
post_data = {
'project': project_name,
'spider': spider,
'cron': cron,
'_xsrf': 'dummy',
}
response = self.fetch('/add_schedule.json', method='POST',
body=urlencode(post_data),
headers={"Cookie": "_xsrf=dummy"})
self.assertEqual(404, response.code)
def test_spider_not_found(self):
project_name = 'test_project'
spider = 'success_spider_NOT_EXIST'
cron = '* * * * *'
post_data = {
'project': project_name,
'spider': spider,
'cron': cron,
'_xsrf': 'dummy',
}
response = self.fetch('/add_schedule.json', method='POST',
body=urlencode(post_data),
headers={"Cookie": "_xsrf=dummy"})
self.assertEqual(404, response.code)
def test_spider_invalid_cron(self):
project_name = 'test_project'
spider = 'success_spider'
cron = '* * * * * BLABLABLA'
post_data = {
'project': project_name,
'spider': spider,
'cron': cron,
'_xsrf': 'dummy',
}
response = self.fetch('/add_schedule.json', method='POST',
body=urlencode(post_data),
headers={"Cookie": "_xsrf=dummy"})
self.assertEqual(400, response.code)
| apache-2.0 |
goneri/dci-control-server | server/db/models.py | 6160 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Red Hat, 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.
import re
from sqlalchemy import create_engine
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.ext.automap import generate_relationship
from sqlalchemy import MetaData
from sqlalchemy.orm.interfaces import ONETOMANY
from sqlalchemy.orm import relationship
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import text
from eve_sqlalchemy.decorators import registerSchema
class DCIModel(object):
def __init__(self, db_uri):
# TODO(Gonéri): Load the value for a configuration file
self.engine = create_engine(db_uri, pool_size=20, max_overflow=0,
encoding='utf8', convert_unicode=True)
self.metadata = MetaData()
self.metadata.reflect(self.engine)
for table in self.metadata.tables:
print(table)
# NOTE(Gonéri): ensure the associated resources list get sorted using
# the created_at key.
def _gen_relationship(base, direction, return_fn,
attrname, local_cls, referred_cls, **kw):
if direction is ONETOMANY:
kw['order_by'] = referred_cls.__table__.columns.created_at
return generate_relationship(
base, direction, return_fn,
attrname, local_cls, referred_cls, **kw)
self.base = automap_base(metadata=self.metadata)
self.base.prepare(generate_relationship=_gen_relationship)
# engine.echo = True
# NOTE(Gonéri): Create the foreign table attribue to be able to
# do job.remoteci.name
for table in self.metadata.tables:
cur_db = getattr(self.base.classes, table)
for column in cur_db.__table__.columns:
m = re.search(r"\.(\w+)_id$", str(column))
if not m:
continue
foreign_table_name = m.group(1)
foreign_table_object = getattr(
self.base.classes, foreign_table_name + 's')
remote_side = None
remote_side = [foreign_table_object.id]
setattr(cur_db, foreign_table_name, relationship(
foreign_table_object, uselist=False,
remote_side=remote_side))
setattr(self.base.classes.products, 'versions', relationship(
self.base.classes.versions, uselist=True, lazy='dynamic'))
setattr(self.base.classes.versions, 'notifications', relationship(
self.base.classes.notifications, uselist=True, lazy='dynamic'))
setattr(self.base.classes.jobs, 'jobstates', relationship(
self.base.classes.jobstates, uselist=True, lazy='dynamic',
order_by=self.base.classes.jobstates.created_at.desc()))
self._Session = sessionmaker(bind=self.engine)
def get_session(self):
# NOTE(Gonéri): We should reuse the Flask-SQLAlchemy session here
return self._Session()
def get_table_description(self, table):
"""Prepare a table description for Eve-Docs
See: https://github.com/hermannsblum/eve-docs
"""
cur_db = getattr(self.base.classes, table)
fields = []
for column in cur_db.__table__.columns:
fields.append(str(column).split('.')[1])
table_description_query = text("""
SELECT
objsubid, description
FROM
pg_description WHERE objoid = :table ::regclass;
""")
result = {
'general': '',
'fields': {}
}
for row in self.engine.execute(table_description_query, table=table):
if row[0] == 0:
result['general'] = row[1]
else:
result['fields'][fields[row[0]]] = row[1]
return result
def generate_eve_domain_configuration(self):
domain = {}
for table in self.metadata.tables:
DB = getattr(self.base.classes, table)
registerSchema(table)(DB)
domain[table] = DB._eve_schema[table]
domain[table].update({
'id_field': 'id',
'item_url': 'regex("[-a-z0-9]{8}-[-a-z0-9]{4}-'
'[-a-z0-9]{4}-[-a-z0-9]{4}-[-a-z0-9]{12}")',
'item_lookup_field': 'id',
'resource_methods': ['GET', 'POST', 'DELETE'],
'item_methods': ['PATCH', 'DELETE', 'PUT', 'GET'],
'public_methods': [],
'public_item_methods': [],
})
domain[table]['schema']['created_at']['required'] = False
domain[table]['schema']['updated_at']['required'] = False
domain[table]['schema']['etag']['required'] = False
domain[table]['datasource']['default_sort'] = [('created_at', 1)]
if 'team_id' in domain[table]['schema']:
domain[table]['schema']['team_id']['required'] = False
domain[table]['auth_field'] = 'team_id'
if hasattr(DB, 'name'):
domain[table].update({
'additional_lookup': {
'url': 'regex("[-_\w\d]+")',
'field': 'name'
}})
domain[table]['description'] = self.get_table_description(table)
# NOTE(Goneri): optional, if the key is missing, we dynamically pick
# a testversion that fit.
domain['jobs']['schema']['testversion_id']['required'] = False
domain['jobs']['datasource']['projection']['jobstates_collection'] = 1
return domain
| apache-2.0 |
LinusU/fbthrift | thrift/compiler/test/fixtures/qualified/gen-cpp/module2_types.cpp | 6333 | /**
* Autogenerated by Thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
#include "thrift/compiler/test/fixtures/qualified/gen-cpp/module2_types.h"
#include "thrift/compiler/test/fixtures/qualified/gen-cpp/module2_reflection.h"
#include <algorithm>
#include <string.h>
namespace MODULE2 {
const uint64_t Struct::_reflection_id;
void Struct::_reflection_register(::apache::thrift::reflection::Schema& schema) {
::MODULE2::module2_reflection_::reflectionInitializer_6048788120110564236(schema);
}
bool Struct::operator == (const Struct & rhs) const {
if (!(this->first == rhs.first))
return false;
if (!(this->second == rhs.second))
return false;
return true;
}
uint32_t Struct::read(apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
apache::thrift::protocol::TType ftype;
int16_t fid;
::apache::thrift::reflection::Schema * schema = iprot->getSchema();
if (schema != nullptr) {
::MODULE2::module2_reflection_::reflectionInitializer_6048788120110564236(*schema);
iprot->setNextStructType(Struct::_reflection_id);
}
xfer += iprot->readStructBegin(fname);
using apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == apache::thrift::protocol::T_STRUCT) {
xfer += this->first.read(iprot);
this->__isset.first = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == apache::thrift::protocol::T_STRUCT) {
xfer += this->second.read(iprot);
this->__isset.second = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
void Struct::__clear() {
first.__clear();
second.__clear();
__isset.__clear();
}
uint32_t Struct::write(apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("Struct");
xfer += oprot->writeFieldBegin("first", apache::thrift::protocol::T_STRUCT, 1);
xfer += this->first.write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("second", apache::thrift::protocol::T_STRUCT, 2);
xfer += this->second.write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
void swap(Struct &a, Struct &b) {
using ::std::swap;
(void)a;
(void)b;
swap(a.first, b.first);
swap(a.second, b.second);
swap(a.__isset, b.__isset);
}
void merge(const Struct& from, Struct& to) {
using apache::thrift::merge;
merge(from.first, to.first);
to.__isset.first = to.__isset.first || from.__isset.first;
merge(from.second, to.second);
to.__isset.second = to.__isset.second || from.__isset.second;
}
void merge(Struct&& from, Struct& to) {
using apache::thrift::merge;
merge(std::move(from.first), to.first);
to.__isset.first = to.__isset.first || from.__isset.first;
merge(std::move(from.second), to.second);
to.__isset.second = to.__isset.second || from.__isset.second;
}
const uint64_t BigStruct::_reflection_id;
void BigStruct::_reflection_register(::apache::thrift::reflection::Schema& schema) {
::MODULE2::module2_reflection_::reflectionInitializer_18288836959267843340(schema);
}
bool BigStruct::operator == (const BigStruct & rhs) const {
if (!(this->s == rhs.s))
return false;
if (!(this->id == rhs.id))
return false;
return true;
}
uint32_t BigStruct::read(apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
apache::thrift::protocol::TType ftype;
int16_t fid;
::apache::thrift::reflection::Schema * schema = iprot->getSchema();
if (schema != nullptr) {
::MODULE2::module2_reflection_::reflectionInitializer_18288836959267843340(*schema);
iprot->setNextStructType(BigStruct::_reflection_id);
}
xfer += iprot->readStructBegin(fname);
using apache::thrift::protocol::TProtocolException;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == apache::thrift::protocol::T_STRUCT) {
xfer += this->s.read(iprot);
this->__isset.s = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->id);
this->__isset.id = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
return xfer;
}
void BigStruct::__clear() {
s.__clear();
id = 0;
__isset.__clear();
}
uint32_t BigStruct::write(apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("BigStruct");
xfer += oprot->writeFieldBegin("s", apache::thrift::protocol::T_STRUCT, 1);
xfer += this->s.write(oprot);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("id", apache::thrift::protocol::T_I32, 2);
xfer += oprot->writeI32(this->id);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
void swap(BigStruct &a, BigStruct &b) {
using ::std::swap;
(void)a;
(void)b;
swap(a.s, b.s);
swap(a.id, b.id);
swap(a.__isset, b.__isset);
}
void merge(const BigStruct& from, BigStruct& to) {
using apache::thrift::merge;
merge(from.s, to.s);
to.__isset.s = to.__isset.s || from.__isset.s;
merge(from.id, to.id);
to.__isset.id = to.__isset.id || from.__isset.id;
}
void merge(BigStruct&& from, BigStruct& to) {
using apache::thrift::merge;
merge(std::move(from.s), to.s);
to.__isset.s = to.__isset.s || from.__isset.s;
merge(std::move(from.id), to.id);
to.__isset.id = to.__isset.id || from.__isset.id;
}
} // namespace
| apache-2.0 |
hairlun/customer-visit-web | src/com/jude/json/JSONObject.java | 27299 | package com.jude.json;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ResourceBundle;
import java.util.Set;
public class JSONObject {
public static DateFormat DEFAULT_DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static DateFormat dateForamt = DEFAULT_DATE_FORMATTER;
private Map<String, Object> map;
public static final Object NULL = new Null();
public static void setDateFormat(DateFormat df) {
dateForamt = df;
}
public JSONObject() {
this.map = new HashMap();
}
public JSONObject(JSONObject jo, String[] names) {
for (int i = 0; i < names.length; ++i)
try {
putOnce(names[i], jo.opt(names[i]));
} catch (Exception ignore) {
}
}
public JSONObject(JSONTokener x) throws JSONException {
if (x.nextClean() != '{')
throw x.syntaxError("A JSONObject text must begin with '{'");
while (true) {
char c = x.nextClean();
switch (c) {
case '\000':
throw x.syntaxError("A JSONObject text must end with '}'");
case '}':
return;
}
x.back();
String key = x.nextValue().toString();
c = x.nextClean();
if (c == '=') {
if (x.next() != '>')
x.back();
} else if (c != ':') {
throw x.syntaxError("Expected a ':' after a key");
}
putOnce(key, x.nextValue());
switch (x.nextClean()) {
case ',':
case ';':
if (x.nextClean() == '}') {
return;
}
x.back();
case '}':
}
}
// return;
//
// throw x.syntaxError("Expected a ',' or '}'");
}
public JSONObject(Map map) {
this.map = new HashMap();
if (map != null) {
Iterator i = map.entrySet().iterator();
while (i.hasNext()) {
Map.Entry e = (Map.Entry) i.next();
Object value = e.getValue();
if (e.getKey() == null) {
continue;
}
if (value != null)
this.map.put(e.getKey().toString(), wrap(value));
else
remove(e.getKey().toString());
}
}
}
public JSONObject(Map map, PropertyFilter filter) {
this.map = new HashMap();
if (map != null) {
Iterator i = map.entrySet().iterator();
while (i.hasNext()) {
Map.Entry e = (Map.Entry) i.next();
Object value = e.getValue();
if (value != null)
this.map.put(e.getKey().toString(), wrap(value, filter));
}
}
}
public JSONObject(Object bean) {
populateMap(bean);
}
public JSONObject fromObject(Object bean) {
populateMap(bean);
return this;
}
@SuppressWarnings("unchecked")
public JSONObject(Object object, final String[] names) {
this.map = new HashMap();
FilterPropertyMapper<String> mapper = new FilterPropertyMapper() {
public String[] include() {
return names;
}
};
populateMap(object, mapper.getFilter());
}
@SuppressWarnings("rawtypes")
public JSONObject fromObjectInclude(Object bean, final String[] names) {
this.map = new HashMap();
FilterPropertyMapper mapper = new FilterPropertyMapper() {
public String[] include() {
return names;
}
};
populateMap(bean, mapper.getFilter());
return this;
}
@SuppressWarnings("rawtypes")
public JSONObject fromObjectExclude(Object bean, final String[] names) {
this.map = new HashMap();
FilterPropertyMapper mapper = new FilterPropertyMapper() {
public String[] exclude() {
return names;
}
};
populateMap(bean, mapper.getFilter());
return this;
}
public JSONObject(Object bean, PropertyFilter filter) {
populateMap(bean, filter);
}
public Object toBean(Class klass) {
try {
Object bean = klass.newInstance();
Iterator it = this.map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
Object value = this.map.get(key);
String setter = key;
if (setter.length() == 1)
setter.toUpperCase();
else if (setter.length() > 1) {
setter = "set" + key.substring(0, 1).toUpperCase() + key.substring(1);
}
Class typeClass = value.getClass();
if (value instanceof JSONArray)
continue;
if (value instanceof JSONObject)
try {
Field field = klass.getDeclaredField(key);
if (field != null) {
field.setAccessible(true);
typeClass = field.getType();
if (!typeClass.isAssignableFrom(Map.class))
;
value = ((JSONObject) value).toBean(typeClass);
}
} catch (NoSuchFieldException e) {
}
try {
Field typeField = typeClass.getDeclaredField("TYPE");
if (typeField != null)
typeClass = (Class) typeField.get(null);
} catch (Exception e) {
}
Class[] parameterTypes = { typeClass };
Method method = null;
try {
method = klass.getDeclaredMethod(setter, parameterTypes);
} catch (NoSuchMethodException e) {
}
if (method != null) {
method.setAccessible(true);
Object[] parameters = { value };
method.invoke(bean, parameters);
}
}
return bean;
} catch (Exception e) {
}
return null;
}
public JSONObject(String source) throws JSONException {
this(new JSONTokener(source));
}
public JSONObject(String baseName, Locale locale) throws JSONException {
ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread()
.getContextClassLoader());
Enumeration keys = bundle.getKeys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
if (key instanceof String) {
String[] path = ((String) key).split("\\.");
int last = path.length - 1;
JSONObject target = this;
for (int i = 0; i < last; ++i) {
String segment = path[i];
JSONObject nextTarget = target.optJSONObject(segment);
if (nextTarget == null) {
nextTarget = new JSONObject();
target.put(segment, nextTarget);
}
target = nextTarget;
}
target.put(path[last], bundle.getString((String) key));
}
}
}
public JSONObject accumulate(String key, Object value) throws JSONException {
testValidity(value);
Object object = opt(key);
if (object == null) {
put(key, (value instanceof JSONArray) ? new JSONArray().put(value) : value);
} else if (object instanceof JSONArray)
((JSONArray) object).put(value);
else {
put(key, new JSONArray().put(object).put(value));
}
return this;
}
public JSONObject append(String key, Object value) throws JSONException {
testValidity(value);
Object object = opt(key);
if (object == null)
put(key, new JSONArray().put(value));
else if (object instanceof JSONArray)
put(key, ((JSONArray) object).put(value));
else {
throw new JSONException("JSONObject[" + key + "] is not a JSONArray.");
}
return this;
}
public static String doubleToString(double d) {
if ((Double.isInfinite(d)) || (Double.isNaN(d))) {
return "null";
}
String string = Double.toString(d);
if ((string.indexOf('.') > 0) && (string.indexOf('e') < 0) && (string.indexOf('E') < 0)) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
}
public Object get(String key) throws JSONException {
if (key == null) {
throw new JSONException("Null key.");
}
Object object = opt(key);
if (object == null) {
throw new JSONException("JSONObject[" + quote(key) + "] not found.");
}
return object;
}
public boolean getBoolean(String key) throws JSONException {
Object object = get(key);
if ((object.equals(Boolean.FALSE))
|| ((object instanceof String) && (((String) object).equalsIgnoreCase("false")))) {
return false;
}
if ((object.equals(Boolean.TRUE))
|| ((object instanceof String) && (((String) object).equalsIgnoreCase("true")))) {
return true;
}
throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean.");
}
public double getDouble(String key) throws JSONException {
Object object = get(key);
try {
return (object instanceof Number) ? ((Number) object).doubleValue() : Double
.parseDouble((String) object);
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) + "] is not a number.");
}
}
public int getInt(String key) throws JSONException {
Object object = get(key);
try {
return (object instanceof Number) ? ((Number) object).intValue() : Integer
.parseInt((String) object);
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) + "] is not an int.");
}
}
public JSONArray getJSONArray(String key) throws JSONException {
Object object = get(key);
if (object instanceof JSONArray) {
return (JSONArray) object;
}
throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray.");
}
public JSONObject getJSONObject(String key) throws JSONException {
Object object = get(key);
if (object instanceof JSONObject) {
return (JSONObject) object;
}
throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject.");
}
public long getLong(String key) throws JSONException {
Object object = get(key);
try {
return (object instanceof Number) ? ((Number) object).longValue() : Long
.parseLong((String) object);
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) + "] is not a long.");
}
}
public static String[] getNames(JSONObject jo) {
int length = jo.length();
if (length == 0) {
return null;
}
Iterator iterator = jo.keys();
String[] names = new String[length];
int i = 0;
while (iterator.hasNext()) {
names[i] = ((String) iterator.next());
++i;
}
return names;
}
public static String[] getNames(Object object) {
if (object == null) {
return null;
}
Class klass = object.getClass();
Field[] fields = klass.getFields();
int length = fields.length;
if (length == 0) {
return null;
}
String[] names = new String[length];
for (int i = 0; i < length; ++i) {
names[i] = fields[i].getName();
}
return names;
}
public String getString(String key) throws JSONException {
Object object = get(key);
return (object == NULL) ? null : object.toString();
}
public boolean has(String key) {
return this.map.containsKey(key);
}
public JSONObject increment(String key) throws JSONException {
Object value = opt(key);
if (value == null)
put(key, 1);
else if (value instanceof Integer)
put(key, ((Integer) value).intValue() + 1);
else if (value instanceof Long)
put(key, ((Long) value).longValue() + 1L);
else if (value instanceof Double)
put(key, ((Double) value).doubleValue() + 1.0D);
else if (value instanceof Float)
put(key, ((Float) value).floatValue() + 1.0F);
else {
throw new JSONException("Unable to increment [" + quote(key) + "].");
}
return this;
}
public boolean isNull(String key) {
return NULL.equals(opt(key));
}
public Iterator<String> keys() {
return this.map.keySet().iterator();
}
public int length() {
return this.map.size();
}
public JSONArray names() {
JSONArray ja = new JSONArray();
Iterator keys = keys();
while (keys.hasNext()) {
ja.put(keys.next());
}
return (ja.length() == 0) ? null : ja;
}
public static String numberToString(Number number) throws JSONException {
if (number == null) {
throw new JSONException("Null pointer");
}
testValidity(number);
String string = number.toString();
if ((string.indexOf('.') > 0) && (string.indexOf('e') < 0) && (string.indexOf('E') < 0)) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
}
public Object opt(String key) {
return (key == null) ? null : this.map.get(key);
}
public boolean optBoolean(String key) {
return optBoolean(key, false);
}
public boolean optBoolean(String key, boolean defaultValue) {
try {
return getBoolean(key);
} catch (Exception e) {
}
return defaultValue;
}
public double optDouble(String key) {
return optDouble(key, (0.0D / 0.0D));
}
public double optDouble(String key, double defaultValue) {
try {
return getDouble(key);
} catch (Exception e) {
}
return defaultValue;
}
public int optInt(String key) {
return optInt(key, 0);
}
public int optInt(String key, int defaultValue) {
try {
return getInt(key);
} catch (Exception e) {
}
return defaultValue;
}
public JSONArray optJSONArray(String key) {
Object o = opt(key);
return (o instanceof JSONArray) ? (JSONArray) o : null;
}
public JSONObject optJSONObject(String key) {
Object object = opt(key);
return (object instanceof JSONObject) ? (JSONObject) object : null;
}
public long optLong(String key) {
return optLong(key, 0L);
}
public long optLong(String key, long defaultValue) {
try {
return getLong(key);
} catch (Exception e) {
}
return defaultValue;
}
public String optString(String key) {
return optString(key, "");
}
public String optString(String key, String defaultValue) {
Object object = opt(key);
return (NULL.equals(object)) ? defaultValue : object.toString();
}
private void populateMap(Object bean) {
populateMap(bean, null);
}
private void populateMap(Object bean, PropertyFilter filter) {
Class klass = bean.getClass();
boolean includeSuperClass = klass.getClassLoader() != null;
Method[] methods = (includeSuperClass) ? klass.getMethods() : klass.getDeclaredMethods();
List list = new ArrayList();
list.addAll(Arrays.asList(methods));
Class superklass = klass.getSuperclass();
if (!superklass.isAssignableFrom(Object.class)) {
includeSuperClass = superklass.getClassLoader() != null;
methods = (includeSuperClass) ? superklass.getMethods() : superklass
.getDeclaredMethods();
list.addAll(Arrays.asList(methods));
}
for (int i = 0; i < list.size(); ++i)
try {
Method method = (Method) list.get(i);
if (Modifier.isPublic(method.getModifiers())) {
String name = method.getName();
String key = "";
if (name.startsWith("get")) {
if ((name.equals("getClass")) || (name.equals("getDeclaringClass"))) {
key = "";
} else
key = name.substring(3);
} else if (name.startsWith("is")) {
key = name.substring(2);
}
if ((key.length() > 0) && (method.getParameterTypes().length == 0)) {
if (Character.isUpperCase(key.charAt(0))) {
if (key.length() == 1)
key = key.toLowerCase();
else if (!Character.isUpperCase(key.charAt(1))) {
key = key.substring(0, 1).toLowerCase() + key.substring(1);
}
Field field;
try {
field = klass.getDeclaredField(key);
} catch (NoSuchFieldException e) {
field = klass.getSuperclass().getDeclaredField(key);
}
field.setAccessible(true);
if ((filter != null) && (field != null)
&& (filter.apply(bean, key, field.get(bean)))) {
key = "";
}
} else {
key = "";
}
if (key.length() > 0) {
Object result = method.invoke(bean, (Object[]) null);
if (result != null)
this.map.put(key, wrap(result));
}
}
}
} catch (Exception ignore) {
}
}
public JSONObject put(String key, boolean value) throws JSONException {
put(key, (value) ? Boolean.TRUE : Boolean.FALSE);
return this;
}
public JSONObject put(String key, Collection value) throws JSONException {
put(key, new JSONArray(value));
return this;
}
public JSONObject put(String key, double value) throws JSONException {
put(key, new Double(value));
return this;
}
public JSONObject put(String key, int value) throws JSONException {
put(key, new Integer(value));
return this;
}
public JSONObject put(String key, long value) throws JSONException {
put(key, new Long(value));
return this;
}
public JSONObject put(String key, Map value) throws JSONException {
put(key, new JSONObject(value));
return this;
}
public JSONObject put(String key, Object value) throws JSONException {
if (key == null) {
throw new JSONException("Null key.");
}
if (value != null) {
testValidity(value);
this.map.put(key, value);
} else {
remove(key);
}
return this;
}
public JSONObject putOnce(String key, Object value) throws JSONException {
if ((key != null) && (value != null)) {
if (opt(key) != null) {
throw new JSONException("Duplicate key \"" + key + "\"");
}
put(key, value);
}
return this;
}
public JSONObject putOpt(String key, Object value) throws JSONException {
if ((key != null) && (value != null)) {
put(key, value);
}
return this;
}
public static String quote(String string) {
if ((string == null) || (string.length() == 0)) {
return "\"\"";
}
char c = '\000';
int len = string.length();
StringBuffer sb = new StringBuffer(len + 4);
sb.append('"');
for (int i = 0; i < len; ++i) {
char b = c;
c = string.charAt(i);
switch (c) {
case '"':
case '\\':
sb.append('\\');
sb.append(c);
break;
case '/':
if (b == '<') {
sb.append('\\');
}
sb.append(c);
break;
case '\b':
sb.append("\\b");
break;
case '\t':
sb.append("\\t");
break;
case '\n':
sb.append("\\n");
break;
case '\f':
sb.append("\\f");
break;
case '\r':
sb.append("\\r");
break;
default:
if ((c < ' ') || ((c >= '') && (c < ' ')) || ((c >= ' ') && (c < '℀'))) {
String hhhh = "000" + Integer.toHexString(c);
sb.append("\\u" + hhhh.substring(hhhh.length() - 4));
} else {
sb.append(c);
}
}
}
sb.append('"');
return sb.toString();
}
public Object remove(String key) {
return this.map.remove(key);
}
public static Object stringToValue(String string) {
if (string.equals("")) {
return string;
}
if (string.equalsIgnoreCase("true")) {
return Boolean.TRUE;
}
if (string.equalsIgnoreCase("false")) {
return Boolean.FALSE;
}
if (string.equalsIgnoreCase("null")) {
return NULL;
}
char b = string.charAt(0);
if (((b >= '0') && (b <= '9')) || (b == '.') || (b == '-') || (b == '+')) {
if ((b == '0') && (string.length() > 2)
&& (((string.charAt(1) == 'x') || (string.charAt(1) == 'X'))))
;
try {
return new Integer(Integer.parseInt(string.substring(2), 16));
} catch (Exception ignore) {
try {
if ((string.indexOf('.') > -1) || (string.indexOf('e') > -1)
|| (string.indexOf('E') > -1)) {
return Double.valueOf(string);
}
Long myLong = new Long(string);
if (myLong.longValue() == myLong.intValue()) {
return new Integer(myLong.intValue());
}
return myLong;
} catch (Exception exception) {
}
}
}
return string;
}
public static void testValidity(Object o) throws JSONException {
if (o != null)
if (o instanceof Double) {
if ((((Double) o).isInfinite()) || (((Double) o).isNaN()))
throw new JSONException("JSON does not allow non-finite numbers.");
} else {
if ((!(o instanceof Float))
|| ((!((Float) o).isInfinite()) && (!((Float) o).isNaN())))
return;
throw new JSONException("JSON does not allow non-finite numbers.");
}
}
public JSONArray toJSONArray(JSONArray names) throws JSONException {
if ((names == null) || (names.length() == 0)) {
return null;
}
JSONArray ja = new JSONArray();
for (int i = 0; i < names.length(); ++i) {
ja.put(opt(names.getString(i)));
}
return ja;
}
public String toString() {
try {
Iterator keys = keys();
StringBuffer sb = new StringBuffer("{");
while (keys.hasNext()) {
if (sb.length() > 1) {
sb.append(',');
}
Object o = keys.next();
sb.append(quote(o.toString()));
sb.append(':');
sb.append(valueToString(this.map.get(o)));
}
sb.append('}');
return sb.toString();
} catch (Exception e) {
}
return null;
}
public String toString(int indentFactor) throws JSONException {
return toString(indentFactor, 0);
}
String toString(int indentFactor, int indent) throws JSONException {
int length = length();
if (length == 0) {
return "{}";
}
Iterator keys = keys();
int newindent = indent + indentFactor;
StringBuffer sb = new StringBuffer("{");
if (length == 1) {
Object object = keys.next();
sb.append(quote(object.toString()));
sb.append(": ");
sb.append(valueToString(this.map.get(object), indentFactor, indent));
} else {
while (keys.hasNext()) {
Object object = keys.next();
if (sb.length() > 1)
sb.append(",\n");
else {
sb.append('\n');
}
for (int i = 0; i < newindent; ++i) {
sb.append(' ');
}
sb.append(quote(object.toString()));
sb.append(": ");
sb.append(valueToString(this.map.get(object), indentFactor, newindent));
}
if (sb.length() > 1) {
sb.append('\n');
for (int i = 0; i < indent; ++i) {
sb.append(' ');
}
}
}
sb.append('}');
return sb.toString();
}
public static String valueToString(Object value) throws JSONException {
if ((value == null) || (value.equals(null))) {
return "null";
}
if (value instanceof JSONString) {
Object object;
try {
object = ((JSONString) value).toJSONString();
} catch (Exception e) {
throw new JSONException(e);
}
if (object instanceof String) {
return (String) object;
}
throw new JSONException("Bad value from toJSONString: " + object);
}
if (value instanceof Number) {
return numberToString((Number) value);
}
if ((value instanceof Boolean) || (value instanceof JSONObject)
|| (value instanceof JSONArray)) {
return value.toString();
}
if (value instanceof Map) {
return new JSONObject((Map) value).toString();
}
if (value instanceof Collection) {
return new JSONArray((Collection) value).toString();
}
if (value.getClass().isArray()) {
return new JSONArray(value).toString();
}
if (value instanceof Date) {
return quote(dateForamt.format(value));
}
return quote(value.toString());
}
static String valueToString(Object value, int indentFactor, int indent) throws JSONException {
if ((value == null) || (value.equals(null)))
return "null";
try {
if (value instanceof JSONString) {
Object o = ((JSONString) value).toJSONString();
if (o instanceof String)
return (String) o;
}
} catch (Exception ignore) {
}
if (value instanceof Number) {
return numberToString((Number) value);
}
if (value instanceof Boolean) {
return value.toString();
}
if (value instanceof JSONObject) {
return ((JSONObject) value).toString(indentFactor, indent);
}
if (value instanceof JSONArray) {
return ((JSONArray) value).toString(indentFactor, indent);
}
if (value instanceof Map) {
return new JSONObject((Map) value).toString(indentFactor, indent);
}
if (value instanceof Collection) {
return new JSONArray((Collection) value).toString(indentFactor, indent);
}
if (value.getClass().isArray()) {
return new JSONArray(value).toString(indentFactor, indent);
}
if (value instanceof Date) {
return quote(dateForamt.format(value));
}
return quote(value.toString());
}
public static Object wrap(Object object) {
return wrap(object, null);
}
public static Object wrap(Object object, PropertyFilter filter) {
try {
if (object == null) {
return NULL;
}
if ((object instanceof JSONObject) || (object instanceof JSONArray)
|| (NULL.equals(object)) || (object instanceof JSONString)
|| (object instanceof Byte) || (object instanceof Character)
|| (object instanceof Short) || (object instanceof Integer)
|| (object instanceof Long) || (object instanceof Boolean)
|| (object instanceof Float) || (object instanceof Double)
|| (object instanceof String) || (object instanceof Date)) {
return object;
}
if (object instanceof Collection) {
return new JSONArray((Collection) object);
}
if (object.getClass().isArray()) {
return new JSONArray(object);
}
if (object instanceof Map) {
return new JSONObject((Map) object);
}
Package objectPackage = object.getClass().getPackage();
String objectPackageName = (objectPackage != null) ? objectPackage.getName() : "";
if ((objectPackageName.startsWith("java.")) || (objectPackageName.startsWith("javax."))
|| (object.getClass().getClassLoader() == null)) {
return object.toString();
}
return new JSONObject(object, filter);
} catch (Exception exception) {
}
return null;
}
public Writer write(Writer writer) throws JSONException {
try {
boolean commanate = false;
Iterator keys = keys();
writer.write(123);
while (keys.hasNext()) {
if (commanate) {
writer.write(44);
}
Object key = keys.next();
writer.write(quote(key.toString()));
writer.write(58);
Object value = this.map.get(key);
if (value instanceof JSONObject)
((JSONObject) value).write(writer);
else if (value instanceof JSONArray)
((JSONArray) value).write(writer);
else {
writer.write(valueToString(value));
}
commanate = true;
}
writer.write(125);
return writer;
} catch (IOException exception) {
throw new JSONException(exception);
}
}
public Map<String, Object> getMyHashMap() {
return this.map;
}
public JSONObject applyWith(JSONObject json) {
Map map = json.getMyHashMap();
Set<Map.Entry<String, Object>> mapEntrySet = map.entrySet();
for (Map.Entry entry : mapEntrySet) {
put((String) entry.getKey(), entry.getValue());
}
return this;
}
private static final class Null {
protected final Object clone() {
return this;
}
public boolean equals(Object object) {
return (object == null) || (object == this);
}
public String toString() {
return "null";
}
}
} | apache-2.0 |
svn2github/scalatest | src/test/scala/org/scalatest/tools/JUnitXmlReporterSuite.scala | 6537 | /*
* Copyright 2001-2008 Artima, 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 org.scalatest.tools
import org.scalatest._
import org.scalatest.events.Ordinal
import org.scalatest.events.SuiteStarting
import org.scalatest.events.SuiteAborted
import org.scalatest.events.SuiteCompleted
import org.scalatest.events.TestStarting
import org.scalatest.events.TestSucceeded
import org.scalatest.events.TestIgnored
import org.scalatest.events.TestFailed
import org.scalatest.events.TestPending
import org.scalatest.events.TestCanceled
import org.scalatest.events.RecordableEvent
import java.io.File
class JUnitXmlReporterSuite extends FunSuite {
val ord1 = new Ordinal(123)
val ord1a = ord1.next
val ord1b = ord1a.next
val ord1c = ord1b.next
val ord1d = ord1c.next
val ord2 = new Ordinal(223)
val ord2a = ord2.next
val ord2b = ord2a.next
val ord2c = ord2b.next
val ord2d = ord2c.next
val ord2e = ord2d.next
val ord2f = ord2e.next
val ord2g = ord2f.next
val ord2h = ord2g.next
val ord2i = ord2h.next
val ord2j = ord2i.next
val ord2k = ord2j.next
val ord2l = ord2k.next
val start1 =
SuiteStarting(
ord1a,
"suite1",
"suiteId1",
None,
None,
None,
None,
None,
"thread1",
123123)
val start2 =
SuiteStarting(
ord1b,
"suite2",
"suiteId2",
None,
None,
None,
None,
None,
"thread2",
123223)
val abort2 =
SuiteAborted(
ord1c,
"aborted message",
"suite2",
"suiteId2",
None,
None,
None,
None,
None,
None)
val complete1 =
SuiteCompleted(
ord1d,
"suite1",
"suiteId1",
None,
None,
None,
None,
None,
None,
"thread1",
123456)
val start3 =
SuiteStarting(
ord2a,
"suite3",
"suiteId3",
None,
None,
None,
None,
None,
"thread1",
123123)
val startTest1 =
TestStarting(
ordinal = ord2b,
suiteName = "suite3",
suiteId = "suiteId3",
suiteClassName = Some("Suite3Class"),
testName = "a pass test",
testText = "a pass test text")
val endTest1 =
TestSucceeded (
ordinal = ord2c,
suiteName = "suite3",
suiteId = "suiteId3",
suiteClassName = Some("Suite3Class"),
testName = "a pass test",
testText = "a pass test text",
recordedEvents = Vector.empty[RecordableEvent])
val ignoreTest1 =
TestIgnored (
ordinal = ord2d,
suiteName = "suite3",
suiteId = "suiteId3",
suiteClassName = Some("Suite3Class"),
testName = "an ignored test",
testText = "an ignored test text")
val startTest2 =
TestStarting(
ordinal = ord2e,
suiteName = "suite3",
suiteId = "suiteId3",
suiteClassName = Some("Suite3Class"),
testName = "a fail test",
testText = "a fail test text")
val failTest2 =
TestFailed (
ordinal = ord2f,
message = "failTest2 message text",
suiteName = "suite3",
suiteId = "suiteId3",
suiteClassName = Some("Suite3Class"),
testName = "a fail test",
testText = "a fail test text",
recordedEvents = Vector.empty[RecordableEvent])
val startTest3 =
TestStarting(
ordinal = ord2g,
suiteName = "suite3",
suiteId = "suiteId3",
suiteClassName = Some("Suite3Class"),
testName = "a pending test",
testText = "a pending test text")
val pendingTest3 =
TestPending (
ordinal = ord2h,
suiteName = "suite3",
suiteId = "suiteId3",
suiteClassName = Some("Suite3Class"),
testName = "a pending test",
testText = "a pending test text",
recordedEvents = Vector.empty[RecordableEvent])
val startTest4 =
TestStarting(
ordinal = ord2i,
suiteName = "suite3",
suiteId = "suiteId3",
suiteClassName = Some("Suite3Class"),
testName = "a canceled test",
testText = "a canceled test text")
val canceledTest4 =
TestCanceled (
ordinal = ord2j,
message = "bailed out",
suiteName = "suite3",
suiteId = "suiteId3",
suiteClassName = Some("Suite3Class"),
testName = "a canceled test",
testText = "a canceled test text",
recordedEvents = Vector.empty[RecordableEvent])
val complete3 =
SuiteCompleted(
ord2k,
"suite3",
"suiteId3",
None,
None,
None,
None,
None,
None,
"thread1",
123456)
val reporter = new JUnitXmlReporter("target")
test("SuiteAborted and SuiteCompleted are recognized as test terminators") {
reporter(start1)
reporter(start2)
reporter(abort2)
reporter(complete1)
val file1 = new File("target/TEST-suiteId1.xml")
val file2 = new File("target/TEST-suiteId2.xml")
assert(file1.exists)
assert(file2.exists)
file1.delete
file2.delete
}
test("test case gets reported") {
reporter(start3)
reporter(startTest1)
reporter(endTest1)
reporter(ignoreTest1)
reporter(startTest2)
reporter(failTest2)
reporter(startTest3)
reporter(pendingTest3)
reporter(startTest4)
reporter(canceledTest4)
reporter(complete3)
val loadnode = xml.XML.loadFile("target/TEST-suiteId3.xml")
val testcases = loadnode \\ "testcase"
val tcIgnored =
testcases.find(tc => (tc \ "@name").toString == "an ignored test").get
val tcFailed =
testcases.find(tc => (tc \ "@name").toString == "a fail test").get
val tcPending =
testcases.find(tc => (tc \ "@name").toString == "a pending test").get
val tcCanceled =
testcases.find(tc => (tc \ "@name").toString == "a canceled test").get
assert(!(tcIgnored \ "skipped").isEmpty)
assert(!(tcFailed \ "failure").isEmpty)
assert(!(tcPending \ "skipped").isEmpty)
assert(!(tcCanceled \ "skipped").isEmpty)
}
}
| apache-2.0 |
GISwilson/NetworksSocketDemo | Net40/NetworkSocket.Fast/Properties/AssemblyInfo.cs | 1365 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("NetworkSocket.Fast")]
[assembly: AssemblyDescription("快速构建Socket通讯的应用")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NetworkSocket.Fast")]
[assembly: AssemblyCopyright("Copyright © Chen Guowei 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("214e91b3-753b-4bbb-9e32-b5802fd09ada")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
| apache-2.0 |
apache/incubator-echarts | src/chart/candlestick/candlestickLayout.ts | 9182 | /*
* 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.
*/
/* global Float32Array */
import {subPixelOptimize} from '../../util/graphic';
import createRenderPlanner from '../helper/createRenderPlanner';
import {parsePercent} from '../../util/number';
import {retrieve2} from 'zrender/src/core/util';
import { StageHandler, StageHandlerProgressParams } from '../../util/types';
import CandlestickSeriesModel from './CandlestickSeries';
import List from '../../data/List';
import { RectLike } from 'zrender/src/core/BoundingRect';
const LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
export interface CandlestickItemLayout {
sign: number
initBaseline: number
ends: number[][]
brushRect: RectLike
}
export interface CandlestickLayoutMeta {
candleWidth: number
isSimpleBox: boolean
}
const candlestickLayout: StageHandler = {
seriesType: 'candlestick',
plan: createRenderPlanner(),
reset: function (seriesModel: CandlestickSeriesModel) {
const coordSys = seriesModel.coordinateSystem;
const data = seriesModel.getData();
const candleWidth = calculateCandleWidth(seriesModel, data);
const cDimIdx = 0;
const vDimIdx = 1;
const coordDims = ['x', 'y'];
const cDim = data.mapDimension(coordDims[cDimIdx]);
const vDims = data.mapDimensionsAll(coordDims[vDimIdx]);
const openDim = vDims[0];
const closeDim = vDims[1];
const lowestDim = vDims[2];
const highestDim = vDims[3];
data.setLayout({
candleWidth: candleWidth,
// The value is experimented visually.
isSimpleBox: candleWidth <= 1.3
} as CandlestickLayoutMeta);
if (cDim == null || vDims.length < 4) {
return;
}
return {
progress: seriesModel.pipelineContext.large
? largeProgress : normalProgress
};
function normalProgress(params: StageHandlerProgressParams, data: List) {
let dataIndex;
while ((dataIndex = params.next()) != null) {
const axisDimVal = data.get(cDim, dataIndex) as number;
const openVal = data.get(openDim, dataIndex) as number;
const closeVal = data.get(closeDim, dataIndex) as number;
const lowestVal = data.get(lowestDim, dataIndex) as number;
const highestVal = data.get(highestDim, dataIndex) as number;
const ocLow = Math.min(openVal, closeVal);
const ocHigh = Math.max(openVal, closeVal);
const ocLowPoint = getPoint(ocLow, axisDimVal);
const ocHighPoint = getPoint(ocHigh, axisDimVal);
const lowestPoint = getPoint(lowestVal, axisDimVal);
const highestPoint = getPoint(highestVal, axisDimVal);
const ends: number[][] = [];
addBodyEnd(ends, ocHighPoint, 0);
addBodyEnd(ends, ocLowPoint, 1);
ends.push(
subPixelOptimizePoint(highestPoint),
subPixelOptimizePoint(ocHighPoint),
subPixelOptimizePoint(lowestPoint),
subPixelOptimizePoint(ocLowPoint)
);
data.setItemLayout(dataIndex, {
sign: getSign(data, dataIndex, openVal, closeVal, closeDim),
initBaseline: openVal > closeVal
? ocHighPoint[vDimIdx] : ocLowPoint[vDimIdx], // open point.
ends: ends,
brushRect: makeBrushRect(lowestVal, highestVal, axisDimVal)
} as CandlestickItemLayout);
}
function getPoint(val: number, axisDimVal: number) {
const p = [];
p[cDimIdx] = axisDimVal;
p[vDimIdx] = val;
return (isNaN(axisDimVal) || isNaN(val))
? [NaN, NaN]
: coordSys.dataToPoint(p);
}
function addBodyEnd(ends: number[][], point: number[], start: number) {
const point1 = point.slice();
const point2 = point.slice();
point1[cDimIdx] = subPixelOptimize(
point1[cDimIdx] + candleWidth / 2, 1, false
);
point2[cDimIdx] = subPixelOptimize(
point2[cDimIdx] - candleWidth / 2, 1, true
);
start
? ends.push(point1, point2)
: ends.push(point2, point1);
}
function makeBrushRect(lowestVal: number, highestVal: number, axisDimVal: number) {
const pmin = getPoint(lowestVal, axisDimVal);
const pmax = getPoint(highestVal, axisDimVal);
pmin[cDimIdx] -= candleWidth / 2;
pmax[cDimIdx] -= candleWidth / 2;
return {
x: pmin[0],
y: pmin[1],
width: vDimIdx ? candleWidth : pmax[0] - pmin[0],
height: vDimIdx ? pmax[1] - pmin[1] : candleWidth
};
}
function subPixelOptimizePoint(point: number[]) {
point[cDimIdx] = subPixelOptimize(point[cDimIdx], 1);
return point;
}
}
function largeProgress(params: StageHandlerProgressParams, data: List) {
// Structure: [sign, x, yhigh, ylow, sign, x, yhigh, ylow, ...]
const points = new LargeArr(params.count * 4);
let offset = 0;
let point;
const tmpIn: number[] = [];
const tmpOut: number[] = [];
let dataIndex;
while ((dataIndex = params.next()) != null) {
const axisDimVal = data.get(cDim, dataIndex) as number;
const openVal = data.get(openDim, dataIndex) as number;
const closeVal = data.get(closeDim, dataIndex) as number;
const lowestVal = data.get(lowestDim, dataIndex) as number;
const highestVal = data.get(highestDim, dataIndex) as number;
if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) {
points[offset++] = NaN;
offset += 3;
continue;
}
points[offset++] = getSign(data, dataIndex, openVal, closeVal, closeDim);
tmpIn[cDimIdx] = axisDimVal;
tmpIn[vDimIdx] = lowestVal;
point = coordSys.dataToPoint(tmpIn, null, tmpOut);
points[offset++] = point ? point[0] : NaN;
points[offset++] = point ? point[1] : NaN;
tmpIn[vDimIdx] = highestVal;
point = coordSys.dataToPoint(tmpIn, null, tmpOut);
points[offset++] = point ? point[1] : NaN;
}
data.setLayout('largePoints', points);
}
}
};
function getSign(data: List, dataIndex: number, openVal: number, closeVal: number, closeDim: string) {
let sign;
if (openVal > closeVal) {
sign = -1;
}
else if (openVal < closeVal) {
sign = 1;
}
else {
sign = dataIndex > 0
// If close === open, compare with close of last record
? (data.get(closeDim, dataIndex - 1) <= closeVal ? 1 : -1)
// No record of previous, set to be positive
: 1;
}
return sign;
}
function calculateCandleWidth(seriesModel: CandlestickSeriesModel, data: List) {
const baseAxis = seriesModel.getBaseAxis();
let extent;
const bandWidth = baseAxis.type === 'category'
? baseAxis.getBandWidth()
: (
extent = baseAxis.getExtent(),
Math.abs(extent[1] - extent[0]) / data.count()
);
const barMaxWidth = parsePercent(
retrieve2(seriesModel.get('barMaxWidth'), bandWidth),
bandWidth
);
const barMinWidth = parsePercent(
retrieve2(seriesModel.get('barMinWidth'), 1),
bandWidth
);
const barWidth = seriesModel.get('barWidth');
return barWidth != null
? parsePercent(barWidth, bandWidth)
// Put max outer to ensure bar visible in spite of overlap.
: Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
}
export default candlestickLayout;
| apache-2.0 |
clescot/webappender | webappender/src/main/java/com/clescot/webappender/formatter/ConsoleFormatter.java | 3415 | package com.clescot.webappender.formatter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
public class ConsoleFormatter extends AbstractFormatter<Row> implements BodyFormatter{
private static final String REQUEST_HEADER_IDENTIFIER = "X-BodyLogger";
@Override
public LinkedHashMap<String, String> formatRows(List<Row> rows,int limit) {
LinkedHashMap<String, String> result = Maps.newLinkedHashMap();
if(rows !=null && !rows.isEmpty()) {
List<Row> formattedRows = getFormatterRows(rows);
try {
int serializedContent =0;
for (Row row : formattedRows) {
if(serializedContent<limit||limit<=0){
String key = serializeRow(row);
serializedContent+=key.length();
result.put(key,"");
}
}
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
return result;
}
private String serializeRow( Row row) throws JsonProcessingException {
StringBuilder rowDecorated = new StringBuilder();
if(row.getLevel().isGreaterOrEqual(ch.qos.logback.classic.Level.DEBUG)) {
String rowInJSON = objectMapper.writeValueAsString(row);
rowDecorated.append("console.");
rowDecorated.append(Level.getConsoleLevel(row));
rowDecorated.append("(");
rowDecorated.append(rowInJSON);
rowDecorated.append(");");
}
return rowDecorated.toString();
}
protected enum Level{
OFF("", ch.qos.logback.classic.Level.OFF),
DEBUG("debug", ch.qos.logback.classic.Level.DEBUG),
INFO("info",ch.qos.logback.classic.Level.INFO),
WARN("warn",ch.qos.logback.classic.Level.WARN),
ERROR("error",ch.qos.logback.classic.Level.ERROR),
ALL("error", ch.qos.logback.classic.Level.ALL);
private final String consoleLevel;
private final ch.qos.logback.classic.Level logbackLevel;
Level(String consoleLevel, ch.qos.logback.classic.Level logbackLevel) {
this.consoleLevel = consoleLevel;
this.logbackLevel = logbackLevel;
}
private static String getConsoleLevel(final Row row){
final ch.qos.logback.classic.Level rowLevel = row.getLevel();
List<Level> levels = Arrays.asList(Level.values());
Level level = Iterables.find(levels, new Predicate<Level>() {
@Override
public boolean apply(Level input) {
return input.getLogbackLevel().equals(rowLevel);
}
},Level.OFF);
return level.getConsoleLevel();
}
public String getConsoleLevel() {
return consoleLevel;
}
public ch.qos.logback.classic.Level getLogbackLevel() {
return logbackLevel;
}
}
@Override
protected String getRequestHeaderIdentifier() {
return REQUEST_HEADER_IDENTIFIER;
}
@Override
protected Row newFormatterRow(Row row) {
return row;
}
}
| apache-2.0 |
tengqm/senlin-container | senlin/tests/unit/engine/actions/test_action_base.py | 34010 | # 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 copy
import mock
from oslo_config import cfg
import six
from senlin.common import exception
from senlin.db.sqlalchemy import api as db_api
from senlin.engine.actions import base as action_base
from senlin.engine import cluster as cluster_mod
from senlin.engine import cluster_policy as cp_mod
from senlin.engine import environment
from senlin.engine import event as EVENT
from senlin.engine import node as node_mod
from senlin.policies import base as policy_mod
from senlin.tests.unit.common import base
from senlin.tests.unit.common import utils
from senlin.tests.unit import fakes
class DummyAction(action_base.Action):
def __init__(self, target, action, context, **kwargs):
super(DummyAction, self).__init__(target, action, context, **kwargs)
class ActionBaseTest(base.SenlinTestCase):
def setUp(self):
super(ActionBaseTest, self).setUp()
self.ctx = utils.dummy_context()
self.action_values = {
'name': 'FAKE_NAME',
'cause': 'FAKE_CAUSE',
'owner': 'FAKE_OWNER',
'interval': 60,
'start_time': 0,
'end_time': 0,
'timeout': 120,
'status': 'FAKE_STATUS',
'status_reason': 'FAKE_STATUS_REASON',
'inputs': {'param': 'value'},
'outputs': {'key': 'output_value'},
'created_at': None,
'updated_at': None,
'data': {'data_key': 'data_value'},
}
def _verify_new_action(self, obj, target, action):
self.assertIsNone(obj.id)
self.assertEqual('', obj.name)
self.assertEqual('', obj.description)
self.assertEqual(target, obj.target)
self.assertEqual(action, obj.action)
self.assertEqual('', obj.cause)
self.assertIsNone(obj.owner)
self.assertEqual(-1, obj.interval)
self.assertIsNone(obj.start_time)
self.assertIsNone(obj.end_time)
self.assertEqual(cfg.CONF.default_action_timeout, obj.timeout)
self.assertEqual('INIT', obj.status)
self.assertEqual('', obj.status_reason)
self.assertEqual({}, obj.inputs)
self.assertEqual({}, obj.outputs)
self.assertIsNone(obj.created_at)
self.assertIsNone(obj.updated_at)
self.assertEqual({}, obj.data)
@mock.patch.object(node_mod.Node, 'load')
@mock.patch.object(cluster_mod.Cluster, 'load')
def test_action_new(self, mock_n_load, mock_c_load):
for action in ['CLUSTER_CREATE', 'NODE_CREATE', 'WHAT_EVER']:
obj = action_base.Action('OBJID', action, self.ctx)
self._verify_new_action(obj, 'OBJID', action)
def test_action_init_with_values(self):
values = copy.deepcopy(self.action_values)
values['id'] = 'FAKE_ID'
values['description'] = 'FAKE_DESC'
values['created_at'] = 'FAKE_CREATED_TIME'
values['updated_at'] = 'FAKE_UPDATED_TIME'
obj = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx,
**values)
self.assertEqual('FAKE_ID', obj.id)
self.assertEqual('FAKE_NAME', obj.name)
self.assertEqual('FAKE_DESC', obj.description)
self.assertEqual('OBJID', obj.target)
self.assertEqual('FAKE_CAUSE', obj.cause)
self.assertEqual('FAKE_OWNER', obj.owner)
self.assertEqual(60, obj.interval)
self.assertEqual(0, obj.start_time)
self.assertEqual(0, obj.end_time)
self.assertEqual(120, obj.timeout)
self.assertEqual('FAKE_STATUS', obj.status)
self.assertEqual('FAKE_STATUS_REASON', obj.status_reason)
self.assertEqual({'param': 'value'}, obj.inputs)
self.assertEqual({'key': 'output_value'}, obj.outputs)
self.assertEqual('FAKE_CREATED_TIME', obj.created_at)
self.assertEqual('FAKE_UPDATED_TIME', obj.updated_at)
self.assertEqual({'data_key': 'data_value'}, obj.data)
def test_action_store_for_create(self):
values = copy.deepcopy(self.action_values)
obj = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx,
**values)
self.assertIsNone(obj.created_at)
self.assertIsNone(obj.updated_at)
# store for creation
res = obj.store(self.ctx)
self.assertIsNotNone(res)
self.assertEqual(obj.id, res)
self.assertIsNotNone(obj.created_at)
self.assertIsNone(obj.updated_at)
def test_action_store_for_update(self):
values = copy.deepcopy(self.action_values)
obj = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx,
**values)
obj_id = obj.store(self.ctx)
self.assertIsNotNone(obj_id)
self.assertIsNotNone(obj.created_at)
self.assertIsNone(obj.updated_at)
# store for creation
res = obj.store(self.ctx)
self.assertIsNotNone(res)
self.assertEqual(obj_id, res)
self.assertEqual(obj.id, res)
self.assertIsNotNone(obj.created_at)
self.assertIsNotNone(obj.updated_at)
def test_from_db_record(self):
values = copy.deepcopy(self.action_values)
obj = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx,
**values)
obj.store(self.ctx)
record = db_api.action_get(self.ctx, obj.id)
action_obj = action_base.Action._from_db_record(record)
self.assertIsInstance(action_obj, action_base.Action)
self.assertEqual(obj.id, action_obj.id)
self.assertEqual(obj.action, action_obj.action)
self.assertEqual(obj.name, action_obj.name)
self.assertEqual(obj.target, action_obj.target)
self.assertEqual(obj.cause, action_obj.cause)
self.assertEqual(obj.owner, action_obj.owner)
self.assertEqual(obj.interval, action_obj.interval)
self.assertEqual(obj.start_time, action_obj.start_time)
self.assertEqual(obj.end_time, action_obj.end_time)
self.assertEqual(obj.timeout, action_obj.timeout)
self.assertEqual(obj.status, action_obj.status)
self.assertEqual(obj.status_reason, action_obj.status_reason)
self.assertEqual(obj.inputs, action_obj.inputs)
self.assertEqual(obj.outputs, action_obj.outputs)
self.assertEqual(obj.created_at, action_obj.created_at)
self.assertEqual(obj.updated_at, action_obj.updated_at)
self.assertEqual(obj.data, action_obj.data)
self.assertEqual(obj.user, action_obj.user)
self.assertEqual(obj.project, action_obj.project)
self.assertEqual(obj.domain, action_obj.domain)
def test_from_db_record_with_empty_fields(self):
values = copy.deepcopy(self.action_values)
del values['inputs']
del values['outputs']
obj = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx,
**values)
obj.store(self.ctx)
record = db_api.action_get(self.ctx, obj.id)
action_obj = action_base.Action._from_db_record(record)
self.assertEqual({}, action_obj.inputs)
self.assertEqual({}, action_obj.outputs)
def test_load(self):
values = copy.deepcopy(self.action_values)
obj = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx, **values)
obj.store(self.ctx)
result = action_base.Action.load(self.ctx, obj.id, None)
# no need to do a thorough test here
self.assertEqual(obj.id, result.id)
self.assertEqual(obj.action, result.action)
db_action = db_api.action_get(self.ctx, obj.id)
result = action_base.Action.load(self.ctx, None, db_action)
# no need to do a thorough test here
self.assertEqual(obj.id, result.id)
self.assertEqual(obj.action, result.action)
def test_load_not_found(self):
# not found due to bad identity
ex = self.assertRaises(exception.ActionNotFound,
action_base.Action.load,
self.ctx, 'non-existent', None)
self.assertEqual('The action (non-existent) could not be found.',
six.text_type(ex))
# not found due to no object
self.patchobject(db_api, 'action_get', return_value=None)
ex = self.assertRaises(exception.ActionNotFound,
action_base.Action.load,
self.ctx, 'whatever', None)
self.assertEqual('The action (whatever) could not be found.',
six.text_type(ex))
def test_load_all(self):
result = action_base.Action.load_all(self.ctx)
self.assertEqual([], [c for c in result])
values = copy.deepcopy(self.action_values)
action1 = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx,
**values)
action1.store(self.ctx)
action2 = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx,
**values)
action2.store(self.ctx)
# NOTE: we don't test all other parameters because the db api tests
# already covered that
results = list(action_base.Action.load_all(self.ctx))
actions = [a.id for a in results]
self.assertEqual(2, len(actions))
self.assertIn(action1.id, actions)
self.assertIn(action2.id, actions)
@mock.patch.object(db_api, 'action_get_all')
def test_load_all_with_params(self, mock_call):
mock_call.return_value = []
results = action_base.Action.load_all(
self.ctx, filters='FAKE_FILTER', limit='FAKE_LIMIT',
marker='FAKE_MARKER', sort='FAKE_SORT')
# the following line is important, or else the generator won't get
# called.
self.assertEqual([], list(results))
mock_call.assert_called_once_with(
self.ctx, filters='FAKE_FILTER', limit='FAKE_LIMIT',
marker='FAKE_MARKER', sort='FAKE_SORT',
project_safe=True)
@mock.patch.object(action_base.Action, 'store')
def test_action_create(self, mock_store):
mock_store.return_value = 'FAKE_ID'
result = action_base.Action.create(self.ctx, 'OBJ_ID', 'CLUSTER_DANCE',
name='test')
self.assertEqual('FAKE_ID', result)
mock_store.assert_called_once_with(self.ctx)
def test_action_delete(self):
result = action_base.Action.delete(self.ctx, 'non-existent')
self.assertIsNone(result)
values = copy.deepcopy(self.action_values)
action1 = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx,
**values)
action1.store(self.ctx)
result = action_base.Action.delete(self.ctx, action1.id)
self.assertIsNone(result)
@mock.patch.object(db_api, 'action_delete')
def test_action_delete_db_call(self, mock_call):
# test db api call
action_base.Action.delete(self.ctx, 'FAKE_ID')
mock_call.assert_called_once_with(self.ctx, 'FAKE_ID', False)
@mock.patch.object(db_api, 'action_signal')
def test_action_signal_bad_command(self, mock_call):
values = copy.deepcopy(self.action_values)
action1 = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx,
**values)
action1.store(self.ctx)
result = action1.signal('BOGUS')
self.assertIsNone(result)
self.assertEqual(0, mock_call.call_count)
@mock.patch.object(db_api, 'action_signal')
@mock.patch.object(EVENT, 'error')
def test_action_signal_cancel(self, mock_error, mock_call):
values = copy.deepcopy(self.action_values)
action = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx,
**values)
action.store(self.ctx)
expected = [action.INIT, action.WAITING, action.READY, action.RUNNING]
for status in expected:
action.status = status
result = action.signal(action.SIG_CANCEL)
self.assertIsNone(result)
self.assertEqual(1, mock_call.call_count)
mock_call.reset_mock()
invalid = [action.SUSPENDED, action.SUCCEEDED, action.CANCELLED,
action.FAILED]
for status in invalid:
action.status = status
result = action.signal(action.SIG_CANCEL)
self.assertIsNone(result)
self.assertEqual(0, mock_call.call_count)
mock_call.reset_mock()
self.assertEqual(1, mock_error.call_count)
mock_error.reset_mock()
@mock.patch.object(db_api, 'action_signal')
@mock.patch.object(EVENT, 'error')
def test_action_signal_suspend(self, mock_error, mock_call):
action = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx)
expected = [action.RUNNING]
for status in expected:
action.status = status
result = action.signal(action.SIG_SUSPEND)
self.assertIsNone(result)
self.assertEqual(1, mock_call.call_count)
mock_call.reset_mock()
invalid = [action.INIT, action.WAITING, action.READY, action.SUSPENDED,
action.SUCCEEDED, action.CANCELLED, action.FAILED]
for status in invalid:
action.status = status
result = action.signal(action.SIG_SUSPEND)
self.assertIsNone(result)
self.assertEqual(0, mock_call.call_count)
mock_call.reset_mock()
self.assertEqual(1, mock_error.call_count)
mock_error.reset_mock()
@mock.patch.object(db_api, 'action_signal')
@mock.patch.object(EVENT, 'error')
def test_action_signal_resume(self, mock_error, mock_call):
action = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx)
expected = [action.SUSPENDED]
for status in expected:
action.status = status
result = action.signal(action.SIG_RESUME)
self.assertIsNone(result)
self.assertEqual(1, mock_call.call_count)
mock_call.reset_mock()
invalid = [action.INIT, action.WAITING, action.READY, action.RUNNING,
action.SUCCEEDED, action.CANCELLED, action.FAILED]
for status in invalid:
action.status = status
result = action.signal(action.SIG_RESUME)
self.assertIsNone(result)
self.assertEqual(0, mock_call.call_count)
mock_call.reset_mock()
self.assertEqual(1, mock_error.call_count)
mock_error.reset_mock()
def test_execute_default(self):
action = action_base.Action.__new__(DummyAction, 'OBJID', 'BOOM',
self.ctx)
res = action.execute()
self.assertEqual(NotImplemented, res)
@mock.patch.object(db_api, 'action_mark_succeeded')
@mock.patch.object(db_api, 'action_mark_failed')
@mock.patch.object(db_api, 'action_mark_cancelled')
@mock.patch.object(db_api, 'action_abandon')
def test_set_status(self, mock_abandon, mark_cancel, mark_fail,
mark_succeed):
action = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx)
action.id = 'FAKE_ID'
action.set_status(action.RES_OK, 'FAKE_REASON')
self.assertEqual(action.SUCCEEDED, action.status)
self.assertEqual('FAKE_REASON', action.status_reason)
mark_succeed.assert_called_once_with(action.context, 'FAKE_ID',
mock.ANY)
action.set_status(action.RES_ERROR, 'FAKE_ERROR')
self.assertEqual(action.FAILED, action.status)
self.assertEqual('FAKE_ERROR', action.status_reason)
mark_fail.assert_called_once_with(action.context, 'FAKE_ID', mock.ANY,
'FAKE_ERROR')
mark_fail.reset_mock()
action.set_status(action.RES_TIMEOUT, 'TIMEOUT_ERROR')
self.assertEqual(action.FAILED, action.status)
self.assertEqual('TIMEOUT_ERROR', action.status_reason)
mark_fail.assert_called_once_with(action.context, 'FAKE_ID', mock.ANY,
'TIMEOUT_ERROR')
mark_fail.reset_mock()
action.set_status(action.RES_CANCEL, 'CANCELLED')
self.assertEqual(action.CANCELLED, action.status)
self.assertEqual('CANCELLED', action.status_reason)
mark_cancel.assert_called_once_with(action.context, 'FAKE_ID',
mock.ANY)
mark_fail.reset_mock()
action.set_status(action.RES_RETRY, 'BUSY')
self.assertEqual(action.READY, action.status)
self.assertEqual('BUSY', action.status_reason)
mock_abandon.assert_called_once_with(action.context, 'FAKE_ID')
@mock.patch.object(db_api, 'action_check_status')
def test_get_status(self, mock_get):
mock_get.return_value = 'FAKE_STATUS'
action = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx)
action.id = 'FAKE_ID'
res = action.get_status()
self.assertEqual('FAKE_STATUS', res)
self.assertEqual('FAKE_STATUS', action.status)
mock_get.assert_called_once_with(action.context, 'FAKE_ID', mock.ANY)
@mock.patch.object(action_base, 'wallclock')
def test_is_timeout(self, mock_time):
action = action_base.Action.__new__(DummyAction, 'OBJ', 'BOOM',
self.ctx)
action.start_time = 1
action.timeout = 10
mock_time.return_value = 9
self.assertFalse(action.is_timeout())
mock_time.return_value = 10
self.assertFalse(action.is_timeout())
mock_time.return_value = 11
self.assertFalse(action.is_timeout())
mock_time.return_value = 12
self.assertTrue(action.is_timeout())
def test_check_signal_timeout(self):
action = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx)
action.id = 'FAKE_ID'
action.timeout = 10
self.patchobject(action, 'is_timeout', return_value=True)
res = action._check_signal()
self.assertEqual(action.RES_TIMEOUT, res)
@mock.patch.object(db_api, 'action_signal_query')
def test_check_signal_signals_caught(self, mock_query):
action = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx)
action.id = 'FAKE_ID'
action.timeout = 100
self.patchobject(action, 'is_timeout', return_value=False)
sig_cmd = mock.Mock()
mock_query.return_value = sig_cmd
res = action._check_signal()
self.assertEqual(sig_cmd, res)
mock_query.assert_called_once_with(action.context, 'FAKE_ID')
@mock.patch.object(db_api, 'action_signal_query')
def test_is_cancelled(self, mock_query):
action = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx)
action.id = 'FAKE_ID'
action.timeout = 100
self.patchobject(action, 'is_timeout', return_value=False)
mock_query.return_value = action.SIG_CANCEL
res = action.is_cancelled()
self.assertTrue(res)
mock_query.assert_called_once_with(action.context, 'FAKE_ID')
mock_query.reset_mock()
mock_query.return_value = None
res = action.is_cancelled()
self.assertFalse(res)
mock_query.assert_called_once_with(action.context, 'FAKE_ID')
@mock.patch.object(db_api, 'action_signal_query')
def test_is_suspended(self, mock_query):
action = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx)
action.id = 'FAKE_ID'
action.timeout = 100
self.patchobject(action, 'is_timeout', return_value=False)
mock_query.return_value = action.SIG_SUSPEND
res = action.is_suspended()
self.assertTrue(res)
mock_query.assert_called_once_with(action.context, 'FAKE_ID')
mock_query.reset_mock()
mock_query.return_value = 'OTHERS'
res = action.is_suspended()
self.assertFalse(res)
mock_query.assert_called_once_with(action.context, 'FAKE_ID')
@mock.patch.object(db_api, 'action_signal_query')
def test_is_resumed(self, mock_query):
action = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx)
action.id = 'FAKE_ID'
action.timeout = 100
self.patchobject(action, 'is_timeout', return_value=False)
mock_query.return_value = action.SIG_RESUME
res = action.is_resumed()
self.assertTrue(res)
mock_query.assert_called_once_with(action.context, 'FAKE_ID')
mock_query.reset_mock()
mock_query.return_value = 'OTHERS'
res = action.is_resumed()
self.assertFalse(res)
mock_query.assert_called_once_with(action.context, 'FAKE_ID')
@mock.patch.object(cp_mod.ClusterPolicy, 'load_all')
def test_policy_check_target_invalid(self, mock_load):
action = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx)
res = action.policy_check('FAKE_CLUSTER', 'WHEN')
self.assertIsNone(res)
self.assertEqual(0, mock_load.call_count)
@mock.patch.object(cp_mod.ClusterPolicy, 'load_all')
def test_policy_check_no_bindings(self, mock_load):
action = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx)
mock_load.return_value = []
res = action.policy_check('FAKE_CLUSTER', 'BEFORE')
self.assertIsNone(res)
self.assertEqual(policy_mod.CHECK_OK, action.data['status'])
mock_load.assert_called_once_with(action.context, 'FAKE_CLUSTER',
sort='priority',
filters={'enabled': True})
@mock.patch.object(db_api, 'dependency_get_depended')
@mock.patch.object(db_api, 'dependency_get_dependents')
def test_action_to_dict(self, mock_dep_by, mock_dep_on):
mock_dep_on.return_value = ['ACTION_1']
mock_dep_by.return_value = ['ACTION_2']
action = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx,
**self.action_values)
action.id = 'FAKE_ID'
expected = {
'id': 'FAKE_ID',
'name': 'FAKE_NAME',
'action': 'OBJECT_ACTION',
'target': 'OBJID',
'cause': 'FAKE_CAUSE',
'owner': 'FAKE_OWNER',
'interval': 60,
'start_time': 0,
'end_time': 0,
'timeout': 120,
'status': 'FAKE_STATUS',
'status_reason': 'FAKE_STATUS_REASON',
'inputs': {'param': 'value'},
'outputs': {'key': 'output_value'},
'depends_on': ['ACTION_1'],
'depended_by': ['ACTION_2'],
'created_at': None,
'updated_at': None,
'data': {'data_key': 'data_value'},
}
res = action.to_dict()
self.assertEqual(expected, res)
mock_dep_on.assert_called_once_with(action.context, 'FAKE_ID')
mock_dep_by.assert_called_once_with(action.context, 'FAKE_ID')
class ActionPolicyCheckTest(base.SenlinTestCase):
def setUp(self):
super(ActionPolicyCheckTest, self).setUp()
self.ctx = utils.dummy_context()
environment.global_env().register_policy('DummyPolicy',
fakes.TestPolicy)
def _create_policy(self):
values = {
'user': self.ctx.user,
'project': self.ctx.project,
}
policy = fakes.TestPolicy('DummyPolicy', 'test-policy', **values)
policy.store(self.ctx)
return policy
def _create_cp_binding(self, cluster_id, policy_id):
values = {'enabled': True}
pb = cp_mod.ClusterPolicy(cluster_id, policy_id, **values)
pb.id = 'FAKE_BINDING_ID'
return pb
@mock.patch.object(policy_mod.Policy, 'post_op')
@mock.patch.object(policy_mod.Policy, 'pre_op')
@mock.patch.object(cp_mod.ClusterPolicy, 'load_all')
@mock.patch.object(policy_mod.Policy, 'load')
def test_policy_check_missing_target(self, mock_load, mock_load_all,
mock_pre_op, mock_post_op):
cluster_id = 'FAKE_CLUSTER_ID'
# Note: policy is mocked
spec = {
'type': 'TestPolicy',
'version': '1.0',
'properties': {'KEY2': 5},
}
policy = fakes.TestPolicy('test-policy', spec)
policy.id = 'FAKE_POLICY_ID'
policy.TARGET = [('BEFORE', 'OBJECT_ACTION')]
# Note: policy binding is created but not stored
pb = self._create_cp_binding(cluster_id, policy.id)
self.assertIsNone(pb.last_op)
mock_load_all.return_value = [pb]
mock_load.return_value = policy
mock_pre_op.return_value = None
mock_post_op.return_value = None
action = action_base.Action(cluster_id, 'OBJECT_ACTION_1', self.ctx)
res = action.policy_check(cluster_id, 'AFTER')
self.assertIsNone(res)
self.assertEqual(policy_mod.CHECK_OK, action.data['status'])
mock_load_all.assert_called_once_with(
action.context, cluster_id, sort='priority',
filters={'enabled': True})
mock_load.assert_called_once_with(action.context, policy.id)
# last_op was updated anyway
self.assertIsNotNone(pb.last_op)
# neither pre_op nor post_op was called, because target not match
self.assertEqual(0, mock_pre_op.call_count)
self.assertEqual(0, mock_post_op.call_count)
@mock.patch.object(cp_mod.ClusterPolicy, 'load_all')
@mock.patch.object(policy_mod.Policy, 'load')
def test_policy_check_pre_op(self, mock_load, mock_load_all):
cluster_id = 'FAKE_CLUSTER_ID'
# Note: policy is mocked
spec = {
'type': 'TestPolicy',
'version': '1.0',
'properties': {'KEY2': 5},
}
policy = fakes.TestPolicy('test-policy', spec)
policy.id = 'FAKE_POLICY_ID'
policy.TARGET = [('BEFORE', 'OBJECT_ACTION')]
# Note: policy binding is created but not stored
pb = self._create_cp_binding(cluster_id, policy.id)
self.assertIsNone(pb.last_op)
mock_load_all.return_value = [pb]
mock_load.return_value = policy
action = action_base.Action(cluster_id, 'OBJECT_ACTION', self.ctx)
res = action.policy_check(cluster_id, 'BEFORE')
self.assertIsNone(res)
self.assertEqual(policy_mod.CHECK_OK, action.data['status'])
mock_load_all.assert_called_once_with(
action.context, cluster_id, sort='priority',
filters={'enabled': True})
mock_load.assert_called_once_with(action.context, policy.id)
# last_op was not updated
self.assertIsNone(pb.last_op)
@mock.patch.object(cp_mod.ClusterPolicy, 'load_all')
@mock.patch.object(policy_mod.Policy, 'load')
def test_policy_check_post_op(self, mock_load, mock_load_all):
cluster_id = 'FAKE_CLUSTER_ID'
# Note: policy is mocked
policy = mock.Mock()
policy.id = 'FAKE_POLICY_ID'
policy.TARGET = [('AFTER', 'OBJECT_ACTION')]
policy.cooldown = 0
# Note: policy binding is created but not stored
pb = self._create_cp_binding(cluster_id, policy.id)
self.assertIsNone(pb.last_op)
mock_load_all.return_value = [pb]
mock_load.return_value = policy
action = action_base.Action(cluster_id, 'OBJECT_ACTION', self.ctx)
res = action.policy_check('FAKE_CLUSTER_ID', 'AFTER')
self.assertIsNone(res)
self.assertEqual(policy_mod.CHECK_OK, action.data['status'])
mock_load_all.assert_called_once_with(
action.context, cluster_id, sort='priority',
filters={'enabled': True})
mock_load.assert_called_once_with(action.context, policy.id)
# last_op was updated for POST check
self.assertIsNotNone(pb.last_op)
# pre_op is called, but post_op was not called
self.assertEqual(0, policy.pre_op.call_count)
policy.post_op.assert_called_once_with(cluster_id, action)
@mock.patch.object(cp_mod.ClusterPolicy, 'load_all')
@mock.patch.object(policy_mod.Policy, 'load')
def test_policy_check_cooldown_inprogress(self, mock_load, mock_load_all):
cluster_id = 'FAKE_CLUSTER_ID'
# Note: policy is mocked
policy = mock.Mock()
policy.id = 'FAKE_POLICY_ID'
policy.TARGET = [('AFTER', 'OBJECT_ACTION')]
# Note: policy binding is created but not stored
pb = self._create_cp_binding(cluster_id, policy.id)
self.patchobject(pb, 'cooldown_inprogress', return_value=True)
self.assertIsNone(pb.last_op)
mock_load_all.return_value = [pb]
mock_load.return_value = policy
action = action_base.Action(cluster_id, 'OBJECT_ACTION', self.ctx)
res = action.policy_check('FAKE_CLUSTER_ID', 'AFTER')
self.assertIsNone(res)
self.assertEqual(policy_mod.CHECK_ERROR, action.data['status'])
self.assertEqual('Policy FAKE_POLICY_ID cooldown is still in '
'progress.', six.text_type(action.data['reason']))
mock_load_all.assert_called_once_with(
action.context, cluster_id, sort='priority',
filters={'enabled': True})
mock_load.assert_called_once_with(action.context, policy.id)
# last_op was updated for POST check
self.assertIsNotNone(pb.last_op)
# neither pre_op nor post_op was not called, due to cooldown
self.assertEqual(0, policy.pre_op.call_count)
self.assertEqual(0, policy.post_op.call_count)
@mock.patch.object(cp_mod.ClusterPolicy, 'load_all')
@mock.patch.object(policy_mod.Policy, 'load')
@mock.patch.object(action_base.Action, '_check_result')
def test_policy_check_abort_in_middle(self, mock_check, mock_load,
mock_load_all):
cluster_id = 'FAKE_CLUSTER_ID'
# Note: both policies are mocked
policy1 = mock.Mock()
policy1.id = 'FAKE_POLICY_ID_1'
policy1.name = 'P1'
policy1.cooldown = 0
policy1.TARGET = [('AFTER', 'OBJECT_ACTION')]
policy2 = mock.Mock()
policy2.id = 'FAKE_POLICY_ID_2'
policy2.name = 'P2'
policy2.cooldown = 0
policy2.TARGET = [('AFTER', 'OBJECT_ACTION')]
action = action_base.Action(cluster_id, 'OBJECT_ACTION', self.ctx)
# Note: policy binding is created but not stored
pb1 = self._create_cp_binding(cluster_id, policy1.id)
pb2 = self._create_cp_binding(cluster_id, policy2.id)
mock_load_all.return_value = [pb1, pb2]
# mock return value for two calls
mock_load.side_effect = [policy1, policy2]
mock_check.side_effect = [False, True]
res = action.policy_check(cluster_id, 'AFTER')
self.assertIsNone(res)
# post_op from policy1 was called, but post_op from policy2 was not
policy1.post_op.assert_called_once_with(cluster_id, action)
self.assertEqual(0, policy2.post_op.call_count)
mock_load_all.assert_called_once_with(
action.context, cluster_id, sort='priority',
filters={'enabled': True})
calls = [mock.call(action.context, policy1.id)]
mock_load.assert_has_calls(calls)
class ActionProcTest(base.SenlinTestCase):
def setUp(self):
super(ActionProcTest, self).setUp()
self.ctx = utils.dummy_context()
@mock.patch.object(EVENT, 'info')
@mock.patch.object(action_base.Action, 'load')
@mock.patch.object(db_api, 'action_mark_succeeded')
def test_action_proc_successful(self, mock_mark, mock_load,
mock_event_info):
action = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx)
action.owner = 'WORKER'
action.start_time = 123456
self.patchobject(action, 'execute',
return_value=(action.RES_OK, 'BIG SUCCESS'))
mock_load.return_value = action
res = action_base.ActionProc(self.ctx, 'ACTION')
self.assertTrue(res)
mock_load.assert_called_once_with(self.ctx, action_id='ACTION')
self.assertEqual(action.SUCCEEDED, action.status)
self.assertEqual('WORKER', action.owner)
self.assertEqual(123456, action.start_time)
self.assertEqual('BIG SUCCESS', action.status_reason)
@mock.patch.object(EVENT, 'info')
@mock.patch.object(action_base.Action, 'load')
@mock.patch.object(db_api, 'action_mark_failed')
def test_action_proc_failed_error(self, mock_mark, mock_load,
mock_event_info):
action = action_base.Action('OBJID', 'OBJECT_ACTION', self.ctx)
action.owner = 'WORKER'
action.start_time = 123456
self.patchobject(action, 'execute', side_effect=Exception('Boom!'))
mock_load.return_value = action
res = action_base.ActionProc(self.ctx, 'ACTION')
self.assertFalse(res)
mock_load.assert_called_once_with(self.ctx, action_id='ACTION')
self.assertEqual(action.FAILED, action.status)
self.assertEqual('Boom!', action.status_reason)
| apache-2.0 |
BVier/Taskana | lib/taskana-core/src/main/java/pro/taskana/BulkOperationResults.java | 3556 | package pro.taskana;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pro.taskana.impl.util.LoggerUtils;
/**
* Returning type for a bulk db interaction with errors. This wrapper is storing them with a
* matching object ID.
*
* @param <K> unique keys for the logs.
* @param <V> type of the stored informations
*/
public class BulkOperationResults<K, V> {
private static final Logger LOGGER = LoggerFactory.getLogger(BulkOperationResults.class);
private Map<K, V> errorMap = new HashMap<>();
/**
* Returning a list of current errors as map. If there are no errors the result will be empty.
*
* @return map of errors which can´t be null.
*/
public Map<K, V> getErrorMap() {
return this.errorMap;
}
/**
* Adding an appearing error to the map and list them by a unique ID as key. NULL keys will be
* ignored.
*
* @param objectId unique key of a entity.
* @param error occurred error of a interaction with the entity
* @return status of adding the values.
*/
public boolean addError(K objectId, V error) {
boolean status = false;
try {
if (objectId != null) {
this.errorMap.put(objectId, error);
status = true;
}
} catch (Exception e) {
LOGGER.warn(
"Can´t add bulkoperation-error, because of a map failure. "
+ "ID={}, error={} and current failure={}",
objectId,
error,
e);
}
return status;
}
/**
* Returning the status of a bulk-error-log.
*
* @return true if there are logged errors.
*/
public boolean containsErrors() {
boolean isContainingErrors = false;
if (!this.errorMap.isEmpty()) {
isContainingErrors = true;
}
return isContainingErrors;
}
/**
* Returns the stored error for a unique ID or NULL if there is no error stored or ID invalid.
*
* @param idKey which is mapped with an error
* @return stored error for ID
*/
public V getErrorForId(K idKey) {
V result = null;
if (idKey != null) {
result = this.errorMap.get(idKey);
}
return result;
}
/**
* Returns the IDs of the Object with failed requests.
*
* @return a List of IDs that could not be processed successfully.
*/
public List<K> getFailedIds() {
return new ArrayList<>(this.errorMap.keySet());
}
/** Clearing the map - all entries will be removed. */
public void clearErrors() {
this.errorMap.clear();
}
/**
* Add all errors from another BulkOperationResult to this.
*
* @param log the other log
*/
public void addAllErrors(BulkOperationResults<K, V> log) {
if (log != null && log.containsErrors()) {
List<K> failedIds = log.getFailedIds();
for (K id : failedIds) {
addError(id, log.getErrorForId(id));
}
}
}
/**
* Map from any exception type to Exception.
*
* @return map of errors which can´t be null.
*/
public BulkOperationResults<K, Exception> mapBulkOperationResults() {
BulkOperationResults<K, Exception> bulkLogMapped = new BulkOperationResults<>();
List<K> failedIds = this.getFailedIds();
for (K id : failedIds) {
bulkLogMapped.addError(id, (Exception) this.getErrorForId(id));
}
return bulkLogMapped;
}
@Override
public String toString() {
return "BulkOperationResults [BulkOperationResults= "
+ LoggerUtils.mapToString(this.errorMap)
+ "]";
}
}
| apache-2.0 |
studiodev/archives | 2012 - Portfolio V5/lib/vendor/symfony/test/functional/fixtures/apps/i18n/modules/i18n/templates/i18nFormSuccess.php | 189 | <form action="<?php echo url_for('i18n/i18nForm') ?>" method="post">
<table>
<?php echo $form ?>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form> | apache-2.0 |
uchenm/CnChess | src/chess/model/stone/Chariot.java | 2535 | /**
* Copyright 2013 Ming Chen<uchenm@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.
*/
package chess.model.stone;
import java.util.Vector;
import chess.model.game.Game;
import chess.model.player.Role;
/*******************************************************
*
* Chariot(JU) of the Chinese Chess
*
*******************************************************/
@SuppressWarnings("serial")
public class Chariot extends Stone implements Cloneable {
public Chariot(Role owner, Location loc, int id, Game game) {
super(owner, loc, id, game);
// Initializing
setOwner(owner);
alive = true;
if (owner.isRed()) {
// the image name of red stone
imageName = "res/images/chariot_red.gif";
} else {
// the image name of black stone
imageName = "res/images/chariot_black.gif";
}
}
protected boolean isGameRuleMove(Location loc) {
boolean result = true;
if (!this.loc.isInLine(loc))
result = false;
if (game.haveStones(this.getLoc(), loc))
result = false;
return result;
}
public Vector<Location> getLegalMoves() {
Vector<Location> v = new Vector<Location>();
// check horizontally
for (int j = 0; j < 10; j++) {
Location legalMove = new Location(getLoc().getX(), j);
if (!this.loc.equals(legalMove) && isLegalMove(legalMove)) {
v.add(legalMove);
}
}
// }
// check vertically
for (int i = 0; i < 9; i++) {
Location legalMove = new Location(i, getLoc().getY());
if (!this.loc.equals(legalMove) && isLegalMove(legalMove)) {
v.add(legalMove);
}
}
return v;
}
public Chariot clone() {
return new Chariot(this.getOwner(), this.getLoc(), this.id, this.game);
}
} | apache-2.0 |
gyfora/flink | flink-tests/src/test/java/org/apache/flink/test/recovery/ProcessFailureCancelingITCase.java | 13152 | /*
* 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.flink.test.recovery;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.time.Deadline;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.io.DiscardingOutputFormat;
import org.apache.flink.client.program.ClusterClient;
import org.apache.flink.client.program.ProgramInvocationException;
import org.apache.flink.client.program.rest.RestClusterClient;
import org.apache.flink.configuration.AkkaOptions;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.HighAvailabilityOptions;
import org.apache.flink.configuration.JobManagerOptions;
import org.apache.flink.configuration.MemorySize;
import org.apache.flink.configuration.RestOptions;
import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.runtime.client.JobStatusMessage;
import org.apache.flink.runtime.clusterframework.ApplicationStatus;
import org.apache.flink.runtime.concurrent.FutureUtils;
import org.apache.flink.runtime.dispatcher.Dispatcher;
import org.apache.flink.runtime.dispatcher.DispatcherGateway;
import org.apache.flink.runtime.dispatcher.DispatcherId;
import org.apache.flink.runtime.dispatcher.MemoryArchivedExecutionGraphStore;
import org.apache.flink.runtime.entrypoint.component.DefaultDispatcherResourceManagerComponentFactory;
import org.apache.flink.runtime.entrypoint.component.DispatcherResourceManagerComponent;
import org.apache.flink.runtime.entrypoint.component.DispatcherResourceManagerComponentFactory;
import org.apache.flink.runtime.heartbeat.HeartbeatServices;
import org.apache.flink.runtime.highavailability.HighAvailabilityServices;
import org.apache.flink.runtime.highavailability.HighAvailabilityServicesUtils;
import org.apache.flink.runtime.metrics.NoOpMetricRegistry;
import org.apache.flink.runtime.resourcemanager.StandaloneResourceManagerFactory;
import org.apache.flink.runtime.rpc.RpcService;
import org.apache.flink.runtime.rpc.RpcUtils;
import org.apache.flink.runtime.rpc.akka.AkkaRpcServiceUtils;
import org.apache.flink.runtime.testingUtils.TestingUtils;
import org.apache.flink.runtime.util.BlobServerResource;
import org.apache.flink.runtime.util.LeaderConnectionInfo;
import org.apache.flink.runtime.util.LeaderRetrievalUtils;
import org.apache.flink.runtime.util.TestingFatalErrorHandler;
import org.apache.flink.runtime.webmonitor.retriever.impl.VoidMetricQueryServiceRetriever;
import org.apache.flink.runtime.zookeeper.ZooKeeperResource;
import org.apache.flink.test.recovery.AbstractTaskManagerProcessFailureRecoveryTest.TaskExecutorProcessEntryPoint;
import org.apache.flink.test.util.TestProcessBuilder;
import org.apache.flink.test.util.TestProcessBuilder.TestProcess;
import org.apache.flink.util.TestLogger;
import org.apache.flink.util.function.CheckedSupplier;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors;
import static org.apache.flink.runtime.testutils.CommonTestUtils.getJavaCommandPath;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* This test makes sure that jobs are canceled properly in cases where
* the task manager went down and did not respond to cancel messages.
*/
@SuppressWarnings("serial")
public class ProcessFailureCancelingITCase extends TestLogger {
@Rule
public final BlobServerResource blobServerResource = new BlobServerResource();
@Rule
public final ZooKeeperResource zooKeeperResource = new ZooKeeperResource();
@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void testCancelingOnProcessFailure() throws Exception {
final Time timeout = Time.minutes(2L);
RestClusterClient<String> clusterClient = null;
TestProcess taskManagerProcess = null;
final TestingFatalErrorHandler fatalErrorHandler = new TestingFatalErrorHandler();
Configuration config = new Configuration();
config.setString(JobManagerOptions.ADDRESS, "localhost");
config.setString(AkkaOptions.ASK_TIMEOUT, "100 s");
config.setString(HighAvailabilityOptions.HA_MODE, "zookeeper");
config.setString(HighAvailabilityOptions.HA_ZOOKEEPER_QUORUM, zooKeeperResource.getConnectString());
config.setString(HighAvailabilityOptions.HA_STORAGE_PATH, temporaryFolder.newFolder().getAbsolutePath());
config.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, 2);
config.set(TaskManagerOptions.MANAGED_MEMORY_SIZE, MemorySize.parse("4m"));
config.set(TaskManagerOptions.NETWORK_MEMORY_MIN, MemorySize.parse("3200k"));
config.set(TaskManagerOptions.NETWORK_MEMORY_MAX, MemorySize.parse("3200k"));
config.set(TaskManagerOptions.TASK_HEAP_MEMORY, MemorySize.parse("128m"));
config.set(TaskManagerOptions.CPU_CORES, 1.0);
config.setInteger(RestOptions.PORT, 0);
final RpcService rpcService = AkkaRpcServiceUtils.createRpcService("localhost", 0, config);
final int jobManagerPort = rpcService.getPort();
config.setInteger(JobManagerOptions.PORT, jobManagerPort);
final DispatcherResourceManagerComponentFactory resourceManagerComponentFactory = DefaultDispatcherResourceManagerComponentFactory.createSessionComponentFactory(
StandaloneResourceManagerFactory.INSTANCE);
DispatcherResourceManagerComponent dispatcherResourceManagerComponent = null;
final ScheduledExecutorService ioExecutor = TestingUtils.defaultExecutor();
final HighAvailabilityServices haServices = HighAvailabilityServicesUtils.createHighAvailabilityServices(
config,
ioExecutor,
HighAvailabilityServicesUtils.AddressResolution.NO_ADDRESS_RESOLUTION);
try {
// check that we run this test only if the java command
// is available on this machine
if (getJavaCommandPath() == null) {
System.out.println("---- Skipping Process Failure test : Could not find java executable ----");
return;
}
dispatcherResourceManagerComponent = resourceManagerComponentFactory.create(
config,
ioExecutor,
rpcService,
haServices,
blobServerResource.getBlobServer(),
new HeartbeatServices(100L, 1000L),
NoOpMetricRegistry.INSTANCE,
new MemoryArchivedExecutionGraphStore(),
VoidMetricQueryServiceRetriever.INSTANCE,
fatalErrorHandler);
final Map<String, String> keyValues = config.toMap();
final ArrayList<String> commands = new ArrayList<>((keyValues.size() << 1) + 8);
TestProcessBuilder taskManagerProcessBuilder = new TestProcessBuilder(TaskExecutorProcessEntryPoint.class.getName());
taskManagerProcessBuilder.addConfigAsMainClassArgs(config);
taskManagerProcess = taskManagerProcessBuilder.start();
final Throwable[] errorRef = new Throwable[1];
// start the test program, which infinitely blocks
Runnable programRunner = new Runnable() {
@Override
public void run() {
try {
ExecutionEnvironment env = ExecutionEnvironment.createRemoteEnvironment("localhost", 1337, config);
env.setParallelism(2);
env.setRestartStrategy(RestartStrategies.noRestart());
env.generateSequence(0, Long.MAX_VALUE)
.map(new MapFunction<Long, Long>() {
@Override
public Long map(Long value) throws Exception {
synchronized (this) {
wait();
}
return 0L;
}
})
.output(new DiscardingOutputFormat<Long>());
env.execute();
}
catch (Throwable t) {
errorRef[0] = t;
}
}
};
Thread programThread = new Thread(programRunner);
// kill the TaskManager
programThread.start();
final DispatcherGateway dispatcherGateway = retrieveDispatcherGateway(rpcService, haServices);
waitUntilAllSlotsAreUsed(dispatcherGateway, timeout);
clusterClient = new RestClusterClient<>(config, "standalone");
final Collection<JobID> jobIds = waitForRunningJobs(clusterClient, timeout);
assertThat(jobIds, hasSize(1));
final JobID jobId = jobIds.iterator().next();
// kill the TaskManager after the job started to run
taskManagerProcess.destroy();
taskManagerProcess = null;
// try to cancel the job
clusterClient.cancel(jobId).get();
// we should see a failure within reasonable time (10s is the ask timeout).
// since the CI environment is often slow, we conservatively give it up to 2 minutes,
// to fail, which is much lower than the failure time given by the heartbeats ( > 2000s)
programThread.join(120000);
assertFalse("The program did not cancel in time (2 minutes)", programThread.isAlive());
Throwable error = errorRef[0];
assertNotNull("The program did not fail properly", error);
assertTrue(error.getCause() instanceof ProgramInvocationException);
// all seems well :-)
}
catch (Exception e) {
printProcessLog("TaskManager", taskManagerProcess.getOutput().toString());
throw e;
}
catch (Error e) {
printProcessLog("TaskManager 1", taskManagerProcess.getOutput().toString());
throw e;
}
finally {
if (taskManagerProcess != null) {
taskManagerProcess.destroy();
}
if (clusterClient != null) {
clusterClient.close();
}
if (dispatcherResourceManagerComponent != null) {
dispatcherResourceManagerComponent.deregisterApplicationAndClose(ApplicationStatus.SUCCEEDED, null);
}
fatalErrorHandler.rethrowError();
RpcUtils.terminateRpcService(rpcService, Time.seconds(100L));
haServices.closeAndCleanupAllData();
}
}
/**
* Helper method to wait until the {@link Dispatcher} has set its fencing token.
*
* @param rpcService to use to connect to the dispatcher
* @param haServices high availability services to connect to the dispatcher
* @return {@link DispatcherGateway}
* @throws Exception if something goes wrong
*/
static DispatcherGateway retrieveDispatcherGateway(RpcService rpcService, HighAvailabilityServices haServices) throws Exception {
final LeaderConnectionInfo leaderConnectionInfo = LeaderRetrievalUtils.retrieveLeaderConnectionInfo(
haServices.getDispatcherLeaderRetriever(),
Duration.ofSeconds(10L));
return rpcService.connect(
leaderConnectionInfo.getAddress(),
DispatcherId.fromUuid(leaderConnectionInfo.getLeaderSessionId()),
DispatcherGateway.class).get();
}
private void waitUntilAllSlotsAreUsed(DispatcherGateway dispatcherGateway, Time timeout) throws ExecutionException, InterruptedException {
FutureUtils.retrySuccessfulWithDelay(
() -> dispatcherGateway.requestClusterOverview(timeout),
Time.milliseconds(50L),
Deadline.fromNow(Duration.ofMillis(timeout.toMilliseconds())),
clusterOverview -> clusterOverview.getNumTaskManagersConnected() >= 1 &&
clusterOverview.getNumSlotsAvailable() == 0 &&
clusterOverview.getNumSlotsTotal() == 2,
TestingUtils.defaultScheduledExecutor())
.get();
}
private Collection<JobID> waitForRunningJobs(ClusterClient<?> clusterClient, Time timeout) throws ExecutionException, InterruptedException {
return FutureUtils.retrySuccessfulWithDelay(
CheckedSupplier.unchecked(clusterClient::listJobs),
Time.milliseconds(50L),
Deadline.fromNow(Duration.ofMillis(timeout.toMilliseconds())),
jobs -> !jobs.isEmpty(),
TestingUtils.defaultScheduledExecutor())
.get()
.stream()
.map(JobStatusMessage::getJobId)
.collect(Collectors.toList());
}
private void printProcessLog(String processName, String log) {
if (log == null || log.length() == 0) {
return;
}
System.out.println("-----------------------------------------");
System.out.println(" BEGIN SPAWNED PROCESS LOG FOR " + processName);
System.out.println("-----------------------------------------");
System.out.println(log);
System.out.println("-----------------------------------------");
System.out.println(" END SPAWNED PROCESS LOG");
System.out.println("-----------------------------------------");
}
}
| apache-2.0 |
itweet/itweet-boot | src/main/java/cn/itweet/modules/admin/document/entiry/Document.java | 1776 | package cn.itweet.modules.admin.document.entiry;
import javax.persistence.*;
import java.util.Date;
/**
* Created by whoami on 22/04/2017.
*/
@Entity
@Table(name = "document")
public class Document {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String filename;
@Column(name = "rule_filename")
private String ruleFilename;
private String type;
private Date date;
/**
* 图片所属栏目
*/
private String columnd;
public String getColumnd() {
return columnd;
}
public void setColumnd(String columnd) {
this.columnd = columnd;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getRuleFilename() {
return ruleFilename;
}
public void setRuleFilename(String ruleFilename) {
this.ruleFilename = ruleFilename;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "Document{" +
"id=" + id +
", filename='" + filename + '\'' +
", ruleFilename='" + ruleFilename + '\'' +
", type='" + type + '\'' +
", date=" + date +
'}';
}
}
| apache-2.0 |
vespa-engine/vespa | node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/container/RegistryCredentials.java | 1662 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.container;
import java.util.Objects;
/**
* Credentials for a container registry server.
*
* @author mpolden
*/
public class RegistryCredentials {
public static final RegistryCredentials none = new RegistryCredentials("", "", "");
private final String username;
private final String password;
private final String registryAddress;
public RegistryCredentials(String username, String password, String registryAddress) {
this.username = Objects.requireNonNull(username);
this.password = Objects.requireNonNull(password);
this.registryAddress = Objects.requireNonNull(registryAddress);
}
public String username() {
return username;
}
public String password() {
return password;
}
public String registryAddress() {
return registryAddress;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RegistryCredentials that = (RegistryCredentials) o;
return username.equals(that.username) &&
password.equals(that.password) &&
registryAddress.equals(that.registryAddress);
}
@Override
public int hashCode() {
return Objects.hash(username, password, registryAddress);
}
@Override
public String toString() {
return "registry credentials for " + registryAddress + " [username=" + username + ",password=" + password + "]";
}
}
| apache-2.0 |
cytotv/vk-server | method/store.getStickersKeywords.php | 108 | <?php
echo '{"response": {"base_url": "https://vk.com/images/stickers/","count": 0,"dictionary": []}}';
?> | apache-2.0 |
dante-mx/openbravopos | src-pos/com/openbravo/pos/config/PanelConfig.java | 1277 | // Openbravo POS is a point of sales application designed for touch screens.
// Copyright (C) 2007-2009 Openbravo, S.L.
// http://www.openbravo.com/product/pos
//
// This file is part of Openbravo POS.
//
// Openbravo POS is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Openbravo POS is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Openbravo POS. If not, see <http://www.gnu.org/licenses/>.
package com.openbravo.pos.config;
import java.awt.Component;
import com.openbravo.pos.forms.AppConfig;
/**
*
* @author adrianromero
*/
public interface PanelConfig {
public void loadProperties(AppConfig config);
public void saveProperties(AppConfig config);
public boolean hasChanged();
public Component getConfigComponent();
}
| apache-2.0 |
chingor13/google-cloud-php | RecaptchaEnterprise/src/V1/AnnotateAssessmentRequest/Annotation.php | 2605 | <?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/recaptchaenterprise/v1/recaptchaenterprise.proto
namespace Google\Cloud\RecaptchaEnterprise\V1\AnnotateAssessmentRequest;
use UnexpectedValueException;
/**
* Enum that reprensents the types of annotations.
*
* Protobuf type <code>google.cloud.recaptchaenterprise.v1.AnnotateAssessmentRequest.Annotation</code>
*/
class Annotation
{
/**
* Default unspecified type.
*
* Generated from protobuf enum <code>ANNOTATION_UNSPECIFIED = 0;</code>
*/
const ANNOTATION_UNSPECIFIED = 0;
/**
* Provides information that the event turned out to be legitimate.
*
* Generated from protobuf enum <code>LEGITIMATE = 1;</code>
*/
const LEGITIMATE = 1;
/**
* Provides information that the event turned out to be fraudulent.
*
* Generated from protobuf enum <code>FRAUDULENT = 2;</code>
*/
const FRAUDULENT = 2;
/**
* Provides information that the event was related to a login event in which
* the user typed the correct password.
*
* Generated from protobuf enum <code>PASSWORD_CORRECT = 3;</code>
*/
const PASSWORD_CORRECT = 3;
/**
* Provides information that the event was related to a login event in which
* the user typed the incorrect password.
*
* Generated from protobuf enum <code>PASSWORD_INCORRECT = 4;</code>
*/
const PASSWORD_INCORRECT = 4;
private static $valueToName = [
self::ANNOTATION_UNSPECIFIED => 'ANNOTATION_UNSPECIFIED',
self::LEGITIMATE => 'LEGITIMATE',
self::FRAUDULENT => 'FRAUDULENT',
self::PASSWORD_CORRECT => 'PASSWORD_CORRECT',
self::PASSWORD_INCORRECT => 'PASSWORD_INCORRECT',
];
public static function name($value)
{
if (!isset(self::$valueToName[$value])) {
throw new UnexpectedValueException(sprintf(
'Enum %s has no name defined for value %s', __CLASS__, $value));
}
return self::$valueToName[$value];
}
public static function value($name)
{
$const = __CLASS__ . '::' . strtoupper($name);
if (!defined($const)) {
throw new UnexpectedValueException(sprintf(
'Enum %s has no value defined for name %s', __CLASS__, $name));
}
return constant($const);
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(Annotation::class, \Google\Cloud\RecaptchaEnterprise\V1\AnnotateAssessmentRequest_Annotation::class);
| apache-2.0 |
sjcdigital/temis-api | src/main/java/com/sjcdigital/temis/model/document/OrdinarySession.java | 1773 | package com.sjcdigital.temis.model.document;
import java.time.LocalDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import com.fasterxml.jackson.annotation.JsonFormat;
/**
* @author fabiohbarbosa
*/
@Document
public class OrdinarySession {
@Id
private String id;
private Integer session;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
private LocalDate date;
@DBRef
private Alderman alderman;
private Boolean isPresent;
private AldermanSurrogate surrogate;
public OrdinarySession() {}
public OrdinarySession( final Integer session, final LocalDate date, final Alderman alderman,
final Boolean isPresent, final AldermanSurrogate surrogate) {
this.session = session;
this.date = date;
this.alderman = alderman;
this.isPresent = isPresent;
this.surrogate = surrogate;
}
public String getId() {
return id;
}
public void setId(final String id) {
this.id = id;
}
public Integer getSession() {
return session;
}
public void setSession(final Integer session) {
this.session = session;
}
public LocalDate getDate() {
return date;
}
public void setDate(final LocalDate date) {
this.date = date;
}
public Alderman getAlderman() {
return alderman;
}
public void setAlderman(final Alderman alderman) {
this.alderman = alderman;
}
public Boolean getPresent() {
return isPresent;
}
public void setPresent(final Boolean present) {
isPresent = present;
}
public AldermanSurrogate getSurrogate() {
return surrogate;
}
public void setSurrogate(final AldermanSurrogate surrogate) {
this.surrogate = surrogate;
}
}
| apache-2.0 |
pablow91/TheResistance | app/src/main/java/eu/stosdev/theresistance/screen/CardPickingScreen.java | 5258 | package eu.stosdev.theresistance.screen;
import android.os.Bundle;
import com.squareup.otto.Subscribe;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import eu.stosdev.theresistance.R;
import eu.stosdev.theresistance.model.card.EstablishConfidenceCard;
import eu.stosdev.theresistance.model.card.InstantPlotCard;
import eu.stosdev.theresistance.model.card.PlotCard;
import eu.stosdev.theresistance.model.card.RevealIdentityCard;
import eu.stosdev.theresistance.model.game.GameState;
import eu.stosdev.theresistance.model.game.Turn;
import eu.stosdev.theresistance.model.messages.AssignPlotCardMessage;
import eu.stosdev.theresistance.model.messages.DrawPlotCardMessage;
import eu.stosdev.theresistance.model.messages.utils.AbsEvent;
import eu.stosdev.theresistance.utils.MessageSender;
import eu.stosdev.theresistance.utils.TypedBus;
import eu.stosdev.theresistance.view.CardPickingView;
import eu.stosdev.theresistance.view.FabController;
import eu.stosdev.theresistance.view.ToolbarController;
import flow.Flow;
import flow.Layout;
import mortar.Blueprint;
import mortar.MortarScope;
import mortar.ViewPresenter;
@Layout(R.layout.card_picking)
public class CardPickingScreen implements Blueprint {
public CardPickingScreen() {
}
@Override public String getMortarScopeName() {
return getClass().getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(injects = CardPickingView.class, addsTo = GameMainScreen.Module.class)
public static class Module {
}
@Singleton
public static class Presenter extends ViewPresenter<CardPickingView> {
private final GameState gameState;
private final TypedBus<AbsEvent> bus;
private final String myParticipantId;
private final ToolbarController toolbarController;
private final FabController fabController;
private final Flow flow;
private final MessageSender messageSender;
private final Turn currentTurn;
@Inject
public Presenter(GameState gameState, TypedBus<AbsEvent> bus, @Named("myParticipantId") String myParticipantId, ToolbarController toolbarController, FabController fabController, @Named("game") Flow flow, MessageSender messageSender) {
this.gameState = gameState;
this.bus = bus;
this.myParticipantId = myParticipantId;
this.toolbarController = toolbarController;
this.fabController = fabController;
this.flow = flow;
this.messageSender = messageSender;
this.currentTurn = gameState.getCurrentTurn();
}
@Override protected void onEnterScope(MortarScope scope) {
bus.register(this);
}
@Override protected void onExitScope() {
bus.unregister(this);
}
@Override protected void onLoad(Bundle savedInstanceState) {
toolbarController.setTitle(R.string.card_picking);
toolbarController.setState(gameState.getCurrentLeader().getParticipantId().equals(myParticipantId));
getView().setCardList(currentTurn.getPickedCards());
checkedIfFinished();
}
@Subscribe public void subscribeDrawPloCardEvent(DrawPlotCardMessage.Event dpce) {
getView().notifyDataChangeSet();
checkedIfFinished();
}
@Subscribe public void subscribeAssignPlotCardMessage(AssignPlotCardMessage.Event apce) {
PlotCard plotCard = gameState.getCurrentTurn().getPickedCards().get(apce.getPlotCard());
getView().checkItem(plotCard);
if (plotCard.getType() == PlotCard.Type.INSTANT) {
if (plotCard.getOwner().equals(myParticipantId)) {
flow.goTo(((InstantPlotCard) plotCard).takeAction());
} else {
flow.goTo(new InstantCardSummaryScreen((RevealIdentityCard) plotCard));
}
} else {
checkedIfFinished();
}
}
private void checkedIfFinished() {
if (currentTurn.getCurrentState() != Turn.State.CARD_PICKING) {
fabController.show(new Runnable() {
@Override public void run() {
flow.goTo(new ChooseTeamScreen());
}
});
}
}
public void onCardSelected(int position) {
PlotCard plotCard = currentTurn.getPickedCards().get(position);
if (plotCard.getOwner() == null) {
if (myParticipantId.equals(gameState.getCurrentLeader().getParticipantId())) {
if (plotCard instanceof EstablishConfidenceCard) {
messageSender.sendMessage(new AssignPlotCardMessage(position, gameState.getCurrentLeader().getParticipantId()));
} else {
flow.goTo(new SelectPlayerForCardScreen(position, plotCard));
}
}
} else if (plotCard.getType() == PlotCard.Type.INSTANT) {
flow.goTo(new InstantCardSummaryScreen((RevealIdentityCard) plotCard));
}
}
}
}
| apache-2.0 |
JaCraig/Canister | SimpleMVCTests/Models/ErrorViewModel.cs | 222 | using System;
namespace SimpleMVCTests.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
} | apache-2.0 |
riganti/infrastructure | src/Infrastructure/Riganti.Utils.Infrastructure.Services/ICurrentUserProvider.cs | 288 | namespace Riganti.Utils.Infrastructure.Services
{
public interface ICurrentUserProvider<out TKey>
{
TKey Id { get; }
string UserName { get; }
string DisplayName { get; }
string Email { get; }
bool IsInRole(string roleName);
}
}
| apache-2.0 |
SciGaP/seagrid-rich-client | src/main/java/gamess/Cosmetics.java | 5078 | package gamess;
import java.awt.Color;
import javax.swing.text.AttributeSet;
import javax.swing.text.Element;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.Highlighter.HighlightPainter;
public class Cosmetics
{
//Underliners
private static final WavedUnderlinePen ERROR_UNDERLINE_PEN = new WavedUnderlinePen(Color.RED);
private static final WavedUnderlinePen WARNING_UNDERLINE_PEN = new WavedUnderlinePen(Color.YELLOW);
//Attributes
public static final SimpleAttributeSet NORMAL_ATTRIBUTE = new SimpleAttributeSet();
public static final SimpleAttributeSet GROUP_ATTRIBUTE = new SimpleAttributeSet();
public static final SimpleAttributeSet COMMENTS_ATTRIBUTE = new SimpleAttributeSet();
public static final SimpleAttributeSet KEYWORD_ATTRIBUTE = new SimpleAttributeSet();
public static final SimpleAttributeSet ERROR_UNDERLINE = new SimpleAttributeSet();
public static final SimpleAttributeSet WARNING_UNDERLINE = new SimpleAttributeSet();
//Colors
public static final Color NORMAL_ATTRIBUTE_COLOR = Color.BLACK;
public static final Color GROUP_ATTRIBUTE_COLOR = Color.RED;
public static final Color KEYWORD_ATTRIBUTE_COLOR = Color.BLUE;
static
{
//Normal AttributeSet
StyleConstants.setForeground(NORMAL_ATTRIBUTE, NORMAL_ATTRIBUTE_COLOR);
StyleConstants.setBold(NORMAL_ATTRIBUTE, false);
//Group AttributeSet
//StyleConstants.setForeground(GROUP_ATTRIBUTE, Color.getHSBColor(4.83456203f,.67f,.44f));
StyleConstants.setForeground(GROUP_ATTRIBUTE, GROUP_ATTRIBUTE_COLOR);
StyleConstants.setBold(GROUP_ATTRIBUTE, true);
//Comment AttributeSet
StyleConstants.setForeground(COMMENTS_ATTRIBUTE, Color.getHSBColor(1.35f, .63f, .71f));
StyleConstants.setBold(COMMENTS_ATTRIBUTE, false);
//Keyword attribute
StyleConstants.setForeground(KEYWORD_ATTRIBUTE, KEYWORD_ATTRIBUTE_COLOR);
StyleConstants.setBold(KEYWORD_ATTRIBUTE, false);
//Error Underline
ERROR_UNDERLINE.addAttribute("UNDERLINEPEN", ERROR_UNDERLINE_PEN);
//Warning Underline
WARNING_UNDERLINE.addAttribute("UNDERLINEPEN", WARNING_UNDERLINE_PEN);
}
public static final SimpleAttributeSet getCustomAttribute(String key, Object value)
{
SimpleAttributeSet toolTipAttribute = new SimpleAttributeSet();
toolTipAttribute.addAttribute(key, value);
return toolTipAttribute;
}
public static final SimpleAttributeSet getCustomAttribute(String key, Object value, AttributeSet existingAttribute)
{
SimpleAttributeSet toolTipAttribute = getCustomAttribute(key, value);
if(existingAttribute != null)
{
toolTipAttribute.setResolveParent(existingAttribute);
}
return toolTipAttribute;
}
public static final void setCharacterAttributes(int startOffset , int length , AttributeSet attribute, boolean replace)
{
StyledDocument styledDocument = GamessGUI.inputFilePane.getStyledDocument();
Element element = null;
element = styledDocument.getCharacterElement(startOffset);
//Do not do anything if the element already contains the same attribute
if(element.getAttributes().containsAttributes(attribute) && replace == false)
return;
styledDocument.setCharacterAttributes(startOffset, length, attribute, replace);
}
public static final void setParagraphAttributes(int startOffset , int length , AttributeSet attribute)
{
StyledDocument styledDocument = GamessGUI.inputFilePane.getStyledDocument();
Element element = null;
element = styledDocument.getParagraphElement(startOffset);
//Do not do anything if the element already contains the same attribute
if(element.getAttributes().containsAttributes(attribute))
return;
styledDocument.setParagraphAttributes(startOffset, length, attribute, true);
setCharacterAttributes(startOffset, length, attribute, true);
}
public static final void setUnderline(int startOffset , int length , AttributeSet attribute)
{
StyledDocument styledDocument = GamessGUI.inputFilePane.getStyledDocument();
styledDocument.setCharacterAttributes(startOffset, length, getCustomAttribute("UNDERLINE", (HighlightPainter)attribute.getAttribute("UNDERLINEPEN")), false);
}
public static final void setTooltip(int startOffset , int length , String tooltip)
{
StyledDocument styledDocument = GamessGUI.inputFilePane.getStyledDocument();
styledDocument.setCharacterAttributes(startOffset, length, getCustomAttribute("TOOLTIP", tooltip), false);
}
public static final String getFormattedToolTip(String tooltip)
{
//previous value was #E6BE8A
return "<html><body bgcolor=#FFFAD2 rightmargin=0 topmargin=0 bottommargin=0 leftmargin=0>" + tooltip.replace("\n", "<br/>") + "</body></html>";
}
public static final String getInputFileToolTip(String tooltip)
{
return "<html><body>" + tooltip.replace("\n", "<br/>") + "</body></html>";
}
public static final String getMenuToolTip(String tooltip)
{
return "<html><body bgcolor=#FFFAD2 rightmargin=0 topmargin=0 bottommargin=0 leftmargin=0>" + tooltip.replace("\n", "<br/>") + "</body></html>";
}
}
| apache-2.0 |
ironfoundry-attic/vcap-client | src/IronFoundry.VcapClient/Models/StatInfo.cs | 615 | // -----------------------------------------------------------------------
// <copyright file="StatInfo.cs" company="Tier 3">
// Copyright © 2012 Tier 3 Inc., All Rights Reserved
// </copyright>
// -----------------------------------------------------------------------
using Newtonsoft.Json;
namespace IronFoundry.Models
{
public class StatInfo : EntityBase
{
[JsonProperty(PropertyName = "state")]
public string State { get; set; }
[JsonProperty(PropertyName = "stats")]
public Stats Stats { get; set; }
[JsonIgnore]
public int ID { get; set; }
}
} | apache-2.0 |
kidaa/kythe | kythe/cxx/indexer/cxx/testdata/template/template_class_template_ctor.cc | 795 | // Checks that we properly handle classes with constructor templates.
//- @foo defines/binding FnFoo
//- FnFoo callableas FooC
int foo() { return 0; }
//- @bar defines/binding FnBar
//- FnBar callableas BarC
int bar() { return 0; }
class C {
public:
template <typename T>
//- FooCall=@"foo()" ref/call FooC
//- FooCall childof CtorC
//- @C defines/binding AbsCtorC
//- CtorC childof AbsCtorC
//- !{ BarCall childof CtorC }
//- BarCallJ childof CtorC
C(T) : i(foo()) { }
//- BarCall=@"bar()" ref/call BarC
int i = bar();
//- BarCallJ=@"bar()" ref/call BarC
int j = bar();
};
template <> C::
//- FooCall2=@"foo()" ref/call FooC
//- FooCall2 childof CtorC2
//- @C defines/binding CtorC2
//- !{ BarCall childof CtorC2 }
//- BarCallJ childof CtorC2
C(float) : i(foo()) { }
| apache-2.0 |
josdavidmo/orion | lang/es-co/instrumentos-es.php | 2284 | <?php
define('PAGINAS', 5);
define('TITULO_INSTRUMENTOS', 'Instrumentos');
define('CODIGO_INSTRUMENTO', 'Código');
define('NOMBRE_INSTRUMENTO', 'Nombre');
define('SECCIONES_INSTRUMENTO', 'Secciones');
define('PREGUNTAS_INSTRUMENTO', 'Preguntas');
define('REQUERIDO_PREGUNTA', 'Requerido');
define('ENUNCIADO_PREGUNTA', 'Enunciado');
define('TIPO_PREGUNTA', 'Tipo');
define('SUBTIPO_PREGUNTA', 'Subtipo');
define('LONGITUD_PREGUNTA', 'Longitud');
define('OPCIONES_RESPUESTAS_PREGUNTA', 'Opciones Respuestas');
define('PREGUNTAS_INSTRUMENTO', 'Preguntas');
define('TITULO_INSTRUMENTOS', 'Instrumentos');
define('TITULO_EDITAR_INSTRUMENTO', 'Editar Instrumento');
define('TITULO_AGREGAR_PREGUNTA', 'Agregar Pregunta');
define('TITULO_EDITAR_PREGUNTA', 'Editar Pregunta');
define('ENCUESTA_AGREGADA_EXITO', 'La Encuesta ha sido agregada con éxito');
define('PREGUNTA_AGREGADA_EXITO', 'La Pregunta ha sido agregada con éxito');
define('PREGUNTA_AGREGADA_ERROR', 'Ocurrio un error al insertar la pregunta');
define('BORRAR_INSTRUMENTO', 'Desea borrar el instrumento');
define('EXITO_BORRAR_INSTRUMENTO', 'El Instrumento ha sido borrado con éxito');
define('ERROR_BORRAR_INSTRUMENTO', 'Ocurrio un error al borrar el instrumento');
define('BORRAR_SECCION', 'Desea borrar la sección');
define('BORRAR_PREGUNTA', 'Desea borrar la pregunta');
define('EXITO_BORRAR_SECCION', 'La Sección ha sido borrada con éxito');
define('ERROR_BORRAR_SECCION', 'Ocurrio un error al borrar la sección');
define('EXITO_BORRAR_PREGUNTA', 'La Pregunta ha sido borrada con éxito');
define('ERROR_BORRAR_PREGUNTA', 'Ocurrio un error al borrar la pregunta');
define('EXITO_ACTUALIZAR_PREGUNTA', 'La Pregunta ha sido actualizada con éxito');
define('ERROR_ACTUALIZAR_PREGUNTA', 'Ocurrio un error al actualizar la pregunta');
define('ERROR_ACTUALIZAR_INSTRUMENTO', 'Ocurrio un error al actualizar el instrumento');
define('EXITO_ACTUALIZAR_INSTRUMENTO', 'El instrumento ha sido actualizado con éxito');
define('INSTRUMENTO', 'Instrumento');
define('TIPO_INSTRUMENTO', 'Tipo de Instrumento');
define('ENCUESTA_AGREGADA_FRACASO', 'Ocurrio un error al insertar el instrumento <hr> Verique que el código no este duplicado');
define('ENCABEZADO_INTRUMENTO', 'Módulo');
?>
| apache-2.0 |
dims/neutron | neutron/pecan_wsgi/hooks/policy_enforcement.py | 9507 | # Copyright (c) 2015 Mirantis, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
from oslo_policy import policy as oslo_policy
from oslo_utils import excutils
from pecan import hooks
import webob
from neutron._i18n import _
from neutron.api.v2 import attributes as v2_attributes
from neutron.common import constants as const
from neutron.extensions import quotasv2
from neutron import manager
from neutron.pecan_wsgi import constants as pecan_constants
from neutron.pecan_wsgi.controllers import quota
from neutron import policy
def _custom_getter(resource, resource_id):
"""Helper function to retrieve resources not served by any plugin."""
if resource == quotasv2.RESOURCE_NAME:
return quota.get_tenant_quotas(resource_id)[quotasv2.RESOURCE_NAME]
class PolicyHook(hooks.PecanHook):
priority = 140
def _fetch_resource(self, neutron_context, resource, resource_id):
attrs = v2_attributes.get_resource_info(resource)
field_list = [name for (name, value) in attrs.items()
if (value.get('required_by_policy') or
value.get('primary_key') or 'default' not in value)]
plugin = manager.NeutronManager.get_plugin_for_resource(resource)
if plugin:
getter = getattr(plugin, 'get_%s' % resource)
# TODO(kevinbenton): the parent_id logic currently in base.py
return getter(neutron_context, resource_id, fields=field_list)
else:
# Some legit resources, like quota, do not have a plugin yet.
# Retrieving the original object is nevertheless important
# for policy checks.
return _custom_getter(resource, resource_id)
def before(self, state):
# This hook should be run only for PUT,POST and DELETE methods and for
# requests targeting a neutron resource
resources = state.request.context.get('resources', [])
if state.request.method not in ('POST', 'PUT', 'DELETE'):
return
# As this routine will likely alter the resources, do a shallow copy
resources_copy = resources[:]
neutron_context = state.request.context.get('neutron_context')
resource = state.request.context.get('resource')
# If there is no resource for this request, don't bother running authZ
# policies
if not resource:
return
collection = state.request.context.get('collection')
needs_prefetch = (state.request.method == 'PUT' or
state.request.method == 'DELETE')
policy.init()
action = '%s_%s' % (pecan_constants.ACTION_MAP[state.request.method],
resource)
# NOTE(salv-orlando): As bulk updates are not supported, in case of PUT
# requests there will be only a single item to process, and its
# identifier would have been already retrieved by the lookup process;
# in the case of DELETE requests there won't be any item to process in
# the request body
merged_resources = []
if needs_prefetch:
try:
item = resources_copy.pop()
except IndexError:
# Ops... this was a delete after all!
item = {}
resource_id = state.request.context.get('resource_id')
obj = copy.copy(self._fetch_resource(neutron_context,
resource,
resource_id))
obj.update(item)
merged_resources.append(obj.copy())
obj[const.ATTRIBUTES_TO_UPDATE] = item.keys()
# Put back the item in the list so that policies could be enforced
resources_copy.append(obj)
# TODO(salv-orlando): as other hooks might need to prefetch resources,
# store them in the request context. However, this should be done in a
# separate hook which is conventietly called before all other hooks
state.request.context['request_resources'] = merged_resources
for item in resources_copy:
try:
policy.enforce(
neutron_context, action, item,
pluralized=collection)
except oslo_policy.PolicyNotAuthorized:
with excutils.save_and_reraise_exception() as ctxt:
# If a tenant is modifying it's own object, it's safe to
# return a 403. Otherwise, pretend that it doesn't exist
# to avoid giving away information.
if (needs_prefetch and
neutron_context.tenant_id != item['tenant_id']):
ctxt.reraise = False
msg = _('The resource could not be found.')
raise webob.exc.HTTPNotFound(msg)
def after(self, state):
neutron_context = state.request.context.get('neutron_context')
resource = state.request.context.get('resource')
collection = state.request.context.get('collection')
if not resource:
# can't filter a resource we don't recognize
return
# NOTE(kevinbenton): extension listing isn't controlled by policy
if resource == 'extension':
return
try:
data = state.response.json
except ValueError:
return
action = '%s_%s' % (pecan_constants.ACTION_MAP[state.request.method],
resource)
if not data or (resource not in data and collection not in data):
return
is_single = resource in data
key = resource if is_single else collection
to_process = [data[resource]] if is_single else data[collection]
# in the single case, we enforce which raises on violation
# in the plural case, we just check so violating items are hidden
policy_method = policy.enforce if is_single else policy.check
plugin = manager.NeutronManager.get_plugin_for_resource(resource)
try:
resp = [self._get_filtered_item(state.request, resource,
collection, item)
for item in to_process
if (state.request.method != 'GET' or
policy_method(neutron_context, action, item,
plugin=plugin,
pluralized=collection))]
except oslo_policy.PolicyNotAuthorized as e:
# This exception must be explicitly caught as the exception
# translation hook won't be called if an error occurs in the
# 'after' handler.
raise webob.exc.HTTPForbidden(e.message)
if is_single:
resp = resp[0]
state.response.json = {key: resp}
def _get_filtered_item(self, request, resource, collection, data):
neutron_context = request.context.get('neutron_context')
to_exclude = self._exclude_attributes_by_policy(
neutron_context, resource, collection, data)
return self._filter_attributes(request, data, to_exclude)
def _filter_attributes(self, request, data, fields_to_strip):
# TODO(kevinbenton): this works but we didn't allow the plugin to
# only fetch the fields we are interested in. consider moving this
# to the call
user_fields = request.params.getall('fields')
return dict(item for item in data.items()
if (item[0] not in fields_to_strip and
(not user_fields or item[0] in user_fields)))
def _exclude_attributes_by_policy(self, context, resource,
collection, data):
"""Identifies attributes to exclude according to authZ policies.
Return a list of attribute names which should be stripped from the
response returned to the user because the user is not authorized
to see them.
"""
attributes_to_exclude = []
for attr_name in data.keys():
attr_data = v2_attributes.get_resource_info(
resource).get(attr_name)
if attr_data and attr_data['is_visible']:
if policy.check(
context,
# NOTE(kevinbenton): this used to reference a
# _plugin_handlers dict, why?
'get_%s:%s' % (resource, attr_name),
data,
might_not_exist=True,
pluralized=collection):
# this attribute is visible, check next one
continue
# if the code reaches this point then either the policy check
# failed or the attribute was not visible in the first place
attributes_to_exclude.append(attr_name)
return attributes_to_exclude
| apache-2.0 |
soundcloud/gocd | config/config-api/src/com/thoughtworks/go/config/elastic/ElasticProfile.java | 1512 | /*
* Copyright 2016 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.config.elastic;
import com.thoughtworks.go.config.ConfigCollection;
import com.thoughtworks.go.config.ConfigTag;
import com.thoughtworks.go.config.PluginProfile;
import com.thoughtworks.go.domain.config.ConfigurationProperty;
import java.util.Collection;
@ConfigTag("profile")
@ConfigCollection(value = ConfigurationProperty.class)
public class ElasticProfile extends PluginProfile {
public ElasticProfile() {
super();
}
public ElasticProfile(String id, String pluginId, ConfigurationProperty... props) {
super(id, pluginId, props);
}
public ElasticProfile(String id, String pluginId, Collection<ConfigurationProperty> configProperties) {
this(id, pluginId, configProperties.toArray(new ConfigurationProperty[0]));
}
@Override
protected String getObjectDescription() {
return "Elastic agent profile";
}
}
| apache-2.0 |
Ruviel21/rpahomov | chapter_001/src/main/java/ru/job4j/tictactoe/Logic3T.java | 2682 | package ru.job4j.tictactoe;
public class Logic3T {
private final Figure3T[][] table;
public Logic3T(Figure3T[][] table) {
this.table = table;
}
public boolean isWinnerX() {
boolean result = false;
if (table[0][0].hasMarkX() & table[1][1].hasMarkX() & table[2][2].hasMarkX()) {
return true;
} else if (table[0][0].hasMarkX() & table[0][1].hasMarkX() & table[0][2].hasMarkX()) {
return true;
} else if (table[1][0].hasMarkX() & table[1][1].hasMarkX() & table[1][2].hasMarkX()) {
return true;
} else if (table[2][0].hasMarkX() & table[2][1].hasMarkX() & table[2][2].hasMarkX()) {
return true;
} else if (table[0][0].hasMarkX() & table[1][0].hasMarkX() & table[2][0].hasMarkX()) {
return true;
} else if (table[0][1].hasMarkX() & table[1][1].hasMarkX() & table[2][1].hasMarkX()) {
return true;
} else if (table[0][2].hasMarkX() & table[1][2].hasMarkX() & table[2][2].hasMarkX()) {
return true;
} else if (table[2][0].hasMarkX() & table[1][1].hasMarkX() & table[0][2].hasMarkX()) {
return true;
}
return result;
}
public boolean isWinnerO() {
boolean result = false;
if (table[0][0].hasMarkO() & table[1][1].hasMarkO() & table[2][2].hasMarkO()) {
return true;
} else if (table[0][0].hasMarkO() & table[0][1].hasMarkO() & table[0][2].hasMarkO()) {
return true;
} else if (table[1][0].hasMarkO() & table[1][1].hasMarkO() & table[1][2].hasMarkO()) {
return true;
} else if (table[2][0].hasMarkO() & table[2][1].hasMarkO() & table[2][2].hasMarkO()) {
return true;
} else if (table[0][0].hasMarkO() & table[1][0].hasMarkO() & table[2][0].hasMarkO()) {
return true;
} else if (table[0][1].hasMarkO() & table[1][1].hasMarkO() & table[2][1].hasMarkO()) {
return true;
} else if (table[0][2].hasMarkO() & table[1][2].hasMarkO() & table[2][2].hasMarkO()) {
return true;
} else if (table[2][0].hasMarkO() & table[1][1].hasMarkO() & table[0][2].hasMarkO()) {
return true;
}
return result;
}
public boolean hasGap() {
boolean result = false;
for (int first = 0; first < this.table.length; first++) {
for (int second = 0; second < this.table.length; second++) {
if (!table[first][second].hasMarkX() & !table[first][second].hasMarkO()) {
result = true;
}
}
}
return result;
}
} | apache-2.0 |
IHTSDO/snow-owl | snomed/com.b2international.snowowl.snomed.importer/src/com/b2international/snowowl/snomed/importer/net4j/DefectType.java | 4386 | /*
* Copyright 2011-2018 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.snomed.importer.net4j;
public enum DefectType {
HEADER_DIFFERENCES("Header format is different from the standard format defined by IHTSDO", false),
INCORRECT_COLUMN_NUMBER("Incorrect column number in release file"),
INVALID_ID("Component identifier is not of the expected type, malformed, or has an incorrect Verhoeff check digit."),
MODULE_CONCEPT_NOT_EXIST("Module concept does not exist"),
NOT_UNIQUE_DESCRIPTION_ID("Description identifier is not unique"),
NOT_UNIQUE_FULLY_SPECIFIED_NAME("Fully specified name is not unique", false),
CONCEPT_DEFINITION_STATUS_NOT_EXIST("Concept refers to a non-existing concept in column 'definitionStatusId'"),
DESCRIPTION_CONCEPT_NOT_EXIST("Description refers to a non-existing concept in column 'conceptId'"),
DESCRIPTION_TYPE_NOT_EXIST("Description refers to a non-existing concept in column 'typeId'"),
DESCRIPTION_CASE_SIGNIFICANCE_NOT_EXIST("Description refers to a non-existing concept in column 'caseSignificanceId'"),
NOT_UNIQUE_RELATIONSHIP_ID("Relationship identifier is not unique"),
RELATIONSHIP_SOURCE_DESTINATION_EQUALS("Relationship source and destination identifiers are equal"),
RELATIONSHIP_REFERENCED_NONEXISTENT_CONCEPT("Relationship refers to a non-existing component"),
RELATIONSHIP_REFERENCED_INACTIVE_CONCEPT("Relationship refers to a inactive component", false),
INCORRECT_REFSET_MEMBER_ID("Reference set member identifier is not a valid universally unique identifier"),
NOT_UNIQUE_REFSET_MEMBER_ID("Reference set member identifier is not unique"),
REFSET_MEMBER_COMPONENT_NOT_EXIST("Reference set member refers to a non-existing component in column 'referencedComponentId'"),
ATTRIBUTE_REFSET_VALUE_CONCEPT_NOT_EXIST("Attribute value reference set member refers to a non-existing concept in column 'valueId'"),
CONCRETE_DOMAIN_VALUE_IS_EMPTY("Concrete domain reference set member value is empty in column 'value'"),
CONCRETE_DOMAIN_TYPE_CONCEPT_NOT_EXIST("Concrete domain reference set member refers to a non-existing concept in column 'typeId'"),
CONCRETE_DOMAIN_CHARACTERISTIC_TYPE_CONCEPT_NOT_EXIST("Concrete domain reference set member refers to a non-existing concept in column 'characteristicTypeId'"),
SIMPLE_MAP_TARGET_IS_EMPTY("Simple map type reference set member target is empty in column 'mapTarget'"),
DESCRIPTION_TYPE_DESCRIPTION_FORMAT_NOT_EXIST("Description type reference set member refers to a non-existing concept in column 'descriptionFormat'"),
DESCRIPTION_TYPE_DESCRIPTION_LENGTH_IS_EMPTY("Description type reference set member value is empty in column 'descriptionLength'"),
ASSOCIATION_REFSET_TARGET_COMPONENT_NOT_EXIST("Association reference set member refers to a non-existing concept in column 'targetComponentId'"),
COMPLEX_MAP_REFERENCED_INVALID_CONCEPT("Complex map reference set member refers to a non-existing concept"),
EXTENDED_MAP_REFERENCED_INVALID_CONCEPT("Extended map reference set member refers to a non-existing concept"),
INVALID_EFFECTIVE_TIME_FORMAT("Effective time format is not valid. Acceptable effective time format is 'yyyyMMdd'."),
INCONSISTENT_TAXONOMY("The concepts below are referenced in active IS A relationships, but are inactive or otherwise not known.", false),
IO_PROBLEM("Encountered an I/O error while running validation."),
EMPTY_REFSET_MEMBER_FIELD("Reference set member field is empty");
private final String label;
private final boolean critical;
private DefectType(final String label) {
this(label, true);
}
private DefectType(final String label, final boolean critical) {
this.label = label;
this.critical = critical;
}
@Override
public String toString() {
return label;
}
public boolean isCritical() {
return critical;
}
}
| apache-2.0 |
timdown/log4javascript2 | src/core.js | 15054 | var log4javascript = (function(globalObj) {
var UNDEFINED = "undefined",
STRING = "string",
NUMBER = "number",
OBJECT = "object",
FUNCTION = "function",
UNKNOWN = "unknown",
startUpTime = new Date(),
environment,
objectToString = Object.prototype.toString;
/* ---------------------------------------------------------------------- */
function Log4JavaScript() {}
var api = new Log4JavaScript();
/* ---------------------------------------------------------------------- */
/* Array-related */
var arrayPrototype = Array.prototype;
var arrayIndexOf = arrayPrototype.indexOf ?
function(arr, val) {
return arr.indexOf(val);
} :
function(arr, val) {
for (var i = 0, len = arr.length; i < len; ++i) {
if (arr[i] === val) {
return i;
}
}
return -1;
};
function forEachArrayLike(arr, callback, thisObject) {
var val;
if (typeof callback != FUNCTION) {
throw new TypeError();
}
thisObject = thisObject || globalObj;
for (var i = 0, len = arr.length; i < len; ++i) {
val = arr[i];
if (typeof val != "undefined") {
callback.call(thisObject, val, i, arr);
}
}
}
var forEach = (typeof arrayPrototype.forEach == FUNCTION) ?
function(arr, callback, thisObject) {
return arr.forEach(callback, thisObject);
} :
forEachArrayLike;
function arrayRemove(arr, val) {
var index = arrayIndexOf(arr, val);
if (index >= 0) {
arr.splice(index, 1);
return true;
} else {
return false;
}
}
function arrayContains(arr, val) {
return arrayIndexOf(arr, val) > -1;
}
function toArray(args, startIndex, endIndex) {
return Array.prototype.slice.call(args, startIndex, endIndex);
}
var nodeListExists = (typeof globalObj.NodeList != UNDEFINED),
htmlCollectionExists = (typeof globalObj.HTMLCollection != UNDEFINED);
/*
We want anything Array-like to be treated as an array in expansions, including host collections such as NodeList
and HTMLCollection. The function for most environments first checks instanceof, then tries the so-called
'Miller Method', then tries duck typing for a finite length property and presence of a splice method, checks for
arguments collection and finally checks for some the array-like host objects NodeList and HTMLCollection.
*/
function isArrayLike(o) {
return o instanceof Array ||
objectToString.call(o) == "[object Array]" ||
(typeof o == OBJECT && isFinite(o.length) &&
/* Duck typing check for Array objects, arguments objects and IE node lists respectively */
(typeof o.splice != UNDEFINED || typeof o.callee == FUNCTION || typeof o.item != UNDEFINED) ) ||
(nodeListExists && o instanceof globalObj.NodeList) ||
(htmlCollectionExists && o instanceof globalObj.HTMLCollection);
}
/* ---------------------------------------------------------------------- */
// Trio of functions taken from Peter Michaux's article:
// http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
function isHostMethod(o, p) {
var t = typeof o[p];
return t == FUNCTION || (!!(t == OBJECT && o[p])) || t == UNKNOWN;
}
function isHostObject(o, p) {
return !!(typeof o[p] == OBJECT && o[p]);
}
function isHostProperty(o, p) {
return typeof o[p] != UNDEFINED;
}
var hostConsoleExists = isHostObject(globalObj, "console");
api.hostConsoleExists = hostConsoleExists;
/* ---------------------------------------------------------------------- */
/* Custom events, implemented as a mixin */
var addCustomEventSupport = (function() {
function createListenersArray(obj, eventType) {
var created = false;
var listeners = obj.eventListeners;
if (!listeners) {
obj.eventListeners = listeners = {};
}
if (!listeners[eventType]) {
listeners[eventType] = [];
created = true;
}
return created;
}
function addEventListener(eventType, listener) {
createListenersArray(this, eventType);
this.eventListeners[eventType].push(listener);
}
function removeEventListener(eventType, listener) {
if (!createListenersArray(this, eventType)) {
arrayRemove(this.eventListeners[eventType], listener);
}
}
function dispatchEvent(eventType, eventArgs) {
if (!createListenersArray(this, eventType)) {
var listeners = this.eventListeners[eventType].slice(0);
for (var i = 0, len = listeners.length; i < len; ++i) {
listeners[i](this, eventType, eventArgs);
}
}
}
return function(obj) {
obj.addEventListener = addEventListener;
obj.removeEventListener = removeEventListener;
obj.dispatchEvent = dispatchEvent;
};
})();
/* ---------------------------------------------------------------------- */
addCustomEventSupport(Log4JavaScript.prototype);
api.version = "2.0";
api.startUpTime = startUpTime;
api.uniqueId = "log4javascript_" + (+startUpTime) + "_" + Math.floor(Math.random() * 1e8);
api.enabled = !( (typeof globalObj.log4javascript_disabled != UNDEFINED) && globalObj.log4javascript_disabled );
api.addCustomEventSupport = addCustomEventSupport;
api.globalObj = globalObj;
api.showStackTraces = false;
function reportError(message, exception) {
api.dispatchEvent("error", { "message": message, "exception": exception });
}
api.reportError = reportError;
api.Arrays = {
indexOf: arrayIndexOf,
remove: arrayRemove,
contains: arrayContains,
toArray: toArray,
isArrayLike: isArrayLike,
forEach: forEach,
forEachArrayLike: forEachArrayLike
};
/* ---------------------------------------------------------------------- */
/* Core feature tests */
function failCoreFeatureTests(failedTestName) {
var fullMessage = "Your environment does not support all the features required by log4javascript." +
"Test failed: " + failedTestName;
if (window) {
fullMessage += [
"\n\nlog4javascript is known to work in the following browsers:\n",
"- Firefox 3.0 and higher",
"- Internet Explorer 7 and higher",
"- Google Chrome",
"- Safari 4 and higher",
"- Opera 9 and higher"
].join("\n");
}
alert(fullMessage);
}
var featureTests = [];
function addFeatureTest(name, testFunc) {
featureTests[featureTests.length] = [name, testFunc];
}
api.addFeatureTest = addFeatureTest;
api.failModule = function(moduleName, message) {
if (hostConsoleExists) {
globalObj.console.log("log4javascript module " + moduleName + " failed to load. Reason: " + message);
}
};
/* ---------------------------------------------------------------------- */
/* Utility functions */
/*
Checks if the specified property can successfully be evaluated on the specified object. This is designed to work
on all objects, including host objects
*/
function canEvaluateProperty(obj, prop) {
var t = typeof obj[prop];
return t != UNKNOWN;
}
api.canEvaluateProperty = canEvaluateProperty;
function toStr(obj) {
if (typeof obj == STRING) {
return obj;
} else {
try {
return String(obj);
} catch (e) {
try {
return objectToString.call(obj);
} catch (eInner) {
return "";
}
}
}
}
function splitIntoLines(str) {
// Normalize all line breaks to just \n and then split on \n
return str.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
}
// Returns a string consisting of len concatenated copies of str
// TODO: Research most efficient way of doing this
function createCharString(str, len) {
var a = [];
a.length = len + 1;
return a.join(str);
}
function leftPad(str, len, padStr) {
return len > 0 ? createCharString(padStr, len) + str : str;
}
function rightPad(str, len, padStr) {
return len > 0 ? str + createCharString(padStr, len) : str;
}
// TODO: Research errors properly
var isError = (function() {
var errorConstructors = [];
var errorPotentialConstructors = [globalObj.Error, globalObj.DOMException, globalObj.RangeException,
globalObj.EventException];
var i = errorPotentialConstructors.length, c;
while (i--) {
c = errorPotentialConstructors[i];
if (typeof c != UNDEFINED) {
errorConstructors.push(c);
}
}
return function(o) {
var i = errorConstructors.length, c;
while (i--) {
c = errorConstructors[i];
if (o instanceof c) {
return true;
}
}
return false;
};
})();
api.isError = isError;
var hasOwnPropertyExists = !!{}.hasOwnProperty;
api.addFeatureTest("hasOwnProperty", function() {
return hasOwnPropertyExists;
});
var extend, extendHostObject;
if (hasOwnPropertyExists) {
api.extend = extend = function(obj, props, deep) {
var o, p;
if (props) {
for (var i in props) {
if (props.hasOwnProperty(i)) {
o = obj[i];
p = props[i];
if (deep && (typeof p == "object") && !isArrayLike(p) && (typeof o == "object") && !isArrayLike(o)) {
extend(o, p, true);
} else {
obj[i] = p;
}
}
}
// Account for special case of toString in IE
if (props.hasOwnProperty("toString")) {
obj.toString = props.toString;
}
}
return obj;
};
api.extendHostObject = extendHostObject = function(obj, props) {
var p;
if (props) {
for (var i in props) {
if (props.hasOwnProperty(i)) {
p = props[i];
if ((typeof p == "object") && isHostObject(obj, i)) {
extendHostObject(obj[i], p);
} else {
obj[i] = p;
}
}
}
}
return obj;
}
}
if (extend) {
api.createSettings = function(defaults) {
function Settings() {}
var proto = Settings.prototype;
extend(proto, defaults);
proto.defaults = defaults;
proto.set = function(props) {
for (var i in props) {
if (defaults.hasOwnProperty(i) && props.hasOwnProperty(i)) {
this[i] = props[i];
}
}
};
return new Settings();
};
extend(api, {
isHostMethod: isHostMethod,
isHostObject: isHostObject,
isHostProperty: isHostProperty
});
}
function getExceptionMessage(ex) {
return ex.message || ex.description || toStr(ex);
}
api.addFeatureTest("encodeURIComponent", function() {
return typeof encodeURIComponent == FUNCTION;
});
function urlEncode(str) {
return encodeURIComponent(str);
}
// Returns the portion of the URL after the last slash
function getUrlFileName(url) {
var lastSlashIndex = Math.max( url.lastIndexOf("/"), url.lastIndexOf("\\") );
return url.substr(lastSlashIndex + 1);
}
api.Strings = {
toStr: toStr,
splitIntoLines: splitIntoLines,
leftPad: leftPad,
rightPad: rightPad,
getUrlFileName: getUrlFileName,
urlEncode: urlEncode
};
// Returns a nicely formatted representation of an error
// TODO: Research safest way of getting string representations of error and error-like objects
function exceptionToStr(ex) {
if (ex) {
var exStr = "Exception: " + getExceptionMessage(ex);
try {
if (typeof ex.lineNumber != UNDEFINED) {
exStr += " on line number " + ex.lineNumber;
}
if (typeof ex.fileName != UNDEFINED) {
exStr += " in file " + getUrlFileName(ex.fileName);
}
} catch (localEx) {
}
if (api.showStackTraces && typeof ex.stack != UNDEFINED) {
exStr += "\r\nStack trace:\r\n" + ex.stack;
}
return exStr;
}
return null;
}
api.exceptionToStr = exceptionToStr;
/* ---------------------------------------------------------------------- */
/* Browser-related */
if (typeof window != UNDEFINED && typeof window.document != UNDEFINED) {
var BrowserEnvironment = function() {
this.isBrowser = true;
};
BrowserEnvironment.prototype = {
addWindowEvent: function(type, listenerFn) {
if (typeof window.addEventListener != UNDEFINED) {
window.addEventListener(type, listenerFn, false);
} else if (typeof window.attachEvent != UNDEFINED) {
window.attachEvent("on" + type, listenerFn);
}
}
};
addCustomEventSupport(BrowserEnvironment.prototype);
api.environment = new BrowserEnvironment();
window.log4javascript = api;
} else {
api.environment = {
isBrowser: false
};
}
/*------------------------------------------------------------------------*/
for (var i = 0, len = featureTests.length; i < len ; ++i) {
if (!featureTests[i][1]()) {
failCoreFeatureTests(featureTests[i][0]);
return null;
}
}
return api;
})(this); | apache-2.0 |
velsubra/Tamil | web-app/src/main/webapp/snippets/groovy.js | 187 | define("ace/snippets/groovy",["require","exports","module"], function(require, exports, module) {
"use strict";
exports.snippetText =undefined;
exports.scope = "groovy";
}); | apache-2.0 |
aalva-gapsi/gapsieventos | src/main/java/org/primefaces/component/fileupload/CommonsFileUploadDecoder.java | 2638 | /*
* Copyright 2009-2014 PrimeTek.
*
* 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.primefaces.component.fileupload;
import javax.faces.context.FacesContext;
import javax.servlet.ServletRequestWrapper;
import org.apache.commons.fileupload.FileItem;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultUploadedFile;
import org.primefaces.webapp.MultipartRequest;
public class CommonsFileUploadDecoder{
public static void decode(FacesContext context, FileUpload fileUpload) {
MultipartRequest multipartRequest = null;
Object request = context.getExternalContext().getRequest();
while(request instanceof ServletRequestWrapper) {
if(request instanceof MultipartRequest) {
multipartRequest = (MultipartRequest) request;
break;
}
else {
request = ((ServletRequestWrapper) request).getRequest();
}
}
if(multipartRequest != null) {
if(fileUpload.getMode().equals("simple")) {
decodeSimple(context, fileUpload, multipartRequest);
}
else {
decodeAdvanced(context, fileUpload, multipartRequest);
}
}
}
private static void decodeSimple(FacesContext context, FileUpload fileUpload, MultipartRequest request) {
FileItem file = request.getFileItem(fileUpload.getSimpleInputDecodeId(context));
if(file != null) {
if(file.getName().equals("")) {
fileUpload.setSubmittedValue("");
} else {
fileUpload.setTransient(true);
fileUpload.setSubmittedValue(new DefaultUploadedFile(file));
}
}
}
private static void decodeAdvanced(FacesContext context, FileUpload fileUpload, MultipartRequest request) {
String clientId = fileUpload.getClientId(context);
FileItem file = request.getFileItem(clientId);
if(file != null) {
fileUpload.setTransient(true);
fileUpload.queueEvent(new FileUploadEvent(fileUpload, new DefaultUploadedFile(file)));
}
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-iotanalytics/src/main/java/com/amazonaws/services/iotanalytics/AWSIoTAnalyticsAsync.java | 60345 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.iotanalytics;
import javax.annotation.Generated;
import com.amazonaws.services.iotanalytics.model.*;
/**
* Interface for accessing AWS IoT Analytics asynchronously. Each asynchronous method will return a Java Future object
* representing the asynchronous operation; overloads which accept an {@code AsyncHandler} can be used to receive
* notification when an asynchronous operation completes.
* <p>
* <b>Note:</b> Do not directly implement this interface, new methods are added to it regularly. Extend from
* {@link com.amazonaws.services.iotanalytics.AbstractAWSIoTAnalyticsAsync} instead.
* </p>
* <p>
* <p>
* AWS IoT Analytics allows you to collect large amounts of device data, process messages, and store them. You can then
* query the data and run sophisticated analytics on it. AWS IoT Analytics enables advanced data exploration through
* integration with Jupyter Notebooks and data visualization through integration with Amazon QuickSight.
* </p>
* <p>
* Traditional analytics and business intelligence tools are designed to process structured data. IoT data often comes
* from devices that record noisy processes (such as temperature, motion, or sound). As a result the data from these
* devices can have significant gaps, corrupted messages, and false readings that must be cleaned up before analysis can
* occur. Also, IoT data is often only meaningful in the context of other data from external sources.
* </p>
* <p>
* AWS IoT Analytics automates the steps required to analyze data from IoT devices. AWS IoT Analytics filters,
* transforms, and enriches IoT data before storing it in a time-series data store for analysis. You can set up the
* service to collect only the data you need from your devices, apply mathematical transforms to process the data, and
* enrich the data with device-specific metadata such as device type and location before storing it. Then, you can
* analyze your data by running queries using the built-in SQL query engine, or perform more complex analytics and
* machine learning inference. AWS IoT Analytics includes pre-built models for common IoT use cases so you can answer
* questions like which devices are about to fail or which customers are at risk of abandoning their wearable devices.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public interface AWSIoTAnalyticsAsync extends AWSIoTAnalytics {
/**
* <p>
* Sends messages to a channel.
* </p>
*
* @param batchPutMessageRequest
* @return A Java Future containing the result of the BatchPutMessage operation returned by the service.
* @sample AWSIoTAnalyticsAsync.BatchPutMessage
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/BatchPutMessage" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<BatchPutMessageResult> batchPutMessageAsync(BatchPutMessageRequest batchPutMessageRequest);
/**
* <p>
* Sends messages to a channel.
* </p>
*
* @param batchPutMessageRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the BatchPutMessage operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.BatchPutMessage
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/BatchPutMessage" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<BatchPutMessageResult> batchPutMessageAsync(BatchPutMessageRequest batchPutMessageRequest,
com.amazonaws.handlers.AsyncHandler<BatchPutMessageRequest, BatchPutMessageResult> asyncHandler);
/**
* <p>
* Cancels the reprocessing of data through the pipeline.
* </p>
*
* @param cancelPipelineReprocessingRequest
* @return A Java Future containing the result of the CancelPipelineReprocessing operation returned by the service.
* @sample AWSIoTAnalyticsAsync.CancelPipelineReprocessing
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/CancelPipelineReprocessing"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<CancelPipelineReprocessingResult> cancelPipelineReprocessingAsync(
CancelPipelineReprocessingRequest cancelPipelineReprocessingRequest);
/**
* <p>
* Cancels the reprocessing of data through the pipeline.
* </p>
*
* @param cancelPipelineReprocessingRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the CancelPipelineReprocessing operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.CancelPipelineReprocessing
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/CancelPipelineReprocessing"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<CancelPipelineReprocessingResult> cancelPipelineReprocessingAsync(
CancelPipelineReprocessingRequest cancelPipelineReprocessingRequest,
com.amazonaws.handlers.AsyncHandler<CancelPipelineReprocessingRequest, CancelPipelineReprocessingResult> asyncHandler);
/**
* <p>
* Creates a channel. A channel collects data from an MQTT topic and archives the raw, unprocessed messages before
* publishing the data to a pipeline.
* </p>
*
* @param createChannelRequest
* @return A Java Future containing the result of the CreateChannel operation returned by the service.
* @sample AWSIoTAnalyticsAsync.CreateChannel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/CreateChannel" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<CreateChannelResult> createChannelAsync(CreateChannelRequest createChannelRequest);
/**
* <p>
* Creates a channel. A channel collects data from an MQTT topic and archives the raw, unprocessed messages before
* publishing the data to a pipeline.
* </p>
*
* @param createChannelRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the CreateChannel operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.CreateChannel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/CreateChannel" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<CreateChannelResult> createChannelAsync(CreateChannelRequest createChannelRequest,
com.amazonaws.handlers.AsyncHandler<CreateChannelRequest, CreateChannelResult> asyncHandler);
/**
* <p>
* Creates a data set. A data set stores data retrieved from a data store by applying a "queryAction" (a SQL query)
* or a "containerAction" (executing a containerized application). This operation creates the skeleton of a data
* set. The data set can be populated manually by calling "CreateDatasetContent" or automatically according to a
* "trigger" you specify.
* </p>
*
* @param createDatasetRequest
* @return A Java Future containing the result of the CreateDataset operation returned by the service.
* @sample AWSIoTAnalyticsAsync.CreateDataset
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/CreateDataset" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<CreateDatasetResult> createDatasetAsync(CreateDatasetRequest createDatasetRequest);
/**
* <p>
* Creates a data set. A data set stores data retrieved from a data store by applying a "queryAction" (a SQL query)
* or a "containerAction" (executing a containerized application). This operation creates the skeleton of a data
* set. The data set can be populated manually by calling "CreateDatasetContent" or automatically according to a
* "trigger" you specify.
* </p>
*
* @param createDatasetRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the CreateDataset operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.CreateDataset
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/CreateDataset" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<CreateDatasetResult> createDatasetAsync(CreateDatasetRequest createDatasetRequest,
com.amazonaws.handlers.AsyncHandler<CreateDatasetRequest, CreateDatasetResult> asyncHandler);
/**
* <p>
* Creates the content of a data set by applying a "queryAction" (a SQL query) or a "containerAction" (executing a
* containerized application).
* </p>
*
* @param createDatasetContentRequest
* @return A Java Future containing the result of the CreateDatasetContent operation returned by the service.
* @sample AWSIoTAnalyticsAsync.CreateDatasetContent
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/CreateDatasetContent"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<CreateDatasetContentResult> createDatasetContentAsync(CreateDatasetContentRequest createDatasetContentRequest);
/**
* <p>
* Creates the content of a data set by applying a "queryAction" (a SQL query) or a "containerAction" (executing a
* containerized application).
* </p>
*
* @param createDatasetContentRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the CreateDatasetContent operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.CreateDatasetContent
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/CreateDatasetContent"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<CreateDatasetContentResult> createDatasetContentAsync(CreateDatasetContentRequest createDatasetContentRequest,
com.amazonaws.handlers.AsyncHandler<CreateDatasetContentRequest, CreateDatasetContentResult> asyncHandler);
/**
* <p>
* Creates a data store, which is a repository for messages.
* </p>
*
* @param createDatastoreRequest
* @return A Java Future containing the result of the CreateDatastore operation returned by the service.
* @sample AWSIoTAnalyticsAsync.CreateDatastore
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/CreateDatastore" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<CreateDatastoreResult> createDatastoreAsync(CreateDatastoreRequest createDatastoreRequest);
/**
* <p>
* Creates a data store, which is a repository for messages.
* </p>
*
* @param createDatastoreRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the CreateDatastore operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.CreateDatastore
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/CreateDatastore" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<CreateDatastoreResult> createDatastoreAsync(CreateDatastoreRequest createDatastoreRequest,
com.amazonaws.handlers.AsyncHandler<CreateDatastoreRequest, CreateDatastoreResult> asyncHandler);
/**
* <p>
* Creates a pipeline. A pipeline consumes messages from one or more channels and allows you to process the messages
* before storing them in a data store. You must specify both a <code>channel</code> and a <code>datastore</code>
* activity and, optionally, as many as 23 additional activities in the <code>pipelineActivities</code> array.
* </p>
*
* @param createPipelineRequest
* @return A Java Future containing the result of the CreatePipeline operation returned by the service.
* @sample AWSIoTAnalyticsAsync.CreatePipeline
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/CreatePipeline" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<CreatePipelineResult> createPipelineAsync(CreatePipelineRequest createPipelineRequest);
/**
* <p>
* Creates a pipeline. A pipeline consumes messages from one or more channels and allows you to process the messages
* before storing them in a data store. You must specify both a <code>channel</code> and a <code>datastore</code>
* activity and, optionally, as many as 23 additional activities in the <code>pipelineActivities</code> array.
* </p>
*
* @param createPipelineRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the CreatePipeline operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.CreatePipeline
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/CreatePipeline" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<CreatePipelineResult> createPipelineAsync(CreatePipelineRequest createPipelineRequest,
com.amazonaws.handlers.AsyncHandler<CreatePipelineRequest, CreatePipelineResult> asyncHandler);
/**
* <p>
* Deletes the specified channel.
* </p>
*
* @param deleteChannelRequest
* @return A Java Future containing the result of the DeleteChannel operation returned by the service.
* @sample AWSIoTAnalyticsAsync.DeleteChannel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DeleteChannel" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<DeleteChannelResult> deleteChannelAsync(DeleteChannelRequest deleteChannelRequest);
/**
* <p>
* Deletes the specified channel.
* </p>
*
* @param deleteChannelRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DeleteChannel operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.DeleteChannel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DeleteChannel" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<DeleteChannelResult> deleteChannelAsync(DeleteChannelRequest deleteChannelRequest,
com.amazonaws.handlers.AsyncHandler<DeleteChannelRequest, DeleteChannelResult> asyncHandler);
/**
* <p>
* Deletes the specified data set.
* </p>
* <p>
* You do not have to delete the content of the data set before you perform this operation.
* </p>
*
* @param deleteDatasetRequest
* @return A Java Future containing the result of the DeleteDataset operation returned by the service.
* @sample AWSIoTAnalyticsAsync.DeleteDataset
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DeleteDataset" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<DeleteDatasetResult> deleteDatasetAsync(DeleteDatasetRequest deleteDatasetRequest);
/**
* <p>
* Deletes the specified data set.
* </p>
* <p>
* You do not have to delete the content of the data set before you perform this operation.
* </p>
*
* @param deleteDatasetRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DeleteDataset operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.DeleteDataset
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DeleteDataset" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<DeleteDatasetResult> deleteDatasetAsync(DeleteDatasetRequest deleteDatasetRequest,
com.amazonaws.handlers.AsyncHandler<DeleteDatasetRequest, DeleteDatasetResult> asyncHandler);
/**
* <p>
* Deletes the content of the specified data set.
* </p>
*
* @param deleteDatasetContentRequest
* @return A Java Future containing the result of the DeleteDatasetContent operation returned by the service.
* @sample AWSIoTAnalyticsAsync.DeleteDatasetContent
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DeleteDatasetContent"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<DeleteDatasetContentResult> deleteDatasetContentAsync(DeleteDatasetContentRequest deleteDatasetContentRequest);
/**
* <p>
* Deletes the content of the specified data set.
* </p>
*
* @param deleteDatasetContentRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DeleteDatasetContent operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.DeleteDatasetContent
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DeleteDatasetContent"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<DeleteDatasetContentResult> deleteDatasetContentAsync(DeleteDatasetContentRequest deleteDatasetContentRequest,
com.amazonaws.handlers.AsyncHandler<DeleteDatasetContentRequest, DeleteDatasetContentResult> asyncHandler);
/**
* <p>
* Deletes the specified data store.
* </p>
*
* @param deleteDatastoreRequest
* @return A Java Future containing the result of the DeleteDatastore operation returned by the service.
* @sample AWSIoTAnalyticsAsync.DeleteDatastore
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DeleteDatastore" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<DeleteDatastoreResult> deleteDatastoreAsync(DeleteDatastoreRequest deleteDatastoreRequest);
/**
* <p>
* Deletes the specified data store.
* </p>
*
* @param deleteDatastoreRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DeleteDatastore operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.DeleteDatastore
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DeleteDatastore" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<DeleteDatastoreResult> deleteDatastoreAsync(DeleteDatastoreRequest deleteDatastoreRequest,
com.amazonaws.handlers.AsyncHandler<DeleteDatastoreRequest, DeleteDatastoreResult> asyncHandler);
/**
* <p>
* Deletes the specified pipeline.
* </p>
*
* @param deletePipelineRequest
* @return A Java Future containing the result of the DeletePipeline operation returned by the service.
* @sample AWSIoTAnalyticsAsync.DeletePipeline
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DeletePipeline" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<DeletePipelineResult> deletePipelineAsync(DeletePipelineRequest deletePipelineRequest);
/**
* <p>
* Deletes the specified pipeline.
* </p>
*
* @param deletePipelineRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DeletePipeline operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.DeletePipeline
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DeletePipeline" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<DeletePipelineResult> deletePipelineAsync(DeletePipelineRequest deletePipelineRequest,
com.amazonaws.handlers.AsyncHandler<DeletePipelineRequest, DeletePipelineResult> asyncHandler);
/**
* <p>
* Retrieves information about a channel.
* </p>
*
* @param describeChannelRequest
* @return A Java Future containing the result of the DescribeChannel operation returned by the service.
* @sample AWSIoTAnalyticsAsync.DescribeChannel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DescribeChannel" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<DescribeChannelResult> describeChannelAsync(DescribeChannelRequest describeChannelRequest);
/**
* <p>
* Retrieves information about a channel.
* </p>
*
* @param describeChannelRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DescribeChannel operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.DescribeChannel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DescribeChannel" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<DescribeChannelResult> describeChannelAsync(DescribeChannelRequest describeChannelRequest,
com.amazonaws.handlers.AsyncHandler<DescribeChannelRequest, DescribeChannelResult> asyncHandler);
/**
* <p>
* Retrieves information about a data set.
* </p>
*
* @param describeDatasetRequest
* @return A Java Future containing the result of the DescribeDataset operation returned by the service.
* @sample AWSIoTAnalyticsAsync.DescribeDataset
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DescribeDataset" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<DescribeDatasetResult> describeDatasetAsync(DescribeDatasetRequest describeDatasetRequest);
/**
* <p>
* Retrieves information about a data set.
* </p>
*
* @param describeDatasetRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DescribeDataset operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.DescribeDataset
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DescribeDataset" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<DescribeDatasetResult> describeDatasetAsync(DescribeDatasetRequest describeDatasetRequest,
com.amazonaws.handlers.AsyncHandler<DescribeDatasetRequest, DescribeDatasetResult> asyncHandler);
/**
* <p>
* Retrieves information about a data store.
* </p>
*
* @param describeDatastoreRequest
* @return A Java Future containing the result of the DescribeDatastore operation returned by the service.
* @sample AWSIoTAnalyticsAsync.DescribeDatastore
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DescribeDatastore" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<DescribeDatastoreResult> describeDatastoreAsync(DescribeDatastoreRequest describeDatastoreRequest);
/**
* <p>
* Retrieves information about a data store.
* </p>
*
* @param describeDatastoreRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DescribeDatastore operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.DescribeDatastore
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DescribeDatastore" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<DescribeDatastoreResult> describeDatastoreAsync(DescribeDatastoreRequest describeDatastoreRequest,
com.amazonaws.handlers.AsyncHandler<DescribeDatastoreRequest, DescribeDatastoreResult> asyncHandler);
/**
* <p>
* Retrieves the current settings of the AWS IoT Analytics logging options.
* </p>
*
* @param describeLoggingOptionsRequest
* @return A Java Future containing the result of the DescribeLoggingOptions operation returned by the service.
* @sample AWSIoTAnalyticsAsync.DescribeLoggingOptions
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DescribeLoggingOptions"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<DescribeLoggingOptionsResult> describeLoggingOptionsAsync(DescribeLoggingOptionsRequest describeLoggingOptionsRequest);
/**
* <p>
* Retrieves the current settings of the AWS IoT Analytics logging options.
* </p>
*
* @param describeLoggingOptionsRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DescribeLoggingOptions operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.DescribeLoggingOptions
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DescribeLoggingOptions"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<DescribeLoggingOptionsResult> describeLoggingOptionsAsync(DescribeLoggingOptionsRequest describeLoggingOptionsRequest,
com.amazonaws.handlers.AsyncHandler<DescribeLoggingOptionsRequest, DescribeLoggingOptionsResult> asyncHandler);
/**
* <p>
* Retrieves information about a pipeline.
* </p>
*
* @param describePipelineRequest
* @return A Java Future containing the result of the DescribePipeline operation returned by the service.
* @sample AWSIoTAnalyticsAsync.DescribePipeline
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DescribePipeline" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<DescribePipelineResult> describePipelineAsync(DescribePipelineRequest describePipelineRequest);
/**
* <p>
* Retrieves information about a pipeline.
* </p>
*
* @param describePipelineRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DescribePipeline operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.DescribePipeline
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DescribePipeline" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<DescribePipelineResult> describePipelineAsync(DescribePipelineRequest describePipelineRequest,
com.amazonaws.handlers.AsyncHandler<DescribePipelineRequest, DescribePipelineResult> asyncHandler);
/**
* <p>
* Retrieves the contents of a data set as pre-signed URIs.
* </p>
*
* @param getDatasetContentRequest
* @return A Java Future containing the result of the GetDatasetContent operation returned by the service.
* @sample AWSIoTAnalyticsAsync.GetDatasetContent
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/GetDatasetContent" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<GetDatasetContentResult> getDatasetContentAsync(GetDatasetContentRequest getDatasetContentRequest);
/**
* <p>
* Retrieves the contents of a data set as pre-signed URIs.
* </p>
*
* @param getDatasetContentRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the GetDatasetContent operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.GetDatasetContent
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/GetDatasetContent" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<GetDatasetContentResult> getDatasetContentAsync(GetDatasetContentRequest getDatasetContentRequest,
com.amazonaws.handlers.AsyncHandler<GetDatasetContentRequest, GetDatasetContentResult> asyncHandler);
/**
* <p>
* Retrieves a list of channels.
* </p>
*
* @param listChannelsRequest
* @return A Java Future containing the result of the ListChannels operation returned by the service.
* @sample AWSIoTAnalyticsAsync.ListChannels
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/ListChannels" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<ListChannelsResult> listChannelsAsync(ListChannelsRequest listChannelsRequest);
/**
* <p>
* Retrieves a list of channels.
* </p>
*
* @param listChannelsRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the ListChannels operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.ListChannels
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/ListChannels" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<ListChannelsResult> listChannelsAsync(ListChannelsRequest listChannelsRequest,
com.amazonaws.handlers.AsyncHandler<ListChannelsRequest, ListChannelsResult> asyncHandler);
/**
* <p>
* Lists information about data set contents that have been created.
* </p>
*
* @param listDatasetContentsRequest
* @return A Java Future containing the result of the ListDatasetContents operation returned by the service.
* @sample AWSIoTAnalyticsAsync.ListDatasetContents
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/ListDatasetContents"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<ListDatasetContentsResult> listDatasetContentsAsync(ListDatasetContentsRequest listDatasetContentsRequest);
/**
* <p>
* Lists information about data set contents that have been created.
* </p>
*
* @param listDatasetContentsRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the ListDatasetContents operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.ListDatasetContents
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/ListDatasetContents"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<ListDatasetContentsResult> listDatasetContentsAsync(ListDatasetContentsRequest listDatasetContentsRequest,
com.amazonaws.handlers.AsyncHandler<ListDatasetContentsRequest, ListDatasetContentsResult> asyncHandler);
/**
* <p>
* Retrieves information about data sets.
* </p>
*
* @param listDatasetsRequest
* @return A Java Future containing the result of the ListDatasets operation returned by the service.
* @sample AWSIoTAnalyticsAsync.ListDatasets
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/ListDatasets" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<ListDatasetsResult> listDatasetsAsync(ListDatasetsRequest listDatasetsRequest);
/**
* <p>
* Retrieves information about data sets.
* </p>
*
* @param listDatasetsRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the ListDatasets operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.ListDatasets
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/ListDatasets" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<ListDatasetsResult> listDatasetsAsync(ListDatasetsRequest listDatasetsRequest,
com.amazonaws.handlers.AsyncHandler<ListDatasetsRequest, ListDatasetsResult> asyncHandler);
/**
* <p>
* Retrieves a list of data stores.
* </p>
*
* @param listDatastoresRequest
* @return A Java Future containing the result of the ListDatastores operation returned by the service.
* @sample AWSIoTAnalyticsAsync.ListDatastores
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/ListDatastores" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<ListDatastoresResult> listDatastoresAsync(ListDatastoresRequest listDatastoresRequest);
/**
* <p>
* Retrieves a list of data stores.
* </p>
*
* @param listDatastoresRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the ListDatastores operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.ListDatastores
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/ListDatastores" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<ListDatastoresResult> listDatastoresAsync(ListDatastoresRequest listDatastoresRequest,
com.amazonaws.handlers.AsyncHandler<ListDatastoresRequest, ListDatastoresResult> asyncHandler);
/**
* <p>
* Retrieves a list of pipelines.
* </p>
*
* @param listPipelinesRequest
* @return A Java Future containing the result of the ListPipelines operation returned by the service.
* @sample AWSIoTAnalyticsAsync.ListPipelines
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/ListPipelines" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<ListPipelinesResult> listPipelinesAsync(ListPipelinesRequest listPipelinesRequest);
/**
* <p>
* Retrieves a list of pipelines.
* </p>
*
* @param listPipelinesRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the ListPipelines operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.ListPipelines
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/ListPipelines" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<ListPipelinesResult> listPipelinesAsync(ListPipelinesRequest listPipelinesRequest,
com.amazonaws.handlers.AsyncHandler<ListPipelinesRequest, ListPipelinesResult> asyncHandler);
/**
* <p>
* Lists the tags (metadata) which you have assigned to the resource.
* </p>
*
* @param listTagsForResourceRequest
* @return A Java Future containing the result of the ListTagsForResource operation returned by the service.
* @sample AWSIoTAnalyticsAsync.ListTagsForResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/ListTagsForResource"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest listTagsForResourceRequest);
/**
* <p>
* Lists the tags (metadata) which you have assigned to the resource.
* </p>
*
* @param listTagsForResourceRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the ListTagsForResource operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.ListTagsForResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/ListTagsForResource"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest listTagsForResourceRequest,
com.amazonaws.handlers.AsyncHandler<ListTagsForResourceRequest, ListTagsForResourceResult> asyncHandler);
/**
* <p>
* Sets or updates the AWS IoT Analytics logging options.
* </p>
* <p>
* Note that if you update the value of any <code>loggingOptions</code> field, it takes up to one minute for the
* change to take effect. Also, if you change the policy attached to the role you specified in the roleArn field
* (for example, to correct an invalid policy) it takes up to 5 minutes for that change to take effect.
* </p>
*
* @param putLoggingOptionsRequest
* @return A Java Future containing the result of the PutLoggingOptions operation returned by the service.
* @sample AWSIoTAnalyticsAsync.PutLoggingOptions
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/PutLoggingOptions" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<PutLoggingOptionsResult> putLoggingOptionsAsync(PutLoggingOptionsRequest putLoggingOptionsRequest);
/**
* <p>
* Sets or updates the AWS IoT Analytics logging options.
* </p>
* <p>
* Note that if you update the value of any <code>loggingOptions</code> field, it takes up to one minute for the
* change to take effect. Also, if you change the policy attached to the role you specified in the roleArn field
* (for example, to correct an invalid policy) it takes up to 5 minutes for that change to take effect.
* </p>
*
* @param putLoggingOptionsRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the PutLoggingOptions operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.PutLoggingOptions
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/PutLoggingOptions" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<PutLoggingOptionsResult> putLoggingOptionsAsync(PutLoggingOptionsRequest putLoggingOptionsRequest,
com.amazonaws.handlers.AsyncHandler<PutLoggingOptionsRequest, PutLoggingOptionsResult> asyncHandler);
/**
* <p>
* Simulates the results of running a pipeline activity on a message payload.
* </p>
*
* @param runPipelineActivityRequest
* @return A Java Future containing the result of the RunPipelineActivity operation returned by the service.
* @sample AWSIoTAnalyticsAsync.RunPipelineActivity
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/RunPipelineActivity"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<RunPipelineActivityResult> runPipelineActivityAsync(RunPipelineActivityRequest runPipelineActivityRequest);
/**
* <p>
* Simulates the results of running a pipeline activity on a message payload.
* </p>
*
* @param runPipelineActivityRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the RunPipelineActivity operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.RunPipelineActivity
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/RunPipelineActivity"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<RunPipelineActivityResult> runPipelineActivityAsync(RunPipelineActivityRequest runPipelineActivityRequest,
com.amazonaws.handlers.AsyncHandler<RunPipelineActivityRequest, RunPipelineActivityResult> asyncHandler);
/**
* <p>
* Retrieves a sample of messages from the specified channel ingested during the specified timeframe. Up to 10
* messages can be retrieved.
* </p>
*
* @param sampleChannelDataRequest
* @return A Java Future containing the result of the SampleChannelData operation returned by the service.
* @sample AWSIoTAnalyticsAsync.SampleChannelData
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/SampleChannelData" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<SampleChannelDataResult> sampleChannelDataAsync(SampleChannelDataRequest sampleChannelDataRequest);
/**
* <p>
* Retrieves a sample of messages from the specified channel ingested during the specified timeframe. Up to 10
* messages can be retrieved.
* </p>
*
* @param sampleChannelDataRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the SampleChannelData operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.SampleChannelData
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/SampleChannelData" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<SampleChannelDataResult> sampleChannelDataAsync(SampleChannelDataRequest sampleChannelDataRequest,
com.amazonaws.handlers.AsyncHandler<SampleChannelDataRequest, SampleChannelDataResult> asyncHandler);
/**
* <p>
* Starts the reprocessing of raw message data through the pipeline.
* </p>
*
* @param startPipelineReprocessingRequest
* @return A Java Future containing the result of the StartPipelineReprocessing operation returned by the service.
* @sample AWSIoTAnalyticsAsync.StartPipelineReprocessing
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/StartPipelineReprocessing"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<StartPipelineReprocessingResult> startPipelineReprocessingAsync(
StartPipelineReprocessingRequest startPipelineReprocessingRequest);
/**
* <p>
* Starts the reprocessing of raw message data through the pipeline.
* </p>
*
* @param startPipelineReprocessingRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the StartPipelineReprocessing operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.StartPipelineReprocessing
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/StartPipelineReprocessing"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<StartPipelineReprocessingResult> startPipelineReprocessingAsync(
StartPipelineReprocessingRequest startPipelineReprocessingRequest,
com.amazonaws.handlers.AsyncHandler<StartPipelineReprocessingRequest, StartPipelineReprocessingResult> asyncHandler);
/**
* <p>
* Adds to or modifies the tags of the given resource. Tags are metadata which can be used to manage a resource.
* </p>
*
* @param tagResourceRequest
* @return A Java Future containing the result of the TagResource operation returned by the service.
* @sample AWSIoTAnalyticsAsync.TagResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/TagResource" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest tagResourceRequest);
/**
* <p>
* Adds to or modifies the tags of the given resource. Tags are metadata which can be used to manage a resource.
* </p>
*
* @param tagResourceRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the TagResource operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.TagResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/TagResource" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest tagResourceRequest,
com.amazonaws.handlers.AsyncHandler<TagResourceRequest, TagResourceResult> asyncHandler);
/**
* <p>
* Removes the given tags (metadata) from the resource.
* </p>
*
* @param untagResourceRequest
* @return A Java Future containing the result of the UntagResource operation returned by the service.
* @sample AWSIoTAnalyticsAsync.UntagResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/UntagResource" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest untagResourceRequest);
/**
* <p>
* Removes the given tags (metadata) from the resource.
* </p>
*
* @param untagResourceRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the UntagResource operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.UntagResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/UntagResource" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest untagResourceRequest,
com.amazonaws.handlers.AsyncHandler<UntagResourceRequest, UntagResourceResult> asyncHandler);
/**
* <p>
* Updates the settings of a channel.
* </p>
*
* @param updateChannelRequest
* @return A Java Future containing the result of the UpdateChannel operation returned by the service.
* @sample AWSIoTAnalyticsAsync.UpdateChannel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/UpdateChannel" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<UpdateChannelResult> updateChannelAsync(UpdateChannelRequest updateChannelRequest);
/**
* <p>
* Updates the settings of a channel.
* </p>
*
* @param updateChannelRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the UpdateChannel operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.UpdateChannel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/UpdateChannel" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<UpdateChannelResult> updateChannelAsync(UpdateChannelRequest updateChannelRequest,
com.amazonaws.handlers.AsyncHandler<UpdateChannelRequest, UpdateChannelResult> asyncHandler);
/**
* <p>
* Updates the settings of a data set.
* </p>
*
* @param updateDatasetRequest
* @return A Java Future containing the result of the UpdateDataset operation returned by the service.
* @sample AWSIoTAnalyticsAsync.UpdateDataset
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/UpdateDataset" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<UpdateDatasetResult> updateDatasetAsync(UpdateDatasetRequest updateDatasetRequest);
/**
* <p>
* Updates the settings of a data set.
* </p>
*
* @param updateDatasetRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the UpdateDataset operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.UpdateDataset
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/UpdateDataset" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<UpdateDatasetResult> updateDatasetAsync(UpdateDatasetRequest updateDatasetRequest,
com.amazonaws.handlers.AsyncHandler<UpdateDatasetRequest, UpdateDatasetResult> asyncHandler);
/**
* <p>
* Updates the settings of a data store.
* </p>
*
* @param updateDatastoreRequest
* @return A Java Future containing the result of the UpdateDatastore operation returned by the service.
* @sample AWSIoTAnalyticsAsync.UpdateDatastore
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/UpdateDatastore" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<UpdateDatastoreResult> updateDatastoreAsync(UpdateDatastoreRequest updateDatastoreRequest);
/**
* <p>
* Updates the settings of a data store.
* </p>
*
* @param updateDatastoreRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the UpdateDatastore operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.UpdateDatastore
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/UpdateDatastore" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<UpdateDatastoreResult> updateDatastoreAsync(UpdateDatastoreRequest updateDatastoreRequest,
com.amazonaws.handlers.AsyncHandler<UpdateDatastoreRequest, UpdateDatastoreResult> asyncHandler);
/**
* <p>
* Updates the settings of a pipeline. You must specify both a <code>channel</code> and a <code>datastore</code>
* activity and, optionally, as many as 23 additional activities in the <code>pipelineActivities</code> array.
* </p>
*
* @param updatePipelineRequest
* @return A Java Future containing the result of the UpdatePipeline operation returned by the service.
* @sample AWSIoTAnalyticsAsync.UpdatePipeline
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/UpdatePipeline" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<UpdatePipelineResult> updatePipelineAsync(UpdatePipelineRequest updatePipelineRequest);
/**
* <p>
* Updates the settings of a pipeline. You must specify both a <code>channel</code> and a <code>datastore</code>
* activity and, optionally, as many as 23 additional activities in the <code>pipelineActivities</code> array.
* </p>
*
* @param updatePipelineRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the UpdatePipeline operation returned by the service.
* @sample AWSIoTAnalyticsAsyncHandler.UpdatePipeline
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/UpdatePipeline" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<UpdatePipelineResult> updatePipelineAsync(UpdatePipelineRequest updatePipelineRequest,
com.amazonaws.handlers.AsyncHandler<UpdatePipelineRequest, UpdatePipelineResult> asyncHandler);
}
| apache-2.0 |
tianzi77/tianzi77.github.io | tools/avalon/router/dist/example2.js | 307752 | /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
var avalon = __webpack_require__(1)
__webpack_require__(2)
var vm = avalon.define({
$id: 'test',
currPath: ''
})
avalon.router.add("/aaa", function (a) {
vm.currPath = this.path
})
avalon.router.add("/bbb", function (a) {
vm.currPath = this.path
})
avalon.router.add("/ccc", function (a) {
vm.currPath = this.path
})
avalon.router.add("/ddd/:ddd/:eee", function (a) {//:ddd为参数
vm.currPath = this.path
})
avalon.history.start({
root: "/mmRouter",
html5: true
})
avalon.scan(document.body)
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {/*!
built in 2016-12-13:18:38 version 2.2.3 by 司徒正美
https://github.com/RubyLouvre/avalon/tree/2.2.2
fix ms-controller BUG, 上下VM相同时,不会进行合并
为监听数组添加toJSON方法
IE7的checked属性应该使用defaultChecked来设置
对旧版firefox的children进行polyfill
修正ms-if,ms-text同在一个元素时出BUG的情况
修正ms-visible,ms-effect同在一个元素时出BUG的情况
修正selected属性同步问题
*/(function (global, factory) {
true ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : global.avalon = factory();
})(this, function () {
'use strict';
var win = typeof window === 'object' ? window : typeof global === 'object' ? global : {};
var inBrowser = !!win.location && win.navigator;
/* istanbul ignore if */
var document$1 = inBrowser ? win.document : {
createElement: Object,
createElementNS: Object,
documentElement: 'xx',
contains: Boolean
};
var root = inBrowser ? document$1.documentElement : {
outerHTML: 'x'
};
var versions = {
objectobject: 7, //IE7-8
objectundefined: 6, //IE6
undefinedfunction: NaN, // other modern browsers
undefinedobject: NaN };
/* istanbul ignore next */
var msie = document$1.documentMode || versions[typeof document$1.all + typeof XMLHttpRequest];
var modern = /NaN|undefined/.test(msie) || msie > 8;
/*
https://github.com/rsms/js-lru
entry entry entry entry
______ ______ ______ ______
| head |.newer => | |.newer => | |.newer => | tail |
| A | | B | | C | | D |
|______| <= older.|______| <= older.|______| <= older.|______|
removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added
*/
function Cache(maxLength) {
// 标识当前缓存数组的大小
this.size = 0;
// 标识缓存数组能达到的最大长度
this.limit = maxLength;
// head(最不常用的项),tail(最常用的项)全部初始化为undefined
this.head = this.tail = void 0;
this._keymap = {};
}
Cache.prototype = {
put: function put(key, value) {
var entry = {
key: key,
value: value
};
this._keymap[key] = entry;
if (this.tail) {
// 如果存在tail(缓存数组的长度不为0),将tail指向新的 entry
this.tail.newer = entry;
entry.older = this.tail;
} else {
// 如果缓存数组的长度为0,将head指向新的entry
this.head = entry;
}
this.tail = entry;
// 如果缓存数组达到上限,则先删除 head 指向的缓存对象
/* istanbul ignore if */
if (this.size === this.limit) {
this.shift();
} else {
this.size++;
}
return value;
},
shift: function shift() {
/* istanbul ignore next */
var entry = this.head;
/* istanbul ignore if */
if (entry) {
// 删除 head ,并改变指向
this.head = this.head.newer;
// 同步更新 _keymap 里面的属性值
this.head.older = entry.newer = entry.older = this._keymap[entry.key] = void 0;
delete this._keymap[entry.key]; //#1029
// 同步更新 缓存数组的长度
this.size--;
}
},
get: function get(key) {
var entry = this._keymap[key];
// 如果查找不到含有`key`这个属性的缓存对象
if (entry === void 0) return;
// 如果查找到的缓存对象已经是 tail (最近使用过的)
/* istanbul ignore if */
if (entry === this.tail) {
return entry.value;
}
// HEAD--------------TAIL
// <.older .newer>
// <--- add direction --
// A B C <D> E
if (entry.newer) {
// 处理 newer 指向
if (entry === this.head) {
// 如果查找到的缓存对象是 head (最近最少使用过的)
// 则将 head 指向原 head 的 newer 所指向的缓存对象
this.head = entry.newer;
}
// 将所查找的缓存对象的下一级的 older 指向所查找的缓存对象的older所指向的值
// 例如:A B C D E
// 如果查找到的是D,那么将E指向C,不再指向D
entry.newer.older = entry.older; // C <-- E.
}
if (entry.older) {
// 处理 older 指向
// 如果查找到的是D,那么C指向E,不再指向D
entry.older.newer = entry.newer; // C. --> E
}
// 处理所查找到的对象的 newer 以及 older 指向
entry.newer = void 0; // D --x
// older指向之前使用过的变量,即D指向E
entry.older = this.tail; // D. --> E
if (this.tail) {
// 将E的newer指向D
this.tail.newer = entry; // E. <-- D
}
// 改变 tail 为D
this.tail = entry;
return entry.value;
}
};
var delayCompile = {};
var directives = {};
function directive(name, opts) {
if (directives[name]) {
avalon.warn(name, 'directive have defined! ');
}
directives[name] = opts;
if (!opts.update) {
opts.update = function () {};
}
if (opts.delay) {
delayCompile[name] = 1;
}
return opts;
}
function delayCompileNodes(dirs) {
for (var i in delayCompile) {
if ('ms-' + i in dirs) {
return true;
}
}
}
var window$1 = win;
function avalon(el) {
return new avalon.init(el);
}
avalon.init = function (el) {
this[0] = this.element = el;
};
avalon.fn = avalon.prototype = avalon.init.prototype;
function shadowCopy(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
}
var rword = /[^, ]+/g;
var rnowhite = /\S+/g; //存在非空字符
var platform = {}; //用于放置平台差异的方法与属性
function oneObject(array, val) {
if (typeof array === 'string') {
array = array.match(rword) || [];
}
var result = {},
value = val !== void 0 ? val : 1;
for (var i = 0, n = array.length; i < n; i++) {
result[array[i]] = value;
}
return result;
}
var op = Object.prototype;
function quote(str) {
return avalon._quote(str);
}
var inspect = op.toString;
var ohasOwn = op.hasOwnProperty;
var ap = Array.prototype;
var hasConsole = typeof console === 'object';
avalon.config = { debug: true };
function log() {
if (hasConsole && avalon.config.debug) {
Function.apply.call(console.log, console, arguments);
}
}
function warn() {
if (hasConsole && avalon.config.debug) {
var method = console.warn || console.log;
// http://qiang106.iteye.com/blog/1721425
Function.apply.call(method, console, arguments);
}
}
function error(e, str) {
throw (e || Error)(str);
}
function noop() {}
function isObject(a) {
return a !== null && typeof a === 'object';
}
function range(start, end, step) {
// 用于生成整数数组
step || (step = 1);
if (end == null) {
end = start || 0;
start = 0;
}
var index = -1,
length = Math.max(0, Math.ceil((end - start) / step)),
result = new Array(length);
while (++index < length) {
result[index] = start;
start += step;
}
return result;
}
var rhyphen = /([a-z\d])([A-Z]+)/g;
function hyphen(target) {
//转换为连字符线风格
return target.replace(rhyphen, '$1-$2').toLowerCase();
}
var rcamelize = /[-_][^-_]/g;
function camelize(target) {
//提前判断,提高getStyle等的效率
if (!target || target.indexOf('-') < 0 && target.indexOf('_') < 0) {
return target;
}
//转换为驼峰风格
return target.replace(rcamelize, function (match) {
return match.charAt(1).toUpperCase();
});
}
var _slice = ap.slice;
function slice(nodes, start, end) {
return _slice.call(nodes, start, end);
}
var rhashcode = /\d\.\d{4}/;
//生成UUID http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
function makeHashCode(prefix) {
/* istanbul ignore next*/
prefix = prefix || 'avalon';
/* istanbul ignore next*/
return String(Math.random() + Math.random()).replace(rhashcode, prefix);
}
//生成事件回调的UUID(用户通过ms-on指令)
function getLongID(fn) {
/* istanbul ignore next */
return fn.uuid || (fn.uuid = makeHashCode('e'));
}
var UUID = 1;
//生成事件回调的UUID(用户通过avalon.bind)
function getShortID(fn) {
/* istanbul ignore next */
return fn.uuid || (fn.uuid = '_' + ++UUID);
}
var rescape = /[-.*+?^${}()|[\]\/\\]/g;
function escapeRegExp(target) {
//http://stevenlevithan.com/regex/xregexp/
//将字符串安全格式化为正则表达式的源码
return (target + '').replace(rescape, '\\$&');
}
var eventHooks = {};
var eventListeners = {};
var validators = {};
var cssHooks = {};
window$1.avalon = avalon;
function createFragment() {
/* istanbul ignore next */
return document$1.createDocumentFragment();
}
var rentities = /&[a-z0-9#]{2,10};/;
var temp = document$1.createElement('div');
shadowCopy(avalon, {
Array: {
merge: function merge(target, other) {
//合并两个数组 avalon2新增
target.push.apply(target, other);
},
ensure: function ensure(target, item) {
//只有当前数组不存在此元素时只添加它
if (target.indexOf(item) === -1) {
return target.push(item);
}
},
removeAt: function removeAt(target, index) {
//移除数组中指定位置的元素,返回布尔表示成功与否
return !!target.splice(index, 1).length;
},
remove: function remove(target, item) {
//移除数组中第一个匹配传参的那个元素,返回布尔表示成功与否
var index = target.indexOf(item);
if (~index) return avalon.Array.removeAt(target, index);
return false;
}
},
evaluatorPool: new Cache(888),
parsers: {
number: function number(a) {
return a === '' ? '' : parseFloat(a) || 0;
},
string: function string(a) {
return a === null || a === void 0 ? '' : a + '';
},
"boolean": function boolean(a) {
if (a === '') return a;
return a === 'true' || a === '1';
}
},
_decode: function _decode(str) {
if (rentities.test(str)) {
temp.innerHTML = str;
return temp.innerText || temp.textContent;
}
return str;
}
});
//============== config ============
function config(settings) {
for (var p in settings) {
var val = settings[p];
if (typeof config.plugins[p] === 'function') {
config.plugins[p](val);
} else {
config[p] = val;
}
}
return this;
}
var plugins = {
interpolate: function interpolate(array) {
var openTag = array[0];
var closeTag = array[1];
if (openTag === closeTag) {
throw new SyntaxError('interpolate openTag cannot equal to closeTag');
}
var str = openTag + 'test' + closeTag;
if (/[<>]/.test(str)) {
throw new SyntaxError('interpolate cannot contains "<" or ">"');
}
config.openTag = openTag;
config.closeTag = closeTag;
var o = escapeRegExp(openTag);
var c = escapeRegExp(closeTag);
config.rtext = new RegExp(o + '(.+?)' + c, 'g');
config.rexpr = new RegExp(o + '([\\s\\S]*)' + c);
}
};
function createAnchor(nodeValue) {
return document$1.createComment(nodeValue);
}
config.plugins = plugins;
config({
interpolate: ['{{', '}}'],
debug: true
});
//============ config ============
shadowCopy(avalon, {
shadowCopy: shadowCopy,
oneObject: oneObject,
inspect: inspect,
ohasOwn: ohasOwn,
rword: rword,
version: "2.2.3",
vmodels: {},
directives: directives,
directive: directive,
eventHooks: eventHooks,
eventListeners: eventListeners,
validators: validators,
cssHooks: cssHooks,
log: log,
noop: noop,
warn: warn,
error: error,
config: config,
modern: modern,
msie: msie,
root: root,
document: document$1,
window: window$1,
inBrowser: inBrowser,
isObject: isObject,
range: range,
slice: slice,
hyphen: hyphen,
camelize: camelize,
escapeRegExp: escapeRegExp,
quote: quote,
makeHashCode: makeHashCode
});
/**
* 此模块用于修复语言的底层缺陷
*/
function isNative(fn) {
return (/\[native code\]/.test(fn)
);
}
/* istanbul ignore if*/
if (!isNative('司徒正美'.trim)) {
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
String.prototype.trim = function () {
return this.replace(rtrim, '');
};
}
var hasDontEnumBug = !{
'toString': null
}.propertyIsEnumerable('toString');
var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype');
var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'];
var dontEnumsLength = dontEnums.length;
/* istanbul ignore if*/
if (!isNative(Object.keys)) {
Object.keys = function (object) {
//ecma262v5 15.2.3.14
var theKeys = [];
var skipProto = hasProtoEnumBug && typeof object === 'function';
if (typeof object === 'string' || object && object.callee) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && ohasOwn.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var ctor = object.constructor,
skipConstructor = ctor && ctor.prototype === object;
for (var j = 0; j < dontEnumsLength; j++) {
var dontEnum = dontEnums[j];
if (!(skipConstructor && dontEnum === 'constructor') && ohasOwn.call(object, dontEnum)) {
theKeys.push(dontEnum);
}
}
}
return theKeys;
};
}
/* istanbul ignore if*/
if (!isNative(Array.isArray)) {
Array.isArray = function (a) {
return Object.prototype.toString.call(a) === '[object Array]';
};
}
/* istanbul ignore if*/
if (!isNative(isNative.bind)) {
/* istanbul ignore next*/
Function.prototype.bind = function (scope) {
if (arguments.length < 2 && scope === void 0) return this;
var fn = this,
argv = arguments;
return function () {
var args = [],
i;
for (i = 1; i < argv.length; i++) {
args.push(argv[i]);
}for (i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}return fn.apply(scope, args);
};
};
}
//https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
/**
* Shim for "fixing" IE's lack of support (IE < 9) for applying slice
* on host objects like NamedNodeMap, NodeList, and HTMLCollection
* (technically, since host objects have been implementation-dependent,
* at least before ES6, IE hasn't needed to work this way).
* Also works on strings, fixes IE < 9 to allow an explicit undefined
* for the 2nd argument (as in Firefox), and prevents errors when
* called on other DOM objects.
*/
try {
// Can't be used with DOM elements in IE < 9
_slice.call(avalon.document.documentElement);
} catch (e) {
// Fails in IE < 9
// This will work for genuine arrays, array-like objects,
// NamedNodeMap (attributes, entities, notations),
// NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes),
// and will not fail on other DOM objects (as do DOM elements in IE < 9)
/* istanbul ignore next*/
ap.slice = function (begin, end) {
// IE < 9 gets unhappy with an undefined end argument
end = typeof end !== 'undefined' ? end : this.length;
// For native Array objects, we use the native slice function
if (Array.isArray(this)) {
return _slice.call(this, begin, end);
}
// For array like object we handle it ourselves.
var i,
cloned = [],
size,
len = this.length;
// Handle negative value for "begin"
var start = begin || 0;
start = start >= 0 ? start : len + start;
// Handle negative value for "end"
var upTo = end ? end : len;
if (end < 0) {
upTo = len + end;
}
// Actual expected size of the slice
size = upTo - start;
if (size > 0) {
cloned = new Array(size);
if (this.charAt) {
for (i = 0; i < size; i++) {
cloned[i] = this.charAt(start + i);
}
} else {
for (i = 0; i < size; i++) {
cloned[i] = this[start + i];
}
}
}
return cloned;
};
}
/* istanbul ignore next*/
function iterator(vars, body, ret) {
var fun = 'for(var ' + vars + 'i=0,n = this.length; i < n; i++){' + body.replace('_', '((i in this) && fn.call(scope,this[i],i,this))') + '}' + ret;
/* jshint ignore:start */
return Function('fn,scope', fun);
/* jshint ignore:end */
}
/* istanbul ignore if*/
if (!isNative(ap.map)) {
avalon.shadowCopy(ap, {
//定位操作,返回数组中第一个等于给定参数的元素的索引值。
indexOf: function indexOf(item, index) {
var n = this.length,
i = ~~index;
if (i < 0) i += n;
for (; i < n; i++) {
if (this[i] === item) return i;
}return -1;
},
//定位操作,同上,不过是从后遍历。
lastIndexOf: function lastIndexOf(item, index) {
var n = this.length,
i = index == null ? n - 1 : index;
if (i < 0) i = Math.max(0, n + i);
for (; i >= 0; i--) {
if (this[i] === item) return i;
}return -1;
},
//迭代操作,将数组的元素挨个儿传入一个函数中执行。Prototype.js的对应名字为each。
forEach: iterator('', '_', ''),
//迭代类 在数组中的每个项上运行一个函数,如果此函数的值为真,则此元素作为新数组的元素收集起来,并返回新数组
filter: iterator('r=[],j=0,', 'if(_)r[j++]=this[i]', 'return r'),
//收集操作,将数组的元素挨个儿传入一个函数中执行,然后把它们的返回值组成一个新数组返回。Prototype.js的对应名字为collect。
map: iterator('r=[],', 'r[i]=_', 'return r'),
//只要数组中有一个元素满足条件(放进给定函数返回true),那么它就返回true。Prototype.js的对应名字为any。
some: iterator('', 'if(_)return true', 'return false'),
//只有数组中的元素都满足条件(放进给定函数返回true),它才返回true。Prototype.js的对应名字为all。
every: iterator('', 'if(!_)return false', 'return true')
});
}
//这里放置存在异议的方法
var compaceQuote = function () {
//https://github.com/bestiejs/json3/blob/master/lib/json3.js
var Escapes = {
92: "\\\\",
34: '\\"',
8: "\\b",
12: "\\f",
10: "\\n",
13: "\\r",
9: "\\t"
};
var leadingZeroes = '000000';
var toPaddedString = function toPaddedString(width, value) {
return (leadingZeroes + (value || 0)).slice(-width);
};
var unicodePrefix = '\\u00';
var escapeChar = function escapeChar(character) {
var charCode = character.charCodeAt(0),
escaped = Escapes[charCode];
if (escaped) {
return escaped;
}
return unicodePrefix + toPaddedString(2, charCode.toString(16));
};
var reEscape = /[\x00-\x1f\x22\x5c]/g;
return function (value) {
/* istanbul ignore next */
reEscape.lastIndex = 0;
/* istanbul ignore next */
return '"' + (reEscape.test(value) ? String(value).replace(reEscape, escapeChar) : value) + '"';
};
}();
try {
avalon._quote = JSON.stringify;
} catch (e) {
/* istanbul ignore next */
avalon._quote = compaceQuote;
}
var class2type = {};
'Boolean Number String Function Array Date RegExp Object Error'.replace(avalon.rword, function (name) {
class2type['[object ' + name + ']'] = name.toLowerCase();
});
avalon.type = function (obj) {
//取得目标的类型
if (obj == null) {
return String(obj);
}
// 早期的webkit内核浏览器实现了已废弃的ecma262v4标准,可以将正则字面量当作函数使用,因此typeof在判定正则时会返回function
return typeof obj === 'object' || typeof obj === 'function' ? class2type[inspect.call(obj)] || 'object' : typeof obj;
};
var rfunction = /^\s*\bfunction\b/;
avalon.isFunction = /* istanbul ignore if */typeof alert === 'object' ? function (fn) {
/* istanbul ignore next */
try {
/* istanbul ignore next */
return rfunction.test(fn + '');
} catch (e) {
/* istanbul ignore next */
return false;
}
} : function (fn) {
return inspect.call(fn) === '[object Function]';
};
// 利用IE678 window == document为true,document == window竟然为false的神奇特性
// 标准浏览器及IE9,IE10等使用 正则检测
/* istanbul ignore next */
function isWindowCompact(obj) {
if (!obj) {
return false;
}
return obj == obj.document && obj.document != obj; //jshint ignore:line
}
var rwindow = /^\[object (?:Window|DOMWindow|global)\]$/;
function isWindowModern(obj) {
return rwindow.test(inspect.call(obj));
}
avalon.isWindow = isWindowModern(avalon.window) ? isWindowModern : isWindowCompact;
var enu;
var enumerateBUG;
for (enu in avalon({})) {
break;
}
enumerateBUG = enu !== '0'; //IE6下为true, 其他为false
/*判定是否是一个朴素的javascript对象(Object),不是DOM对象,不是BOM对象,不是自定义类的实例*/
/* istanbul ignore next */
function isPlainObjectCompact(obj, key) {
if (!obj || avalon.type(obj) !== 'object' || obj.nodeType || avalon.isWindow(obj)) {
return false;
}
try {
//IE内置对象没有constructor
if (obj.constructor && !ohasOwn.call(obj, 'constructor') && !ohasOwn.call(obj.constructor.prototype, 'isPrototypeOf')) {
return false;
}
var isVBscript = obj.$vbthis;
} catch (e) {
//IE8 9会在这里抛错
return false;
}
/* istanbul ignore if */
if (enumerateBUG) {
for (key in obj) {
return ohasOwn.call(obj, key);
}
}
for (key in obj) {}
return key === undefined$1 || ohasOwn.call(obj, key);
}
/* istanbul ignore next */
function isPlainObjectModern(obj) {
// 简单的 typeof obj === 'object'检测,会致使用isPlainObject(window)在opera下通不过
return inspect.call(obj) === '[object Object]' && Object.getPrototypeOf(obj) === Object.prototype;
}
/* istanbul ignore next */
avalon.isPlainObject = /\[native code\]/.test(Object.getPrototypeOf) ? isPlainObjectModern : isPlainObjectCompact;
var rcanMix = /object|function/;
//与jQuery.extend方法,可用于浅拷贝,深拷贝
/* istanbul ignore next */
avalon.mix = avalon.fn.mix = function () {
var n = arguments.length,
isDeep = false,
i = 0,
array = [];
if (arguments[0] === true) {
isDeep = true;
i = 1;
}
//将所有非空对象变成空对象
for (; i < n; i++) {
var el = arguments[i];
el = el && rcanMix.test(typeof el) ? el : {};
array.push(el);
}
if (array.length === 1) {
array.unshift(this);
}
return innerExtend(isDeep, array);
};
var undefined$1;
function innerExtend(isDeep, array) {
var target = array[0],
copyIsArray,
clone,
name;
for (var i = 1, length = array.length; i < length; i++) {
//只处理非空参数
var options = array[i];
var noCloneArrayMethod = Array.isArray(options);
for (name in options) {
if (noCloneArrayMethod && !options.hasOwnProperty(name)) {
continue;
}
try {
var src = target[name];
var copy = options[name]; //当options为VBS对象时报错
} catch (e) {
continue;
}
// 防止环引用
if (target === copy) {
continue;
}
if (isDeep && copy && (avalon.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && Array.isArray(src) ? src : [];
} else {
clone = src && avalon.isPlainObject(src) ? src : {};
}
target[name] = innerExtend(isDeep, [clone, copy]);
} else if (copy !== undefined$1) {
target[name] = copy;
}
}
}
return target;
}
var rarraylike = /(Array|List|Collection|Map|Arguments)\]$/;
/*判定是否类数组,如节点集合,纯数组,arguments与拥有非负整数的length属性的纯JS对象*/
/* istanbul ignore next */
function isArrayLike(obj) {
if (!obj) return false;
var n = obj.length;
if (n === n >>> 0) {
//检测length属性是否为非负整数
var type = inspect.call(obj);
if (rarraylike.test(type)) return true;
if (type !== '[object Object]') return false;
try {
if ({}.propertyIsEnumerable.call(obj, 'length') === false) {
//如果是原生对象
return rfunction.test(obj.item || obj.callee);
}
return true;
} catch (e) {
//IE的NodeList直接抛错
return !obj.window; //IE6-8 window
}
}
return false;
}
avalon.each = function (obj, fn) {
if (obj) {
//排除null, undefined
var i = 0;
if (isArrayLike(obj)) {
for (var n = obj.length; i < n; i++) {
if (fn(i, obj[i]) === false) break;
}
} else {
for (i in obj) {
if (obj.hasOwnProperty(i) && fn(i, obj[i]) === false) {
break;
}
}
}
}
};
(function () {
var welcomeIntro = ["%cavalon.js %c" + avalon.version + " %cin debug mode, %cmore...", "color: rgb(114, 157, 52); font-weight: normal;", "color: rgb(85, 85, 85); font-weight: normal;", "color: rgb(85, 85, 85); font-weight: normal;", "color: rgb(82, 140, 224); font-weight: normal; text-decoration: underline;"];
var welcomeMessage = "You're running avalon in debug mode - messages will be printed to the console to help you fix problems and optimise your application.\n\n" + 'To disable debug mode, add this line at the start of your app:\n\n avalon.config({debug: false});\n\n' + 'Debug mode also automatically shut down amicably when your app is minified.\n\n' + "Get help and support:\n https://segmentfault.com/t/avalon\n http://avalonjs.coding.me/\n http://www.baidu-x.com/?q=avalonjs\n http://www.avalon.org.cn/\n\nFound a bug? Raise an issue:\n https://github.com/RubyLouvre/avalon/issues\n\n";
if (typeof console === 'object') {
var con = console;
var method = con.groupCollapsed || con.log;
Function.apply.call(method, con, welcomeIntro);
con.log(welcomeMessage);
if (method !== console.log) {
con.groupEnd(welcomeIntro);
}
}
})();
function toFixedFix(n, prec) {
var k = Math.pow(10, prec);
return '' + (Math.round(n * k) / k).toFixed(prec);
}
function numberFilter(number, decimals, point, thousands) {
//https://github.com/txgruppi/number_format
//form http://phpjs.org/functions/number_format/
//number 必需,要格式化的数字
//decimals 可选,规定多少个小数位。
//point 可选,规定用作小数点的字符串(默认为 . )。
//thousands 可选,规定用作千位分隔符的字符串(默认为 , ),如果设置了该参数,那么所有其他参数都是必需的。
number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 3 : Math.abs(decimals),
sep = thousands || ",",
dec = point || ".",
s = '';
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
/** //好像没有用
var s1 = s[1] || ''
if (s1.length < prec) {
s1 += new Array(prec - s[1].length + 1).join('0')
s[1] = s1
}
**/
return s.join(dec);
}
var rscripts = /<script[^>]*>([\S\s]*?)<\/script\s*>/gim;
var ron = /\s+(on[^=\s]+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g;
var ropen = /<\w+\b(?:(["'])[^"]*?(\1)|[^>])*>/ig;
var rsanitize = {
a: /\b(href)\=("javascript[^"]*"|'javascript[^']*')/ig,
img: /\b(src)\=("javascript[^"]*"|'javascript[^']*')/ig,
form: /\b(action)\=("javascript[^"]*"|'javascript[^']*')/ig
};
//https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// <a href="javasc
ript:alert('XSS')">chrome</a>
// <a href="data:text/html;base64, PGltZyBzcmM9eCBvbmVycm9yPWFsZXJ0KDEpPg==">chrome</a>
// <a href="jav ascript:alert('XSS');">IE67chrome</a>
// <a href="jav	ascript:alert('XSS');">IE67chrome</a>
// <a href="jav
ascript:alert('XSS');">IE67chrome</a>
function sanitizeFilter(str) {
return str.replace(rscripts, "").replace(ropen, function (a, b) {
var match = a.toLowerCase().match(/<(\w+)\s/);
if (match) {
//处理a标签的href属性,img标签的src属性,form标签的action属性
var reg = rsanitize[match[1]];
if (reg) {
a = a.replace(reg, function (s, name, value) {
var quote = value.charAt(0);
return name + "=" + quote + "javascript:void(0)" + quote; // jshint ignore:line
});
}
}
return a.replace(ron, " ").replace(/\s+/g, " "); //移除onXXX事件
});
}
/*
'yyyy': 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
'yy': 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
'y': 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
'MMMM': Month in year (January-December)
'MMM': Month in year (Jan-Dec)
'MM': Month in year, padded (01-12)
'M': Month in year (1-12)
'dd': Day in month, padded (01-31)
'd': Day in month (1-31)
'EEEE': Day in Week,(Sunday-Saturday)
'EEE': Day in Week, (Sun-Sat)
'HH': Hour in day, padded (00-23)
'H': Hour in day (0-23)
'hh': Hour in am/pm, padded (01-12)
'h': Hour in am/pm, (1-12)
'mm': Minute in hour, padded (00-59)
'm': Minute in hour (0-59)
'ss': Second in minute, padded (00-59)
's': Second in minute (0-59)
'a': am/pm marker
'Z': 4 digit (+sign) representation of the timezone offset (-1200-+1200)
format string can also be one of the following predefined localizable formats:
'medium': equivalent to 'MMM d, y h:mm:ss a' for en_US locale (e.g. Sep 3, 2010 12:05:08 pm)
'short': equivalent to 'M/d/yy h:mm a' for en_US locale (e.g. 9/3/10 12:05 pm)
'fullDate': equivalent to 'EEEE, MMMM d,y' for en_US locale (e.g. Friday, September 3, 2010)
'longDate': equivalent to 'MMMM d, y' for en_US locale (e.g. September 3, 2010
'mediumDate': equivalent to 'MMM d, y' for en_US locale (e.g. Sep 3, 2010)
'shortDate': equivalent to 'M/d/yy' for en_US locale (e.g. 9/3/10)
'mediumTime': equivalent to 'h:mm:ss a' for en_US locale (e.g. 12:05:08 pm)
'shortTime': equivalent to 'h:mm a' for en_US locale (e.g. 12:05 pm)
*/
function toInt(str) {
return parseInt(str, 10) || 0;
}
function padNumber(num, digits, trim) {
var neg = '';
/* istanbul ignore if*/
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while (num.length < digits) {
num = '0' + num;
}if (trim) num = num.substr(num.length - digits);
return neg + num;
}
function dateGetter(name, size, offset, trim) {
return function (date) {
var value = date["get" + name]();
if (offset > 0 || value > -offset) value += offset;
if (value === 0 && offset === -12) {
/* istanbul ignore next*/
value = 12;
}
return padNumber(value, size, trim);
};
}
function dateStrGetter(name, shortForm) {
return function (date, formats) {
var value = date["get" + name]();
var get = (shortForm ? "SHORT" + name : name).toUpperCase();
return formats[get][value];
};
}
function timeZoneGetter(date) {
var zone = -1 * date.getTimezoneOffset();
var paddedZone = zone >= 0 ? "+" : "";
paddedZone += padNumber(Math[zone > 0 ? "floor" : "ceil"](zone / 60), 2) + padNumber(Math.abs(zone % 60), 2);
return paddedZone;
}
//取得上午下午
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
}
var DATE_FORMATS = {
yyyy: dateGetter("FullYear", 4),
yy: dateGetter("FullYear", 2, 0, true),
y: dateGetter("FullYear", 1),
MMMM: dateStrGetter("Month"),
MMM: dateStrGetter("Month", true),
MM: dateGetter("Month", 2, 1),
M: dateGetter("Month", 1, 1),
dd: dateGetter("Date", 2),
d: dateGetter("Date", 1),
HH: dateGetter("Hours", 2),
H: dateGetter("Hours", 1),
hh: dateGetter("Hours", 2, -12),
h: dateGetter("Hours", 1, -12),
mm: dateGetter("Minutes", 2),
m: dateGetter("Minutes", 1),
ss: dateGetter("Seconds", 2),
s: dateGetter("Seconds", 1),
sss: dateGetter("Milliseconds", 3),
EEEE: dateStrGetter("Day"),
EEE: dateStrGetter("Day", true),
a: ampmGetter,
Z: timeZoneGetter
};
var rdateFormat = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/;
var raspnetjson = /^\/Date\((\d+)\)\/$/;
function dateFilter(date, format) {
var locate = dateFilter.locate,
text = "",
parts = [],
fn,
match;
format = format || "mediumDate";
format = locate[format] || format;
if (typeof date === "string") {
if (/^\d+$/.test(date)) {
date = toInt(date);
} else if (raspnetjson.test(date)) {
date = +RegExp.$1;
} else {
var trimDate = date.trim();
var dateArray = [0, 0, 0, 0, 0, 0, 0];
var oDate = new Date(0);
//取得年月日
trimDate = trimDate.replace(/^(\d+)\D(\d+)\D(\d+)/, function (_, a, b, c) {
var array = c.length === 4 ? [c, a, b] : [a, b, c];
dateArray[0] = toInt(array[0]); //年
dateArray[1] = toInt(array[1]) - 1; //月
dateArray[2] = toInt(array[2]); //日
return "";
});
var dateSetter = oDate.setFullYear;
var timeSetter = oDate.setHours;
trimDate = trimDate.replace(/[T\s](\d+):(\d+):?(\d+)?\.?(\d)?/, function (_, a, b, c, d) {
dateArray[3] = toInt(a); //小时
dateArray[4] = toInt(b); //分钟
dateArray[5] = toInt(c); //秒
if (d) {
//毫秒
dateArray[6] = Math.round(parseFloat("0." + d) * 1000);
}
return "";
});
var tzHour = 0;
var tzMin = 0;
trimDate = trimDate.replace(/Z|([+-])(\d\d):?(\d\d)/, function (z, symbol, c, d) {
dateSetter = oDate.setUTCFullYear;
timeSetter = oDate.setUTCHours;
if (symbol) {
tzHour = toInt(symbol + c);
tzMin = toInt(symbol + d);
}
return '';
});
dateArray[3] -= tzHour;
dateArray[4] -= tzMin;
dateSetter.apply(oDate, dateArray.slice(0, 3));
timeSetter.apply(oDate, dateArray.slice(3));
date = oDate;
}
}
if (typeof date === 'number') {
date = new Date(date);
}
while (format) {
match = rdateFormat.exec(format);
/* istanbul ignore else */
if (match) {
parts = parts.concat(match.slice(1));
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
parts.forEach(function (value) {
fn = DATE_FORMATS[value];
text += fn ? fn(date, locate) : value.replace(/(^'|'$)/g, "").replace(/''/g, "'");
});
return text;
}
var locate = {
AMPMS: {
0: '上午',
1: '下午'
},
DAY: {
0: '星期日',
1: '星期一',
2: '星期二',
3: '星期三',
4: '星期四',
5: '星期五',
6: '星期六'
},
MONTH: {
0: '1月',
1: '2月',
2: '3月',
3: '4月',
4: '5月',
5: '6月',
6: '7月',
7: '8月',
8: '9月',
9: '10月',
10: '11月',
11: '12月'
},
SHORTDAY: {
'0': '周日',
'1': '周一',
'2': '周二',
'3': '周三',
'4': '周四',
'5': '周五',
'6': '周六'
},
fullDate: 'y年M月d日EEEE',
longDate: 'y年M月d日',
medium: 'yyyy-M-d H:mm:ss',
mediumDate: 'yyyy-M-d',
mediumTime: 'H:mm:ss',
'short': 'yy-M-d ah:mm',
shortDate: 'yy-M-d',
shortTime: 'ah:mm'
};
locate.SHORTMONTH = locate.MONTH;
dateFilter.locate = locate;
/*
https://github.com/hufyhang/orderBy/blob/master/index.js
*/
function orderBy(array, by, decend) {
var type = avalon.type(array);
if (type !== 'array' && type !== 'object') throw 'orderBy只能处理对象或数组';
var criteria = typeof by == 'string' ? function (el) {
return el && el[by];
} : typeof by === 'function' ? by : function (el) {
return el;
};
var mapping = {};
var temp = [];
var index = 0;
for (var key in array) {
if (array.hasOwnProperty(key)) {
var val = array[key];
var k = criteria(val, key);
if (k in mapping) {
mapping[k].push(key);
} else {
mapping[k] = [key];
}
temp.push(k);
}
}
temp.sort();
if (decend < 0) {
temp.reverse();
}
var _array = type === 'array';
var target = _array ? [] : {};
return recovery(target, temp, function (k) {
var key = mapping[k].shift();
if (_array) {
target.push(array[key]);
} else {
target[key] = array[key];
}
});
}
function filterBy(array, search) {
var type = avalon.type(array);
if (type !== 'array' && type !== 'object') throw 'filterBy只能处理对象或数组';
var args = avalon.slice(arguments, 2);
var stype = avalon.type(search);
if (stype === 'function') {
var criteria = search;
} else if (stype === 'string' || stype === 'number') {
if (search === '') {
return array;
} else {
var reg = new RegExp(avalon.escapeRegExp(search), 'i');
criteria = function criteria(el) {
return reg.test(el);
};
}
} else {
return array;
}
array = convertArray(array).filter(function (el, i) {
return !!criteria.apply(el, [el.value, i].concat(args));
});
var isArray$$1 = type === 'array';
var target = isArray$$1 ? [] : {};
return recovery(target, array, function (el) {
if (isArray$$1) {
target.push(el.value);
} else {
target[el.key] = el.value;
}
});
}
function selectBy(data, array, defaults) {
if (avalon.isObject(data) && !Array.isArray(data)) {
var target = [];
return recovery(target, array, function (name) {
target.push(data.hasOwnProperty(name) ? data[name] : defaults ? defaults[name] : '');
});
} else {
return data;
}
}
function limitBy(input, limit, begin) {
var type = avalon.type(input);
if (type !== 'array' && type !== 'object') throw 'limitBy只能处理对象或数组';
//必须是数值
if (typeof limit !== 'number') {
return input;
}
//不能为NaN
if (limit !== limit) {
return input;
}
//将目标转换为数组
if (type === 'object') {
input = convertArray(input);
}
var n = input.length;
limit = Math.floor(Math.min(n, limit));
begin = typeof begin === 'number' ? begin : 0;
if (begin < 0) {
begin = Math.max(0, n + begin);
}
var data = [];
for (var i = begin; i < n; i++) {
if (data.length === limit) {
break;
}
data.push(input[i]);
}
var isArray$$1 = type === 'array';
if (isArray$$1) {
return data;
}
var target = {};
return recovery(target, data, function (el) {
target[el.key] = el.value;
});
}
function recovery(ret, array, callback) {
for (var i = 0, n = array.length; i < n; i++) {
callback(array[i]);
}
return ret;
}
//Chrome谷歌浏览器中js代码Array.sort排序的bug乱序解决办法
//http://www.cnblogs.com/yzeng/p/3949182.html
function convertArray(array) {
var ret = [],
i = 0;
for (var key in array) {
if (array.hasOwnProperty(key)) {
ret[i] = {
oldIndex: i,
value: array[key],
key: key
};
i++;
}
}
return ret;
}
var eventFilters = {
stop: function stop(e) {
e.stopPropagation();
return e;
},
prevent: function prevent(e) {
e.preventDefault();
return e;
}
};
var keys = {
esc: 27,
tab: 9,
enter: 13,
space: 32,
del: 46,
up: 38,
left: 37,
right: 39,
down: 40
};
for (var name$1 in keys) {
(function (filter, key) {
eventFilters[filter] = function (e) {
if (e.which !== key) {
e.$return = true;
}
return e;
};
})(name$1, keys[name$1]);
}
//https://github.com/teppeis/htmlspecialchars
function escapeFilter(str) {
if (str == null) return '';
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
}
var filters = avalon.filters = {};
avalon.composeFilters = function () {
var args = arguments;
return function (value) {
for (var i = 0, arr; arr = args[i++];) {
var name = arr[0];
var filter = avalon.filters[name];
if (typeof filter === 'function') {
arr[0] = value;
try {
value = filter.apply(0, arr);
} catch (e) {}
}
}
return value;
};
};
avalon.escapeHtml = escapeFilter;
avalon.mix(filters, {
uppercase: function uppercase(str) {
return String(str).toUpperCase();
},
lowercase: function lowercase(str) {
return String(str).toLowerCase();
},
truncate: function truncate(str, length, end) {
//length,新字符串长度,truncation,新字符串的结尾的字段,返回新字符串
if (!str) {
return '';
}
str = String(str);
if (isNaN(length)) {
length = 30;
}
end = typeof end === "string" ? end : "...";
return str.length > length ? str.slice(0, length - end.length) + end : /* istanbul ignore else*/
str;
},
camelize: avalon.camelize,
date: dateFilter,
escape: escapeFilter,
sanitize: sanitizeFilter,
number: numberFilter,
currency: function currency(amount, symbol, fractionSize) {
return (symbol || '\xA5') + numberFilter(amount, isFinite(fractionSize) ? /* istanbul ignore else*/fractionSize : 2);
}
}, { filterBy: filterBy, orderBy: orderBy, selectBy: selectBy, limitBy: limitBy }, eventFilters);
var rcheckedType = /^(?:checkbox|radio)$/;
/* istanbul ignore next */
function fixElement(dest, src) {
if (dest.nodeType !== 1) {
return;
}
var nodeName = dest.nodeName.toLowerCase();
if (nodeName === "script") {
if (dest.text !== src.text) {
dest.type = "noexec";
dest.text = src.text;
dest.type = src.type || "";
}
} else if (nodeName === 'object') {
var params = src.childNodes;
if (dest.childNodes.length !== params.length) {
avalon.clearHTML(dest);
for (var i = 0, el; el = params[i++];) {
dest.appendChild(el.cloneNode(true));
}
}
} else if (nodeName === 'input' && rcheckedType.test(src.nodeName)) {
dest.defaultChecked = dest.checked = src.checked;
if (dest.value !== src.value) {
dest.value = src.value;
}
} else if (nodeName === 'option') {
dest.defaultSelected = dest.selected = src.defaultSelected;
} else if (nodeName === 'input' || nodeName === 'textarea') {
dest.defaultValue = src.defaultValue;
}
}
/* istanbul ignore next */
function getAll(context) {
return typeof context.getElementsByTagName !== 'undefined' ? context.getElementsByTagName('*') : typeof context.querySelectorAll !== 'undefined' ? context.querySelectorAll('*') : [];
}
/* istanbul ignore next */
function fixClone(src) {
var target = src.cloneNode(true);
//http://www.myexception.cn/web/665613.html
// target.expando = null
var t = getAll(target);
var s = getAll(src);
for (var i = 0; i < s.length; i++) {
fixElement(t[i], s[i]);
}
return target;
}
/* istanbul ignore next */
function fixContains(root, el) {
try {
//IE6-8,游离于DOM树外的文本节点,访问parentNode有时会抛错
while (el = el.parentNode) {
if (el === root) return true;
}
} catch (e) {}
return false;
}
avalon.contains = fixContains;
avalon.cloneNode = function (a) {
return a.cloneNode(true);
};
//IE6-11的文档对象没有contains
/* istanbul ignore next */
function shimHack() {
if (msie < 10) {
avalon.cloneNode = fixClone;
}
if (!document$1.contains) {
document$1.contains = function (b) {
return fixContains(document$1, b);
};
}
if (avalon.modern) {
if (!document$1.createTextNode('x').contains) {
Node.prototype.contains = function (child) {
//IE6-8没有Node对象
return fixContains(this, child);
};
}
}
//firefox 到11时才有outerHTML
function fixFF(prop, cb) {
if (!(prop in root) && HTMLElement.prototype.__defineGetter__) {
HTMLElement.prototype.__defineGetter__(prop, cb);
}
}
fixFF('outerHTML', function () {
var div = document$1.createElement('div');
div.appendChild(this);
return div.innerHTML;
});
fixFF('children', function () {
var children = [];
for (var i = 0, el; el = this.childNodes[i++];) {
if (el.nodeType === 1) {
children.push(el);
}
}
return children;
});
fixFF('innerText', function () {
//firefox45+, chrome4+ http://caniuse.com/#feat=innertext
return this.textContent;
});
}
if (inBrowser) {
shimHack();
}
function ClassList(node) {
this.node = node;
}
ClassList.prototype = {
toString: function toString() {
var node = this.node;
var cls = node.className;
var str = typeof cls === 'string' ? cls : cls.baseVal;
var match = str.match(rnowhite);
return match ? match.join(' ') : '';
},
contains: function contains(cls) {
return (' ' + this + ' ').indexOf(' ' + cls + ' ') > -1;
},
add: function add(cls) {
if (!this.contains(cls)) {
this.set(this + ' ' + cls);
}
},
remove: function remove(cls) {
this.set((' ' + this + ' ').replace(' ' + cls + ' ', ' '));
},
set: function set(cls) {
cls = cls.trim();
var node = this.node;
if (typeof node.className === 'object') {
//SVG元素的className是一个对象 SVGAnimatedString { baseVal='', animVal=''},只能通过set/getAttribute操作
node.setAttribute('class', cls);
} else {
node.className = cls;
}
if (!cls) {
node.removeAttribute('class');
}
//toggle存在版本差异,因此不使用它
}
};
function classListFactory(node) {
if (!('classList' in node)) {
node.classList = new ClassList(node);
}
return node.classList;
}
'add,remove'.replace(rword, function (method) {
avalon.fn[method + 'Class'] = function (cls) {
var el = this[0] || {};
//https://developer.mozilla.org/zh-CN/docs/Mozilla/Firefox/Releases/26
if (cls && typeof cls === 'string' && el.nodeType === 1) {
cls.replace(rnowhite, function (c) {
classListFactory(el)[method](c);
});
}
return this;
};
});
avalon.shadowCopy(avalon.fn, {
hasClass: function hasClass(cls) {
var el = this[0] || {};
return el.nodeType === 1 && classListFactory(el).contains(cls);
},
toggleClass: function toggleClass(value, stateVal) {
var isBool = typeof stateVal === 'boolean';
var me = this;
String(value).replace(rnowhite, function (c) {
var state = isBool ? stateVal : !me.hasClass(c);
me[state ? 'addClass' : 'removeClass'](c);
});
return this;
}
});
var propMap = { //不规则的属性名映射
'accept-charset': 'acceptCharset',
'char': 'ch',
charoff: 'chOff',
'class': 'className',
'for': 'htmlFor',
'http-equiv': 'httpEquiv'
};
/*
contenteditable不是布尔属性
http://www.zhangxinxu.com/wordpress/2016/01/contenteditable-plaintext-only/
contenteditable=''
contenteditable='events'
contenteditable='caret'
contenteditable='plaintext-only'
contenteditable='true'
contenteditable='false'
*/
var bools = ['autofocus,autoplay,async,allowTransparency,checked,controls', 'declare,disabled,defer,defaultChecked,defaultSelected,', 'isMap,loop,multiple,noHref,noResize,noShade', 'open,readOnly,selected'].join(',');
bools.replace(/\w+/g, function (name) {
propMap[name.toLowerCase()] = name;
});
var anomaly = ['accessKey,bgColor,cellPadding,cellSpacing,codeBase,codeType,colSpan', 'dateTime,defaultValue,contentEditable,frameBorder,longDesc,maxLength,' + 'marginWidth,marginHeight,rowSpan,tabIndex,useMap,vSpace,valueType,vAlign'].join(',');
anomaly.replace(/\w+/g, function (name) {
propMap[name.toLowerCase()] = name;
});
//module.exports = propMap
function isVML(src) {
var nodeName = src.nodeName;
return nodeName.toLowerCase() === nodeName && !!src.scopeName && src.outerText === '';
}
var rvalidchars = /^[\],:{}\s]*$/;
var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
var rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g;
var rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g;
function compactParseJSON(data) {
if (typeof data === 'string') {
data = data.trim();
if (data) {
if (rvalidchars.test(data.replace(rvalidescape, '@').replace(rvalidtokens, ']').replace(rvalidbraces, ''))) {
return new Function('return ' + data)(); // jshint ignore:line
}
}
throw TypeError('Invalid JSON: [' + data + ']');
}
return data;
}
var rsvg = /^\[object SVG\w*Element\]$/;
var ramp = /&/g;
function updateAttrs(node, attrs) {
for (var attrName in attrs) {
try {
var val = attrs[attrName];
// 处理路径属性
/* istanbul ignore if*/
//处理HTML5 data-*属性 SVG
if (attrName.indexOf('data-') === 0 || rsvg.test(node)) {
node.setAttribute(attrName, val);
} else {
var propName = propMap[attrName] || attrName;
/* istanbul ignore if */
if (typeof node[propName] === 'boolean') {
if (propName === 'checked') {
node.defaultChecked = !!val;
}
node[propName] = !!val;
//布尔属性必须使用el.xxx = true|false方式设值
//如果为false, IE全系列下相当于setAttribute(xxx,''),
//会影响到样式,需要进一步处理
}
if (val === false) {
//移除属性
node.removeAttribute(propName);
continue;
}
//IE6中classNamme, htmlFor等无法检测它们为内建属性
if (avalon.msie < 8 && /[A-Z]/.test(propName)) {
node[propName] = val + '';
continue;
}
//SVG只能使用setAttribute(xxx, yyy), VML只能使用node.xxx = yyy ,
//HTML的固有属性必须node.xxx = yyy
/* istanbul ignore next */
var isInnate = !avalon.modern && isVML(node) ? true : isInnateProps(node.nodeName, attrName);
if (isInnate) {
if (attrName === 'href' || attrName === 'src') {
/* istanbul ignore if */
if (avalon.msie < 8) {
val = String(val).replace(ramp, '&'); //处理IE67自动转义的问题
}
}
node[propName] = val + '';
} else {
node.setAttribute(attrName, val);
}
}
} catch (e) {
// 对象不支持此属性或方法 src https://github.com/ecomfe/zrender
// 未知名称。\/n
// e.message大概这样,需要trim
//IE6-8,元素节点不支持其他元素节点的内置属性,如src, href, for
/* istanbul ignore next */
avalon.log(String(e.message).trim(), attrName, val);
}
}
}
var innateMap = {};
function isInnateProps(nodeName, attrName) {
var key = nodeName + ":" + attrName;
if (key in innateMap) {
return innateMap[key];
}
return innateMap[key] = attrName in document$1.createElement(nodeName);
}
try {
avalon.parseJSON = JSON.parse;
} catch (e) {
/* istanbul ignore next */
avalon.parseJSON = compactParseJSON;
}
avalon.fn.attr = function (name, value) {
if (arguments.length === 2) {
this[0].setAttribute(name, value);
return this;
} else {
return this[0].getAttribute(name);
}
};
var cssMap = {
'float': 'cssFloat'
};
avalon.cssNumber = oneObject('animationIterationCount,columnCount,order,flex,flexGrow,flexShrink,fillOpacity,fontWeight,lineHeight,opacity,orphans,widows,zIndex,zoom');
var prefixes = ['', '-webkit-', '-o-', '-moz-', '-ms-'];
/* istanbul ignore next */
avalon.cssName = function (name, host, camelCase) {
if (cssMap[name]) {
return cssMap[name];
}
host = host || avalon.root.style || {};
for (var i = 0, n = prefixes.length; i < n; i++) {
camelCase = avalon.camelize(prefixes[i] + name);
if (camelCase in host) {
return cssMap[name] = camelCase;
}
}
return null;
};
/* istanbul ignore next */
avalon.css = function (node, name, value, fn) {
//读写删除元素节点的样式
if (node instanceof avalon) {
node = node[0];
}
if (node.nodeType !== 1) {
return;
}
var prop = avalon.camelize(name);
name = avalon.cssName(prop) || /* istanbul ignore next*/prop;
if (value === void 0 || typeof value === 'boolean') {
//获取样式
fn = cssHooks[prop + ':get'] || cssHooks['@:get'];
if (name === 'background') {
name = 'backgroundColor';
}
var val = fn(node, name);
return value === true ? parseFloat(val) || 0 : val;
} else if (value === '') {
//请除样式
node.style[name] = '';
} else {
//设置样式
if (value == null || value !== value) {
return;
}
if (isFinite(value) && !avalon.cssNumber[prop]) {
value += 'px';
}
fn = cssHooks[prop + ':set'] || cssHooks['@:set'];
fn(node, name, value);
}
};
/* istanbul ignore next */
avalon.fn.css = function (name, value) {
if (avalon.isPlainObject(name)) {
for (var i in name) {
avalon.css(this, i, name[i]);
}
} else {
var ret = avalon.css(this, name, value);
}
return ret !== void 0 ? ret : this;
};
/* istanbul ignore next */
avalon.fn.position = function () {
var offsetParent,
offset,
elem = this[0],
parentOffset = {
top: 0,
left: 0
};
if (!elem) {
return parentOffset;
}
if (this.css('position') === 'fixed') {
offset = elem.getBoundingClientRect();
} else {
offsetParent = this.offsetParent(); //得到真正的offsetParent
offset = this.offset(); // 得到正确的offsetParent
if (offsetParent[0].tagName !== 'HTML') {
parentOffset = offsetParent.offset();
}
parentOffset.top += avalon.css(offsetParent[0], 'borderTopWidth', true);
parentOffset.left += avalon.css(offsetParent[0], 'borderLeftWidth', true);
// Subtract offsetParent scroll positions
parentOffset.top -= offsetParent.scrollTop();
parentOffset.left -= offsetParent.scrollLeft();
}
return {
top: offset.top - parentOffset.top - avalon.css(elem, 'marginTop', true),
left: offset.left - parentOffset.left - avalon.css(elem, 'marginLeft', true)
};
};
/* istanbul ignore next */
avalon.fn.offsetParent = function () {
var offsetParent = this[0].offsetParent;
while (offsetParent && avalon.css(offsetParent, 'position') === 'static') {
offsetParent = offsetParent.offsetParent;
}
return avalon(offsetParent || avalon.root);
};
/* istanbul ignore next */
cssHooks['@:set'] = function (node, name, value) {
try {
//node.style.width = NaN;node.style.width = 'xxxxxxx';
//node.style.width = undefine 在旧式IE下会抛异常
node.style[name] = value;
} catch (e) {}
};
/* istanbul ignore next */
cssHooks['@:get'] = function (node, name) {
if (!node || !node.style) {
throw new Error('getComputedStyle要求传入一个节点 ' + node);
}
var ret,
styles = window$1.getComputedStyle(node, null);
if (styles) {
ret = name === 'filter' ? styles.getPropertyValue(name) : styles[name];
if (ret === '') {
ret = node.style[name]; //其他浏览器需要我们手动取内联样式
}
}
return ret;
};
cssHooks['opacity:get'] = function (node) {
var ret = cssHooks['@:get'](node, 'opacity');
return ret === '' ? '1' : ret;
};
'top,left'.replace(avalon.rword, function (name) {
cssHooks[name + ':get'] = function (node) {
var computed = cssHooks['@:get'](node, name);
return (/px$/.test(computed) ? computed : avalon(node).position()[name] + 'px'
);
};
});
var cssShow = {
position: 'absolute',
visibility: 'hidden',
display: 'block'
};
var rdisplayswap = /^(none|table(?!-c[ea]).+)/;
/* istanbul ignore next */
function showHidden(node, array) {
//http://www.cnblogs.com/rubylouvre/archive/2012/10/27/2742529.html
if (node.offsetWidth <= 0) {
//opera.offsetWidth可能小于0
if (rdisplayswap.test(cssHooks['@:get'](node, 'display'))) {
var obj = {
node: node
};
for (var name in cssShow) {
obj[name] = node.style[name];
node.style[name] = cssShow[name];
}
array.push(obj);
}
var parent = node.parentNode;
if (parent && parent.nodeType === 1) {
showHidden(parent, array);
}
}
}
/* istanbul ignore next*/
avalon.each({
Width: 'width',
Height: 'height'
}, function (name, method) {
var clientProp = 'client' + name,
scrollProp = 'scroll' + name,
offsetProp = 'offset' + name;
cssHooks[method + ':get'] = function (node, which, override) {
var boxSizing = -4;
if (typeof override === 'number') {
boxSizing = override;
}
which = name === 'Width' ? ['Left', 'Right'] : ['Top', 'Bottom'];
var ret = node[offsetProp]; // border-box 0
if (boxSizing === 2) {
// margin-box 2
return ret + avalon.css(node, 'margin' + which[0], true) + avalon.css(node, 'margin' + which[1], true);
}
if (boxSizing < 0) {
// padding-box -2
ret = ret - avalon.css(node, 'border' + which[0] + 'Width', true) - avalon.css(node, 'border' + which[1] + 'Width', true);
}
if (boxSizing === -4) {
// content-box -4
ret = ret - avalon.css(node, 'padding' + which[0], true) - avalon.css(node, 'padding' + which[1], true);
}
return ret;
};
cssHooks[method + '&get'] = function (node) {
var hidden = [];
showHidden(node, hidden);
var val = cssHooks[method + ':get'](node);
for (var i = 0, obj; obj = hidden[i++];) {
node = obj.node;
for (var n in obj) {
if (typeof obj[n] === 'string') {
node.style[n] = obj[n];
}
}
}
return val;
};
avalon.fn[method] = function (value) {
//会忽视其display
var node = this[0];
if (arguments.length === 0) {
if (node.setTimeout) {
//取得窗口尺寸
return node['inner' + name] || node.document.documentElement[clientProp] || node.document.body[clientProp]; //IE6下前两个分别为undefined,0
}
if (node.nodeType === 9) {
//取得页面尺寸
var doc = node.documentElement;
//FF chrome html.scrollHeight< body.scrollHeight
//IE 标准模式 : html.scrollHeight> body.scrollHeight
//IE 怪异模式 : html.scrollHeight 最大等于可视窗口多一点?
return Math.max(node.body[scrollProp], doc[scrollProp], node.body[offsetProp], doc[offsetProp], doc[clientProp]);
}
return cssHooks[method + '&get'](node);
} else {
return this.css(method, value);
}
};
avalon.fn['inner' + name] = function () {
return cssHooks[method + ':get'](this[0], void 0, -2);
};
avalon.fn['outer' + name] = function (includeMargin) {
return cssHooks[method + ':get'](this[0], void 0, includeMargin === true ? 2 : 0);
};
});
function getWindow(node) {
return node.window || node.defaultView || node.parentWindow || false;
}
/* istanbul ignore if */
if (msie < 9) {
cssMap['float'] = 'styleFloat';
var rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i;
var rposition = /^(top|right|bottom|left)$/;
var ralpha = /alpha\([^)]+\)/i;
var ropactiy = /(opacity|\d(\d|\.)*)/g;
var ie8 = msie === 8;
var salpha = 'DXImageTransform.Microsoft.Alpha';
var border = {
thin: ie8 ? '1px' : '2px',
medium: ie8 ? '3px' : '4px',
thick: ie8 ? '5px' : '6px'
};
cssHooks['@:get'] = function (node, name) {
//取得精确值,不过它有可能是带em,pc,mm,pt,%等单位
var currentStyle = node.currentStyle;
var ret = currentStyle[name];
if (rnumnonpx.test(ret) && !rposition.test(ret)) {
//①,保存原有的style.left, runtimeStyle.left,
var style = node.style,
left = style.left,
rsLeft = node.runtimeStyle.left;
//②由于③处的style.left = xxx会影响到currentStyle.left,
//因此把它currentStyle.left放到runtimeStyle.left,
//runtimeStyle.left拥有最高优先级,不会style.left影响
node.runtimeStyle.left = currentStyle.left;
//③将精确值赋给到style.left,然后通过IE的另一个私有属性 style.pixelLeft
//得到单位为px的结果;fontSize的分支见http://bugs.jquery.com/ticket/760
style.left = name === 'fontSize' ? '1em' : ret || 0;
ret = style.pixelLeft + 'px';
//④还原 style.left,runtimeStyle.left
style.left = left;
node.runtimeStyle.left = rsLeft;
}
if (ret === 'medium') {
name = name.replace('Width', 'Style');
//border width 默认值为medium,即使其为0'
if (currentStyle[name] === 'none') {
ret = '0px';
}
}
return ret === '' ? 'auto' : border[ret] || ret;
};
cssHooks['opacity:set'] = function (node, name, value) {
var style = node.style;
var opacity = Number(value) <= 1 ? 'alpha(opacity=' + value * 100 + ')' : '';
var filter = style.filter || '';
style.zoom = 1;
//不能使用以下方式设置透明度
//node.filters.alpha.opacity = value * 100
style.filter = (ralpha.test(filter) ? filter.replace(ralpha, opacity) : filter + ' ' + opacity).trim();
if (!style.filter) {
style.removeAttribute('filter');
}
};
cssHooks['opacity:get'] = function (node) {
var match = node.style.filter.match(ropactiy) || [];
var ret = false;
for (var i = 0, el; el = match[i++];) {
if (el === 'opacity') {
ret = true;
} else if (ret) {
return el / 100 + '';
}
}
return '1'; //确保返回的是字符串
};
}
/* istanbul ignore next */
avalon.fn.offset = function () {
//取得距离页面左右角的坐标
var node = this[0],
box = {
left: 0,
top: 0
};
if (!node || !node.tagName || !node.ownerDocument) {
return box;
}
var doc = node.ownerDocument;
var body = doc.body;
var root$$1 = doc.documentElement;
var win = doc.defaultView || doc.parentWindow;
if (!avalon.contains(root$$1, node)) {
return box;
}
//http://hkom.blog1.fc2.com/?mode=m&no=750 body的偏移量是不包含margin的
//我们可以通过getBoundingClientRect来获得元素相对于client的rect.
//http://msdn.microsoft.com/en-us/library/ms536433.aspx
if (node.getBoundingClientRect) {
box = node.getBoundingClientRect(); // BlackBerry 5, iOS 3 (original iPhone)
}
//chrome/IE6: body.scrollTop, firefox/other: root.scrollTop
var clientTop = root$$1.clientTop || body.clientTop,
clientLeft = root$$1.clientLeft || body.clientLeft,
scrollTop = Math.max(win.pageYOffset || 0, root$$1.scrollTop, body.scrollTop),
scrollLeft = Math.max(win.pageXOffset || 0, root$$1.scrollLeft, body.scrollLeft);
// 把滚动距离加到left,top中去。
// IE一些版本中会自动为HTML元素加上2px的border,我们需要去掉它
// http://msdn.microsoft.com/en-us/library/ms533564(VS.85).aspx
return {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
};
//生成avalon.fn.scrollLeft, avalon.fn.scrollTop方法
/* istanbul ignore next */
avalon.each({
scrollLeft: 'pageXOffset',
scrollTop: 'pageYOffset'
}, function (method, prop) {
avalon.fn[method] = function (val) {
var node = this[0] || {};
var win = getWindow(node);
var root$$1 = avalon.root;
var top = method === 'scrollTop';
if (!arguments.length) {
return win ? prop in win ? win[prop] : root$$1[method] : node[method];
} else {
if (win) {
win.scrollTo(!top ? val : avalon(win).scrollLeft(), top ? val : avalon(win).scrollTop());
} else {
node[method] = val;
}
}
};
});
function getDuplexType(elem) {
var ret = elem.tagName.toLowerCase();
if (ret === 'input') {
return rcheckedType.test(elem.type) ? 'checked' : elem.type;
}
return ret;
}
/**
* IE6/7/8中,如果option没有value值,那么将返回空字符串。
* IE9/Firefox/Safari/Chrome/Opera 中先取option的value值,如果没有value属性,则取option的innerText值。
* IE11及W3C,如果没有指定value,那么node.value默认为node.text(存在trim作),但IE9-10则是取innerHTML(没trim操作)
*/
function getOption(node) {
if (node.hasAttribute && node.hasAttribute('value')) {
return node.getAttribute('value');
}
var attr = node.getAttributeNode('value');
if (attr && attr.specified) {
return attr.value;
}
return node.innerHTML.trim();
}
var valHooks = {
'option:get': msie ? getOption : function (node) {
return node.value;
},
'select:get': function selectGet(node, value) {
var option,
options = node.options,
index = node.selectedIndex,
getter = valHooks['option:get'],
one = node.type === 'select-one' || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ? max : one ? index : 0;
for (; i < max; i++) {
option = options[i];
//IE6-9在reset后不会改变selected,需要改用i === index判定
//我们过滤所有disabled的option元素,但在safari5下,
//如果设置optgroup为disable,那么其所有孩子都disable
//因此当一个元素为disable,需要检测其是否显式设置了disable及其父节点的disable情况
if ((option.selected || i === index) && !option.disabled && (!option.parentNode.disabled || option.parentNode.tagName !== 'OPTGROUP')) {
value = getter(option);
if (one) {
return value;
}
//收集所有selected值组成数组返回
values.push(value);
}
}
return values;
},
'select:set': function selectSet(node, values, optionSet) {
values = [].concat(values); //强制转换为数组
var getter = valHooks['option:get'];
for (var i = 0, el; el = node.options[i++];) {
if (el.selected = values.indexOf(getter(el)) > -1) {
optionSet = true;
}
}
if (!optionSet) {
node.selectedIndex = -1;
}
}
};
avalon.fn.val = function (value) {
var node = this[0];
if (node && node.nodeType === 1) {
var get = arguments.length === 0;
var access = get ? ':get' : ':set';
var fn = valHooks[getDuplexType(node) + access];
if (fn) {
var val = fn(node, value);
} else if (get) {
return (node.value || '').replace(/\r/g, '');
} else {
node.value = value;
}
}
return get ? val : this;
};
/*
* 将要检测的字符串的字符串替换成??123这样的格式
*/
var stringNum = 0;
var stringPool = {
map: {}
};
var rfill = /\?\?\d+/g;
function dig(a) {
var key = '??' + stringNum++;
stringPool.map[key] = a;
return key + ' ';
}
function fill(a) {
var val = stringPool.map[a];
return val;
}
function clearString(str) {
var array = readString(str);
for (var i = 0, n = array.length; i < n; i++) {
str = str.replace(array[i], dig);
}
return str;
}
function readString(str) {
var end,
s = 0;
var ret = [];
for (var i = 0, n = str.length; i < n; i++) {
var c = str.charAt(i);
if (!end) {
if (c === "'") {
end = "'";
s = i;
} else if (c === '"') {
end = '"';
s = i;
}
} else {
if (c === end) {
ret.push(str.slice(s, i + 1));
end = false;
}
}
}
return ret;
}
var voidTag = {
area: 1,
base: 1,
basefont: 1,
bgsound: 1,
br: 1,
col: 1,
command: 1,
embed: 1,
frame: 1,
hr: 1,
img: 1,
input: 1,
keygen: 1,
link: 1,
meta: 1,
param: 1,
source: 1,
track: 1,
wbr: 1
};
var orphanTag = {
script: 1,
style: 1,
textarea: 1,
xmp: 1,
noscript: 1,
template: 1
};
/*
* 此模块只用于文本转虚拟DOM,
* 因为在真实浏览器会对我们的HTML做更多处理,
* 如, 添加额外属性, 改变结构
* 此模块就是用于模拟这些行为
*/
function makeOrphan(node, nodeName, innerHTML) {
switch (nodeName) {
case 'style':
case 'script':
case 'noscript':
case 'template':
case 'xmp':
node.children = [{
nodeName: '#text',
nodeValue: innerHTML
}];
break;
case 'textarea':
var props = node.props;
props.type = nodeName;
props.value = innerHTML;
node.children = [{
nodeName: '#text',
nodeValue: innerHTML
}];
break;
case 'option':
node.children = [{
nodeName: '#text',
nodeValue: trimHTML(innerHTML)
}];
break;
}
}
//专门用于处理option标签里面的标签
var rtrimHTML = /<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi;
function trimHTML(v) {
return String(v).replace(rtrimHTML, '').trim();
}
//widget rule duplex validate
//如果直接将tr元素写table下面,那么浏览器将将它们(相邻的那几个),放到一个动态创建的tbody底下
function makeTbody(nodes) {
var tbody,
needAddTbody = false,
count = 0,
start = 0,
n = nodes.length;
for (var i = 0; i < n; i++) {
var node = nodes[i];
if (!tbody) {
if (node.nodeName === 'tr') {
//收集tr及tr两旁的注释节点
tbody = {
nodeName: 'tbody',
props: {},
children: []
};
tbody.children.push(node);
needAddTbody = true;
if (start === 0) start = i;
nodes[i] = tbody;
}
} else {
if (node.nodeName !== 'tr' && node.children) {
tbody = false;
} else {
tbody.children.push(node);
count++;
nodes[i] = 0;
}
}
}
if (needAddTbody) {
for (i = start; i < n; i++) {
if (nodes[i] === 0) {
nodes.splice(i, 1);
i--;
count--;
if (count === 0) {
break;
}
}
}
}
}
function validateDOMNesting(parent, child) {
var parentTag = parent.nodeName;
var tag = child.nodeName;
var parentChild = nestObject[parentTag];
if (parentChild) {
if (parentTag === 'p') {
if (pNestChild[tag]) {
avalon.warn('P element can not add these childlren:\n' + Object.keys(pNestChild));
return false;
}
} else if (!parentChild[tag]) {
avalon.warn(parentTag.toUpperCase() + 'element only add these children:\n' + Object.keys(parentChild) + '\nbut you add ' + tag.toUpperCase() + ' !!');
return false;
}
}
return true;
}
function makeObject(str) {
return oneObject(str + ',template,#document-fragment,#comment');
}
var pNestChild = oneObject('div,ul,ol,dl,table,h1,h2,h3,h4,h5,h6,form,fieldset');
var tNestChild = makeObject('tr,style,script');
var nestObject = {
p: pNestChild,
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
select: makeObject('option,optgroup,#text'),
optgroup: makeObject('option,#text'),
option: makeObject('#text'),
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
// No special behavior since these rules fall back to "in body" mode for
// all except special table nodes which cause bad parsing behavior anyway.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
tr: makeObject('th,td,style,script'),
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
tbody: tNestChild,
tfoot: tNestChild,
thead: tNestChild,
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
colgroup: makeObject('col'),
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
// table: oneObject('caption,colgroup,tbody,thead,tfoot,style,script,template,#document-fragment'),
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
head: makeObject('base,basefont,bgsound,link,style,script,meta,title,noscript,noframes'),
// https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
html: oneObject('head,body')
};
/**
* ------------------------------------------------------------
* avalon2.1.1的新式lexer
* 将字符串变成一个虚拟DOM树,方便以后进一步变成模板函数
* 此阶段只会生成VElement,VText,VComment
* ------------------------------------------------------------
*/
function nomalString(str) {
return avalon.unescapeHTML(str.replace(rfill, fill));
}
//https://github.com/rviscomi/trunk8/blob/master/trunk8.js
var ropenTag = /^<([-A-Za-z0-9_]+)\s*([^>]*?)(\/?)>/;
var rendTag = /^<\/([^>]+)>/;
var rtagStart = /[\!\/a-z]/i; //闭标签的第一个字符,开标签的第一个英文,注释节点的!
var rlineSp = /\\n\s*/g;
var rattrs = /([^=\s]+)(?:\s*=\s*(\S+))?/;
var rcontent = /\S/; //判定里面有没有内容
function fromString(str) {
return from(str);
}
avalon.lexer = fromString;
var strCache = new Cache(100);
function AST() {}
AST.prototype = {
init: function init(str) {
this.ret = [];
var stack = [];
stack.last = function () {
return stack[stack.length - 1];
};
this.stack = stack;
this.str = str;
},
gen: function gen() {
var breakIndex = 999999;
do {
this.tryGenText();
this.tryGenComment();
this.tryGenOpenTag();
this.tryGenCloseTag();
var node = this.node;
this.node = 0;
if (!node || --breakIndex === 0) {
break;
}
if (node.end) {
if (node.nodeName === 'table') {
makeTbody(node.children);
}
delete node.end;
}
} while (this.str.length);
return this.ret;
},
fixPos: function fixPos(str, i) {
var tryCount = str.length - i;
while (tryCount--) {
if (!rtagStart.test(str.charAt(i + 1))) {
i = str.indexOf('<', i + 1);
} else {
break;
}
}
if (tryCount === 0) {
i = str.length;
}
return i;
},
tryGenText: function tryGenText() {
var str = this.str;
if (str.charAt(0) !== '<') {
//处理文本节点
var i = str.indexOf('<');
if (i === -1) {
i = str.length;
} else if (!rtagStart.test(str.charAt(i + 1))) {
//处理`内容2 {{ (idx1 < < < 1 ? 'red' : 'blue' ) + a }} ` 的情况
i = this.fixPos(str, i);
}
var nodeValue = str.slice(0, i).replace(rfill, fill);
this.str = str.slice(i);
this.node = {
nodeName: '#text',
nodeValue: nodeValue
};
if (rcontent.test(nodeValue)) {
this.tryGenChildren(); //不收集空白节点
}
}
},
tryGenComment: function tryGenComment() {
if (!this.node) {
var str = this.str;
var i = str.indexOf('<!--'); //处理注释节点
/* istanbul ignore if*/
if (i === 0) {
var l = str.indexOf('-->');
if (l === -1) {
avalon.error('注释节点没有闭合' + str);
}
var nodeValue = str.slice(4, l).replace(rfill, fill);
this.str = str.slice(l + 3);
this.node = {
nodeName: '#comment',
nodeValue: nodeValue
};
this.tryGenChildren();
}
}
},
tryGenOpenTag: function tryGenOpenTag() {
if (!this.node) {
var str = this.str;
var match = str.match(ropenTag); //处理元素节点开始部分
if (match) {
var nodeName = match[1];
var props = {};
if (/^[A-Z]/.test(nodeName) && avalon.components[nodeName]) {
props.is = nodeName;
}
nodeName = nodeName.toLowerCase();
var isVoidTag = !!voidTag[nodeName] || match[3] === '\/';
var node = this.node = {
nodeName: nodeName,
props: {},
children: [],
isVoidTag: isVoidTag
};
var attrs = match[2];
if (attrs) {
this.genProps(attrs, node.props);
}
this.tryGenChildren();
str = str.slice(match[0].length);
if (isVoidTag) {
node.end = true;
} else {
this.stack.push(node);
if (orphanTag[nodeName] || nodeName === 'option') {
var index = str.indexOf('</' + nodeName + '>');
var innerHTML = str.slice(0, index).trim();
str = str.slice(index);
makeOrphan(node, nodeName, nomalString(innerHTML));
}
}
this.str = str;
}
}
},
tryGenCloseTag: function tryGenCloseTag() {
if (!this.node) {
var str = this.str;
var match = str.match(rendTag); //处理元素节点结束部分
if (match) {
var nodeName = match[1].toLowerCase();
var last = this.stack.last();
/* istanbul ignore if*/
if (!last) {
avalon.error(match[0] + '前面缺少<' + nodeName + '>');
/* istanbul ignore else*/
} else if (last.nodeName !== nodeName) {
var errMsg = last.nodeName + '没有闭合,请注意属性的引号';
avalon.warn(errMsg);
avalon.error(errMsg);
}
var node = this.stack.pop();
node.end = true;
this.node = node;
this.str = str.slice(match[0].length);
}
}
},
tryGenChildren: function tryGenChildren() {
var node = this.node;
var p = this.stack.last();
if (p) {
validateDOMNesting(p, node);
p.children.push(node);
} else {
this.ret.push(node);
}
},
genProps: function genProps(attrs, props) {
while (attrs) {
var arr = rattrs.exec(attrs);
if (arr) {
var name = arr[1];
var value = arr[2] || '';
attrs = attrs.replace(arr[0], '');
if (value) {
//https://github.com/RubyLouvre/avalon/issues/1844
if (value.indexOf('??') === 0) {
value = nomalString(value).replace(rlineSp, '').slice(1, -1);
}
}
if (!(name in props)) {
props[name] = value;
}
} else {
break;
}
}
}
};
var vdomAst = new AST();
function from(str) {
var cacheKey = str;
var cached = strCache.get(cacheKey);
if (cached) {
return avalon.mix(true, [], cached);
}
stringPool.map = {};
str = clearString(str);
vdomAst.init(str);
var ret = vdomAst.gen();
strCache.put(cacheKey, avalon.mix(true, [], ret));
return ret;
}
var rhtml = /<|&#?\w+;/;
var htmlCache = new Cache(128);
var rxhtml = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig;
avalon.parseHTML = function (html) {
var fragment = createFragment();
//处理非字符串
if (typeof html !== 'string') {
return fragment;
}
//处理非HTML字符串
if (!rhtml.test(html)) {
return document$1.createTextNode(html);
}
html = html.replace(rxhtml, '<$1></$2>').trim();
var hasCache = htmlCache.get(html);
if (hasCache) {
return avalon.cloneNode(hasCache);
}
var vnodes = fromString(html);
for (var i = 0, el; el = vnodes[i++];) {
var child = avalon.vdom(el, 'toDOM');
fragment.appendChild(child);
}
if (html.length < 1024) {
htmlCache.put(html, fragment);
}
return fragment;
};
avalon.innerHTML = function (node, html) {
var parsed = avalon.parseHTML(html);
this.clearHTML(node);
node.appendChild(parsed);
};
//https://github.com/karloespiritu/escapehtmlent/blob/master/index.js
avalon.unescapeHTML = function (html) {
return String(html).replace(/"/g, '"').replace(/'/g, '\'').replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');
};
avalon.clearHTML = function (node) {
/* istanbul ignore next */
while (node.lastChild) {
node.removeChild(node.lastChild);
}
return node;
};
//http://www.feiesoft.com/html/events.html
//http://segmentfault.com/q/1010000000687977/a-1020000000688757
var canBubbleUp = {
click: true,
dblclick: true,
keydown: true,
keypress: true,
keyup: true,
mousedown: true,
mousemove: true,
mouseup: true,
mouseover: true,
mouseout: true,
wheel: true,
mousewheel: true,
input: true,
change: true,
beforeinput: true,
compositionstart: true,
compositionupdate: true,
compositionend: true,
select: true,
//http://blog.csdn.net/lee_magnum/article/details/17761441
cut: true,
copy: true,
paste: true,
beforecut: true,
beforecopy: true,
beforepaste: true,
focusin: true,
focusout: true,
DOMFocusIn: true,
DOMFocusOut: true,
DOMActivate: true,
dragend: true,
datasetchanged: true
};
/* istanbul ignore if */
var hackSafari = avalon.modern && document$1.ontouchstart;
//添加fn.bind, fn.unbind, bind, unbind
avalon.fn.bind = function (type, fn, phase) {
if (this[0]) {
//此方法不会链
return avalon.bind(this[0], type, fn, phase);
}
};
avalon.fn.unbind = function (type, fn, phase) {
if (this[0]) {
var args = _slice.call(arguments);
args.unshift(this[0]);
avalon.unbind.apply(0, args);
}
return this;
};
/*绑定事件*/
avalon.bind = function (elem, type, fn) {
if (elem.nodeType === 1) {
var value = elem.getAttribute('avalon-events') || '';
//如果是使用ms-on-*绑定的回调,其uuid格式为e12122324,
//如果是使用bind方法绑定的回调,其uuid格式为_12
var uuid = getShortID(fn);
var hook = eventHooks[type];
/* istanbul ignore if */
if (type === 'click' && hackSafari) {
elem.addEventListener('click', avalon.noop);
}
/* istanbul ignore if */
if (hook) {
type = hook.type || type;
if (hook.fix) {
fn = hook.fix(elem, fn);
fn.uuid = uuid;
}
}
var key = type + ':' + uuid;
avalon.eventListeners[fn.uuid] = fn;
/* istanbul ignore if */
if (value.indexOf(type + ':') === -1) {
//同一种事件只绑定一次
if (canBubbleUp[type] || avalon.modern && focusBlur[type]) {
delegateEvent(type);
} else {
avalon._nativeBind(elem, type, dispatch);
}
}
var keys = value.split(',');
/* istanbul ignore if */
if (keys[0] === '') {
keys.shift();
}
if (keys.indexOf(key) === -1) {
keys.push(key);
setEventId(elem, keys.join(','));
//将令牌放进avalon-events属性中
}
} else {
/* istanbul ignore next */
avalon._nativeBind(elem, type, fn);
}
return fn; //兼容之前的版本
};
function setEventId(node, value) {
node.setAttribute('avalon-events', value);
}
/* istanbul ignore next */
avalon.unbind = function (elem, type, fn) {
if (elem.nodeType === 1) {
var value = elem.getAttribute('avalon-events') || '';
switch (arguments.length) {
case 1:
avalon._nativeUnBind(elem, type, dispatch);
elem.removeAttribute('avalon-events');
break;
case 2:
value = value.split(',').filter(function (str) {
return str.indexOf(type + ':') === -1;
}).join(',');
setEventId(elem, value);
break;
default:
var search = type + ':' + fn.uuid;
value = value.split(',').filter(function (str) {
return str !== search;
}).join(',');
setEventId(elem, value);
delete avalon.eventListeners[fn.uuid];
break;
}
} else {
avalon._nativeUnBind(elem, type, fn);
}
};
var typeRegExp = {};
function collectHandlers(elem, type, handlers) {
var value = elem.getAttribute('avalon-events');
if (value && (elem.disabled !== true || type !== 'click')) {
var uuids = [];
var reg = typeRegExp[type] || (typeRegExp[type] = new RegExp("\\b" + type + '\\:([^,\\s]+)', 'g'));
value.replace(reg, function (a, b) {
uuids.push(b);
return a;
});
if (uuids.length) {
handlers.push({
elem: elem,
uuids: uuids
});
}
}
elem = elem.parentNode;
var g = avalon.gestureEvents || {};
if (elem && elem.getAttribute && (canBubbleUp[type] || g[type])) {
collectHandlers(elem, type, handlers);
}
}
var rhandleHasVm = /^e/;
function dispatch(event) {
event = new avEvent(event);
var type = event.type;
var elem = event.target;
var handlers = [];
collectHandlers(elem, type, handlers);
var i = 0,
j,
uuid,
handler;
while ((handler = handlers[i++]) && !event.cancelBubble) {
var host = event.currentTarget = handler.elem;
j = 0;
while (uuid = handler.uuids[j++]) {
if (event.stopImmediate) {
break;
}
var fn = avalon.eventListeners[uuid];
if (fn) {
var vm = rhandleHasVm.test(uuid) ? handler.elem._ms_context_ : 0;
if (vm && vm.$hashcode === false) {
return avalon.unbind(elem, type, fn);
}
var ret = fn.call(vm || elem, event);
if (ret === false) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
var focusBlur = {
focus: true,
blur: true
};
function delegateEvent(type) {
var value = root.getAttribute('delegate-events') || '';
if (value.indexOf(type) === -1) {
//IE6-8会多次绑定同种类型的同一个函数,其他游览器不会
var arr = value.match(avalon.rword) || [];
arr.push(type);
root.setAttribute('delegate-events', arr.join(','));
avalon._nativeBind(root, type, dispatch, !!focusBlur[type]);
}
}
var eventProto = {
webkitMovementY: 1,
webkitMovementX: 1,
keyLocation: 1,
fixEvent: function fixEvent() {},
preventDefault: function preventDefault() {
var e = this.originalEvent || {};
e.returnValue = this.returnValue = false;
if (modern && e.preventDefault) {
e.preventDefault();
}
},
stopPropagation: function stopPropagation() {
var e = this.originalEvent || {};
e.cancelBubble = this.cancelBubble = true;
if (modern && e.stopPropagation) {
e.stopPropagation();
}
},
stopImmediatePropagation: function stopImmediatePropagation() {
this.stopPropagation();
this.stopImmediate = true;
},
toString: function toString() {
return '[object Event]'; //#1619
}
};
function avEvent(event) {
if (event.originalEvent) {
return event;
}
for (var i in event) {
if (!eventProto[i]) {
this[i] = event[i];
}
}
if (!this.target) {
this.target = event.srcElement;
}
var target = this.target;
this.fixEvent();
this.timeStamp = new Date() - 0;
this.originalEvent = event;
}
avEvent.prototype = eventProto;
//针对firefox, chrome修正mouseenter, mouseleave
/* istanbul ignore if */
if (!('onmouseenter' in root)) {
avalon.each({
mouseenter: 'mouseover',
mouseleave: 'mouseout'
}, function (origType, fixType) {
eventHooks[origType] = {
type: fixType,
fix: function fix(elem, fn) {
return function (e) {
var t = e.relatedTarget;
if (!t || t !== elem && !(elem.compareDocumentPosition(t) & 16)) {
delete e.type;
e.type = origType;
return fn.apply(this, arguments);
}
};
}
};
});
}
//针对IE9+, w3c修正animationend
avalon.each({
AnimationEvent: 'animationend',
WebKitAnimationEvent: 'webkitAnimationEnd'
}, function (construct, fixType) {
if (window$1[construct] && !eventHooks.animationend) {
eventHooks.animationend = {
type: fixType
};
}
});
/* istanbul ignore if */
if (!("onmousewheel" in document$1)) {
/* IE6-11 chrome mousewheel wheelDetla 下 -120 上 120
firefox DOMMouseScroll detail 下3 上-3
firefox wheel detlaY 下3 上-3
IE9-11 wheel deltaY 下40 上-40
chrome wheel deltaY 下100 上-100 */
var fixWheelType = document$1.onwheel !== void 0 ? 'wheel' : 'DOMMouseScroll';
var fixWheelDelta = fixWheelType === 'wheel' ? 'deltaY' : 'detail';
eventHooks.mousewheel = {
type: fixWheelType,
fix: function fix(elem, fn) {
return function (e) {
var delta = e[fixWheelDelta] > 0 ? -120 : 120;
e.wheelDelta = ~~elem._ms_wheel_ + delta;
elem._ms_wheel_ = e.wheelDeltaY = e.wheelDelta;
e.wheelDeltaX = 0;
if (Object.defineProperty) {
Object.defineProperty(e, 'type', {
value: 'mousewheel'
});
}
return fn.apply(this, arguments);
};
}
};
}
/* istanbul ignore if */
if (!modern) {
delete canBubbleUp.change;
delete canBubbleUp.select;
}
/* istanbul ignore next */
avalon._nativeBind = modern ? function (el, type, fn, capture) {
el.addEventListener(type, fn, !!capture);
} : function (el, type, fn) {
el.attachEvent('on' + type, fn);
};
/* istanbul ignore next */
avalon._nativeUnBind = modern ? function (el, type, fn, a) {
el.removeEventListener(type, fn, !!a);
} : function (el, type, fn) {
el.detachEvent('on' + type, fn);
};
/* istanbul ignore next */
avalon.fireDom = function (elem, type, opts) {
if (document$1.createEvent) {
var hackEvent = document$1.createEvent('Events');
hackEvent.initEvent(type, true, true, opts);
avalon.shadowCopy(hackEvent, opts);
elem.dispatchEvent(hackEvent);
} else if (root.contains(elem)) {
//IE6-8触发事件必须保证在DOM树中,否则报'SCRIPT16389: 未指明的错误'
hackEvent = document$1.createEventObject();
if (opts) avalon.shadowCopy(hackEvent, opts);
try {
elem.fireEvent('on' + type, hackEvent);
} catch (e) {
avalon.log('fireDom', type, 'args error');
}
}
};
var rmouseEvent = /^(?:mouse|contextmenu|drag)|click/;
/* istanbul ignore next */
avEvent.prototype.fixEvent = function () {
var event = this;
if (event.which == null && event.type.indexOf('key') === 0) {
event.which = event.charCode != null ? event.charCode : event.keyCode;
}
if (rmouseEvent.test(event.type) && !('pageX' in event)) {
var DOC = event.target.ownerDocument || document$1;
var box = DOC.compatMode === 'BackCompat' ? DOC.body : DOC.documentElement;
event.pageX = event.clientX + (box.scrollLeft >> 0) - (box.clientLeft >> 0);
event.pageY = event.clientY + (box.scrollTop >> 0) - (box.clientTop >> 0);
event.wheelDeltaY = ~~event.wheelDelta;
event.wheelDeltaX = 0;
}
};
//针对IE6-8修正input
/* istanbul ignore if */
if (!('oninput' in document$1.createElement('input'))) {
eventHooks.input = {
type: 'propertychange',
fix: function fix(elem, fn) {
return function (e) {
if (e.propertyName === 'value') {
e.type = 'input';
return fn.apply(this, arguments);
}
};
}
};
}
var readyList = [];
function fireReady(fn) {
avalon.isReady = true;
while (fn = readyList.shift()) {
fn(avalon);
}
}
avalon.ready = function (fn) {
readyList.push(fn);
if (avalon.isReady) {
fireReady();
}
};
avalon.ready(function () {
avalon.scan && avalon.scan(document$1.body);
});
/* istanbul ignore next */
function bootstrap() {
function doScrollCheck() {
try {
//IE下通过doScrollCheck检测DOM树是否建完
root.doScroll('left');
fireReady();
} catch (e) {
setTimeout(doScrollCheck);
}
}
if (document$1.readyState === 'complete') {
setTimeout(fireReady); //如果在domReady之外加载
} else if (document$1.addEventListener) {
document$1.addEventListener('DOMContentLoaded', fireReady, false);
} else if (document$1.attachEvent) {
//必须传入三个参数,否则在firefox4-26中报错
//caught exception: [Exception... "Not enough arguments" nsresult: "0x
document$1.attachEvent('onreadystatechange', function () {
if (document$1.readyState === 'complete') {
fireReady();
}
});
try {
var isTop = window$1.frameElement === null;
} catch (e) {}
if (root.doScroll && isTop && window$1.external) {
//fix IE iframe BUG
doScrollCheck();
}
}
avalon.bind(window$1, 'load', fireReady);
}
if (inBrowser) {
bootstrap();
}
/**
* ------------------------------------------------------------
* DOM Api
* shim,class,data,css,val,html,event,ready
* ------------------------------------------------------------
*/
function fromDOM(dom) {
return [from$1(dom)];
}
function from$1(node) {
var type = node.nodeName.toLowerCase();
switch (type) {
case '#text':
case '#comment':
return {
nodeName: type,
dom: node,
nodeValue: node.nodeValue
};
default:
var props = markProps(node, node.attributes || []);
var vnode = {
nodeName: type,
dom: node,
isVoidTag: !!voidTag[type],
props: props
};
if (type === 'option') {
//即便你设置了option.selected = true,
//option.attributes也找不到selected属性
props.selected = node.selected;
}
if (orphanTag[type] || type === 'option') {
makeOrphan(vnode, type, node.text || node.innerHTML);
if (node.childNodes.length === 1) {
vnode.children[0].dom = node.firstChild;
}
} else if (!vnode.isVoidTag) {
vnode.children = [];
for (var i = 0, el; el = node.childNodes[i++];) {
var child = from$1(el);
if (/\S/.test(child.nodeValue)) {
vnode.children.push(child);
}
}
}
return vnode;
}
}
var rformElement = /input|textarea|select/i;
function markProps(node, attrs) {
var ret = {};
for (var i = 0, n = attrs.length; i < n; i++) {
var attr = attrs[i];
if (attr.specified) {
//IE6-9不会将属性名变小写,比如它会将用户的contenteditable变成contentEditable
ret[attr.name.toLowerCase()] = attr.value;
}
}
if (rformElement.test(node.nodeName)) {
ret.type = node.type;
var a = node.getAttributeNode('value');
if (a && /\S/.test(a.value)) {
//IE6,7中无法取得checkbox,radio的value
ret.value = a.value;
}
}
var style = node.style.cssText;
if (style) {
ret.style = style;
}
//类名 = 去重(静态类名+动态类名+ hover类名? + active类名)
if (ret.type === 'select-one') {
ret.selectedIndex = node.selectedIndex;
}
return ret;
}
function VText(text) {
this.nodeName = '#text';
this.nodeValue = text;
}
VText.prototype = {
constructor: VText,
toDOM: function toDOM() {
/* istanbul ignore if*/
if (this.dom) return this.dom;
var v = avalon._decode(this.nodeValue);
return this.dom = document$1.createTextNode(v);
},
toHTML: function toHTML() {
return this.nodeValue;
}
};
function VComment(text) {
this.nodeName = '#comment';
this.nodeValue = text;
}
VComment.prototype = {
constructor: VComment,
toDOM: function toDOM() {
if (this.dom) return this.dom;
return this.dom = document$1.createComment(this.nodeValue);
},
toHTML: function toHTML() {
return '<!--' + this.nodeValue + '-->';
}
};
function VElement(type, props, children, isVoidTag) {
this.nodeName = type;
this.props = props;
this.children = children;
this.isVoidTag = isVoidTag;
}
VElement.prototype = {
constructor: VElement,
toDOM: function toDOM() {
if (this.dom) return this.dom;
var dom,
tagName = this.nodeName;
if (avalon.modern && svgTags[tagName]) {
dom = createSVG(tagName);
/* istanbul ignore next*/
} else if (!avalon.modern && (VMLTags[tagName] || rvml.test(tagName))) {
dom = createVML(tagName);
} else {
dom = document$1.createElement(tagName);
}
var props = this.props || {};
for (var i in props) {
var val = props[i];
if (skipFalseAndFunction(val)) {
/* istanbul ignore if*/
if (specalAttrs[i] && avalon.msie < 8) {
specalAttrs[i](dom, val);
} else {
dom.setAttribute(i, val + '');
}
}
}
var c = this.children || [];
var template = c[0] ? c[0].nodeValue : '';
switch (this.nodeName) {
case 'script':
dom.type = 'noexec';
dom.text = template;
try {
dom.innerHTML = template;
} catch (e) {}
dom.type = props.type || '';
break;
case 'noscript':
dom.textContent = template;
case 'style':
case 'xmp':
case 'template':
try {
dom.innerHTML = template;
} catch (e) {
/* istanbul ignore next*/
this.hackIE(dom, this.nodeName, template);
}
break;
case 'option':
//IE6-8,为option添加文本子节点,不会同步到text属性中
/* istanbul ignore next */
if (msie < 9) dom.text = template;
default:
/* istanbul ignore next */
if (!this.isVoidTag && this.children) {
this.children.forEach(function (el) {
return c && dom.appendChild(avalon.vdom(c, 'toDOM'));
});
}
break;
}
return this.dom = dom;
},
/* istanbul ignore next */
hackIE: function hackIE(dom, nodeName, template) {
switch (nodeName) {
case 'style':
dom.setAttribute('type', 'text/css');
dom.styleSheet.cssText = template;
break;
case 'xmp': //IE6-8,XMP元素里面只能有文本节点,不能使用innerHTML
case 'noscript':
dom.textContent = template;
break;
}
},
toHTML: function toHTML() {
var arr = [];
var props = this.props || {};
for (var i in props) {
var val = props[i];
if (skipFalseAndFunction(val)) {
arr.push(i + '=' + avalon.quote(props[i] + ''));
}
}
arr = arr.length ? ' ' + arr.join(' ') : '';
var str = '<' + this.nodeName + arr;
if (this.isVoidTag) {
return str + '/>';
}
str += '>';
if (this.children) {
str += this.children.map(function (el) {
return el ? avalon.vdom(el, 'toHTML') : '';
}).join('');
}
return str + '</' + this.nodeName + '>';
}
};
function skipFalseAndFunction(a) {
return a !== false && Object(a) !== a;
}
/* istanbul ignore next */
var specalAttrs = {
"class": function _class(dom, val) {
dom.className = val;
},
style: function style(dom, val) {
dom.style.cssText = val;
},
type: function type(dom, val) {
try {
//textarea,button 元素在IE6,7设置 type 属性会抛错
dom.type = val;
} catch (e) {}
},
'for': function _for(dom, val) {
dom.setAttribute('for', val);
dom.htmlFor = val;
}
};
function createSVG(type) {
return document$1.createElementNS('http://www.w3.org/2000/svg', type);
}
var svgTags = avalon.oneObject('circle,defs,ellipse,image,line,' + 'path,polygon,polyline,rect,symbol,text,use,g,svg');
var rvml = /^\w+\:\w+/;
/* istanbul ignore next*/
function createVML(type) {
if (document$1.styleSheets.length < 31) {
document$1.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)");
} else {
// no more room, add to the existing one
// http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
document$1.styleSheets[0].addRule(".rvml", "behavior:url(#default#VML)");
}
var arr = type.split(':');
if (arr.length === 1) {
arr.unshift('v');
}
var tag = arr[1];
var ns = arr[0];
if (!document$1.namespaces[ns]) {
document$1.namespaces.add(ns, "urn:schemas-microsoft-com:vml");
}
return document$1.createElement('<' + ns + ':' + tag + ' class="rvml">');
}
var VMLTags = avalon.oneObject('shape,line,polyline,rect,roundrect,oval,arc,' + 'curve,background,image,shapetype,group,fill,' + 'stroke,shadow, extrusion, textbox, imagedata, textpath');
function VFragment(children, key, val, index) {
this.nodeName = '#document-fragment';
this.children = children;
this.key = key;
this.val = val;
this.index = index;
this.props = {};
}
VFragment.prototype = {
constructor: VFragment,
toDOM: function toDOM() {
if (this.dom) return this.dom;
var f = this.toFragment();
//IE6-11 docment-fragment都没有children属性
this.split = f.lastChild;
return this.dom = f;
},
dispose: function dispose() {
this.toFragment();
this.innerRender && this.innerRender.dispose();
for (var i in this) {
this[i] = null;
}
},
toFragment: function toFragment() {
var f = createFragment();
this.children.forEach(function (el) {
return f.appendChild(avalon.vdom(el, 'toDOM'));
});
return f;
},
toHTML: function toHTML() {
var c = this.children;
return c.map(function (el) {
return avalon.vdom(el, 'toHTML');
}).join('');
}
};
/**
* 虚拟DOM的4大构造器
*/
avalon.mix(avalon, {
VText: VText,
VComment: VComment,
VElement: VElement,
VFragment: VFragment
});
var constNameMap = {
'#text': 'VText',
'#document-fragment': 'VFragment',
'#comment': 'VComment'
};
var vdom = avalon.vdomAdaptor = avalon.vdom = function (obj, method) {
if (!obj) {
//obj在ms-for循环里面可能是null
return method === "toHTML" ? '' : createFragment();
}
var nodeName = obj.nodeName;
if (!nodeName) {
return new avalon.VFragment(obj)[method]();
}
var constName = constNameMap[nodeName] || 'VElement';
return avalon[constName].prototype[method].call(obj);
};
avalon.domize = function (a) {
return avalon.vdom(a, 'toDOM');
};
/**
$$skipArray:是系统级通用的不可监听属性
$skipArray: 是当前对象特有的不可监听属性
不同点是
$$skipArray被hasOwnProperty后返回false
$skipArray被hasOwnProperty后返回true
*/
var falsy;
var $$skipArray = {
$id: falsy,
$render: falsy,
$track: falsy,
$element: falsy,
$watch: falsy,
$fire: falsy,
$events: falsy,
$accessors: falsy,
$hashcode: falsy,
$mutations: falsy,
$vbthis: falsy,
$vbsetter: falsy
};
avalon.pendingActions = [];
avalon.uniqActions = {};
avalon.inTransaction = 0;
config.trackDeps = false;
avalon.track = function () {
if (config.trackDeps) {
avalon.log.apply(avalon, arguments);
}
};
/**
* Batch is a pseudotransaction, just for purposes of memoizing ComputedValues when nothing else does.
* During a batch `onBecomeUnobserved` will be called at most once per observable.
* Avoids unnecessary recalculations.
*/
function runActions() {
if (avalon.isRunningActions === true || avalon.inTransaction > 0) return;
avalon.isRunningActions = true;
var tasks = avalon.pendingActions.splice(0, avalon.pendingActions.length);
for (var i = 0, task; task = tasks[i++];) {
task.update();
delete avalon.uniqActions[task.uuid];
}
avalon.isRunningActions = false;
}
function propagateChanged(target) {
var list = target.observers;
for (var i = 0, el; el = list[i++];) {
el.schedule(); //通知action, computed做它们该做的事
}
}
//将自己抛到市场上卖
function reportObserved(target) {
var action = avalon.trackingAction || null;
if (action !== null) {
avalon.track('征收到', target.expr);
action.mapIDs[target.uuid] = target;
}
}
var targetStack = [];
function collectDeps(action, getter) {
if (!action.observers) return;
var preAction = avalon.trackingAction;
if (preAction) {
targetStack.push(preAction);
}
avalon.trackingAction = action;
avalon.track('【action】', action.type, action.expr, '开始征收依赖项');
//多个observe持有同一个action
action.mapIDs = {}; //重新收集依赖
var hasError = true,
result;
try {
result = getter.call(action);
hasError = false;
} finally {
if (hasError) {
avalon.warn('collectDeps fail', getter + '');
action.mapIDs = {};
avalon.trackingAction = preAction;
} else {
// 确保它总是为null
avalon.trackingAction = targetStack.pop();
try {
resetDeps(action);
} catch (e) {
avalon.warn(e);
}
}
return result;
}
}
function resetDeps(action) {
var prev = action.observers,
curr = [],
checked = {},
ids = [];
for (var i in action.mapIDs) {
var dep = action.mapIDs[i];
if (!dep.isAction) {
if (!dep.observers) {
//如果它已经被销毁
delete action.mapIDs[i];
continue;
}
ids.push(dep.uuid);
curr.push(dep);
checked[dep.uuid] = 1;
if (dep.lastAccessedBy === action.uuid) {
continue;
}
dep.lastAccessedBy = action.uuid;
avalon.Array.ensure(dep.observers, action);
}
}
var ids = ids.sort().join(',');
if (ids === action.ids) {
return;
}
action.ids = ids;
if (!action.isComputed) {
action.observers = curr;
} else {
action.depsCount = curr.length;
action.deps = avalon.mix({}, action.mapIDs);
action.depsVersion = {};
for (var _i in action.mapIDs) {
var _dep = action.mapIDs[_i];
action.depsVersion[_dep.uuid] = _dep.version;
}
}
for (var _i2 = 0, _dep2; _dep2 = prev[_i2++];) {
if (!checked[_dep2.uuid]) {
avalon.Array.remove(_dep2.observers, action);
}
}
}
function transaction(action, thisArg, args) {
args = args || [];
var name = 'transaction ' + (action.name || action.displayName || 'noop');
transactionStart(name);
var res = action.apply(thisArg, args);
transactionEnd(name);
return res;
}
avalon.transaction = transaction;
function transactionStart(name) {
avalon.inTransaction += 1;
}
function transactionEnd(name) {
if (--avalon.inTransaction === 0) {
avalon.isRunningActions = false;
runActions();
}
}
var keyMap = avalon.oneObject("break,case,catch,continue,debugger,default,delete,do,else,false," + "finally,for,function,if,in,instanceof,new,null,return,switch,this," + "throw,true,try,typeof,var,void,while,with," + /* 关键字*/
"abstract,boolean,byte,char,class,const,double,enum,export,extends," + "final,float,goto,implements,import,int,interface,long,native," + "package,private,protected,public,short,static,super,synchronized," + "throws,transient,volatile");
var skipMap = avalon.mix({
Math: 1,
Date: 1,
$event: 1,
window: 1,
__vmodel__: 1,
avalon: 1
}, keyMap);
var rvmKey = /(^|[^\w\u00c0-\uFFFF_])(@|##)(?=[$\w])/g;
var ruselessSp = /\s*(\.|\|)\s*/g;
var rshortCircuit = /\|\|/g;
var brackets = /\(([^)]*)\)/;
var rpipeline = /\|(?=\?\?)/;
var rregexp = /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\\\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/g;
var robjectProp = /\.[\w\.\$]+/g; //对象的属性 el.xxx 中的xxx
var robjectKey = /(\{|\,)\s*([\$\w]+)\s*:/g; //对象的键名与冒号 {xxx:1,yyy: 2}中的xxx, yyy
var rfilterName = /\|(\w+)/g;
var rlocalVar = /[$a-zA-Z_][$a-zA-Z0-9_]*/g;
var exprCache = new Cache(300);
function addScopeForLocal(str) {
return str.replace(robjectProp, dig).replace(rlocalVar, function (el) {
if (!skipMap[el]) {
return "__vmodel__." + el;
}
return el;
});
}
function addScope(expr, type) {
var cacheKey = expr + ':' + type;
var cache = exprCache.get(cacheKey);
if (cache) {
return cache.slice(0);
}
stringPool.map = {};
//https://github.com/RubyLouvre/avalon/issues/1849
var input = expr.replace(rregexp, function (a, b) {
return b + dig(a.slice(b.length));
}); //移除所有正则
input = clearString(input); //移除所有字符串
input = input.replace(rshortCircuit, dig). //移除所有短路运算符
replace(ruselessSp, '$1'). //移除.|两端空白
replace(robjectKey, function (_, a, b) {
//移除所有键名
return a + dig(b) + ':'; //比如 ms-widget="[{is:'ms-address-wrap', $id:'address'}]"这样极端的情况
}).replace(rvmKey, '$1__vmodel__.'). //转换@与##为__vmodel__
replace(rfilterName, function (a, b) {
//移除所有过滤器的名字
return '|' + dig(b);
});
input = addScopeForLocal(input); //在本地变量前添加__vmodel__
var filters = input.split(rpipeline); //根据管道符切割表达式
var body = filters.shift().replace(rfill, fill).trim();
if (/\?\?\d/.test(body)) {
body = body.replace(rfill, fill);
}
if (filters.length) {
filters = filters.map(function (filter) {
var bracketArgs = '';
filter = filter.replace(brackets, function (a, b) {
if (/\S/.test(b)) {
bracketArgs += ',' + b; //还原字符串,正则,短路运算符
}
return '';
});
var arg = '[' + avalon.quote(filter.trim()) + bracketArgs + ']';
return arg;
});
filters = 'avalon.composeFilters(' + filters + ')(__value__)';
filters = filters.replace(rfill, fill);
} else {
filters = '';
}
return exprCache.put(cacheKey, [body, filters]);
}
var rhandleName = /^__vmodel__\.[$\w\.]+$/;
var rfixIE678 = /__vmodel__\.([^(]+)\(([^)]*)\)/;
function makeHandle(body) {
if (rhandleName.test(body)) {
body = body + '($event)';
}
/* istanbul ignore if */
if (msie < 9) {
body = body.replace(rfixIE678, function (a, b, c) {
return '__vmodel__.' + b + '.call(__vmodel__' + (/\S/.test(c) ? ',' + c : '') + ')';
});
}
return body;
}
function createGetter(expr, type) {
var arr = addScope(expr, type),
body;
if (!arr[1]) {
body = arr[0];
} else {
body = arr[1].replace(/__value__\)$/, arr[0] + ')');
}
try {
return new Function('__vmodel__', 'return ' + body + ';');
/* istanbul ignore next */
} catch (e) {
avalon.log('parse getter: [', expr, body, ']error');
return avalon.noop;
}
}
/**
* 生成表达式设值函数
* @param {String} expr
*/
function createSetter(expr, type) {
var arr = addScope(expr, type);
var body = 'try{ ' + arr[0] + ' = __value__}catch(e){}';
try {
return new Function('__vmodel__', '__value__', body + ';');
/* istanbul ignore next */
} catch (e) {
avalon.log('parse setter: ', expr, ' error');
return avalon.noop;
}
}
var actionUUID = 1;
//需要重构
function Action(vm, options, callback) {
for (var i in options) {
if (protectedMenbers[i] !== 1) {
this[i] = options[i];
}
}
this.vm = vm;
this.observers = [];
this.callback = callback;
this.uuid = ++actionUUID;
this.ids = '';
this.mapIDs = {}; //这个用于去重
this.isAction = true;
var expr = this.expr;
// 缓存取值函数
if (typeof this.getter !== 'function') {
this.getter = createGetter(expr, this.type);
}
// 缓存设值函数(双向数据绑定)
if (this.type === 'duplex') {
this.setter = createSetter(expr, this.type);
}
// 缓存表达式旧值
this.oldValue = null;
// 表达式初始值 & 提取依赖
if (!this.node) {
this.value = this.get();
}
}
Action.prototype = {
getValue: function getValue() {
var scope = this.vm;
try {
return this.getter.call(scope, scope);
} catch (e) {
avalon.log(this.getter + ' exec error');
}
},
setValue: function setValue(value) {
var scope = this.vm;
if (this.setter) {
this.setter.call(scope, scope, value);
}
},
// get --> getValue --> getter
get: function get(fn) {
var name = 'action track ' + this.type;
if (this.deep) {
avalon.deepCollect = true;
}
var value = collectDeps(this, this.getValue);
if (this.deep && avalon.deepCollect) {
avalon.deepCollect = false;
}
return value;
},
/**
* 在更新视图前保存原有的value
*/
beforeUpdate: function beforeUpdate() {
var v = this.value;
return this.oldValue = v && v.$events ? v.$model : v;
},
update: function update(args, uuid) {
var oldVal = this.beforeUpdate();
var newVal = this.value = this.get();
var callback = this.callback;
if (callback && this.diff(newVal, oldVal, args)) {
callback.call(this.vm, this.value, oldVal, this.expr);
}
this._isScheduled = false;
},
schedule: function schedule() {
if (!this._isScheduled) {
this._isScheduled = true;
if (!avalon.uniqActions[this.uuid]) {
avalon.uniqActions[this.uuid] = 1;
avalon.pendingActions.push(this);
}
runActions(); //这里会还原_isScheduled
}
},
removeDepends: function removeDepends() {
var self = this;
this.observers.forEach(function (depend) {
avalon.Array.remove(depend.observers, self);
});
},
/**
* 比较两个计算值是否,一致,在for, class等能复杂数据类型的指令中,它们会重写diff复法
*/
diff: function diff(a, b) {
return a !== b;
},
/**
* 销毁指令
*/
dispose: function dispose() {
this.value = null;
this.removeDepends();
if (this.beforeDispose) {
this.beforeDispose();
}
for (var i in this) {
delete this[i];
}
}
};
var protectedMenbers = {
vm: 1,
callback: 1,
observers: 1,
oldValue: 1,
value: 1,
getValue: 1,
setValue: 1,
get: 1,
removeDepends: 1,
beforeUpdate: 1,
update: 1,
//diff
//getter
//setter
//expr
//vdom
//type: "for"
//name: "ms-for"
//attrName: ":for"
//param: "click"
//beforeDispose
dispose: 1
};
/**
*
与Computed等共享UUID
*/
var obid = 1;
function Mutation(expr, value, vm) {
//构造函数
this.expr = expr;
if (value) {
var childVm = platform.createProxy(value, this);
if (childVm) {
value = childVm;
}
}
this.value = value;
this.vm = vm;
try {
vm.$mutations[expr] = this;
} catch (ignoreIE) {}
this.uuid = ++obid;
this.updateVersion();
this.mapIDs = {};
this.observers = [];
}
Mutation.prototype = {
get: function get() {
if (avalon.trackingAction) {
this.collect(); //被收集
var childOb = this.value;
if (childOb && childOb.$events) {
if (Array.isArray(childOb)) {
childOb.forEach(function (item) {
if (item && item.$events) {
item.$events.__dep__.collect();
}
});
} else if (avalon.deepCollect) {
for (var key in childOb) {
if (childOb.hasOwnProperty(key)) {
var collectIt = childOb[key];
}
}
}
}
}
return this.value;
},
collect: function collect() {
avalon.track(name, '被收集');
reportObserved(this);
},
updateVersion: function updateVersion() {
this.version = Math.random() + Math.random();
},
notify: function notify() {
transactionStart();
propagateChanged(this);
transactionEnd();
},
set: function set(newValue) {
var oldValue = this.value;
if (newValue !== oldValue) {
if (avalon.isObject(newValue)) {
var hash = oldValue && oldValue.$hashcode;
var childVM = platform.createProxy(newValue, this);
if (childVM) {
if (hash) {
childVM.$hashcode = hash;
}
newValue = childVM;
}
}
this.value = newValue;
this.updateVersion();
this.notify();
}
}
};
function getBody(fn) {
var entire = fn.toString();
return entire.substring(entire.indexOf('{}') + 1, entire.lastIndexOf('}'));
}
//如果不存在三目,if,方法
var instability = /(\?|if\b|\(.+\))/;
function __create(o) {
var __ = function __() {};
__.prototype = o;
return new __();
}
function __extends(child, parent) {
if (typeof parent === 'function') {
var proto = child.prototype = __create(parent.prototype);
proto.constructor = child;
}
}
var Computed = function (_super) {
__extends(Computed, _super);
function Computed(name, options, vm) {
//构造函数
_super.call(this, name, undefined, vm);
delete options.get;
delete options.set;
avalon.mix(this, options);
this.deps = {};
this.type = 'computed';
this.depsVersion = {};
this.isComputed = true;
this.trackAndCompute();
if (!('isStable' in this)) {
this.isStable = !instability.test(getBody(this.getter));
}
}
var cp = Computed.prototype;
cp.trackAndCompute = function () {
if (this.isStable && this.depsCount > 0) {
this.getValue();
} else {
collectDeps(this, this.getValue.bind(this));
}
};
cp.getValue = function () {
return this.value = this.getter.call(this.vm);
};
cp.schedule = function () {
var observers = this.observers;
var i = observers.length;
while (i--) {
var d = observers[i];
if (d.schedule) {
d.schedule();
}
}
};
cp.shouldCompute = function () {
if (this.isStable) {
//如果变动因子确定,那么只比较变动因子的版本
var toComputed = false;
for (var i in this.deps) {
if (this.deps[i].version !== this.depsVersion[i]) {
toComputed = true;
this.deps[i].version = this.depsVersion[i];
}
}
return toComputed;
}
return true;
};
cp.set = function () {
if (this.setter) {
avalon.transaction(this.setter, this.vm, arguments);
}
};
cp.get = function () {
//当被设置了就不稳定,当它被访问了一次就是稳定
this.collect();
if (this.shouldCompute()) {
this.trackAndCompute();
// console.log('computed 2 分支')
this.updateVersion();
// this.reportChanged()
}
//下面这一行好像没用
return this.value;
};
return Computed;
}(Mutation);
/**
* 这里放置ViewModel模块的共用方法
* avalon.define: 全框架最重要的方法,生成用户VM
* IProxy, 基本用户数据产生的一个数据对象,基于$model与vmodel之间的形态
* modelFactory: 生成用户VM
* canHijack: 判定此属性是否该被劫持,加入数据监听与分发的的逻辑
* createProxy: listFactory与modelFactory的封装
* createAccessor: 实现数据监听与分发的重要对象
* itemFactory: ms-for循环中产生的代理VM的生成工厂
* fuseFactory: 两个ms-controller间产生的代理VM的生成工厂
*/
avalon.define = function (definition) {
var $id = definition.$id;
if (!$id) {
avalon.error('vm.$id must be specified');
}
if (avalon.vmodels[$id]) {
avalon.warn('error:[' + $id + '] had defined!');
}
var vm = platform.modelFactory(definition);
return avalon.vmodels[$id] = vm;
};
/**
* 在末来的版本,avalon改用Proxy来创建VM,因此
*/
function IProxy(definition, dd) {
avalon.mix(this, definition);
avalon.mix(this, $$skipArray);
this.$hashcode = avalon.makeHashCode('$');
this.$id = this.$id || this.$hashcode;
this.$events = {
__dep__: dd || new Mutation(this.$id)
};
if (avalon.config.inProxyMode) {
delete this.$mutations;
this.$accessors = {};
this.$computed = {};
this.$track = '';
} else {
this.$accessors = {
$model: modelAccessor
};
}
if (dd === void 0) {
this.$watch = platform.watchFactory(this.$events);
this.$fire = platform.fireFactory(this.$events);
} else {
delete this.$watch;
delete this.$fire;
}
}
platform.modelFactory = function modelFactory(definition, dd) {
var $computed = definition.$computed || {};
delete definition.$computed;
var core = new IProxy(definition, dd);
var $accessors = core.$accessors;
var keys = [];
platform.hideProperty(core, '$mutations', {});
for (var key in definition) {
if (key in $$skipArray) continue;
var val = definition[key];
keys.push(key);
if (canHijack(key, val)) {
$accessors[key] = createAccessor(key, val);
}
}
for (var _key in $computed) {
if (_key in $$skipArray) continue;
var val = $computed[_key];
if (typeof val === 'function') {
val = {
get: val
};
}
if (val && val.get) {
val.getter = val.get;
val.setter = val.set;
avalon.Array.ensure(keys, _key);
$accessors[_key] = createAccessor(_key, val, true);
}
}
//将系统API以unenumerable形式加入vm,
//添加用户的其他不可监听属性或方法
//重写$track
//并在IE6-8中增添加不存在的hasOwnPropert方法
var vm = platform.createViewModel(core, $accessors, core);
platform.afterCreate(vm, core, keys, !dd);
return vm;
};
var $proxyItemBackdoorMap = {};
function canHijack(key, val, $proxyItemBackdoor) {
if (key in $$skipArray) return false;
if (key.charAt(0) === '$') {
if ($proxyItemBackdoor) {
if (!$proxyItemBackdoorMap[key]) {
$proxyItemBackdoorMap[key] = 1;
avalon.warn('ms-for\u4E2D\u7684\u53D8\u91CF' + key + '\u4E0D\u518D\u5EFA\u8BAE\u4EE5$\u4E3A\u524D\u7F00');
}
return true;
}
return false;
}
if (val == null) {
avalon.warn('定义vmodel时' + key + '的属性值不能为null undefine');
return true;
}
if (/error|date|function|regexp/.test(avalon.type(val))) {
return false;
}
return !(val && val.nodeName && val.nodeType);
}
function createProxy(target, dd) {
if (target && target.$events) {
return target;
}
var vm;
if (Array.isArray(target)) {
vm = platform.listFactory(target, false, dd);
} else if (isObject(target)) {
vm = platform.modelFactory(target, dd);
}
return vm;
}
platform.createProxy = createProxy;
platform.itemFactory = function itemFactory(before, after) {
var keyMap = before.$model;
var core = new IProxy(keyMap);
var state = avalon.shadowCopy(core.$accessors, before.$accessors); //防止互相污染
var data = after.data;
//core是包含系统属性的对象
//keyMap是不包含系统属性的对象, keys
for (var key in data) {
var val = keyMap[key] = core[key] = data[key];
state[key] = createAccessor(key, val);
}
var keys = Object.keys(keyMap);
var vm = platform.createViewModel(core, state, core);
platform.afterCreate(vm, core, keys);
return vm;
};
function createAccessor(key, val, isComputed) {
var mutation = null;
var Accessor = isComputed ? Computed : Mutation;
return {
get: function Getter() {
if (!mutation) {
mutation = new Accessor(key, val, this);
}
return mutation.get();
},
set: function Setter(newValue) {
if (!mutation) {
mutation = new Accessor(key, val, this);
}
mutation.set(newValue);
},
enumerable: true,
configurable: true
};
}
platform.fuseFactory = function fuseFactory(before, after) {
var keyMap = avalon.mix(before.$model, after.$model);
var core = new IProxy(avalon.mix(keyMap, {
$id: before.$id + after.$id
}));
var state = avalon.mix(core.$accessors, before.$accessors, after.$accessors); //防止互相污染
var keys = Object.keys(keyMap);
//将系统API以unenumerable形式加入vm,并在IE6-8中添加hasOwnPropert方法
var vm = platform.createViewModel(core, state, core);
platform.afterCreate(vm, core, keys, false);
return vm;
};
function toJson(val) {
var xtype = avalon.type(val);
if (xtype === 'array') {
var array = [];
for (var i = 0; i < val.length; i++) {
array[i] = toJson(val[i]);
}
return array;
} else if (xtype === 'object') {
if (typeof val.$track === 'string') {
var obj = {};
var arr = val.$track.match(/[^☥]+/g) || [];
arr.forEach(function (i) {
var value = val[i];
obj[i] = value && value.$events ? toJson(value) : value;
});
return obj;
}
}
return val;
}
var modelAccessor = {
get: function get() {
return toJson(this);
},
set: avalon.noop,
enumerable: false,
configurable: true
};
platform.toJson = toJson;
platform.modelAccessor = modelAccessor;
var _splice = ap.splice;
var __array__ = {
set: function set(index, val) {
if (index >>> 0 === index && this[index] !== val) {
if (index > this.length) {
throw Error(index + 'set方法的第一个参数不能大于原数组长度');
}
this.splice(index, 1, val);
}
},
toJSON: function toJSON() {
//为了解决IE6-8的解决,通过此方法显式地求取数组的$model
return this.$model = platform.toJson(this);
},
contains: function contains(el) {
//判定是否包含
return this.indexOf(el) !== -1;
},
ensure: function ensure(el) {
if (!this.contains(el)) {
//只有不存在才push
this.push(el);
return true;
}
return false;
},
pushArray: function pushArray(arr) {
return this.push.apply(this, arr);
},
remove: function remove(el) {
//移除第一个等于给定值的元素
return this.removeAt(this.indexOf(el));
},
removeAt: function removeAt(index) {
//移除指定索引上的元素
if (index >>> 0 === index) {
return this.splice(index, 1);
}
return [];
},
clear: function clear() {
this.removeAll();
return this;
},
removeAll: function removeAll(all) {
//移除N个元素
var size = this.length;
var eliminate = Array.isArray(all) ? function (el) {
return all.indexOf(el) !== -1;
} : typeof all === 'function' ? all : false;
if (eliminate) {
for (var i = this.length - 1; i >= 0; i--) {
if (eliminate(this[i], i)) {
_splice.call(this, i, 1);
}
}
} else {
_splice.call(this, 0, this.length);
}
this.toJSON();
this.$events.__dep__.notify();
}
};
function hijackMethods(array) {
for (var i in __array__) {
platform.hideProperty(array, i, __array__[i]);
}
}
var __method__ = ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'];
__method__.forEach(function (method) {
var original = ap[method];
__array__[method] = function () {
// 继续尝试劫持数组元素的属性
var core = this.$events;
var args = platform.listFactory(arguments, true, core.__dep__);
var result = original.apply(this, args);
this.toJSON();
core.__dep__.notify(method);
return result;
};
});
function listFactory(array, stop, dd) {
if (!stop) {
hijackMethods(array);
if (modern) {
Object.defineProperty(array, '$model', platform.modelAccessor);
}
platform.hideProperty(array, '$hashcode', avalon.makeHashCode('$'));
platform.hideProperty(array, '$events', { __dep__: dd || new Mutation() });
}
var _dd = array.$events && array.$events.__dep__;
for (var i = 0, n = array.length; i < n; i++) {
var item = array[i];
if (isObject(item)) {
array[i] = platform.createProxy(item, _dd);
}
}
return array;
}
platform.listFactory = listFactory;
//如果浏览器不支持ecma262v5的Object.defineProperties或者存在BUG,比如IE8
//标准浏览器使用__defineGetter__, __defineSetter__实现
var canHideProperty = true;
try {
Object.defineProperty({}, '_', {
value: 'x'
});
delete $$skipArray.$vbsetter;
delete $$skipArray.$vbthis;
} catch (e) {
/* istanbul ignore next*/
canHideProperty = false;
}
var protectedVB = { $vbthis: 1, $vbsetter: 1 };
/* istanbul ignore next */
function hideProperty(host, name, value) {
if (canHideProperty) {
Object.defineProperty(host, name, {
value: value,
writable: true,
enumerable: false,
configurable: true
});
} else if (!protectedVB[name]) {
/* istanbul ignore next */
host[name] = value;
}
}
function watchFactory(core) {
return function $watch(expr, callback, deep) {
var w = new Action(core.__proxy__, {
deep: deep,
type: 'user',
expr: expr
}, callback);
if (!core[expr]) {
core[expr] = [w];
} else {
core[expr].push(w);
}
return function () {
w.dispose();
avalon.Array.remove(core[expr], w);
if (core[expr].length === 0) {
delete core[expr];
}
};
};
}
function fireFactory(core) {
return function $fire(expr, a) {
var list = core[expr];
if (Array.isArray(list)) {
for (var i = 0, w; w = list[i++];) {
w.callback.call(w.vm, a, w.value, w.expr);
}
}
};
}
function wrapIt(str) {
return '☥' + str + '☥';
}
function afterCreate(vm, core, keys, bindThis) {
var ac = vm.$accessors;
//隐藏系统属性
for (var key in $$skipArray) {
if (avalon.msie < 9 && core[key] === void 0) continue;
hideProperty(vm, key, core[key]);
}
//为不可监听的属性或方法赋值
for (var i = 0; i < keys.length; i++) {
var _key2 = keys[i];
if (!(_key2 in ac)) {
if (bindThis && typeof core[_key2] === 'function') {
vm[_key2] = core[_key2].bind(vm);
continue;
}
vm[_key2] = core[_key2];
}
}
vm.$track = keys.join('☥');
function hasOwnKey(key) {
return wrapIt(vm.$track).indexOf(wrapIt(key)) > -1;
}
if (avalon.msie < 9) {
vm.hasOwnProperty = hasOwnKey;
}
vm.$events.__proxy__ = vm;
}
platform.hideProperty = hideProperty;
platform.fireFactory = fireFactory;
platform.watchFactory = watchFactory;
platform.afterCreate = afterCreate;
var createViewModel = Object.defineProperties;
var defineProperty;
var timeBucket = new Date() - 0;
/* istanbul ignore if*/
if (!canHideProperty) {
if ('__defineGetter__' in avalon) {
defineProperty = function defineProperty(obj, prop, desc) {
if ('value' in desc) {
obj[prop] = desc.value;
}
if ('get' in desc) {
obj.__defineGetter__(prop, desc.get);
}
if ('set' in desc) {
obj.__defineSetter__(prop, desc.set);
}
return obj;
};
createViewModel = function createViewModel(obj, descs) {
for (var prop in descs) {
if (descs.hasOwnProperty(prop)) {
defineProperty(obj, prop, descs[prop]);
}
}
return obj;
};
}
/* istanbul ignore if*/
if (msie < 9) {
var VBClassPool = {};
window.execScript([// jshint ignore:line
'Function parseVB(code)', '\tExecuteGlobal(code)', 'End Function' //转换一段文本为VB代码
].join('\n'), 'VBScript');
var VBMediator = function VBMediator(instance, accessors, name, value) {
// jshint ignore:line
var accessor = accessors[name];
if (arguments.length === 4) {
accessor.set.call(instance, value);
} else {
return accessor.get.call(instance);
}
};
createViewModel = function createViewModel(name, accessors, properties) {
// jshint ignore:line
var buffer = [];
buffer.push('\tPrivate [$vbsetter]', '\tPublic [$accessors]', '\tPublic Default Function [$vbthis](ac' + timeBucket + ', s' + timeBucket + ')', '\t\tSet [$accessors] = ac' + timeBucket + ': set [$vbsetter] = s' + timeBucket, '\t\tSet [$vbthis] = Me', //链式调用
'\tEnd Function');
//添加普通属性,因为VBScript对象不能像JS那样随意增删属性,必须在这里预先定义好
var uniq = {
$vbthis: true,
$vbsetter: true,
$accessors: true
};
for (name in $$skipArray) {
if (!uniq[name]) {
buffer.push('\tPublic [' + name + ']');
uniq[name] = true;
}
}
//添加访问器属性
for (name in accessors) {
if (uniq[name]) {
continue;
}
uniq[name] = true;
buffer.push(
//由于不知对方会传入什么,因此set, let都用上
'\tPublic Property Let [' + name + '](val' + timeBucket + ')', //setter
'\t\tCall [$vbsetter](Me, [$accessors], "' + name + '", val' + timeBucket + ')', '\tEnd Property', '\tPublic Property Set [' + name + '](val' + timeBucket + ')', //setter
'\t\tCall [$vbsetter](Me, [$accessors], "' + name + '", val' + timeBucket + ')', '\tEnd Property', '\tPublic Property Get [' + name + ']', //getter
'\tOn Error Resume Next', //必须优先使用set语句,否则它会误将数组当字符串返回
'\t\tSet[' + name + '] = [$vbsetter](Me, [$accessors],"' + name + '")', '\tIf Err.Number <> 0 Then', '\t\t[' + name + '] = [$vbsetter](Me, [$accessors],"' + name + '")', '\tEnd If', '\tOn Error Goto 0', '\tEnd Property');
}
for (name in properties) {
if (!uniq[name]) {
uniq[name] = true;
buffer.push('\tPublic [' + name + ']');
}
}
buffer.push('\tPublic [hasOwnProperty]');
buffer.push('End Class');
var body = buffer.join('\r\n');
var className = VBClassPool[body];
if (!className) {
className = avalon.makeHashCode('VBClass');
window.parseVB('Class ' + className + body);
window.parseVB(['Function ' + className + 'Factory(acc, vbm)', //创建实例并传入两个关键的参数
'\tDim o', '\tSet o = (New ' + className + ')(acc, vbm)', '\tSet ' + className + 'Factory = o', 'End Function'].join('\r\n'));
VBClassPool[body] = className;
}
var ret = window[className + 'Factory'](accessors, VBMediator); //得到其产品
return ret; //得到其产品
};
}
}
platform.createViewModel = createViewModel;
var impDir = avalon.directive('important', {
priority: 1,
getScope: function getScope(name, scope) {
var v = avalon.vmodels[name];
if (v) return v;
throw 'error! no vmodel called ' + name;
},
update: function update(node, attrName, $id) {
if (!avalon.inBrowser) return;
var dom = avalon.vdom(node, 'toDOM');
if (dom.nodeType === 1) {
dom.removeAttribute(attrName);
avalon(dom).removeClass('ms-controller');
}
var vm = avalon.vmodels[$id];
if (vm) {
vm.$element = dom;
vm.$render = this;
vm.$fire('onReady');
delete vm.$events.onReady;
}
}
});
var impCb = impDir.update;
avalon.directive('controller', {
priority: 2,
getScope: function getScope(name, scope) {
var v = avalon.vmodels[name];
if (v) {
v.$render = this;
if (scope && scope !== v) {
return platform.fuseFactory(scope, v);
}
return v;
}
return scope;
},
update: impCb
});
avalon.directive('skip', {
delay: true
});
var arrayWarn = {};
var cssDir = avalon.directive('css', {
diff: function diff(newVal, oldVal) {
if (Object(newVal) === newVal) {
newVal = platform.toJson(newVal); //安全的遍历VBscript
if (Array.isArray(newVal)) {
//转换成对象
var b = {};
newVal.forEach(function (el) {
el && avalon.shadowCopy(b, el);
});
newVal = b;
if (!arrayWarn[this.type]) {
avalon.warn('ms-' + this.type + '指令的值不建议使用数组形式了!');
arrayWarn[this.type] = 1;
}
}
var hasChange = false;
var patch = {};
if (!oldVal) {
//如果一开始为空
patch = newVal;
hasChange = true;
} else {
if (this.deep) {
var deep = typeof this.deep === 'number' ? this.deep : 6;
for (var i in newVal) {
//diff差异点
if (!deepEquals(newVal[i], oldVal[i], 4)) {
this.value = newVal;
return true;
}
patch[i] = newVal[i];
}
} else {
for (var _i3 in newVal) {
//diff差异点
if (newVal[_i3] !== oldVal[_i3]) {
hasChange = true;
}
patch[_i3] = newVal[_i3];
}
}
for (var _i4 in oldVal) {
if (!(_i4 in patch)) {
hasChange = true;
patch[_i4] = '';
}
}
}
if (hasChange) {
this.value = patch;
return true;
}
}
return false;
},
update: function update(vdom, value) {
var dom = vdom.dom;
if (dom && dom.nodeType === 1) {
var wrap = avalon(dom);
for (var name in value) {
wrap.css(name, value[name]);
}
}
}
});
var cssDiff = cssDir.diff;
function getEnumerableKeys(obj) {
var res = [];
for (var key in obj) {
res.push(key);
}return res;
}
function deepEquals(a, b, level) {
if (level === 0) return a === b;
if (a === null && b === null) return true;
if (a === undefined && b === undefined) return true;
var aIsArray = Array.isArray(a);
if (aIsArray !== Array.isArray(b)) {
return false;
}
if (aIsArray) {
return equalArray(a, b, level);
} else if (typeof a === "object" && typeof b === "object") {
return equalObject(a, b, level);
}
return a === b;
}
function equalArray(a, b, level) {
if (a.length !== b.length) {
return false;
}
for (var i = a.length - 1; i >= 0; i--) {
try {
if (!deepEquals(a[i], b[i], level - 1)) {
return false;
}
} catch (noThisPropError) {
return false;
}
}
return true;
}
function equalObject(a, b, level) {
if (a === null || b === null) return false;
if (getEnumerableKeys(a).length !== getEnumerableKeys(b).length) return false;
for (var prop in a) {
if (!(prop in b)) return false;
try {
if (!deepEquals(a[prop], b[prop], level - 1)) {
return false;
}
} catch (noThisPropError) {
return false;
}
}
return true;
}
/**
* ------------------------------------------------------------
* 检测浏览器对CSS动画的支持与API名
* ------------------------------------------------------------
*/
var checker = {
TransitionEvent: 'transitionend',
WebKitTransitionEvent: 'webkitTransitionEnd',
OTransitionEvent: 'oTransitionEnd',
otransitionEvent: 'otransitionEnd'
};
var css3 = void 0;
var tran = void 0;
var ani = void 0;
var name$2 = void 0;
var animationEndEvent = void 0;
var transitionEndEvent = void 0;
var transition = false;
var animation = false;
//有的浏览器同时支持私有实现与标准写法,比如webkit支持前两种,Opera支持1、3、4
for (name$2 in checker) {
if (window$1[name$2]) {
tran = checker[name$2];
break;
}
/* istanbul ignore next */
try {
var a = document.createEvent(name$2);
tran = checker[name$2];
break;
} catch (e) {}
}
if (typeof tran === 'string') {
transition = css3 = true;
transitionEndEvent = tran;
}
//animationend有两个可用形态
//IE10+, Firefox 16+ & Opera 12.1+: animationend
//Chrome/Safari: webkitAnimationEnd
//http://blogs.msdn.com/b/davrous/archive/2011/12/06/introduction-to-css3-animat ions.aspx
//IE10也可以使用MSAnimationEnd监听,但是回调里的事件 type依然为animationend
// el.addEventListener('MSAnimationEnd', function(e) {
// alert(e.type)// animationend!!!
// })
checker = {
'AnimationEvent': 'animationend',
'WebKitAnimationEvent': 'webkitAnimationEnd'
};
for (name$2 in checker) {
if (window$1[name$2]) {
ani = checker[name$2];
break;
}
}
if (typeof ani === 'string') {
animation = css3 = true;
animationEndEvent = ani;
}
var effectDir = avalon.directive('effect', {
priority: 5,
diff: function diff(effect) {
var vdom = this.node;
if (typeof effect === 'string') {
this.value = effect = {
is: effect
};
avalon.warn('ms-effect的指令值不再支持字符串,必须是一个对象');
}
this.value = vdom.effect = effect;
var ok = cssDiff.call(this, effect, this.oldValue);
var me = this;
if (ok) {
setTimeout(function () {
vdom.animating = true;
effectDir.update.call(me, vdom, vdom.effect);
});
vdom.animating = false;
return true;
}
return false;
},
update: function update(vdom, change, opts) {
var dom = vdom.dom;
if (dom && dom.nodeType === 1) {
//要求配置对象必须指定is属性,action必须是布尔或enter,leave,move
var option = change || opts;
var is = option.is;
var globalOption = avalon.effects[is];
if (!globalOption) {
//如果没有定义特效
avalon.warn(is + ' effect is undefined');
return;
}
var finalOption = {};
var action = actionMaps[option.action];
if (typeof Effect.prototype[action] !== 'function') {
avalon.warn('action is undefined');
return;
}
//必须预定义特效
var effect = new avalon.Effect(dom);
avalon.mix(finalOption, globalOption, option, { action: action });
if (finalOption.queue) {
animationQueue.push(function () {
effect[action](finalOption);
});
callNextAnimation();
} else {
effect[action](finalOption);
}
return true;
}
}
});
var move = 'move';
var leave = 'leave';
var enter = 'enter';
var actionMaps = {
'true': enter,
'false': leave,
enter: enter,
leave: leave,
move: move,
'undefined': enter
};
var animationQueue = [];
function callNextAnimation() {
var fn = animationQueue[0];
if (fn) {
fn();
}
}
avalon.effects = {};
avalon.effect = function (name, opts) {
var definition = avalon.effects[name] = opts || {};
if (css3 && definition.css !== false) {
patchObject(definition, 'enterClass', name + '-enter');
patchObject(definition, 'enterActiveClass', definition.enterClass + '-active');
patchObject(definition, 'leaveClass', name + '-leave');
patchObject(definition, 'leaveActiveClass', definition.leaveClass + '-active');
}
return definition;
};
function patchObject(obj, name, value) {
if (!obj[name]) {
obj[name] = value;
}
}
var Effect = function Effect(dom) {
this.dom = dom;
};
avalon.Effect = Effect;
Effect.prototype = {
enter: createAction('Enter'),
leave: createAction('Leave'),
move: createAction('Move')
};
function execHooks(options, name, el) {
var fns = [].concat(options[name]);
for (var i = 0, fn; fn = fns[i++];) {
if (typeof fn === 'function') {
fn(el);
}
}
}
var staggerCache = new Cache(128);
function createAction(action) {
var lower = action.toLowerCase();
return function (option) {
var dom = this.dom;
var elem = avalon(dom);
//处理与ms-for指令相关的stagger
//========BEGIN=====
var staggerTime = isFinite(option.stagger) ? option.stagger * 1000 : 0;
if (staggerTime) {
if (option.staggerKey) {
var stagger = staggerCache.get(option.staggerKey) || staggerCache.put(option.staggerKey, {
count: 0,
items: 0
});
stagger.count++;
stagger.items++;
}
}
var staggerIndex = stagger && stagger.count || 0;
//=======END==========
var stopAnimationID;
var animationDone = function animationDone(e) {
var isOk = e !== false;
if (--dom.__ms_effect_ === 0) {
avalon.unbind(dom, transitionEndEvent);
avalon.unbind(dom, animationEndEvent);
}
clearTimeout(stopAnimationID);
var dirWord = isOk ? 'Done' : 'Abort';
execHooks(option, 'on' + action + dirWord, dom);
if (stagger) {
if (--stagger.items === 0) {
stagger.count = 0;
}
}
if (option.queue) {
animationQueue.shift();
callNextAnimation();
}
};
//执行开始前的钩子
execHooks(option, 'onBefore' + action, dom);
if (option[lower]) {
//使用JS方式执行动画
option[lower](dom, function (ok) {
animationDone(ok !== false);
});
} else if (css3) {
//使用CSS3方式执行动画
elem.addClass(option[lower + 'Class']);
elem.removeClass(getNeedRemoved(option, lower));
if (!dom.__ms_effect_) {
//绑定动画结束事件
elem.bind(transitionEndEvent, animationDone);
elem.bind(animationEndEvent, animationDone);
dom.__ms_effect_ = 1;
} else {
dom.__ms_effect_++;
}
setTimeout(function () {
//用xxx-active代替xxx类名的方式 触发CSS3动画
var time = avalon.root.offsetWidth === NaN;
elem.addClass(option[lower + 'ActiveClass']);
//计算动画时长
time = getAnimationTime(dom);
if (!time === 0) {
//立即结束动画
animationDone(false);
} else if (!staggerTime) {
//如果动画超出时长还没有调用结束事件,这可能是元素被移除了
//如果强制结束动画
stopAnimationID = setTimeout(function () {
animationDone(false);
}, time + 32);
}
}, 17 + staggerTime * staggerIndex); // = 1000/60
}
};
}
avalon.applyEffect = function (dom, vdom, opts) {
var cb = opts.cb;
var curEffect = vdom.effect;
if (curEffect && dom && dom.nodeType === 1) {
var hook = opts.hook;
var old = curEffect[hook];
if (cb) {
if (Array.isArray(old)) {
old.push(cb);
} else if (old) {
curEffect[hook] = [old, cb];
} else {
curEffect[hook] = [cb];
}
}
getAction(opts);
avalon.directives.effect.update(vdom, curEffect, avalon.shadowCopy({}, opts));
} else if (cb) {
cb(dom);
}
};
/**
* 获取方向
*/
function getAction(opts) {
if (!opts.action) {
return opts.action = opts.hook.replace(/^on/, '').replace(/Done$/, '').toLowerCase();
}
}
/**
* 需要移除的类名
*/
function getNeedRemoved(options, name) {
var name = name === 'leave' ? 'enter' : 'leave';
return Array(name + 'Class', name + 'ActiveClass').map(function (cls) {
return options[cls];
}).join(' ');
}
/**
* 计算动画长度
*/
var transitionDuration = avalon.cssName('transition-duration');
var animationDuration = avalon.cssName('animation-duration');
var rsecond = /\d+s$/;
function toMillisecond(str) {
var ratio = rsecond.test(str) ? 1000 : 1;
return parseFloat(str) * ratio;
}
function getAnimationTime(dom) {
var computedStyles = window$1.getComputedStyle(dom, null);
var tranDuration = computedStyles[transitionDuration];
var animDuration = computedStyles[animationDuration];
return toMillisecond(tranDuration) || toMillisecond(animDuration);
}
/**
*
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="dist/avalon.js"></script>
<script>
avalon.effect('animate')
var vm = avalon.define({
$id: 'ani',
a: true
})
</script>
<style>
.animate-enter, .animate-leave{
width:100px;
height:100px;
background: #29b6f6;
transition:all 2s;
-moz-transition: all 2s;
-webkit-transition: all 2s;
-o-transition:all 2s;
}
.animate-enter-active, .animate-leave{
width:300px;
height:300px;
}
.animate-leave-active{
width:100px;
height:100px;
}
</style>
</head>
<body>
<div :controller='ani' >
<p><input type='button' value='click' :click='@a =!@a'></p>
<div :effect="{is:'animate',action:@a}"></div>
</div>
</body>
</html>
*
*/
var none = 'none';
function parseDisplay(elem, val) {
//用于取得此类标签的默认display值
var doc = elem.ownerDocument;
var nodeName = elem.nodeName;
var key = '_' + nodeName;
if (!parseDisplay[key]) {
var temp = doc.body.appendChild(doc.createElement(nodeName));
val = avalon.css(temp, 'display');
doc.body.removeChild(temp);
if (val === none) {
val = 'block';
}
parseDisplay[key] = val;
}
return parseDisplay[key];
}
avalon.parseDisplay = parseDisplay;
avalon.directive('visible', {
diff: function diff(newVal, oldVal) {
var n = !!newVal;
if (oldVal === void 0 || n !== oldVal) {
this.value = n;
return true;
}
},
ready: true,
update: function update(vdom, show) {
var dom = vdom.dom;
if (dom && dom.nodeType === 1) {
var display = dom.style.display;
var value;
if (show) {
if (display === none) {
value = vdom.displayValue;
if (!value) {
dom.style.display = '';
if (dom.style.cssText === '') {
dom.removeAttribute('style');
}
}
}
if (dom.style.display === '' && avalon(dom).css('display') === none &&
// fix firefox BUG,必须挂到页面上
avalon.contains(dom.ownerDocument, dom)) {
value = parseDisplay(dom);
}
} else {
if (display !== none) {
value = none;
vdom.displayValue = display;
}
}
var cb = function cb() {
if (value !== void 0) {
dom.style.display = value;
}
};
avalon.applyEffect(dom, vdom, {
hook: show ? 'onEnterDone' : 'onLeaveDone',
cb: cb
});
}
}
});
avalon.directive('text', {
delay: true,
init: function init() {
var node = this.node;
if (node.isVoidTag) {
avalon.error('自闭合元素不能使用ms-text');
}
var child = { nodeName: '#text', nodeValue: this.getValue() };
node.children.splice(0, node.children.length, child);
if (inBrowser) {
avalon.clearHTML(node.dom);
node.dom.appendChild(avalon.vdom(child, 'toDOM'));
}
this.node = child;
var type = 'expr';
this.type = this.name = type;
var directive$$1 = avalon.directives[type];
var me = this;
this.callback = function (value) {
directive$$1.update.call(me, me.node, value);
};
}
});
avalon.directive('expr', {
update: function update(vdom, value) {
vdom.nodeValue = value;
//https://github.com/RubyLouvre/avalon/issues/1834
if (vdom.dom) if (value === '') value = '\u200B';
vdom.dom.data = value;
}
});
avalon.directive('attr', {
diff: cssDiff,
update: function update(vdom, value) {
var props = vdom.props;
for (var i in value) {
if (!!value[i] === false) {
delete props[i];
} else {
props[i] = value[i];
}
}
var dom = vdom.dom;
if (dom && dom.nodeType === 1) {
updateAttrs(dom, value);
}
}
});
avalon.directive('html', {
update: function update(vdom, value) {
this.beforeDispose();
this.innerRender = avalon.scan('<div class="ms-html-container">' + value + '</div>', this.vm, function () {
var oldRoot = this.root;
if (vdom.children) vdom.children.length = 0;
vdom.children = oldRoot.children;
this.root = vdom;
if (vdom.dom) avalon.clearHTML(vdom.dom);
});
},
beforeDispose: function beforeDispose() {
if (this.innerRender) {
this.innerRender.dispose();
}
},
delay: true
});
avalon.directive('if', {
delay: true,
priority: 5,
init: function init() {
this.placeholder = createAnchor('if');
var props = this.node.props;
delete props['ms-if'];
delete props[':if'];
this.fragment = avalon.vdom(this.node, 'toHTML');
},
diff: function diff(newVal, oldVal) {
var n = !!newVal;
if (oldVal === void 0 || n !== oldVal) {
this.value = n;
return true;
}
},
update: function update(vdom, value) {
if (this.isShow === void 0 && value) {
continueScan(this, vdom);
return;
}
this.isShow = value;
var placeholder = this.placeholder;
if (value) {
var p = placeholder.parentNode;
continueScan(this, vdom);
p && p.replaceChild(vdom.dom, placeholder);
} else {
//移除DOM
this.beforeDispose();
vdom.nodeValue = 'if';
vdom.nodeName = '#comment';
delete vdom.children;
var dom = vdom.dom;
var p = dom && dom.parentNode;
vdom.dom = placeholder;
if (p) {
p.replaceChild(placeholder, dom);
}
}
},
beforeDispose: function beforeDispose() {
if (this.innerRender) {
this.innerRender.dispose();
}
}
});
function continueScan(instance, vdom) {
var innerRender = instance.innerRender = avalon.scan(instance.fragment, instance.vm);
avalon.shadowCopy(vdom, innerRender.root);
delete vdom.nodeValue;
}
avalon.directive('on', {
beforeInit: function beforeInit() {
this.getter = avalon.noop;
},
init: function init() {
var vdom = this.node;
var underline = this.name.replace('ms-on-', 'e').replace('-', '_');
var uuid = underline + '_' + this.expr.replace(/\s/g, '').replace(/[^$a-z]/ig, function (e) {
return e.charCodeAt(0);
});
var fn = avalon.eventListeners[uuid];
if (!fn) {
var arr = addScope(this.expr);
var body = arr[0],
filters = arr[1];
body = makeHandle(body);
if (filters) {
filters = filters.replace(/__value__/g, '$event');
filters += '\nif($event.$return){\n\treturn;\n}';
}
var ret = ['try{', '\tvar __vmodel__ = this;', '\t' + filters, '\treturn ' + body, '}catch(e){avalon.log(e, "in on dir")}'].filter(function (el) {
return (/\S/.test(el)
);
});
fn = new Function('$event', ret.join('\n'));
fn.uuid = uuid;
avalon.eventListeners[uuid] = fn;
}
var dom = avalon.vdom(vdom, 'toDOM');
dom._ms_context_ = this.vm;
this.eventType = this.param.replace(/\-(\d)$/, '');
delete this.param;
avalon(dom).bind(this.eventType, fn);
},
beforeDispose: function beforeDispose() {
avalon(this.node.dom).unbind(this.eventType);
}
});
var rforAs = /\s+as\s+([$\w]+)/;
var rident = /^[$a-zA-Z_][$a-zA-Z0-9_]*$/;
var rinvalid = /^(null|undefined|NaN|window|this|\$index|\$id)$/;
var rargs = /[$\w_]+/g;
avalon.directive('for', {
delay: true,
priority: 3,
beforeInit: function beforeInit() {
var str = this.expr,
asName;
str = str.replace(rforAs, function (a, b) {
/* istanbul ignore if */
if (!rident.test(b) || rinvalid.test(b)) {
avalon.error('alias ' + b + ' is invalid --- must be a valid JS identifier which is not a reserved name.');
} else {
asName = b;
}
return '';
});
var arr = str.split(' in ');
var kv = arr[0].match(rargs);
if (kv.length === 1) {
//确保avalon._each的回调有三个参数
kv.unshift('$key');
}
this.expr = arr[1];
this.keyName = kv[0];
this.valName = kv[1];
this.signature = avalon.makeHashCode('for');
if (asName) {
this.asName = asName;
}
delete this.param;
},
init: function init() {
var cb = this.userCb;
if (typeof cb === 'string' && cb) {
var arr = addScope(cb, 'for');
var body = makeHandle(arr[0]);
this.userCb = new Function('$event', 'var __vmodel__ = this\nreturn ' + body);
}
this.node.forDir = this; //暴露给component/index.js中的resetParentChildren方法使用
this.fragment = ['<div>', this.fragment, '<!--', this.signature, '--></div>'].join('');
this.cache = {};
},
diff: function diff(newVal, oldVal) {
/* istanbul ignore if */
if (this.updating) {
return;
}
this.updating = true;
var traceIds = createFragments(this, newVal);
if (this.oldTrackIds === void 0) return true;
if (this.oldTrackIds !== traceIds) {
this.oldTrackIds = traceIds;
return true;
}
},
update: function update() {
if (!this.preFragments) {
this.fragments = this.fragments || [];
mountList(this);
} else {
diffList(this);
updateList(this);
}
if (this.userCb) {
this.userCb.call(this.vm, {
type: 'rendered',
target: this.begin.dom,
signature: this.signature
});
}
delete this.updating;
},
beforeDispose: function beforeDispose() {
this.fragments.forEach(function (el) {
el.dispose();
});
}
});
function getTraceKey(item) {
var type = typeof item;
return item && type === 'object' ? item.$hashcode : type + ':' + item;
}
//创建一组fragment的虚拟DOM
function createFragments(instance, obj) {
if (isObject(obj)) {
var array = Array.isArray(obj);
var ids = [];
var fragments = [],
i = 0;
instance.isArray = array;
if (instance.fragments) {
instance.preFragments = instance.fragments;
avalon.each(obj, function (key, value) {
var k = array ? getTraceKey(value) : key;
fragments.push({
key: k,
val: value,
index: i++
});
ids.push(k);
});
instance.fragments = fragments;
} else {
avalon.each(obj, function (key, value) {
var k = array ? getTraceKey(value) : key;
fragments.push(new VFragment([], k, value, i++));
ids.push(k);
});
instance.fragments = fragments;
}
return ids.join(';;');
} else {
return NaN;
}
}
function mountList(instance) {
var args = instance.fragments.map(function (fragment, index) {
FragmentDecorator(fragment, instance, index);
saveInCache(instance.cache, fragment);
return fragment;
});
var list = instance.parentChildren;
var i = list.indexOf(instance.begin);
list.splice.apply(list, [i + 1, 0].concat(args));
}
function diffList(instance) {
var cache = instance.cache;
var newCache = {};
var fuzzy = [];
var list = instance.preFragments;
list.forEach(function (el) {
el._dispose = true;
});
instance.fragments.forEach(function (c, index) {
var fragment = isInCache(cache, c.key);
//取出之前的文档碎片
if (fragment) {
delete fragment._dispose;
fragment.oldIndex = fragment.index;
fragment.index = index; // 相当于 c.index
resetVM(fragment.vm, instance.keyName);
fragment.vm[instance.keyName] = instance.isArray ? index : fragment.key;
saveInCache(newCache, fragment);
} else {
//如果找不到就进行模糊搜索
fuzzy.push(c);
}
});
fuzzy.forEach(function (c) {
var fragment = fuzzyMatchCache(cache, c.key);
if (fragment) {
//重复利用
fragment.oldIndex = fragment.index;
fragment.key = c.key;
var val = fragment.val = c.val;
var index = fragment.index = c.index;
fragment.vm[instance.valName] = val;
fragment.vm[instance.keyName] = instance.isArray ? index : fragment.key;
delete fragment._dispose;
} else {
c = new VFragment([], c.key, c.val, c.index);
fragment = FragmentDecorator(c, instance, c.index);
list.push(fragment);
}
saveInCache(newCache, fragment);
});
instance.fragments = list;
list.sort(function (a, b) {
return a.index - b.index;
});
instance.cache = newCache;
}
function resetVM(vm, a, b) {
vm.$accessors[a].value = NaN;
}
function updateList(instance) {
var before = instance.begin.dom;
var parent = before.parentNode;
var list = instance.fragments;
var end = instance.end.dom;
for (var i = 0, item; item = list[i]; i++) {
if (item._dispose) {
list.splice(i, 1);
i--;
item.dispose();
continue;
}
if (item.oldIndex !== item.index) {
var f = item.toFragment();
var isEnd = before.nextSibling === null;
parent.insertBefore(f, before.nextSibling);
if (isEnd && !parent.contains(end)) {
parent.insertBefore(end, before.nextSibling);
}
}
before = item.split;
}
var ch = instance.parentChildren;
var startIndex = ch.indexOf(instance.begin);
var endIndex = ch.indexOf(instance.end);
list.splice.apply(ch, [startIndex + 1, endIndex - startIndex].concat(list));
}
/**
*
* @param {type} fragment
* @param {type} this
* @param {type} index
* @returns { key, val, index, oldIndex, this, dom, split, vm}
*/
function FragmentDecorator(fragment, instance, index) {
var data = {};
data[instance.keyName] = instance.isArray ? index : fragment.key;
data[instance.valName] = fragment.val;
if (instance.asName) {
data[instance.asName] = instance.value;
}
var vm = fragment.vm = platform.itemFactory(instance.vm, {
data: data
});
if (instance.isArray) {
vm.$watch(instance.valName, function (a) {
if (instance.value && instance.value.set) {
instance.value.set(vm[instance.keyName], a);
}
});
} else {
vm.$watch(instance.valName, function (a) {
instance.value[fragment.key] = a;
});
}
fragment.index = index;
fragment.innerRender = avalon.scan(instance.fragment, vm, function () {
var oldRoot = this.root;
ap.push.apply(fragment.children, oldRoot.children);
this.root = fragment;
});
return fragment;
}
// 新位置: 旧位置
function isInCache(cache, id) {
var c = cache[id];
if (c) {
var arr = c.arr;
/* istanbul ignore if*/
if (arr) {
var r = arr.pop();
if (!arr.length) {
c.arr = 0;
}
return r;
}
delete cache[id];
return c;
}
}
//[1,1,1] number1 number1_ number1__
function saveInCache(cache, component) {
var trackId = component.key;
if (!cache[trackId]) {
cache[trackId] = component;
} else {
var c = cache[trackId];
var arr = c.arr || (c.arr = []);
arr.push(component);
}
}
function fuzzyMatchCache(cache) {
var key;
for (var id in cache) {
var key = id;
break;
}
if (key) {
return isInCache(cache, key);
}
}
//根据VM的属性值或表达式的值切换类名,ms-class='xxx yyy zzz:flag'
//http://www.cnblogs.com/rubylouvre/archive/2012/12/17/2818540.html
function classNames() {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
var argType = typeof arg;
if (argType === 'string' || argType === 'number' || arg === true) {
classes.push(arg);
} else if (Array.isArray(arg)) {
classes.push(classNames.apply(null, arg));
} else if (argType === 'object') {
for (var key in arg) {
if (arg.hasOwnProperty(key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
avalon.directive('class', {
diff: function diff(newVal, oldVal) {
var type = this.type;
var vdom = this.node;
var classEvent = vdom.classEvent || {};
if (type === 'hover') {
//在移出移入时切换类名
classEvent.mouseenter = activateClass;
classEvent.mouseleave = abandonClass;
} else if (type === 'active') {
//在获得焦点时切换类名
classEvent.tabIndex = vdom.props.tabindex || -1;
classEvent.mousedown = activateClass;
classEvent.mouseup = abandonClass;
classEvent.mouseleave = abandonClass;
}
vdom.classEvent = classEvent;
var className = classNames(newVal);
if (typeof oldVal === void 0 || oldVal !== className) {
this.value = className;
vdom['change-' + type] = className;
return true;
}
},
update: function update(vdom, value) {
var dom = vdom.dom;
if (dom && dom.nodeType == 1) {
var dirType = this.type;
var change = 'change-' + dirType;
var classEvent = vdom.classEvent;
if (classEvent) {
for (var i in classEvent) {
if (i === 'tabIndex') {
dom[i] = classEvent[i];
} else {
avalon.bind(dom, i, classEvent[i]);
}
}
vdom.classEvent = {};
}
var names = ['class', 'hover', 'active'];
names.forEach(function (type) {
if (dirType !== type) return;
if (type === 'class') {
dom && setClass(dom, value);
} else {
var oldClass = dom.getAttribute(change);
if (oldClass) {
avalon(dom).removeClass(oldClass);
}
var name = 'change-' + type;
dom.setAttribute(name, value);
}
});
}
}
});
directives.active = directives.hover = directives['class'];
var classMap = {
mouseenter: 'change-hover',
mouseleave: 'change-hover',
mousedown: 'change-active',
mouseup: 'change-active'
};
function activateClass(e) {
var elem = e.target;
avalon(elem).addClass(elem.getAttribute(classMap[e.type]) || '');
}
function abandonClass(e) {
var elem = e.target;
var name = classMap[e.type];
avalon(elem).removeClass(elem.getAttribute(name) || '');
if (name !== 'change-active') {
avalon(elem).removeClass(elem.getAttribute('change-active') || '');
}
}
function setClass(dom, neo) {
var old = dom.getAttribute('change-class');
if (old !== neo) {
avalon(dom).removeClass(old).addClass(neo);
dom.setAttribute('change-class', neo);
}
}
getLongID(activateClass);
getLongID(abandonClass);
function lookupOption(vdom, values) {
vdom.children && vdom.children.forEach(function (el) {
if (el.nodeName === 'option') {
setOption(el, values);
} else {
lookupOption(el, values);
}
});
}
function setOption(vdom, values) {
var props = vdom.props;
if (!('disabled' in props)) {
var value = getOptionValue(vdom, props).trim();
props.selected = values.indexOf(value) !== -1;
if (vdom.dom) {
vdom.dom.selected = props.selected;
}
}
}
function getOptionValue(vdom, props) {
if (props && 'value' in props) {
return props.value;
}
var arr = [];
vdom.children.forEach(function (el) {
if (el.nodeName === '#text') {
arr.push(el.nodeValue);
} else if (el.nodeName === '#document-fragment') {
arr.push(getOptionValue(el));
}
});
return arr.join('');
}
function getSelectedValue(vdom, arr) {
vdom.children.forEach(function (el) {
if (el.nodeName === 'option') {
if (el.props.selected === true) arr.push(getOptionValue(el, el.props));
} else if (el.children) {
getSelectedValue(el, arr);
}
});
return arr;
}
var rchangeFilter = /\|\s*change\b/;
var rdebounceFilter = /\|\s*debounce(?:\(([^)]+)\))?/;
function duplexBeforeInit() {
var expr = this.expr;
if (rchangeFilter.test(expr)) {
this.isChanged = true;
expr = expr.replace(rchangeFilter, '');
}
var match = expr.match(rdebounceFilter);
if (match) {
expr = expr.replace(rdebounceFilter, '');
if (!this.isChanged) {
this.debounceTime = parseInt(match[1], 10) || 300;
}
}
this.expr = expr;
}
function duplexInit() {
var expr = this.expr;
var node = this.node;
var etype = node.props.type;
this.parseValue = parseValue;
//处理数据转换器
var parsers = this.param,
dtype;
var isChecked = false;
parsers = parsers ? parsers.split('-').map(function (a) {
if (a === 'checked') {
isChecked = true;
}
return a;
}) : [];
node.duplex = this;
if (rcheckedType.test(etype) && isChecked) {
//如果是radio, checkbox,判定用户使用了checked格式函数没有
parsers = [];
dtype = 'radio';
this.isChecked = isChecked;
}
this.parsers = parsers;
if (!/input|textarea|select/.test(node.nodeName)) {
if ('contenteditable' in node.props) {
dtype = 'contenteditable';
}
} else if (!dtype) {
dtype = node.nodeName === 'select' ? 'select' : etype === 'checkbox' ? 'checkbox' : etype === 'radio' ? 'radio' : 'input';
}
this.dtype = dtype;
var isChanged = false,
debounceTime = 0;
//判定是否使用了 change debounce 过滤器
// this.isChecked = /boolean/.test(parsers)
if (dtype !== 'input' && dtype !== 'contenteditable') {
delete this.isChange;
delete this.debounceTime;
} else if (!this.isChecked) {
this.isString = true;
}
var cb = node.props['data-duplex-changed'];
if (cb) {
var arr = addScope(cb, 'xx');
var body = makeHandle(arr[0]);
this.userCb = new Function('$event', 'var __vmodel__ = this\nreturn ' + body);
}
}
function duplexDiff(newVal, oldVal) {
if (Array.isArray(newVal)) {
if (newVal + '' !== this.compareVal) {
this.compareVal = newVal + '';
return true;
}
} else {
newVal = this.parseValue(newVal);
if (!this.isChecked) {
this.value = newVal += '';
}
if (newVal !== this.compareVal) {
this.compareVal = newVal;
return true;
}
}
}
function duplexValidate(node, vdom) {
//将当前虚拟DOM的duplex添加到它上面的表单元素的validate指令的fields数组中
var field = vdom.duplex;
var rules = vdom.rules;
if (rules && !field.validator) {
while (node && node.nodeType === 1) {
var validator = node._ms_validate_;
if (validator) {
field.rules = rules;
field.validator = validator;
if (avalon.Array.ensure(validator.fields, field)) {
validator.addField(field);
}
break;
}
node = node.parentNode;
}
}
}
var valueHijack = true;
try {
//#272 IE9-IE11, firefox
var setters = {};
var aproto = HTMLInputElement.prototype;
var bproto = HTMLTextAreaElement.prototype;
var newSetter = function newSetter(value) {
// jshint ignore:line
setters[this.tagName].call(this, value);
var data = this._ms_duplex_;
if (!this.caret && data && data.isString) {
data.duplexCb.call(this, { type: 'setter' });
}
};
var inputProto = HTMLInputElement.prototype;
Object.getOwnPropertyNames(inputProto); //故意引发IE6-8等浏览器报错
setters['INPUT'] = Object.getOwnPropertyDescriptor(aproto, 'value').set;
Object.defineProperty(aproto, 'value', {
set: newSetter
});
setters['TEXTAREA'] = Object.getOwnPropertyDescriptor(bproto, 'value').set;
Object.defineProperty(bproto, 'value', {
set: newSetter
});
valueHijack = false;
} catch (e) {
//在chrome 43中 ms-duplex终于不需要使用定时器实现双向绑定了
// http://updates.html5rocks.com/2015/04/DOM-attributes-now-on-the-prototype
// https://docs.google.com/document/d/1jwA8mtClwxI-QJuHT7872Z0pxpZz8PBkf2bGAbsUtqs/edit?pli=1
}
function parseValue(val) {
for (var i = 0, k; k = this.parsers[i++];) {
var fn = avalon.parsers[k];
if (fn) {
val = fn.call(this, val);
}
}
return val;
}
var updateView = {
input: function input() {
//处理单个value值处理
this.node.props.value = this.value + '';
this.dom.value = this.value;
},
updateChecked: function updateChecked(vdom, checked) {
if (vdom.dom) {
vdom.dom.defaultChecked = vdom.dom.checked = checked;
}
},
radio: function radio() {
//处理单个checked属性
var node = this.node;
var nodeValue = node.props.value;
var checked;
if (this.isChecked) {
checked = !!this.value;
} else {
checked = this.value + '' === nodeValue;
}
node.props.checked = checked;
updateView.updateChecked(node, checked);
},
checkbox: function checkbox() {
//处理多个checked属性
var node = this.node;
var props = node.props;
var value = props.value + '';
var values = [].concat(this.value);
var checked = values.some(function (el) {
return el + '' === value;
});
props.defaultChecked = props.checked = checked;
updateView.updateChecked(node, checked);
},
select: function select() {
//处理子级的selected属性
var a = Array.isArray(this.value) ? this.value.map(String) : this.value + '';
lookupOption(this.node, a);
},
contenteditable: function contenteditable() {
//处理单个innerHTML
var vnodes = fromString(this.value);
var fragment = createFragment();
for (var i = 0, el; el = vnodes[i++];) {
var child = avalon.vdom(el, 'toDOM');
fragment.appendChild(child);
}
avalon.clearHTML(this.dom).appendChild(fragment);
var list = this.node.children;
list.length = 0;
Array.prototype.push.apply(list, vnodes);
this.duplexCb.call(this.dom);
}
};
var updateDataActions = {
input: function input(prop) {
//处理单个value值处理
var field = this;
prop = prop || 'value';
var dom = field.dom;
var rawValue = dom[prop];
var parsedValue = field.parseValue(rawValue);
//有时候parse后一致,vm不会改变,但input里面的值
field.value = rawValue;
field.setValue(parsedValue);
duplexCb(field);
var pos = field.pos;
/* istanbul ignore if */
if (dom.caret) {
field.setCaret(dom, pos);
}
//vm.aaa = '1234567890'
//处理 <input ms-duplex='@aaa|limitBy(8)'/>{{@aaa}} 这种格式化同步不一致的情况
},
radio: function radio() {
var field = this;
if (field.isChecked) {
var val = !field.value;
field.setValue(val);
duplexCb(field);
} else {
updateDataActions.input.call(field);
field.value = NaN;
}
},
checkbox: function checkbox() {
var field = this;
var array = field.value;
if (!Array.isArray(array)) {
avalon.warn('ms-duplex应用于checkbox上要对应一个数组');
array = [array];
}
var method = field.dom.checked ? 'ensure' : 'remove';
if (array[method]) {
var val = field.parseValue(field.dom.value);
array[method](val);
duplexCb(field);
}
this.__test__ = array;
},
select: function select() {
var field = this;
var val = avalon(field.dom).val(); //字符串或字符串数组
if (val + '' !== this.value + '') {
if (Array.isArray(val)) {
//转换布尔数组或其他
val = val.map(function (v) {
return field.parseValue(v);
});
} else {
val = field.parseValue(val);
}
field.setValue(val);
duplexCb(field);
}
},
contenteditable: function contenteditable() {
updateDataActions.input.call(this, 'innerHTML');
}
};
function duplexCb(field) {
if (field.userCb) {
field.userCb.call(field.vm, {
type: 'changed',
target: field.dom
});
}
}
function updateDataHandle(event) {
var elem = this;
var field = elem._ms_duplex_;
if (elem.composing) {
//防止onpropertychange引发爆栈
return;
}
if (elem.value === field.value) {
return;
}
/* istanbul ignore if*/
if (elem.caret) {
try {
var pos = field.getCaret(elem);
field.pos = pos;
} catch (e) {}
}
/* istanbul ignore if*/
if (field.debounceTime > 4) {
var timestamp = new Date();
var left = timestamp - field.time || 0;
field.time = timestamp;
/* istanbul ignore if*/
if (left >= field.debounceTime) {
updateDataActions[field.dtype].call(field);
/* istanbul ignore else*/
} else {
clearTimeout(field.debounceID);
field.debounceID = setTimeout(function () {
updateDataActions[field.dtype].call(field);
}, left);
}
} else {
updateDataActions[field.dtype].call(field);
}
}
/*
* 通过绑定事件同步vmodel
* 总共有三种方式同步视图
* 1. 各种事件 input, change, click, propertychange, keydown...
* 2. value属性重写
* 3. 定时器轮询
*/
function updateDataEvents(dom, data) {
var events = {};
//添加需要监听的事件
switch (data.dtype) {
case 'radio':
case 'checkbox':
events.click = updateDataHandle;
break;
case 'select':
events.change = updateDataHandle;
break;
case 'contenteditable':
/* istanbul ignore if */
if (data.isChanged) {
events.blur = updateDataHandle;
/* istanbul ignore else */
} else {
/* istanbul ignore if*/
if (avalon.modern) {
if (window$1.webkitURL) {
// http://code.metager.de/source/xref/WebKit/LayoutTests/fast/events/
// https://bugs.webkit.org/show_bug.cgi?id=110742
events.webkitEditableContentChanged = updateDataHandle;
} else if (window$1.MutationEvent) {
events.DOMCharacterDataModified = updateDataHandle;
}
events.input = updateDataHandle;
/* istanbul ignore else */
} else {
events.keydown = updateModelKeyDown;
events.paste = updateModelDelay;
events.cut = updateModelDelay;
events.focus = closeComposition;
events.blur = openComposition;
}
}
break;
case 'input':
/* istanbul ignore if */
if (data.isChanged) {
events.change = updateDataHandle;
/* istanbul ignore else */
} else {
//http://www.cnblogs.com/rubylouvre/archive/2013/02/17/2914604.html
//http://www.matts411.com/post/internet-explorer-9-oninput/
if (msie < 10) {
//IE6-8的propertychange有问题,第一次用JS修改值时不会触发,而且你是全部清空value也不会触发
//IE9的propertychange不支持自动完成,退格,删除,复制,贴粘,剪切或点击右边的小X的清空操作
events.propertychange = updateModelHack;
events.paste = updateModelDelay;
events.cut = updateModelDelay;
//IE9在第一次删除字符时不会触发oninput
events.keyup = updateModelKeyDown;
} else {
events.input = updateDataHandle;
events.compositionstart = openComposition;
//微软拼音输入法的问题需要在compositionend事件中处理
events.compositionend = closeComposition;
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
//处理低版本的标准浏览器,通过Int8Array进行区分
if (!/\[native code\]/.test(window$1.Int8Array)) {
events.keydown = updateModelKeyDown; //safari < 5 opera < 11
events.paste = updateModelDelay; //safari < 5
events.cut = updateModelDelay; //safari < 5
if (window$1.netscape) {
// Firefox <= 3.6 doesn't fire the 'input' event when text is filled in through autocomplete
events.DOMAutoComplete = updateDataHandle;
}
}
}
}
break;
}
if (/password|text/.test(dom.type)) {
events.focus = openCaret; //判定是否使用光标修正功能
events.blur = closeCaret;
data.getCaret = getCaret;
data.setCaret = setCaret;
}
for (var name in events) {
avalon.bind(dom, name, events[name]);
}
}
function updateModelHack(e) {
if (e.propertyName === 'value') {
updateDataHandle.call(this, e);
}
}
function updateModelDelay(e) {
var elem = this;
setTimeout(function () {
updateDataHandle.call(elem, e);
}, 0);
}
function openCaret() {
this.caret = true;
}
/* istanbul ignore next */
function closeCaret() {
this.caret = false;
}
/* istanbul ignore next */
function openComposition() {
this.composing = true;
}
/* istanbul ignore next */
function closeComposition(e) {
this.composing = false;
updateModelDelay.call(this, e);
}
/* istanbul ignore next */
function updateModelKeyDown(e) {
var key = e.keyCode;
// ignore
// command modifiers arrows
if (key === 91 || 15 < key && key < 19 || 37 <= key && key <= 40) return;
updateDataHandle.call(this, e);
}
getShortID(openCaret);
getShortID(closeCaret);
getShortID(openComposition);
getShortID(closeComposition);
getShortID(updateDataHandle);
getShortID(updateModelHack);
getShortID(updateModelDelay);
getShortID(updateModelKeyDown);
//IE6-8要处理光标时需要异步
var mayBeAsync = function mayBeAsync(fn) {
setTimeout(fn, 0);
};
/* istanbul ignore next */
function setCaret(target, cursorPosition) {
var range$$1;
if (target.createTextRange) {
mayBeAsync(function () {
target.focus();
range$$1 = target.createTextRange();
range$$1.collapse(true);
range$$1.moveEnd('character', cursorPosition);
range$$1.moveStart('character', cursorPosition);
range$$1.select();
});
} else {
target.focus();
if (target.selectionStart !== undefined) {
target.setSelectionRange(cursorPosition, cursorPosition);
}
}
}
/* istanbul ignore next*/
function getCaret(target) {
var start = 0;
var normalizedValue;
var range$$1;
var textInputRange;
var len;
var endRange;
if (target.selectionStart + target.selectionEnd > -1) {
start = target.selectionStart;
} else {
range$$1 = document$1.selection.createRange();
if (range$$1 && range$$1.parentElement() === target) {
len = target.value.length;
normalizedValue = target.value.replace(/\r\n/g, '\n');
textInputRange = target.createTextRange();
textInputRange.moveToBookmark(range$$1.getBookmark());
endRange = target.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints('StartToEnd', endRange) > -1) {
start = len;
} else {
start = -textInputRange.moveStart('character', -len);
start += normalizedValue.slice(0, start).split('\n').length - 1;
}
}
}
return start;
}
avalon.directive('duplex', {
priority: 9999999,
beforeInit: duplexBeforeInit,
init: duplexInit,
diff: duplexDiff,
update: function update(vdom, value) {
var dom = vdom.dom;
if (!this.dom) {
this.dom = dom;
this.duplexCb = updateDataHandle;
dom._ms_duplex_ = this;
//绑定事件
updateDataEvents(dom, this);
//添加验证
duplexValidate(dom, vdom);
}
//如果不支持input.value的Object.defineProperty的属性支持,
//需要通过轮询同步, chrome 42及以下版本需要这个hack
pollValue.call(this, avalon.msie, valueHijack);
//更新视图
updateView[this.dtype].call(this);
}
});
function pollValue(isIE, valueHijack$$1) {
var dom = this.dom;
if (this.isString && valueHijack$$1 && !isIE && !dom.valueHijack) {
dom.valueHijack = updateDataHandle;
var intervalID = setInterval(function () {
if (!avalon.contains(avalon.root, dom)) {
clearInterval(intervalID);
} else {
dom.valueHijack({ type: 'poll' });
}
}, 30);
return intervalID;
}
}
avalon.__pollValue = pollValue; //export to test
/* istanbul ignore if */
if (avalon.msie < 8) {
var oldUpdate = updateView.updateChecked;
updateView.updateChecked = function (vdom, checked) {
var dom = vdom.dom;
if (dom) {
setTimeout(function () {
oldUpdate(vdom, checked);
dom.firstCheckedIt = 1;
}, dom.firstCheckedIt ? 31 : 16);
//IE6,7 checkbox, radio是使用defaultChecked控制选中状态,
//并且要先设置defaultChecked后设置checked
//并且必须设置延迟(因为必须插入DOM树才生效)
}
};
}
avalon.directive('rules', {
diff: function diff(rules) {
if (isObject(rules)) {
var vdom = this.node;
vdom.rules = platform.toJson(rules);
if (vdom.duplex) {
vdom.duplex.rules = vdom.rules;
}
return true;
}
}
});
function isRegExp(value) {
return avalon.type(value) === 'regexp';
}
var rmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i;
var rurl = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
function isCorrectDate(value) {
if (typeof value === "string" && value) {
//是字符串但不能是空字符
var arr = value.split("-"); //可以被-切成3份,并且第1个是4个字符
if (arr.length === 3 && arr[0].length === 4) {
var year = ~~arr[0]; //全部转换为非负整数
var month = ~~arr[1] - 1;
var date = ~~arr[2];
var d = new Date(year, month, date);
return d.getFullYear() === year && d.getMonth() === month && d.getDate() === date;
}
}
return false;
}
//https://github.com/adform/validator.js/blob/master/validator.js
avalon.shadowCopy(avalon.validators, {
pattern: {
message: '必须匹配{{pattern}}这样的格式',
get: function get(value, field, next) {
var elem = field.dom;
var data = field.data;
if (!isRegExp(data.pattern)) {
var h5pattern = elem.getAttribute("pattern");
data.pattern = new RegExp('^(?:' + h5pattern + ')$');
}
next(data.pattern.test(value));
return value;
}
},
digits: {
message: '必须整数',
get: function get(value, field, next) {
//整数
next(/^\-?\d+$/.test(value));
return value;
}
},
number: {
message: '必须数字',
get: function get(value, field, next) {
//数值
next(!!value && isFinite(value)); // isFinite('') --> true
return value;
}
},
norequired: {
message: '',
get: function get(value, field, next) {
next(true);
return value;
}
},
required: {
message: '必须填写',
get: function get(value, field, next) {
next(value !== '');
return value;
}
},
equalto: {
message: '密码输入不一致',
get: function get(value, field, next) {
var id = String(field.data.equalto);
var other = avalon(document.getElementById(id)).val() || "";
next(value === other);
return value;
}
},
date: {
message: '日期格式不正确',
get: function get(value, field, next) {
var data = field.data;
if (isRegExp(data.date)) {
next(data.date.test(value));
} else {
next(isCorrectDate(value));
}
return value;
}
},
url: {
message: 'URL格式不正确',
get: function get(value, field, next) {
next(rurl.test(value));
return value;
}
},
email: {
message: 'email格式不正确',
get: function get(value, field, next) {
next(rmail.test(value));
return value;
}
},
minlength: {
message: '最少输入{{minlength}}个字',
get: function get(value, field, next) {
var num = parseInt(field.data.minlength, 10);
next(value.length >= num);
return value;
}
},
maxlength: {
message: '最多输入{{maxlength}}个字',
get: function get(value, field, next) {
var num = parseInt(field.data.maxlength, 10);
next(value.length <= num);
return value;
}
},
min: {
message: '输入值不能小于{{min}}',
get: function get(value, field, next) {
var num = parseInt(field.data.min, 10);
next(parseFloat(value) >= num);
return value;
}
},
max: {
message: '输入值不能大于{{max}}',
get: function get(value, field, next) {
var num = parseInt(field.data.max, 10);
next(parseFloat(value) <= num);
return value;
}
},
chs: {
message: '必须是中文字符',
get: function get(value, field, next) {
next(/^[\u4e00-\u9fa5]+$/.test(value));
return value;
}
}
});
var valiDir = avalon.directive('validate', {
diff: function diff(validator) {
var vdom = this.node;
if (vdom.validator) {
return;
}
if (isObject(validator)) {
//注意,这个Form标签的虚拟DOM有两个验证对象
//一个是vmValidator,它是用户VM上的那个原始子对象,也是一个VM
//一个是validator,它是vmValidator.$model, 这是为了防止IE6-8添加子属性时添加的hack
//也可以称之为safeValidate
vdom.vmValidator = validator;
validator = platform.toJson(validator);
vdom.validator = validator;
for (var name in valiDir.defaults) {
if (!validator.hasOwnProperty(name)) {
validator[name] = valiDir.defaults[name];
}
}
validator.fields = validator.fields || [];
return true;
}
},
update: function update(vdom) {
var validator = vdom.validator;
var dom = vdom.dom;
validator.dom = dom;
dom._ms_validate_ = validator;
//为了方便用户手动执行验证,我们需要为原始vmValidate上添加一个onManual方法
var v = vdom.vmValidator;
try {
v.onManual = onManual;
} catch (e) {}
delete vdom.vmValidator;
dom.setAttribute('novalidate', 'novalidate');
function onManual() {
valiDir.validateAll.call(validator, validator.onValidateAll);
}
/* istanbul ignore if */
if (validator.validateAllInSubmit) {
avalon.bind(dom, 'submit', function (e) {
e.preventDefault();
onManual();
});
}
/* istanbul ignore if */
if (typeof validator.onInit === 'function') {
//vmodels是不包括vmodel的
validator.onInit.call(dom, {
type: 'init',
target: dom,
validator: validator
});
}
},
validateAll: function validateAll(callback) {
var validator = this;
var fn = typeof callback === 'function' ? callback : validator.onValidateAll;
var promises = validator.fields.filter(function (field) {
var el = field.dom;
return el && !el.disabled && validator.dom.contains(el);
}).map(function (field) {
return valiDir.validate(field, true);
});
var uniq = {};
return Promise.all(promises).then(function (array) {
var reasons = array.concat.apply([], array);
if (validator.deduplicateInValidateAll) {
reasons = reasons.filter(function (reason) {
var el = reason.element;
var uuid = el.uniqueID || (el.uniqueID = setTimeout('1'));
if (uniq[uuid]) {
return false;
} else {
return uniq[uuid] = true;
}
});
}
fn.call(validator.dom, reasons); //这里只放置未通过验证的组件
});
},
addField: function addField(field) {
var validator = this;
var node = field.dom;
/* istanbul ignore if */
if (validator.validateInKeyup && !field.isChanged && !field.debounceTime) {
avalon.bind(node, 'keyup', function (e) {
validator.validate(field, 0, e);
});
}
/* istanbul ignore if */
if (validator.validateInBlur) {
avalon.bind(node, 'blur', function (e) {
validator.validate(field, 0, e);
});
}
/* istanbul ignore if */
if (validator.resetInFocus) {
avalon.bind(node, 'focus', function (e) {
validator.onReset.call(node, e, field);
});
}
},
validate: function validate(field, isValidateAll, event) {
var promises = [];
var value = field.value;
var elem = field.dom;
/* istanbul ignore if */
if (typeof Promise !== 'function') {
//avalon-promise不支持phantomjs
avalon.wain('please npm install es6-promise or bluebird');
}
/* istanbul ignore if */
if (elem.disabled) return;
var rules = field.rules;
var ngs = [],
isOk = true;
if (!(rules.norequired && value === '')) {
for (var ruleName in rules) {
var ruleValue = rules[ruleName];
if (ruleValue === false) continue;
var hook = avalon.validators[ruleName];
var resolve;
promises.push(new Promise(function (a, b) {
resolve = a;
}));
var next = function next(a) {
var reason = {
element: elem,
data: field.data,
message: elem.getAttribute('data-' + ruleName + '-message') || elem.getAttribute('data-message') || hook.message,
validateRule: ruleName,
getMessage: getMessage
};
if (a) {
resolve(true);
} else {
isOk = false;
ngs.push(reason);
resolve(false);
}
};
field.data = {};
field.data[ruleName] = ruleValue;
hook.get(value, field, next);
}
}
//如果promises不为空,说明经过验证拦截器
return Promise.all(promises).then(function (array) {
if (!isValidateAll) {
var validator = field.validator;
if (isOk) {
validator.onSuccess.call(elem, [{
data: field.data,
element: elem
}], event);
} else {
validator.onError.call(elem, ngs, event);
}
validator.onComplete.call(elem, ngs, event);
}
return ngs;
});
}
});
var rformat = /\\?{{([^{}]+)\}}/gm;
function getMessage() {
var data = this.data || {};
return this.message.replace(rformat, function (_, name) {
return data[name] == null ? '' : data[name];
});
}
valiDir.defaults = {
validate: valiDir.validate,
addField: valiDir.addField, //供内部使用,收集此元素底下的所有ms-duplex的域对象
onError: avalon.noop,
onSuccess: avalon.noop,
onComplete: avalon.noop,
onManual: avalon.noop,
onReset: avalon.noop,
onValidateAll: avalon.noop,
validateInBlur: true, //@config {Boolean} true,在blur事件中进行验证,触发onSuccess, onError, onComplete回调
validateInKeyup: true, //@config {Boolean} true,在keyup事件中进行验证,触发onSuccess, onError, onComplete回调
validateAllInSubmit: true, //@config {Boolean} true,在submit事件中执行onValidateAll回调
resetInFocus: true, //@config {Boolean} true,在focus事件中执行onReset回调,
deduplicateInValidateAll: false //@config {Boolean} false,在validateAll回调中对reason数组根据元素节点进行去重
};
/**
* 一个directive装饰器
* @returns {directive}
*/
// DirectiveDecorator(scope, binding, vdom, this)
// Decorator(vm, options, callback)
function Directive(vm, binding, vdom, render) {
var type = binding.type;
var decorator = avalon.directives[type];
if (inBrowser) {
var dom = avalon.vdom(vdom, 'toDOM');
if (dom.nodeType === 1) {
dom.removeAttribute(binding.attrName);
}
vdom.dom = dom;
}
var callback = decorator.update ? function (value) {
if (!render.mount && /css|visible|duplex/.test(type)) {
render.callbacks.push(function () {
decorator.update.call(directive$$1, directive$$1.node, value);
});
} else {
decorator.update.call(directive$$1, directive$$1.node, value);
}
} : avalon.noop;
for (var key in decorator) {
binding[key] = decorator[key];
}
binding.node = vdom;
var directive$$1 = new Action(vm, binding, callback);
if (directive$$1.init) {
//这里可能会重写node, callback, type, name
directive$$1.init();
}
directive$$1.update();
return directive$$1;
}
var eventMap = avalon.oneObject('animationend,blur,change,input,' + 'click,dblclick,focus,keydown,keypress,keyup,mousedown,mouseenter,' + 'mouseleave,mousemove,mouseout,mouseover,mouseup,scan,scroll,submit', 'on');
function parseAttributes(dirs, tuple) {
var node = tuple[0],
uniq = {},
bindings = [];
var hasIf = false;
for (var name in dirs) {
var value = dirs[name];
var arr = name.split('-');
// ms-click
if (name in node.props) {
var attrName = name;
} else {
attrName = ':' + name.slice(3);
}
if (eventMap[arr[1]]) {
arr.splice(1, 0, 'on');
}
//ms-on-click
if (arr[1] === 'on') {
arr[3] = parseFloat(arr[3]) || 0;
}
var type = arr[1];
if (type === 'controller' || type === 'important') continue;
if (directives[type]) {
var binding = {
type: type,
param: arr[2],
attrName: attrName,
name: arr.join('-'),
expr: value,
priority: directives[type].priority || type.charCodeAt(0) * 100
};
if (type === 'if') {
hasIf = true;
}
if (type === 'on') {
binding.priority += arr[3];
}
if (!uniq[binding.name]) {
uniq[binding.name] = value;
bindings.push(binding);
if (type === 'for') {
return [avalon.mix(binding, tuple[3])];
}
}
}
}
bindings.sort(byPriority);
if (hasIf) {
var ret = [];
for (var i = 0, el; el = bindings[i++];) {
ret.push(el);
if (el.type === 'if') {
return ret;
}
}
}
return bindings;
}
function byPriority(a, b) {
return a.priority - b.priority;
}
var rimprovePriority = /[+-\?]/;
var rinnerValue = /__value__\)$/;
function parseInterpolate(dir) {
var rlineSp = /\n\r?/g;
var str = dir.nodeValue.trim().replace(rlineSp, '');
var tokens = [];
do {
//aaa{{@bbb}}ccc
var index = str.indexOf(config.openTag);
index = index === -1 ? str.length : index;
var value = str.slice(0, index);
if (/\S/.test(value)) {
tokens.push(avalon.quote(avalon._decode(value)));
}
str = str.slice(index + config.openTag.length);
if (str) {
index = str.indexOf(config.closeTag);
var value = str.slice(0, index);
var expr = avalon.unescapeHTML(value);
if (/\|\s*\w/.test(expr)) {
//如果存在过滤器,优化干掉
var arr = addScope(expr, 'expr');
if (arr[1]) {
expr = arr[1].replace(rinnerValue, arr[0] + ')');
}
}
if (rimprovePriority) {
expr = '(' + expr + ')';
}
tokens.push(expr);
str = str.slice(index + config.closeTag.length);
}
} while (str.length);
return [{
expr: tokens.join('+'),
name: 'expr',
type: 'expr'
}];
}
function getChildren(arr) {
var count = 0;
for (var i = 0, el; el = arr[i++];) {
if (el.nodeName === '#document-fragment') {
count += getChildren(el.children);
} else {
count += 1;
}
}
return count;
}
function groupTree(parent, children) {
children && children.forEach(function (vdom) {
if (!vdom) return;
var vlength = vdom.children && getChildren(vdom.children);
if (vdom.nodeName === '#document-fragment') {
var dom = createFragment();
} else {
dom = avalon.vdom(vdom, 'toDOM');
var domlength = dom.childNodes && dom.childNodes.length;
if (domlength && vlength && domlength > vlength) {
if (!appendChildMayThrowError[dom.nodeName]) {
avalon.clearHTML(dom);
}
}
}
if (vlength) {
groupTree(dom, vdom.children);
if (vdom.nodeName === 'select') {
var values = [];
getSelectedValue(vdom, values);
lookupOption(vdom, values);
}
}
//高级版本可以尝试 querySelectorAll
try {
if (!appendChildMayThrowError[parent.nodeName]) {
parent.appendChild(dom);
}
} catch (e) {}
});
}
function dumpTree(elem) {
var firstChild;
while (firstChild = elem.firstChild) {
if (firstChild.nodeType === 1) {
dumpTree(firstChild);
}
elem.removeChild(firstChild);
}
}
function getRange(childNodes, node) {
var i = childNodes.indexOf(node) + 1;
var deep = 1,
nodes = [],
end;
nodes.start = i;
while (node = childNodes[i++]) {
nodes.push(node);
if (node.nodeName === '#comment') {
if (startWith(node.nodeValue, 'ms-for:')) {
deep++;
} else if (node.nodeValue === 'ms-for-end:') {
deep--;
if (deep === 0) {
end = node;
nodes.pop();
break;
}
}
}
}
nodes.end = end;
return nodes;
}
function startWith(long, short) {
return long.indexOf(short) === 0;
}
var appendChildMayThrowError = {
'#text': 1,
'#comment': 1,
script: 1,
style: 1,
noscript: 1
};
/**
* 生成一个渲染器,并作为它第一个遇到的ms-controller对应的VM的$render属性
* @param {String|DOM} node
* @param {ViewModel|Undefined} vm
* @param {Function|Undefined} beforeReady
* @returns {Render}
*/
avalon.scan = function (node, vm, beforeReady) {
return new Render(node, vm, beforeReady || avalon.noop);
};
/**
* avalon.scan 的内部实现
*/
function Render(node, vm, beforeReady) {
this.root = node; //如果传入的字符串,确保只有一个标签作为根节点
this.vm = vm;
this.beforeReady = beforeReady;
this.bindings = []; //收集待加工的绑定属性
this.callbacks = [];
this.directives = [];
this.init();
}
Render.prototype = {
/**
* 开始扫描指定区域
* 收集绑定属性
* 生成指令并建立与VM的关联
*/
init: function init() {
var vnodes;
if (this.root && this.root.nodeType > 0) {
vnodes = fromDOM(this.root); //转换虚拟DOM
//将扫描区域的每一个节点与其父节点分离,更少指令对DOM操作时,对首屏输出造成的频繁重绘
dumpTree(this.root);
} else if (typeof this.root === 'string') {
vnodes = fromString(this.root); //转换虚拟DOM
} else {
return avalon.warn('avalon.scan first argument must element or HTML string');
}
this.root = vnodes[0];
this.vnodes = vnodes;
this.scanChildren(vnodes, this.vm, true);
},
scanChildren: function scanChildren(children, scope, isRoot) {
for (var i = 0; i < children.length; i++) {
var vdom = children[i];
switch (vdom.nodeName) {
case '#text':
scope && this.scanText(vdom, scope);
break;
case '#comment':
scope && this.scanComment(vdom, scope, children);
break;
case '#document-fragment':
this.scanChildren(vdom.children, scope, false);
break;
default:
this.scanTag(vdom, scope, children, false);
break;
}
}
if (isRoot) {
this.complete();
}
},
/**
* 从文本节点获取指令
* @param {type} vdom
* @param {type} scope
* @returns {undefined}
*/
scanText: function scanText(vdom, scope) {
if (config.rexpr.test(vdom.nodeValue)) {
this.bindings.push([vdom, scope, {
nodeValue: vdom.nodeValue
}]);
}
},
/**
* 从注释节点获取指令
* @param {type} vdom
* @param {type} scope
* @param {type} parentChildren
* @returns {undefined}
*/
scanComment: function scanComment(vdom, scope, parentChildren) {
if (startWith(vdom.nodeValue, 'ms-for:')) {
this.getForBinding(vdom, scope, parentChildren);
}
},
/**
* 从元素节点的nodeName与属性中获取指令
* @param {type} vdom
* @param {type} scope
* @param {type} parentChildren
* @param {type} isRoot 用于执行complete方法
* @returns {undefined}
*/
scanTag: function scanTag(vdom, scope, parentChildren, isRoot) {
var dirs = {},
attrs = vdom.props,
hasDir,
hasFor;
for (var attr in attrs) {
var value = attrs[attr];
var oldName = attr;
if (attr.charAt(0) === ':') {
attr = 'ms-' + attr.slice(1);
}
if (startWith(attr, 'ms-')) {
dirs[attr] = value;
var type = attr.match(/\w+/g)[1];
type = eventMap[type] || type;
if (!directives[type]) {
avalon.warn(attr + ' has not registered!');
}
hasDir = true;
}
if (attr === 'ms-for') {
hasFor = value;
delete attrs[oldName];
}
}
var $id = dirs['ms-important'] || dirs['ms-controller'];
if ($id) {
/**
* 后端渲染
* serverTemplates后端给avalon添加的对象,里面都是模板,
* 将原来后端渲染好的区域再还原成原始样子,再被扫描
*/
var templateCaches = avalon.serverTemplates;
var temp = templateCaches && templateCaches[$id];
if (temp) {
avalon.log('前端再次渲染后端传过来的模板');
var node = fromString(tmpl)[0];
for (var i in node) {
vdom[i] = node[i];
}
delete templateCaches[$id];
this.scanTag(vdom, scope, parentChildren, isRoot);
return;
}
//推算出指令类型
var type = dirs['ms-important'] === $id ? 'important' : 'controller';
//推算出用户定义时属性名,是使用ms-属性还是:属性
var attrName = 'ms-' + type in attrs ? 'ms-' + type : ':' + type;
if (inBrowser) {
delete attrs[attrName];
}
var dir = directives[type];
scope = dir.getScope.call(this, $id, scope);
if (!scope) {
return;
} else {
var clazz = attrs['class'];
if (clazz) {
attrs['class'] = (' ' + clazz + ' ').replace(' ms-controller ', '').trim();
}
}
var render = this;
scope.$render = render;
this.callbacks.push(function () {
//用于删除ms-controller
dir.update.call(render, vdom, attrName, $id);
});
}
if (hasFor) {
if (vdom.dom) {
vdom.dom.removeAttribute(oldName);
}
return this.getForBindingByElement(vdom, scope, parentChildren, hasFor);
}
if (/^ms\-/.test(vdom.nodeName)) {
attrs.is = vdom.nodeName;
}
if (attrs['is']) {
if (!dirs['ms-widget']) {
dirs['ms-widget'] = '{}';
}
hasDir = true;
}
if (hasDir) {
this.bindings.push([vdom, scope, dirs]);
}
var children = vdom.children;
//如果存在子节点,并且不是容器元素(script, stype, textarea, xmp...)
if (!orphanTag[vdom.nodeName] && children && children.length && !delayCompileNodes(dirs)) {
this.scanChildren(children, scope, false);
}
},
/**
* 将绑定属性转换为指令
* 执行各种回调与优化指令
* @returns {undefined}
*/
complete: function complete() {
this.yieldDirectives();
this.beforeReady();
if (inBrowser) {
var root$$1 = this.root;
if (inBrowser) {
var rootDom = avalon.vdom(root$$1, 'toDOM');
groupTree(rootDom, root$$1.children);
}
}
this.mount = true;
var fn;
while (fn = this.callbacks.pop()) {
fn();
}
this.optimizeDirectives();
},
/**
* 将收集到的绑定属性进行深加工,最后转换指令
* @returns {Array<tuple>}
*/
yieldDirectives: function yieldDirectives() {
var tuple;
while (tuple = this.bindings.shift()) {
var vdom = tuple[0],
scope = tuple[1],
dirs = tuple[2],
bindings = [];
if ('nodeValue' in dirs) {
bindings = parseInterpolate(dirs);
} else if (!('ms-skip' in dirs)) {
bindings = parseAttributes(dirs, tuple);
}
for (var i = 0, binding; binding = bindings[i++];) {
var dir = directives[binding.type];
if (!inBrowser && /on|duplex|active|hover/.test(binding.type)) {
continue;
}
if (dir.beforeInit) {
dir.beforeInit.call(binding);
}
var directive$$1 = new Directive(scope, binding, vdom, this);
this.directives.push(directive$$1);
}
}
},
/**
* 修改指令的update与callback方法,让它们以后执行时更加高效
* @returns {undefined}
*/
optimizeDirectives: function optimizeDirectives() {
for (var i = 0, el; el = this.directives[i++];) {
el.callback = directives[el.type].update;
el.update = newUpdate;
el._isScheduled = false;
}
},
update: function update() {
for (var i = 0, el; el = this.directives[i++];) {
el.update();
}
},
/**
* 销毁所有指令
* @returns {undefined}
*/
dispose: function dispose() {
var list = this.directives || [];
for (var i = 0, el; el = list[i++];) {
el.dispose();
}
//防止其他地方的this.innerRender && this.innerRender.dispose报错
for (var _i5 in this) {
if (_i5 !== 'dispose') delete this[_i5];
}
},
/**
* 将循环区域转换为for指令
* @param {type} begin 注释节点
* @param {type} scope
* @param {type} parentChildren
* @param {type} userCb 循环结束回调
* @returns {undefined}
*/
getForBinding: function getForBinding(begin, scope, parentChildren, userCb) {
var expr = begin.nodeValue.replace('ms-for:', '').trim();
begin.nodeValue = 'ms-for:' + expr;
var nodes = getRange(parentChildren, begin);
var end = nodes.end;
var fragment = avalon.vdom(nodes, 'toHTML');
parentChildren.splice(nodes.start, nodes.length);
begin.props = {};
this.bindings.push([begin, scope, {
'ms-for': expr
}, {
begin: begin,
end: end,
expr: expr,
userCb: userCb,
fragment: fragment,
parentChildren: parentChildren
}]);
},
/**
* 在带ms-for元素节点旁添加两个注释节点,组成循环区域
* @param {type} vdom
* @param {type} scope
* @param {type} parentChildren
* @param {type} expr
* @returns {undefined}
*/
getForBindingByElement: function getForBindingByElement(vdom, scope, parentChildren, expr) {
var index = parentChildren.indexOf(vdom); //原来带ms-for的元素节点
var props = vdom.props;
var begin = {
nodeName: '#comment',
nodeValue: 'ms-for:' + expr
};
if (props.slot) {
begin.slot = props.slot;
delete props.slot;
}
var end = {
nodeName: '#comment',
nodeValue: 'ms-for-end:'
};
parentChildren.splice(index, 1, begin, vdom, end);
this.getForBinding(begin, scope, parentChildren, props['data-for-rendered']);
}
};
var viewID;
function newUpdate() {
var oldVal = this.beforeUpdate();
var newVal = this.value = this.get();
if (this.callback && this.diff(newVal, oldVal)) {
this.callback(this.node, this.value);
var vm = this.vm;
var $render = vm.$render;
var list = vm.$events['onViewChange'];
/* istanbul ignore if */
if (list && $render && $render.root && !avalon.viewChanging) {
if (viewID) {
clearTimeout(viewID);
viewID = null;
}
viewID = setTimeout(function () {
list.forEach(function (el) {
el.callback.call(vm, {
type: 'viewchange',
target: $render.root,
vmodel: vm
});
});
});
}
}
this._isScheduled = false;
}
var events = 'onInit,onReady,onViewChange,onDispose,onEnter,onLeave';
var componentEvents = avalon.oneObject(events);
function toObject(value) {
var value = platform.toJson(value);
if (Array.isArray(value)) {
var v = {};
value.forEach(function (el) {
el && avalon.shadowCopy(v, el);
});
return v;
}
return value;
}
var componentQueue = [];
avalon.directive('widget', {
delay: true,
priority: 4,
deep: true,
init: function init() {
//cached属性必须定义在组件容器里面,不是template中
var vdom = this.node;
this.cacheVm = !!vdom.props.cached;
if (vdom.dom && vdom.nodeName === '#comment') {
var comment = vdom.dom;
}
var oldValue = this.getValue();
var value = toObject(oldValue);
//外部VM与内部VM
// ===创建组件的VM==BEGIN===
var is = vdom.props.is || value.is;
this.is = is;
var component = avalon.components[is];
//外部传入的总大于内部
if (!('fragment' in this)) {
if (!vdom.isVoidTag) {
//提取组件容器内部的东西作为模板
var text = vdom.children[0];
if (text && text.nodeValue) {
this.fragment = text.nodeValue;
} else {
this.fragment = avalon.vdom(vdom.children, 'toHTML');
}
} else {
this.fragment = false;
}
}
//如果组件还没有注册,那么将原元素变成一个占位用的注释节点
if (!component) {
this.readyState = 0;
vdom.nodeName = '#comment';
vdom.nodeValue = 'unresolved component placeholder';
delete vdom.dom;
avalon.Array.ensure(componentQueue, this);
return;
}
this.readyState = 1;
//如果是非空元素,比如说xmp, ms-*, template
var id = value.id || value.$id;
var hasCache = avalon.vmodels[id];
var fromCache = false;
if (hasCache) {
comVm = hasCache;
this.comVm = comVm;
replaceRoot(this, comVm.$render);
fromCache = true;
} else {
var comVm = createComponentVm(component, value, is);
fireComponentHook(comVm, vdom, 'Init');
this.comVm = comVm;
// ===创建组件的VM==END===
var innerRender = avalon.scan(component.template, comVm);
comVm.$render = innerRender;
replaceRoot(this, innerRender);
var nodesWithSlot = [];
var directives$$1 = [];
if (this.fragment || component.soleSlot) {
var curVM = this.fragment ? this.vm : comVm;
var curText = this.fragment || '{{##' + component.soleSlot + '}}';
var childBoss = avalon.scan('<div>' + curText + '</div>', curVM, function () {
nodesWithSlot = this.root.children;
});
directives$$1 = childBoss.directives;
this.childBoss = childBoss;
for (var i in childBoss) {
delete childBoss[i];
}
}
Array.prototype.push.apply(innerRender.directives, directives$$1);
var arraySlot = [],
objectSlot = {};
//从用户写的元素内部 收集要移动到 新创建的组件内部的元素
if (component.soleSlot) {
arraySlot = nodesWithSlot;
} else {
nodesWithSlot.forEach(function (el, i) {
//要求带slot属性
if (el.slot) {
var nodes = getRange(nodesWithSlot, el);
nodes.push(nodes.end);
nodes.unshift(el);
objectSlot[el.slot] = nodes;
} else if (el.props) {
var name = el.props.slot;
if (name) {
delete el.props.slot;
if (Array.isArray(objectSlot[name])) {
objectSlot[name].push(el);
} else {
objectSlot[name] = [el];
}
}
}
});
}
//将原来元素的所有孩子,全部移动新的元素的第一个slot的位置上
if (component.soleSlot) {
insertArraySlot(innerRender.vnodes, arraySlot);
} else {
insertObjectSlot(innerRender.vnodes, objectSlot);
}
}
if (comment) {
var dom = avalon.vdom(vdom, 'toDOM');
comment.parentNode.replaceChild(dom, comment);
comVm.$element = innerRender.root.dom = dom;
delete this.reInit;
}
//处理DOM节点
dumpTree(vdom.dom);
comVm.$element = vdom.dom;
groupTree(vdom.dom, vdom.children);
if (fromCache) {
fireComponentHook(comVm, vdom, 'Enter');
} else {
fireComponentHook(comVm, vdom, 'Ready');
}
},
diff: function diff(newVal, oldVal) {
if (cssDiff.call(this, newVal, oldVal)) {
return true;
}
},
update: function update(vdom, value) {
//this.oldValue = value //★★防止递归
switch (this.readyState) {
case 0:
if (this.reInit) {
this.init();
}
break;
case 1:
this.readyState++;
break;
default:
this.readyState++;
var comVm = this.comVm;
avalon.viewChanging = true;
avalon.transaction(function () {
for (var i in value) {
if (comVm.hasOwnProperty(i)) {
if (Array.isArray(value[i])) {
comVm[i] = value[i].concat();
} else {
comVm[i] = value[i];
}
}
}
});
//要保证要先触发孩子的ViewChange 然后再到它自己的ViewChange
fireComponentHook(comVm, vdom, 'ViewChange');
delete avalon.viewChanging;
break;
}
this.value = avalon.mix(true, {}, value);
},
beforeDispose: function beforeDispose() {
var comVm = this.comVm;
if (!this.cacheVm) {
fireComponentHook(comVm, this.node, 'Dispose');
comVm.$hashcode = false;
delete avalon.vmodels[comVm.$id];
this.innerRender && this.innerRender.dispose();
} else {
fireComponentHook(comVm, this.node, 'Leave');
}
}
});
function replaceRoot(instance, innerRender) {
instance.innerRender = innerRender;
var root$$1 = innerRender.root;
var vdom = instance.node;
var slot = vdom.props.slot;
for (var i in root$$1) {
vdom[i] = root$$1[i];
}
if (vdom.props && slot) {
vdom.props.slot = slot;
}
innerRender.root = vdom;
innerRender.vnodes[0] = vdom;
}
function fireComponentHook(vm, vdom, name) {
var list = vm.$events['on' + name];
if (list) {
list.forEach(function (el) {
setTimeout(function () {
el.callback.call(vm, {
type: name.toLowerCase(),
target: vdom.dom,
vmodel: vm
});
}, 0);
});
}
}
function createComponentVm(component, value, is) {
var hooks = [];
var defaults = component.defaults;
collectHooks(defaults, hooks);
collectHooks(value, hooks);
var obj = {};
for (var i in defaults) {
var val = value[i];
if (val == null) {
obj[i] = defaults[i];
} else {
obj[i] = val;
}
}
obj.$id = value.id || value.$id || avalon.makeHashCode(is);
delete obj.id;
var def = avalon.mix(true, {}, obj);
var vm = avalon.define(def);
hooks.forEach(function (el) {
vm.$watch(el.type, el.cb);
});
return vm;
}
function collectHooks(a, list) {
for (var i in a) {
if (componentEvents[i]) {
if (typeof a[i] === 'function' && i.indexOf('on') === 0) {
list.unshift({
type: i,
cb: a[i]
});
}
//delete a[i] 这里不能删除,会导致再次切换时没有onReady
}
}
}
function resetParentChildren(nodes, arr) {
var dir = arr && arr[0] && arr[0].forDir;
if (dir) {
dir.parentChildren = nodes;
}
}
function insertArraySlot(nodes, arr) {
for (var i = 0, el; el = nodes[i]; i++) {
if (el.nodeName === 'slot') {
resetParentChildren(nodes, arr);
nodes.splice.apply(nodes, [i, 1].concat(arr));
break;
} else if (el.children) {
insertArraySlot(el.children, arr);
}
}
}
function insertObjectSlot(nodes, obj) {
for (var i = 0, el; el = nodes[i]; i++) {
if (el.nodeName === 'slot') {
var name = el.props.name;
resetParentChildren(nodes, obj[name]);
nodes.splice.apply(nodes, [i, 1].concat(obj[name]));
continue;
} else if (el.children) {
insertObjectSlot(el.children, obj);
}
}
}
avalon.components = {};
avalon.component = function (name, component) {
/**
* template: string
* defaults: object
* soleSlot: string
*/
avalon.components[name] = component;
for (var el, i = 0; el = componentQueue[i]; i++) {
if (el.is === name) {
componentQueue.splice(i, 1);
el.reInit = true;
delete el.value;
el.update();
i--;
}
}
};
return avalon;
});
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 2 */
/***/ function(module, exports) {
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
/*
*
* version 1.0
* built in 2015.11.19
*/
var mmHistory = __webpack_require__(6)
var storage = __webpack_require__(7)
function Router() {
this.rules = []
}
var placeholder = /([:*])(\w+)|\{(\w+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g
Router.prototype = storage
avalon.mix(storage, {
error: function (callback) {
this.errorback = callback
},
_pathToRegExp: function (pattern, opts) {
var keys = opts.keys = [],
// segments = opts.segments = [],
compiled = '^', last = 0, m, name, regexp, segment;
while ((m = placeholder.exec(pattern))) {
name = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null
regexp = m[4] || (m[1] == '*' ? '.*' : 'string')
segment = pattern.substring(last, m.index);
var type = this.$types[regexp]
var key = {
name: name
}
if (type) {
regexp = type.pattern
key.decode = type.decode
}
keys.push(key)
compiled += quoteRegExp(segment, regexp, false)
// segments.push(segment)
last = placeholder.lastIndex
}
segment = pattern.substring(last);
compiled += quoteRegExp(segment) + (opts.strict ? opts.last : "\/?") + '$';
var sensitive = typeof opts.caseInsensitive === "boolean" ? opts.caseInsensitive : true
// segments.push(segment);
opts.regexp = new RegExp(compiled, sensitive ? 'i' : undefined);
return opts
},
//添加一个路由规则
add: function (path, callback, opts) {
var array = this.rules
if (path.charAt(0) !== "/") {
avalon.error("avalon.router.add的第一个参数必须以/开头")
}
opts = opts || {}
opts.callback = callback
if (path.length > 2 && path.charAt(path.length - 1) === "/") {
path = path.slice(0, -1)
opts.last = "/"
}
avalon.Array.ensure(array, this._pathToRegExp(path, opts))
},
//判定当前URL与已有状态对象的路由规则是否符合
route: function (path, query) {
path = path.trim()
var rules = this.rules
for (var i = 0, el; el = rules[i++]; ) {
var args = path.match(el.regexp)
if (args) {
el.query = query || {}
el.path = path
el.params = {}
var keys = el.keys
args.shift()
if (keys.length) {
this._parseArgs(args, el)
}
return el.callback.apply(el, args)
}
}
if (this.errorback) {
this.errorback()
}
},
_parseArgs: function (match, stateObj) {
var keys = stateObj.keys
for (var j = 0, jn = keys.length; j < jn; j++) {
var key = keys[j]
var value = match[j] || ''
if (typeof key.decode === 'function') {//在这里尝试转换参数的类型
var val = key.decode(value)
} else {
try {
val = JSON.parse(value)
} catch (e) {
val = value
}
}
match[j] = stateObj.params[key.name] = val
}
},
/*
* @interface avalon.router.navigate 设置历史(改变URL)
* @param hash 访问的url hash
*/
navigate: function (hash, mode) {
var parsed = parseQuery(hash)
var newHash = this.route(parsed.path, parsed.query)
if(isLegalPath(newHash)){
hash = newHash
}
//保存到本地储存或cookie
avalon.router.setLastPath(hash)
// 模式0, 不改变URL, 不产生历史实体, 执行回调
// 模式1, 改变URL, 不产生历史实体, 执行回调
// 模式2, 改变URL, 产生历史实体, 执行回调
if (mode === 1) {
avalon.history.setHash(hash, true)
} else if (mode === 2) {
avalon.history.setHash(hash)
}
return hash
},
/*
* @interface avalon.router.when 配置重定向规则
* @param path 被重定向的表达式,可以是字符串或者数组
* @param redirect 重定向的表示式或者url
*/
when: function (path, redirect) {
var me = this,
path = path instanceof Array ? path : [path]
avalon.each(path, function (index, p) {
me.add(p, function () {
var info = me.urlFormate(redirect, this.params, this.query)
me.navigate(info.path + info.query)
})
})
return this
},
urlFormate: function (url, params, query) {
var query = query ? queryToString(query) : "",
hash = url.replace(placeholder, function (mat) {
var key = mat.replace(/[\{\}]/g, '').split(":")
key = key[0] ? key[0] : key[1]
return params[key] !== undefined ? params[key] : ''
}).replace(/^\//g, '')
return {
path: hash,
query: query
}
},
/* *
`'/hello/'` - 匹配'/hello/'或'/hello'
`'/user/:id'` - 匹配 '/user/bob' 或 '/user/1234!!!' 或 '/user/' 但不匹配 '/user' 与 '/user/bob/details'
`'/user/{id}'` - 同上
`'/user/{id:[^/]*}'` - 同上
`'/user/{id:[0-9a-fA-F]{1,8}}'` - 要求ID匹配/[0-9a-fA-F]{1,8}/这个子正则
`'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the
path into the parameter 'path'.
`'/files/*path'` - ditto.
*/
// avalon.router.get("/ddd/:dddID/",callback)
// avalon.router.get("/ddd/{dddID}/",callback)
// avalon.router.get("/ddd/{dddID:[0-9]{4}}/",callback)
// avalon.router.get("/ddd/{dddID:int}/",callback)
// 我们甚至可以在这里添加新的类型,avalon.router.$type.d4 = { pattern: '[0-9]{4}', decode: Number}
// avalon.router.get("/ddd/{dddID:d4}/",callback)
$types: {
date: {
pattern: "[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])",
decode: function (val) {
return new Date(val.replace(/\-/g, "/"))
}
},
string: {
pattern: "[^\\/]*",
decode: function (val) {
return val;
}
},
bool: {
decode: function (val) {
return parseInt(val, 10) === 0 ? false : true;
},
pattern: "0|1"
},
'int': {
decode: function (val) {
return parseInt(val, 10);
},
pattern: "\\d+"
}
}
})
module.exports = avalon.router = new Router
function parseQuery(url) {
var array = url.split("?"), query = {}, path = array[0], querystring = array[1]
if (querystring) {
var seg = querystring.split("&"),
len = seg.length, i = 0, s;
for (; i < len; i++) {
if (!seg[i]) {
continue
}
s = seg[i].split("=")
query[decodeURIComponent(s[0])] = decodeURIComponent(s[1])
}
}
return {
path: path,
query: query
}
}
function isLegalPath(path){
if(path === '/')
return true
if(typeof path === 'string' && path.length > 1 && path.charAt(0) === '/'){
return true
}
}
function queryToString(obj) {
if (typeof obj === 'string')
return obj
var str = []
for (var i in obj) {
if (i === "query")
continue
str.push(i + '=' + encodeURIComponent(obj[i]))
}
return str.length ? '?' + str.join("&") : ''
}
function quoteRegExp(string, pattern, isOptional) {
var result = string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&");
if (!pattern)
return result;
var flag = isOptional ? '?' : '';
return result + flag + '(' + pattern + ')' + flag;
}
/***/ },
/* 1 */,
/* 2 */,
/* 3 */,
/* 4 */,
/* 5 */,
/* 6 */
/***/ function(module, exports) {
/*!
* mmHistory
* 用于监听地址栏的变化
* https://github.com/flatiron/director/blob/master/lib/director/browser.js
* https://github.com/visionmedia/page.js/blob/master/page.js
*/
var location = document.location
var oldIE = avalon.msie <= 7
var supportPushState = !!(window.history.pushState)
var supportHashChange = !!("onhashchange" in window && (!window.VBArray || !oldIE))
var defaults = {
root: "/",
html5: false,
hashPrefix: "!",
iframeID: null, //IE6-7,如果有在页面写死了一个iframe,这样似乎刷新的时候不会丢掉之前的历史
interval: 50, //IE6-7,使用轮询,这是其时间时隔,
autoScroll: false
}
var mmHistory = {
hash: getHash(location.href),
check: function () {
var h = getHash(location.href)
if (h !== this.hash) {
this.hash = h
this.onHashChanged()
}
},
fire: function () {
switch (this.mode) {
case 'popstate':
window.onpopstate && window.onpopstate()
break
case 'hashchange':
window.onhashchange && window.onhashchange()
break
default:
this.onHashChanged()
break
}
},
start: function (options) {
if (this.started)
throw new Error('avalon.history has already been started')
this.started = true
//监听模式
if (typeof options === 'boolean') {
options = {
html5: options
}
}
options = avalon.mix({}, defaults, options || {})
if (options.fireAnchor) {
options.autoScroll = true
}
var rootPath = options.root
if (!/^\//.test(rootPath)) {
avalon.error('root配置项必须以/字符开始, 以非/字符结束')
}
if (rootPath.length > 1) {
options.root = rootPath.replace(/\/$/, '')
}
var html5Mode = options.html5
this.options = options
this.mode = html5Mode ? "popstate" : "hashchange"
if (!supportPushState) {
if (html5Mode) {
avalon.warn("浏览器不支持HTML5 pushState,平稳退化到onhashchange!")
}
this.mode = "hashchange"
}
if (!supportHashChange) {
this.mode = "iframepoll"
}
avalon.log('avalon run mmHistory in the ', this.mode, 'mode')
//IE6不支持maxHeight, IE7支持XMLHttpRequest, IE8支持window.Element,querySelector,
//IE9支持window.Node, window.HTMLElement, IE10不支持条件注释
// 支持popstate 就监听popstate
// 支持hashchange 就监听hashchange(IE8,IE9,FF3)
// 否则的话只能每隔一段时间进行检测了(IE6, IE7)
switch (this.mode) {
case "popstate" :
// At least for now HTML5 history is available for 'modern' browsers only
// There is an old bug in Chrome that causes onpopstate to fire even
// upon initial page load. Since the handler is run manually in init(),
// this would cause Chrome to run it twise. Currently the only
// workaround seems to be to set the handler after the initial page load
// http://code.google.com/p/chromium/issues/detail?id=63040
setTimeout(function () {
window.onpopstate = mmHistory.onHashChanged
}, 500)
break
case "hashchange":
window.onhashchange = mmHistory.onHashChanged
break
case "iframepoll":
avalon.ready(function () {
var iframe = document.createElement('iframe')
iframe.id = options.iframeID
iframe.style.display = 'none'
document.body.appendChild(iframe)
mmHistory.iframe = iframe
mmHistory.writeFrame('')
if (avalon.msie) {
function onPropertyChange() {
if (event.propertyName === 'location') {
mmHistory.check()
}
}
document.attachEvent('onpropertychange', onPropertyChange)
mmHistory.onPropertyChange = onPropertyChange
}
mmHistory.intervalID = window.setInterval(function () {
mmHistory.check()
}, options.interval)
})
break
}
//页面加载时触发onHashChanged
this.onHashChanged()
},
stop: function () {
switch (this.mode) {
case "popstate" :
window.onpopstate = avalon.noop
break
case "hashchange":
window.onhashchange = avalon.noop
break
case "iframepoll":
if (this.iframe) {
document.body.removeChild(this.iframe)
this.iframe = null
}
if (this.onPropertyChange) {
document.detachEvent('onpropertychange', this.onPropertyChange)
}
clearInterval(this.intervalID)
break
}
this.started = false
},
setHash: function (s, replace) {
// Mozilla always adds an entry to the history
switch (this.mode) {
case 'iframepoll':
if (replace) {
var iframe = this.iframe
if (iframe) {
//contentWindow 兼容各个浏览器,可取得子窗口的 window 对象。
//contentDocument Firefox 支持,> ie8 的ie支持。可取得子窗口的 document 对象。
iframe.contentWindow._hash = s
}
} else {
this.writeFrame(s)
}
break
case 'popstate':
//http://stackoverflow.com/questions/9235304/how-to-replace-the-location-hash-and-only-keep-the-last-history-entry
var path = (this.options.root + '/' + s).replace(/\/+/g, '/')
if (replace) {
window.history.replaceState({}, document.title, path)
} else {
window.history.pushState({}, document.title, path)
}
// Fire an onpopstate event manually since pushing does not obviously
// trigger the pop event.
this.fire()
break
default:
var newHash = this.options.hashPrefix + s
if (replace && location.hash !== newHash) {
history.back()
}
location.hash = newHash
break
}
return this
},
writeFrame: function (s) {
// IE support...
var f = mmHistory.iframe
var d = f.contentDocument || f.contentWindow.document
d.open()
d.write("<script>_hash = '" + s + "'; onload = parent.avalon.history.syncHash;<script>")
d.close()
},
syncHash: function () {
// IE support...
var s = this._hash
if (s !== getHash(location.href)) {
location.hash = s
}
return this
},
getPath: function () {
var path = location.pathname
var path = path.split(this.options.root)[1]
if (path.charAt(0) !== '/') {
path = '/' + path
}
return path
},
onHashChanged: function (hash, onClick) {
if (!onClick) {
hash = mmHistory.mode === 'popstate' ? mmHistory.getPath() :
location.href.replace(/.*#!?/, '')
//console.log(hash, oldHash, 'ddd')
}
hash = decodeURIComponent(hash)
hash = hash.charAt(0) === '/' ? hash : '/' + hash
if (hash !== mmHistory.hash) {
mmHistory.hash = hash
if (avalon.router) {
hash = avalon.router.navigate(hash, 0)
}
if (onClick) {
mmHistory.setHash(hash)
}
if (onClick && mmHistory.options.autoScroll) {
autoScroll(hash.slice(1))
}
}
}
}
function getHash(path) {
// IE6直接用location.hash取hash,可能会取少一部分内容
// 比如 http://www.cnblogs.com/rubylouvre#stream/xxxxx?lang=zh_c
// ie6 => location.hash = #stream/xxxxx
// 其他浏览器 => location.hash = #stream/xxxxx?lang=zh_c
// firefox 会自作多情对hash进行decodeURIComponent
// 又比如 http://www.cnblogs.com/rubylouvre/#!/home/q={%22thedate%22:%2220121010~20121010%22}
// firefox 15 => #!/home/q={"thedate":"20121010~20121010"}
// 其他浏览器 => #!/home/q={%22thedate%22:%2220121010~20121010%22}
var index = path.indexOf("#")
if (index === -1) {
return ''
}
return decodeURI(path.slice(index))
}
function which(e) {
return null === e.which ? e.button : e.which
}
function sameOrigin(href) {
var origin = location.protocol + '//' + location.hostname
if (location.port)
origin += ':' + location.port
return (href && (0 === href.indexOf(origin)))
}
//https://github.com/asual/jquery-address/blob/master/src/jquery.address.js
//劫持页面上所有点击事件,如果事件源来自链接或其内部,
//并且它不会跳出本页,并且以"#/"或"#!/"开头,那么触发updateLocation方法
//
avalon.bind(document, "click", function (e) {
//https://github.com/angular/angular.js/blob/master/src/ng/location.js
//下面十种情况将阻止进入路由系列
//1. 路由器没有启动
if (!mmHistory.started) {
return
}
//2. 不是左键点击或使用组合键
if (e.ctrlKey || e.metaKey || e.shiftKey || e.which === 2 || e.button === 2) {
return
}
//3. 此事件已经被阻止
if (e.returnValue === false) {
return
}
//4. 目标元素不A标签,或不在A标签之内
var el = e.path ? e.path[0] : e.target
while (el.nodeName !== "A") {
el = el.parentNode
if (!el || el.tagName === "BODY") {
return
}
}
//5. 没有定义href属性或在hash模式下,只有一个#
//IE6/7直接用getAttribute返回完整路径
var href = el.getAttribute('href', 2) || el.getAttribute("xlink:href") || ''
if (href.slice(0, 2) !== '#!') {
return
}
//6. 目标链接是用于下载资源或指向外部
if (el.hasAttribute('download') || el.getAttribute('rel') === 'external')
return
//7. 只是邮箱地址
if (href.indexOf('mailto:') > -1) {
return
}
//8. 目标链接要新开窗口
if (el.target && el.target !== '_self') {
return
}
e.preventDefault()
console.log(href.replace('#!', ''))
mmHistory.onHashChanged(href.replace('#!', ''), true)
})
//得到页面第一个符合条件的A标签
function getFirstAnchor(name) {
var list = document.getElementsByTagName('A')
for (var i = 0, el; el = list[i++]; ) {
if (el.name === name) {
return el
}
}
}
function getOffset(elem) {
var position = avalon(elem).css('position'), offset
if (position !== 'fixed') {
offset = 0
} else {
offset = elem.getBoundingClientRect().bottom
}
return offset
}
function autoScroll(hash) {
//取得页面拥有相同ID的元素
var elem = document.getElementById(hash)
if (!elem) {
//取得页面拥有相同name的A元素
elem = getFirstAnchor(hash)
}
if (elem) {
elem.scrollIntoView()
var offset = getOffset(elem)
if (offset) {
var elemTop = elem.getBoundingClientRect().top
window.scrollBy(0, elemTop - offset.top)
}
} else {
window.scrollTo(0, 0)
}
}
function isHasHash() {
return !(location.hash === '' || location.hash === '#')
}
module.exports = avalon.history = mmHistory
/***/ },
/* 7 */
/***/ function(module, exports) {
function supportLocalStorage() {
try {
localStorage.setItem("avalon", 1)
localStorage.removeItem("avalon")
return true
} catch (e) {
return false
}
}
function escapeCookie(value) {
return String(value).replace(/[,;"\\=\s%]/g, function (character) {
return encodeURIComponent(character)
});
}
var ret = {}
if (supportLocalStorage()) {
ret.getLastPath = function () {
return localStorage.getItem('msLastPath')
}
var cookieID
ret.setLastPath = function (path) {
if (cookieID) {
clearTimeout(cookieID)
cookieID = null
}
localStorage.setItem("msLastPath", path)
cookieID = setTimeout(function () {
localStorage.removItem("msLastPath")
}, 1000 * 60 * 60 * 24)
}
} else {
ret.getLastPath = function () {
return getCookie.getItem('msLastPath')
}
ret.setLastPath = function (path) {
setCookie('msLastPath', path)
}
function setCookie(key, value) {
var date = new Date()//将date设置为1天以后的时间
date.setTime(date.getTime() + 1000 * 60 * 60 * 24)
document.cookie = escapeCookie(key) + '=' + escapeCookie(value) + ';expires=' + date.toGMTString()
}
function getCookie(name) {
var m = String(document.cookie).match(new RegExp('(?:^| )' + name + '(?:(?:=([^;]*))|;|$)')) || ["", ""]
return decodeURIComponent(m[1])
}
}
module.exports = ret
/***/ }
/******/ ]);
/***/ }
/******/ ]); | apache-2.0 |
spotify/heroic | heroic-test/src/test/java/com/spotify/heroic/suggest/elasticsearch/SuggestBackendKVRestIT.java | 1377 | /*
* Copyright (c) 2020 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.suggest.elasticsearch;
import com.spotify.heroic.elasticsearch.ClientWrapper;
import com.spotify.heroic.elasticsearch.RestClientWrapper;
import java.util.List;
public class SuggestBackendKVRestIT extends AbstractSuggestBackendKVIT {
@Override
protected ClientWrapper setupClient() {
List<String> seeds = List.of(
esContainer.getTcpHost().getHostName()
+ ":" + esContainer.getContainer().getMappedPort(9200));
return new RestClientWrapper(seeds);
}
}
| apache-2.0 |
jayceyxc/hue | apps/jobbrowser/src/jobbrowser/views.py | 25163 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. 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 logging
import re
import string
import time
import urllib2
import urlparse
from urllib import quote_plus
from lxml import html
from django.http import HttpResponseRedirect
from django.utils.functional import wraps
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from desktop.log.access import access_warn, access_log_level
from desktop.lib.rest.http_client import RestException
from desktop.lib.rest.resource import Resource
from desktop.lib.django_util import JsonResponse, render_json, render, copy_query_dict
from desktop.lib.json_utils import JSONEncoderForHTML
from desktop.lib.exceptions import MessageException
from desktop.lib.exceptions_renderable import PopupException
from desktop.views import register_status_bar_view
from hadoop import cluster
from hadoop.api.jobtracker.ttypes import ThriftJobPriority, TaskTrackerNotFoundException, ThriftJobState
from hadoop.yarn.clients import get_log_client
from hadoop.yarn import resource_manager_api as resource_manager_api
LOG = logging.getLogger(__name__)
try:
from beeswax.hive_site import hiveserver2_impersonation_enabled
except:
LOG.warn('Hive is not enabled')
def hiveserver2_impersonation_enabled(): return True
from jobbrowser.conf import LOG_OFFSET, SHARE_JOBS
from jobbrowser.api import get_api, ApplicationNotRunning, JobExpired
from jobbrowser.models import Job, JobLinkage, Tracker, Cluster, can_view_job, LinkJobLogs, can_kill_job
from jobbrowser.yarn_models import Application
LOG_OFFSET_BYTES = LOG_OFFSET.get()
def check_job_permission(view_func):
"""
Ensure that the user has access to the job.
Assumes that the wrapped function takes a 'jobid' param named 'job'.
"""
def decorate(request, *args, **kwargs):
jobid = kwargs['job']
try:
job = get_job(request, job_id=jobid)
except ApplicationNotRunning, e:
LOG.warn('Job %s has not yet been accepted by the RM, will poll for status.' % jobid)
return job_not_assigned(request, jobid, request.path)
if not SHARE_JOBS.get() and not request.user.is_superuser \
and job.user != request.user.username and not can_view_job(request.user.username, job):
raise PopupException(_("You don't have permission to access job %(id)s.") % {'id': jobid})
kwargs['job'] = job
return view_func(request, *args, **kwargs)
return wraps(view_func)(decorate)
def get_job(request, job_id):
try:
job = get_api(request.user, request.jt).get_job(jobid=job_id)
except ApplicationNotRunning, e:
if e.job.get('state', '').lower() == 'accepted':
rm_api = resource_manager_api.get_resource_manager(request.user)
job = Application(e.job, rm_api)
else:
raise e # Job has not yet been accepted by RM
except JobExpired, e:
raise PopupException(_('Job %s has expired.') % job_id, detail=_('Cannot be found on the History Server.'))
except Exception, e:
msg = 'Could not find job %s.'
LOG.exception(msg % job_id)
raise PopupException(_(msg) % job_id, detail=e)
return job
def apps(request):
return render('job_browser.mako', request, {
'is_embeddable': request.GET.get('is_embeddable', False),
'is_mini': request.GET.get('is_mini', False),
'hiveserver2_impersonation_enabled': hiveserver2_impersonation_enabled()
})
def job_not_assigned(request, jobid, path):
if request.GET.get('format') == 'json':
result = {'status': -1, 'message': ''}
try:
get_api(request.user, request.jt).get_job(jobid=jobid)
result['status'] = 0
except ApplicationNotRunning, e:
result['status'] = 1
except Exception, e:
result['message'] = _('Error polling job %s: %s') % (jobid, e)
return JsonResponse(result, encoder=JSONEncoderForHTML)
else:
return render('job_not_assigned.mako', request, {'jobid': jobid, 'path': path})
def jobs(request):
user = request.POST.get('user', request.user.username)
state = request.POST.get('state')
text = request.POST.get('text')
retired = request.POST.get('retired')
time_value = request.POST.get('time_value', 7)
time_unit = request.POST.get('time_unit', 'days')
if request.POST.get('format') == 'json':
try:
# Limit number of jobs to be 1000
jobs = get_api(request.user, request.jt).get_jobs(user=request.user, username=user, state=state, text=text,
retired=retired, limit=1000, time_value=int(time_value), time_unit=time_unit)
except Exception, ex:
ex_message = str(ex)
if 'Connection refused' in ex_message or 'standby RM' in ex_message:
raise PopupException(_('Resource Manager cannot be contacted or might be down.'))
elif 'Could not connect to' in ex_message:
raise PopupException(_('Job Tracker cannot be contacted or might be down.'))
else:
raise PopupException(ex)
json_jobs = {
'jobs': [massage_job_for_json(job, request) for job in jobs],
}
return JsonResponse(json_jobs, encoder=JSONEncoderForHTML)
return render('jobs.mako', request, {
'request': request,
'state_filter': state,
'user_filter': user,
'text_filter': text,
'retired': retired,
'filtered': not (state == 'all' and user == '' and text == ''),
'is_yarn': cluster.is_yarn(),
'hiveserver2_impersonation_enabled': hiveserver2_impersonation_enabled()
})
def massage_job_for_json(job, request=None, user=None):
job = {
'id': job.jobId,
'shortId': job.jobId_short,
'name': hasattr(job, 'jobName') and job.jobName or '',
'status': job.status,
'yarnStatus': hasattr(job, 'yarnStatus') and job.yarnStatus or '',
'url': job.jobId and reverse('jobbrowser.views.single_job', kwargs={'job': job.jobId}) or '',
'logs': job.jobId and reverse('jobbrowser.views.job_single_logs', kwargs={'job': job.jobId}) or '',
'queueName': hasattr(job, 'queueName') and job.queueName or _('N/A'),
'priority': hasattr(job, 'priority') and job.priority.lower() or _('N/A'),
'user': job.user,
'isRetired': job.is_retired,
'isMR2': job.is_mr2,
'progress': hasattr(job, 'progress') and job.progress or '',
'mapProgress': hasattr(job, 'mapProgress') and job.mapProgress or '',
'reduceProgress': hasattr(job, 'reduceProgress') and job.reduceProgress or '',
'setupProgress': hasattr(job, 'setupProgress') and job.setupProgress or '',
'cleanupProgress': hasattr(job, 'cleanupProgress') and job.cleanupProgress or '',
'desiredMaps': job.desiredMaps,
'desiredReduces': job.desiredReduces,
'applicationType': hasattr(job, 'applicationType') and job.applicationType or None,
'mapsPercentComplete': int(job.maps_percent_complete) if job.maps_percent_complete else '',
'finishedMaps': job.finishedMaps,
'finishedReduces': job.finishedReduces,
'reducesPercentComplete': int(job.reduces_percent_complete) if job.reduces_percent_complete else '',
'jobFile': hasattr(job, 'jobFile') and job.jobFile or '',
'launchTimeMs': hasattr(job, 'launchTimeMs') and job.launchTimeMs or 0,
'launchTimeFormatted': hasattr(job, 'launchTimeFormatted') and job.launchTimeFormatted or '',
'startTimeMs': hasattr(job, 'startTimeMs') and job.startTimeMs or 0,
'startTimeFormatted': hasattr(job, 'startTimeFormatted') and job.startTimeFormatted or '',
'finishTimeMs': hasattr(job, 'finishTimeMs') and job.finishTimeMs or 0,
'finishTimeFormatted': hasattr(job, 'finishTimeFormatted') and job.finishTimeFormatted or '',
'durationFormatted': hasattr(job, 'durationFormatted') and job.durationFormatted or '',
'durationMs': hasattr(job, 'durationInMillis') and job.durationInMillis or 0,
'canKill': can_kill_job(job, request.user if request else user),
'killUrl': job.jobId and reverse('jobbrowser.views.kill_job', kwargs={'job': job.jobId}) or '',
}
return job
def massage_task_for_json(task):
task = {
'id': task.taskId,
'shortId': task.taskId_short,
'url': task.taskId and reverse('jobbrowser.views.single_task', kwargs={'job': task.jobId, 'taskid': task.taskId}) or '',
'logs': task.taskAttemptIds and reverse('jobbrowser.views.single_task_attempt_logs', kwargs={'job': task.jobId, 'taskid': task.taskId, 'attemptid': task.taskAttemptIds[-1]}) or '',
'type': task.taskType
}
return task
def single_spark_job(request, job):
if request.REQUEST.get('format') == 'json':
json_job = {
'job': massage_job_for_json(job, request)
}
return JsonResponse(json_job, encoder=JSONEncoderForHTML)
else:
return render('job.mako', request, {
'request': request,
'job': job
})
@check_job_permission
def single_job(request, job):
def cmp_exec_time(task1, task2):
return cmp(task1.execStartTimeMs, task2.execStartTimeMs)
if job.applicationType == 'SPARK':
return single_spark_job(request, job)
failed_tasks = job.filter_tasks(task_states=('failed',))
failed_tasks.sort(cmp_exec_time)
recent_tasks = job.filter_tasks(task_states=('running', 'succeeded',))
recent_tasks.sort(cmp_exec_time, reverse=True)
if request.REQUEST.get('format') == 'json':
json_failed_tasks = [massage_task_for_json(task) for task in failed_tasks]
json_recent_tasks = [massage_task_for_json(task) for task in recent_tasks]
json_job = {
'job': massage_job_for_json(job, request),
'failedTasks': json_failed_tasks,
'recentTasks': json_recent_tasks
}
return JsonResponse(json_job, encoder=JSONEncoderForHTML)
return render('job.mako', request, {
'request': request,
'job': job,
'failed_tasks': failed_tasks and failed_tasks[:5] or [],
'recent_tasks': recent_tasks and recent_tasks[:5] or [],
})
@check_job_permission
def job_counters(request, job):
return render("counters.html", request, {"counters": job.counters})
@access_log_level(logging.WARN)
@check_job_permission
def kill_job(request, job):
if request.method != "POST":
raise Exception(_("kill_job may only be invoked with a POST (got a %(method)s).") % {'method': request.method})
try:
job.kill()
except Exception, e:
LOG.exception('Killing job')
raise PopupException(e)
cur_time = time.time()
api = get_api(request.user, request.jt)
while time.time() - cur_time < 15:
try:
job = api.get_job(jobid=job.jobId)
except Exception, e:
LOG.warn('Failed to get job with ID %s: %s' % (job.jobId, e))
else:
if job.status not in ["RUNNING", "QUEUED"]:
if request.REQUEST.get("next"):
return HttpResponseRedirect(request.REQUEST.get("next"))
elif request.REQUEST.get("format") == "json":
return JsonResponse({'status': 0}, encoder=JSONEncoderForHTML)
else:
raise MessageException("Job Killed")
time.sleep(1)
raise Exception(_("Job did not appear as killed within 15 seconds."))
@check_job_permission
def job_attempt_logs(request, job, attempt_index=0):
return render("job_attempt_logs.mako", request, {
"attempt_index": attempt_index,
"job": job,
"log_offset": LOG_OFFSET_BYTES
})
@check_job_permission
def job_attempt_logs_json(request, job, attempt_index=0, name='syslog', offset=LOG_OFFSET_BYTES):
"""For async log retrieval as Yarn servers are very slow"""
log_link = None
response = {'status': -1}
try:
jt = get_api(request.user, request.jt)
app = jt.get_application(job.jobId)
if app['applicationType'] == 'MAPREDUCE':
if app['finalStatus'] in ('SUCCEEDED', 'FAILED', 'KILLED'):
attempt_index = int(attempt_index)
attempt = job.job_attempts['jobAttempt'][attempt_index]
log_link = attempt['logsLink']
# Reformat log link to use YARN RM, replace node addr with node ID addr
log_link = log_link.replace(attempt['nodeHttpAddress'], attempt['nodeId'])
elif app['state'] == 'RUNNING':
log_link = app['amContainerLogs']
except (KeyError, RestException), e:
raise KeyError(_("Cannot find job attempt '%(id)s'.") % {'id': job.jobId}, e)
except Exception, e:
raise Exception(_("Failed to get application for job %s: %s") % (job.jobId, e))
if log_link:
link = '/%s/' % name
params = {}
if offset != 0:
params['start'] = offset
root = Resource(get_log_client(log_link), urlparse.urlsplit(log_link)[2], urlencode=False)
api_resp = None
try:
api_resp = root.get(link, params=params)
log = html.fromstring(api_resp, parser=html.HTMLParser()).xpath('/html/body/table/tbody/tr/td[2]')[0].text_content()
response['status'] = 0
response['log'] = LinkJobLogs._make_hdfs_links(log)
except Exception, e:
response['log'] = _('Failed to retrieve log: %s' % e)
try:
debug_info = '\nLog Link: %s' % log_link
if api_resp:
debug_info += '\nHTML Response: %s' % response
response['debug'] = debug_info
LOG.error(debug_info)
except:
LOG.exception('failed to create debug info')
return JsonResponse(response)
@check_job_permission
def job_single_logs(request, job, offset=LOG_OFFSET_BYTES):
"""
Try to smartly detect the most useful task attempt (e.g. Oozie launcher, failed task) and get its MR logs.
"""
def cmp_exec_time(task1, task2):
return cmp(task1.execStartTimeMs, task2.execStartTimeMs)
task = None
failed_tasks = job.filter_tasks(task_states=('failed',))
failed_tasks.sort(cmp_exec_time)
if failed_tasks:
task = failed_tasks[0]
if not task.taskAttemptIds and len(failed_tasks) > 1: # In some cases the last task ends up without any attempt
task = failed_tasks[1]
else:
task_states = ['running', 'succeeded']
if job.is_mr2:
task_states.append('scheduled')
recent_tasks = job.filter_tasks(task_states=task_states, task_types=('map', 'reduce',))
recent_tasks.sort(cmp_exec_time, reverse=True)
if recent_tasks:
task = recent_tasks[0]
if task is None or not task.taskAttemptIds:
raise PopupException(_("No tasks found for job %(id)s.") % {'id': job.jobId})
params = {'job': job.jobId, 'taskid': task.taskId, 'attemptid': task.taskAttemptIds[-1], 'offset': offset}
return single_task_attempt_logs(request, **params)
@check_job_permission
def tasks(request, job):
"""
We get here from /jobs/job/tasks?filterargs, with the options being:
page=<n> - Controls pagination. Defaults to 1.
tasktype=<type> - Type can be one of hadoop.job_tracker.VALID_TASK_TYPES
("map", "reduce", "job_cleanup", "job_setup")
taskstate=<state> - State can be one of hadoop.job_tracker.VALID_TASK_STATES
("succeeded", "failed", "running", "pending", "killed")
tasktext=<text> - Where <text> is a string matching info on the task
"""
ttypes = request.GET.get('tasktype')
tstates = request.GET.get('taskstate')
ttext = request.GET.get('tasktext')
pagenum = int(request.GET.get('page', 1))
pagenum = pagenum > 0 and pagenum or 1
filters = {
'task_types': ttypes and set(ttypes.split(',')) or None,
'task_states': tstates and set(tstates.split(',')) or None,
'task_text': ttext,
'pagenum': pagenum,
}
jt = get_api(request.user, request.jt)
task_list = jt.get_tasks(job.jobId, **filters)
filter_params = copy_query_dict(request.GET, ('tasktype', 'taskstate', 'tasktext')).urlencode()
return render("tasks.mako", request, {
'request': request,
'filter_params': filter_params,
'job': job,
'task_list': task_list,
'tasktype': ttypes,
'taskstate': tstates,
'tasktext': ttext
})
@check_job_permission
def single_task(request, job, taskid):
jt = get_api(request.user, request.jt)
job_link = jt.get_job_link(job.jobId)
task = job_link.get_task(taskid)
return render("task.mako", request, {
'task': task,
'joblnk': job_link
})
@check_job_permission
def single_task_attempt(request, job, taskid, attemptid):
jt = get_api(request.user, request.jt)
job_link = jt.get_job_link(job.jobId)
task = job_link.get_task(taskid)
try:
attempt = task.get_attempt(attemptid)
except (KeyError, RestException), e:
raise PopupException(_("Cannot find attempt '%(id)s' in task") % {'id': attemptid}, e)
return render("attempt.mako", request, {
"attempt": attempt,
"taskid": taskid,
"joblnk": job_link,
"task": task
})
@check_job_permission
def single_task_attempt_logs(request, job, taskid, attemptid, offset=LOG_OFFSET_BYTES):
jt = get_api(request.user, request.jt)
job_link = jt.get_job_link(job.jobId)
task = job_link.get_task(taskid)
try:
attempt = task.get_attempt(attemptid)
except (KeyError, RestException), e:
raise KeyError(_("Cannot find attempt '%(id)s' in task") % {'id': attemptid}, e)
first_log_tab = 0
try:
# Add a diagnostic log
if job_link.is_mr2:
diagnostic_log = attempt.diagnostics
else:
diagnostic_log = ", ".join(task.diagnosticMap[attempt.attemptId])
logs = [diagnostic_log]
# Add remaining logs
logs += [section.strip() for section in attempt.get_task_log(offset=offset)]
log_tab = [i for i, log in enumerate(logs) if log]
if log_tab:
first_log_tab = log_tab[0]
except TaskTrackerNotFoundException:
# Four entries,
# for diagnostic, stdout, stderr and syslog
logs = [_("Failed to retrieve log. TaskTracker not found.")] * 4
except urllib2.URLError:
logs = [_("Failed to retrieve log. TaskTracker not ready.")] * 4
context = {
"attempt": attempt,
"taskid": taskid,
"joblnk": job_link,
"task": task,
"logs": logs,
"first_log_tab": first_log_tab,
}
if request.GET.get('format') == 'python':
return context
else:
context['logs'] = [LinkJobLogs._make_links(log) for i, log in enumerate(logs)]
if request.GET.get('format') == 'json':
response = {
"logs": context['logs'],
"isRunning": job.status.lower() in ('running', 'pending', 'prep')
}
return JsonResponse(response)
else:
return render("attempt_logs.mako", request, context)
@check_job_permission
def task_attempt_counters(request, job, taskid, attemptid):
"""
We get here from /jobs/jobid/tasks/taskid/attempts/attemptid/counters
(phew!)
"""
job_link = JobLinkage(request.jt, job.jobId)
task = job_link.get_task(taskid)
attempt = task.get_attempt(attemptid)
counters = {}
if attempt:
counters = attempt.counters
return render("counters.html", request, {'counters':counters})
@access_log_level(logging.WARN)
def kill_task_attempt(request, attemptid):
"""
We get here from /jobs/jobid/tasks/taskid/attempts/attemptid/kill
TODO: security
"""
ret = request.jt.kill_task_attempt(request.jt.thriftattemptid_from_string(attemptid))
return render_json({})
def trackers(request):
"""
We get here from /trackers
"""
trackers = get_tasktrackers(request)
return render("tasktrackers.mako", request, {'trackers':trackers})
def single_tracker(request, trackerid):
jt = get_api(request.user, request.jt)
try:
tracker = jt.get_tracker(trackerid)
except Exception, e:
raise PopupException(_('The tracker could not be contacted.'), detail=e)
return render("tasktracker.mako", request, {'tracker':tracker})
def container(request, node_manager_http_address, containerid):
jt = get_api(request.user, request.jt)
try:
tracker = jt.get_tracker(node_manager_http_address, containerid)
except Exception, e:
# TODO: add a redirect of some kind
raise PopupException(_('The container disappears as soon as the job finishes.'), detail=e)
return render("container.mako", request, {'tracker':tracker})
def clusterstatus(request):
"""
We get here from /clusterstatus
"""
return render("clusterstatus.html", request, Cluster(request.jt))
def queues(request):
"""
We get here from /queues
"""
return render("queues.html", request, { "queuelist" : request.jt.queues()})
@check_job_permission
def set_job_priority(request, job):
"""
We get here from /jobs/job/setpriority?priority=PRIORITY
"""
priority = request.GET.get("priority")
jid = request.jt.thriftjobid_from_string(job.jobId)
request.jt.set_job_priority(jid, ThriftJobPriority._NAMES_TO_VALUES[priority])
return render_json({})
CONF_VARIABLE_REGEX = r"\$\{(.+)\}"
def make_substitutions(conf):
"""
Substitute occurences of ${foo} with conf[foo], recursively, in all the values
of the conf dict.
Note that the Java code may also substitute Java properties in, which
this code does not have.
"""
r = re.compile(CONF_VARIABLE_REGEX)
def sub(s, depth=0):
# Malformed / malicious confs could make this loop infinitely
if depth > 100:
logging.warn("Max recursion depth exceeded when substituting jobconf value: %s" % s)
return s
m = r.search(s)
if m:
for g in [g for g in m.groups() if g in conf]:
substr = "${%s}" % g
s = s.replace(substr, sub(conf[g], depth+1))
return s
for k, v in conf.items():
conf[k] = sub(v)
return conf
##################################
## Helper functions
def get_shorter_id(hadoop_job_id):
return "_".join(hadoop_job_id.split("_")[-2:])
def format_counter_name(s):
"""
Makes counter/config names human readable:
FOOBAR_BAZ -> "Foobar Baz"
foo_barBaz -> "Foo Bar Baz"
"""
def splitCamels(s):
""" Convert "fooBar" to "foo bar" """
return re.sub(r'[a-z][A-Z]',
lambda x: x.group(0)[0] + " " + x.group(0)[1].lower(),
s)
return string.capwords(re.sub('_', ' ', splitCamels(s)).lower())
def get_state_link(request, option=None, val='', VALID_OPTIONS = ("state", "user", "text", "taskstate")):
"""
constructs the query string for the state of the current query for the jobs page.
pass in the request, and an optional option/value pair; these are used for creating
links to turn on the filter, while preserving the other present settings.
"""
states = []
val = quote_plus(val)
assert option is None or option in VALID_OPTIONS
states = dict()
for o in VALID_OPTIONS:
if o in request.GET:
states[o] = request.GET[o]
if option is not None:
states[option] = val
return "&".join([ "%s=%s" % (key, quote_plus(value)) for key, value in states.iteritems() ])
## All Unused below
# DEAD?
def dock_jobs(request):
username = request.user.username
matching_jobs = get_job_count_by_state(request, username)
return render("jobs_dock_info.mako", request, {
'jobs': matching_jobs
}, force_template=True)
register_status_bar_view(dock_jobs)
def get_tasktrackers(request):
"""
Return a ThriftTaskTrackerStatusList object containing all task trackers
"""
return [ Tracker(tracker) for tracker in request.jt.all_task_trackers().trackers]
def get_single_job(request, jobid):
"""
Returns the job which matches jobid.
"""
return Job.from_id(jt=request.jt, jobid=jobid)
def get_job_count_by_state(request, username):
"""
Returns the number of comlpeted, running, and failed jobs for a user.
"""
res = {
'completed': 0,
'running': 0,
'failed': 0,
'killed': 0,
'all': 0
}
jobcounts = request.jt.get_job_count_by_user(username)
res['completed'] = jobcounts.nSucceeded
res['running'] = jobcounts.nPrep + jobcounts.nRunning
res['failed'] = jobcounts.nFailed
res['killed'] = jobcounts.nKilled
res['all'] = res['completed'] + res['running'] + res['failed'] + res['killed']
return res
def jobbrowser(request):
"""
jobbrowser.jsp - a - like.
"""
# TODO(bc): Is this view even reachable?
def check_job_state(state):
return lambda job: job.status == state
status = request.jt.cluster_status()
alljobs = [] #get_matching_jobs(request)
runningjobs = filter(check_job_state('RUNNING'), alljobs)
completedjobs = filter(check_job_state('COMPLETED'), alljobs)
failedjobs = filter(check_job_state('FAILED'), alljobs)
killedjobs = filter(check_job_state('KILLED'), alljobs)
jobqueues = request.jt.queues()
return render("jobbrowser.html", request, {
"clusterstatus" : status,
"queues" : jobqueues,
"alljobs" : alljobs,
"runningjobs" : runningjobs,
"failedjobs" : failedjobs,
"killedjobs" : killedjobs,
"completedjobs" : completedjobs
})
| apache-2.0 |
jarrodek/feed-reader | paper/lib_new/core-dropdown/demo.html.0.js | 212 |
Polymer({
toggle: function() {
if (!this.dropdown) {
this.dropdown = this.querySelector('core-dropdown');
}
this.dropdown && this.dropdown.toggle();
}
});
| apache-2.0 |
BroadleafCommerce/blc-paypal | services/src/main/java/org/broadleafcommerce/vendor/paypal/domain/PayerInfo.java | 4023 | /*
* Copyright (C) 2009 - 2020 Broadleaf Commerce
*
* Licensed under the Broadleaf End User License Agreement (EULA), Version 1.1 (the
* "Commercial License" located at http://license.broadleafcommerce.org/commercial_license-1.1.txt).
*
* Alternatively, the Commercial License may be replaced with a mutually agreed upon license (the
* "Custom License") between you and Broadleaf Commerce. You may not use this file except in
* compliance with the applicable license.
*
* NOTICE: All information contained herein is, and remains the property of Broadleaf Commerce, LLC
* The intellectual and technical concepts contained herein are proprietary to Broadleaf Commerce,
* LLC and may be covered by U.S. and Foreign Patents, patents in process, and are protected by
* trade secret or copyright law. Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained from Broadleaf Commerce, LLC.
*/
package org.broadleafcommerce.vendor.paypal.domain;
import com.paypal.base.rest.PayPalModel;
public class PayerInfo extends PayPalModel {
private String account_id;
private String email_address;
private Name payer_name;
public String getAccount_id() {
return this.account_id;
}
public PayerInfo setAccount_id(String account_id) {
this.account_id = account_id;
return this;
}
public String getEmail_address() {
return this.email_address;
}
public PayerInfo setEmail_address(String email_address) {
this.email_address = email_address;
return this;
}
public Name getPayer_name() {
return this.payer_name;
}
public PayerInfo setPayer_name(Name payer_name) {
this.payer_name = payer_name;
return this;
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
public boolean equals(final java.lang.Object o) {
if (o == this)
return true;
if (!(o instanceof PayerInfo))
return false;
final PayerInfo other = (PayerInfo) o;
if (!other.canEqual((java.lang.Object) this))
return false;
if (!super.equals(o))
return false;
final java.lang.Object this$account_id = this.getAccount_id();
final java.lang.Object other$account_id = other.getAccount_id();
if (this$account_id == null ? other$account_id != null
: !this$account_id.equals(other$account_id))
return false;
final java.lang.Object this$email_address = this.getEmail_address();
final java.lang.Object other$email_address = other.getEmail_address();
if (this$email_address == null ? other$email_address != null
: !this$email_address.equals(other$email_address))
return false;
final java.lang.Object this$payer_name = this.getPayer_name();
final java.lang.Object other$payer_name = other.getPayer_name();
if (this$payer_name == null ? other$payer_name != null
: !this$payer_name.equals(other$payer_name))
return false;
return true;
}
@java.lang.SuppressWarnings("all")
protected boolean canEqual(final java.lang.Object other) {
return other instanceof PayerInfo;
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
public int hashCode() {
final int PRIME = 59;
int result = 1;
result = result * PRIME + super.hashCode();
final java.lang.Object $account_id = this.getAccount_id();
result = result * PRIME + ($account_id == null ? 43 : $account_id.hashCode());
final java.lang.Object $email_address = this.getEmail_address();
result = result * PRIME + ($email_address == null ? 43 : $email_address.hashCode());
final java.lang.Object $payer_name = this.getPayer_name();
result = result * PRIME + ($payer_name == null ? 43 : $payer_name.hashCode());
return result;
}
}
| apache-2.0 |
addthis/tracboard | src/webroot/dialogs.inc.php | 3707 | <?php
/**
* Copyright 2011 Clearspring Technologies
*
* 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.
*/
?>
<div class="dialog-wrapper"></div>
<div id="add-ticket-dlg">
<div class="content-outer">
<div class="content-inner">
<label>Type: <?php echo buildTypeChoiceMarkup() ?></label>
<label>Priority: <?php echo buildPriorityChoiceMarkup() ?></label>
<label>To: <?php echo buildOwnerChoiceMarkup() ?></label>
<div class="clearer"></div>
<label>Component: <?php echo buildComponentChoiceMarkup($trac) ?></label>
<label>Scope: <?php echo buildScopeChoiceMarkup() ?></label>
<div class="clearer"></div>
<label>Blocking: <input id="ticket-blocking" type="text" size="14"></input></label>
<label>Blocked by: <input id="ticket-blocked-by" type="text" size="14"></input></label>
<div class="clearer"></div>
<textarea id="ticket-summary" name="ticketSummary" class="ticket-summary" cols="35" rows="3" style="width: 100%;"></textarea><div class="clearer"></div>
<div style="text-align: right; padding-top: 10px;">
<input type="button" id="ticket-create-in-trac" name="openInTrac" value="Use Trac's Form..." /> <input type="button" id="ticket-create" name="createTicket" value="Create Now" /> <input type="button" id="ticket-cancel" name="ticketCancel" value="Cancel"/>
</div>
</div>
</div>
</div>
<div id="edit-ticket-dlg">
<div class="content-outer">
<div class="content-inner">
<div style="text-align: right; padding-bottom: 10px; border-bottom: 1px solid #ADADAD; width: 100%; margin-bottom: 10px;">
Quick Actions:
<span id="backlog-ticket-span" style="padding: 5px;"><input type="button" id="backlog-ticket" name="backlogTicket" value="Defer to Backlog"/></span>
<span id="complete-ticket-span"style="padding: 5px;"><input type="button" id="complete-ticket" name="completeTicket" value="Mark Completed" /></span>
<span id="reopen-ticket-span"style="padding: 5px;"><input type="button" id="reopen-ticket" name="reopenTicket" value="Reopen"/></span>
</div>
<label>Type: <?php echo buildTypeChoiceMarkup() ?></label>
<label>Priority: <?php echo buildPriorityChoiceMarkup() ?></label>
<label>To: <?php echo buildOwnerChoiceMarkup() ?></label>
<div class="clearer"></div>
<label>Component: <?php echo buildComponentChoiceMarkup($trac) ?></label>
<label>Scope: <?php echo buildScopeChoiceMarkup() ?></label>
<div class="clearer"></div>
<label>Blocking: <input id="ticket-blocking" type="text" size="14"></input></label>
<label>Blocked by: <input id="ticket-blocked-by" type="text" size="14"></input></label>
<div class="clearer"></div>
<textarea name="summary" id="ticket-summary" cols="35" rows="3" style="width: 100%;"></textarea><div class="clearer"></div>
<div style="text-align: right; padding-top: 10px;">
<input type="button" id="ticket-edit" name="editTicket" value="Done"/> <input type="button" id="ticket-cancel" name="ticketCancel" value="Cancel" />
</div>
</div>
</div>
</div> | apache-2.0 |
RadekKoubsky/SilverWare | camel-microservice-provider/src/main/java/io/silverware/microservices/providers/camel/CamelMicroserviceProvider.java | 8408 | /*
* -----------------------------------------------------------------------\
* SilverWare
*
* Copyright (C) 2010 - 2013 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 io.silverware.microservices.providers.camel;
import io.silverware.microservices.Context;
import io.silverware.microservices.MicroserviceMetaData;
import io.silverware.microservices.SilverWareException;
import io.silverware.microservices.providers.MicroserviceProvider;
import io.silverware.microservices.silver.CamelSilverService;
import io.silverware.microservices.util.DeployStats;
import io.silverware.microservices.util.DeploymentScanner;
import io.silverware.microservices.util.Utils;
import org.apache.camel.CamelContext;
import org.apache.camel.Component;
import org.apache.camel.ConsumerTemplate;
import org.apache.camel.Endpoint;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.Route;
import org.apache.camel.TypeConverter;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.model.RoutesDefinition;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author <a href="mailto:marvenec@gmail.com">Martin Večeřa</a>
*/
public class CamelMicroserviceProvider implements MicroserviceProvider, CamelSilverService {
private static final Logger log = LogManager.getLogger(CamelMicroserviceProvider.class);
private Context context;
private CamelContext camelContext;
private final List<RouteBuilder> routes = new ArrayList<>();
private Set<String> routeResources;
private final DeployStats stats = new DeployStats();
private void createCamelContext() throws SilverWareException {
Set<Class<? extends CamelContextFactory>> camelContextFactories = DeploymentScanner.getContextInstance(context).lookupSubtypes(CamelContextFactory.class);
if (camelContextFactories.size() >= 2) {
throw new SilverWareException("More than one CamelContextFactories found.");
} else if (camelContextFactories.size() == 1) {
Class<? extends CamelContextFactory> clazz = camelContextFactories.iterator().next();
try {
CamelContextFactory camelContextFactory = clazz.newInstance();
camelContext = camelContextFactory.createCamelContext(context);
} catch (InstantiationException | IllegalAccessException e) {
throw new SilverWareException(String.format("Cannot instantiate Camel context factory %s: ", clazz.getName()), e);
}
} else {
camelContext = new DefaultCamelContext();
}
context.getProperties().put(CAMEL_CONTEXT, camelContext);
}
private void loadRoutesFromClasses() {
final Set<Class<? extends RouteBuilder>> routeBuilders = DeploymentScanner.getContextInstance(context).lookupSubtypes(RouteBuilder.class);
if (log.isDebugEnabled()) {
log.debug("Initializing Camel route resources...");
}
stats.setFound(routeBuilders.size());
for (Class<? extends RouteBuilder> clazz : routeBuilders) {
if (log.isDebugEnabled()) {
log.debug("Creating Camel route builder: " + clazz.getName());
}
if (clazz.getName().equals(AdviceWithRouteBuilder.class.getName())) {
if (log.isDebugEnabled()) {
log.debug("Skipping " + clazz.getName() + ". This is an internal Camel route builder.");
}
stats.incSkipped();
} else {
try {
if (!Modifier.isAbstract(clazz.getModifiers())) {
final Constructor c = clazz.getConstructor();
final RouteBuilder r = (RouteBuilder) c.newInstance();
routes.add(r);
} else {
stats.incSkipped();
}
} catch (Error | Exception e) {
log.error("Cannot initialize Camel route builder: " + clazz.getName(), e);
}
}
}
}
private void loadRoutesFromXml() {
routeResources = DeploymentScanner.getContextInstance(context).lookupResources(".*camel-.*\\.xml");
}
@Override
public void initialize(final Context context) {
this.context = context;
loadRoutesFromClasses();
loadRoutesFromXml();
}
@Override
public Context getContext() {
return context;
}
@Override
public void run() {
if (routes.size() > 0 || routeResources.size() > 0) {
try {
log.info("Hello from Camel microservice provider!");
createCamelContext();
for (final RouteBuilder builder : routes) {
try {
camelContext.addRoutes(builder);
stats.incDeployed();
} catch (Exception e) {
log.warn("Unable to start Camel route " + builder.getClass().getName(), e);
stats.incSkipped();
}
}
final ModelCamelContext model = (ModelCamelContext) camelContext;
for (final String routeResource : routeResources) {
try {
final RoutesDefinition definition = model.loadRoutesDefinition(this.getClass().getResourceAsStream("/" + routeResource));
model.addRouteDefinitions(definition.getRoutes());
stats.incDeployed();
} catch (Exception e) {
log.warn(String.format("Cannot initialize routes in %s: ", routeResource), e);
stats.incSkipped();
}
}
log.info("Total Camel route resources " + stats.toString() + ".");
camelContext.start();
try {
while (!Thread.currentThread().isInterrupted()) {
Thread.sleep(1000);
}
} catch (InterruptedException ie) {
Utils.shutdownLog(log, ie);
} finally {
try {
camelContext.stop();
} catch (Exception e) {
log.trace("Weld was shut down before Camel and destroyed the context: ", e);
}
}
} catch (Exception e) {
log.error("Camel microservice provider failed: ", e);
}
} else {
log.warn("No route resources to start. Camel microservice provider is terminated.");
}
}
@Override
public Set<Object> lookupMicroservice(final MicroserviceMetaData metaData) {
if (Route.class.isAssignableFrom(metaData.getType())) {
return Collections.singleton(camelContext.getRoute(metaData.getName()));
} else if (Endpoint.class.isAssignableFrom(metaData.getType())) {
return Collections.singleton(camelContext.getEndpoint(metaData.getName()));
} else if (TypeConverter.class.isAssignableFrom(metaData.getType())) {
return Collections.singleton(camelContext.getTypeConverter());
} else if (Component.class.isAssignableFrom(metaData.getType())) {
return Collections.singleton(camelContext.getComponent(metaData.getName()));
} else if (ConsumerTemplate.class.isAssignableFrom(metaData.getType())) {
return Collections.singleton(camelContext.createConsumerTemplate());
} else if (ProducerTemplate.class.isAssignableFrom(metaData.getType())) {
return Collections.singleton(camelContext.createProducerTemplate());
}
return new HashSet<>();
}
}
| apache-2.0 |
ericchiang/kubernetes | plugin/pkg/scheduler/scheduler_test.go | 19837 | /*
Copyright 2014 The Kubernetes 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 scheduler
import (
"errors"
"fmt"
"reflect"
"testing"
"time"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/diff"
"k8s.io/apimachinery/pkg/util/wait"
clientcache "k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/kubernetes/pkg/api/legacyscheme"
"k8s.io/kubernetes/plugin/pkg/scheduler/algorithm"
"k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates"
"k8s.io/kubernetes/plugin/pkg/scheduler/core"
"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache"
schedulertesting "k8s.io/kubernetes/plugin/pkg/scheduler/testing"
"k8s.io/kubernetes/plugin/pkg/scheduler/util"
)
type fakeBinder struct {
b func(binding *v1.Binding) error
}
func (fb fakeBinder) Bind(binding *v1.Binding) error { return fb.b(binding) }
type fakePodConditionUpdater struct{}
func (fc fakePodConditionUpdater) Update(pod *v1.Pod, podCondition *v1.PodCondition) error {
return nil
}
type fakePodPreemptor struct{}
func (fp fakePodPreemptor) GetUpdatedPod(pod *v1.Pod) (*v1.Pod, error) {
return pod, nil
}
func (fp fakePodPreemptor) DeletePod(pod *v1.Pod) error {
return nil
}
func (fp fakePodPreemptor) UpdatePodAnnotations(pod *v1.Pod, annots map[string]string) error {
return nil
}
func (fp fakePodPreemptor) RemoveNominatedNodeAnnotation(pod *v1.Pod) error {
return nil
}
func podWithID(id, desiredHost string) *v1.Pod {
return &v1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: id, SelfLink: util.Test.SelfLink(string(v1.ResourcePods), id)},
Spec: v1.PodSpec{
NodeName: desiredHost,
},
}
}
func deletingPod(id string) *v1.Pod {
deletionTimestamp := metav1.Now()
return &v1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: id, SelfLink: util.Test.SelfLink(string(v1.ResourcePods), id), DeletionTimestamp: &deletionTimestamp},
Spec: v1.PodSpec{
NodeName: "",
},
}
}
func podWithPort(id, desiredHost string, port int) *v1.Pod {
pod := podWithID(id, desiredHost)
pod.Spec.Containers = []v1.Container{
{Name: "ctr", Ports: []v1.ContainerPort{{HostPort: int32(port)}}},
}
return pod
}
func podWithResources(id, desiredHost string, limits v1.ResourceList, requests v1.ResourceList) *v1.Pod {
pod := podWithID(id, desiredHost)
pod.Spec.Containers = []v1.Container{
{Name: "ctr", Resources: v1.ResourceRequirements{Limits: limits, Requests: requests}},
}
return pod
}
type mockScheduler struct {
machine string
err error
}
func (es mockScheduler) Schedule(pod *v1.Pod, ml algorithm.NodeLister) (string, error) {
return es.machine, es.err
}
func (es mockScheduler) Predicates() map[string]algorithm.FitPredicate {
return nil
}
func (es mockScheduler) Prioritizers() []algorithm.PriorityConfig {
return nil
}
func (es mockScheduler) Preempt(pod *v1.Pod, nodeLister algorithm.NodeLister, scheduleErr error) (*v1.Node, []*v1.Pod, []*v1.Pod, error) {
return nil, nil, nil, nil
}
func TestScheduler(t *testing.T) {
eventBroadcaster := record.NewBroadcaster()
eventBroadcaster.StartLogging(t.Logf).Stop()
errS := errors.New("scheduler")
errB := errors.New("binder")
testNode := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "machine1"}}
table := []struct {
injectBindError error
sendPod *v1.Pod
algo algorithm.ScheduleAlgorithm
expectErrorPod *v1.Pod
expectForgetPod *v1.Pod
expectAssumedPod *v1.Pod
expectError error
expectBind *v1.Binding
eventReason string
}{
{
sendPod: podWithID("foo", ""),
algo: mockScheduler{testNode.Name, nil},
expectBind: &v1.Binding{ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Target: v1.ObjectReference{Kind: "Node", Name: testNode.Name}},
expectAssumedPod: podWithID("foo", testNode.Name),
eventReason: "Scheduled",
}, {
sendPod: podWithID("foo", ""),
algo: mockScheduler{testNode.Name, errS},
expectError: errS,
expectErrorPod: podWithID("foo", ""),
eventReason: "FailedScheduling",
}, {
sendPod: podWithID("foo", ""),
algo: mockScheduler{testNode.Name, nil},
expectBind: &v1.Binding{ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Target: v1.ObjectReference{Kind: "Node", Name: testNode.Name}},
expectAssumedPod: podWithID("foo", testNode.Name),
injectBindError: errB,
expectError: errB,
expectErrorPod: podWithID("foo", testNode.Name),
expectForgetPod: podWithID("foo", testNode.Name),
eventReason: "FailedScheduling",
}, {
sendPod: deletingPod("foo"),
algo: mockScheduler{"", nil},
eventReason: "FailedScheduling",
},
}
for i, item := range table {
var gotError error
var gotPod *v1.Pod
var gotForgetPod *v1.Pod
var gotAssumedPod *v1.Pod
var gotBinding *v1.Binding
configurator := &FakeConfigurator{
Config: &Config{
SchedulerCache: &schedulertesting.FakeCache{
ForgetFunc: func(pod *v1.Pod) {
gotForgetPod = pod
},
AssumeFunc: func(pod *v1.Pod) {
gotAssumedPod = pod
},
},
NodeLister: schedulertesting.FakeNodeLister(
[]*v1.Node{&testNode},
),
Algorithm: item.algo,
Binder: fakeBinder{func(b *v1.Binding) error {
gotBinding = b
return item.injectBindError
}},
PodConditionUpdater: fakePodConditionUpdater{},
Error: func(p *v1.Pod, err error) {
gotPod = p
gotError = err
},
NextPod: func() *v1.Pod {
return item.sendPod
},
Recorder: eventBroadcaster.NewRecorder(legacyscheme.Scheme, v1.EventSource{Component: "scheduler"}),
},
}
s, _ := NewFromConfigurator(configurator, nil...)
called := make(chan struct{})
events := eventBroadcaster.StartEventWatcher(func(e *v1.Event) {
if e, a := item.eventReason, e.Reason; e != a {
t.Errorf("%v: expected %v, got %v", i, e, a)
}
close(called)
})
s.scheduleOne()
<-called
if e, a := item.expectAssumedPod, gotAssumedPod; !reflect.DeepEqual(e, a) {
t.Errorf("%v: assumed pod: wanted %v, got %v", i, e, a)
}
if e, a := item.expectErrorPod, gotPod; !reflect.DeepEqual(e, a) {
t.Errorf("%v: error pod: wanted %v, got %v", i, e, a)
}
if e, a := item.expectForgetPod, gotForgetPod; !reflect.DeepEqual(e, a) {
t.Errorf("%v: forget pod: wanted %v, got %v", i, e, a)
}
if e, a := item.expectError, gotError; !reflect.DeepEqual(e, a) {
t.Errorf("%v: error: wanted %v, got %v", i, e, a)
}
if e, a := item.expectBind, gotBinding; !reflect.DeepEqual(e, a) {
t.Errorf("%v: error: %s", i, diff.ObjectDiff(e, a))
}
events.Stop()
}
}
func TestSchedulerNoPhantomPodAfterExpire(t *testing.T) {
stop := make(chan struct{})
defer close(stop)
queuedPodStore := clientcache.NewFIFO(clientcache.MetaNamespaceKeyFunc)
scache := schedulercache.New(100*time.Millisecond, stop)
pod := podWithPort("pod.Name", "", 8080)
node := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "machine1"}}
scache.AddNode(&node)
nodeLister := schedulertesting.FakeNodeLister([]*v1.Node{&node})
predicateMap := map[string]algorithm.FitPredicate{"PodFitsHostPorts": predicates.PodFitsHostPorts}
scheduler, bindingChan, _ := setupTestSchedulerWithOnePodOnNode(t, queuedPodStore, scache, nodeLister, predicateMap, pod, &node)
waitPodExpireChan := make(chan struct{})
timeout := make(chan struct{})
go func() {
for {
select {
case <-timeout:
return
default:
}
pods, err := scache.List(labels.Everything())
if err != nil {
t.Fatalf("cache.List failed: %v", err)
}
if len(pods) == 0 {
close(waitPodExpireChan)
return
}
time.Sleep(100 * time.Millisecond)
}
}()
// waiting for the assumed pod to expire
select {
case <-waitPodExpireChan:
case <-time.After(wait.ForeverTestTimeout):
close(timeout)
t.Fatalf("timeout timeout in waiting pod expire after %v", wait.ForeverTestTimeout)
}
// We use conflicted pod ports to incur fit predicate failure if first pod not removed.
secondPod := podWithPort("bar", "", 8080)
queuedPodStore.Add(secondPod)
scheduler.scheduleOne()
select {
case b := <-bindingChan:
expectBinding := &v1.Binding{
ObjectMeta: metav1.ObjectMeta{Name: "bar"},
Target: v1.ObjectReference{Kind: "Node", Name: node.Name},
}
if !reflect.DeepEqual(expectBinding, b) {
t.Errorf("binding want=%v, get=%v", expectBinding, b)
}
case <-time.After(wait.ForeverTestTimeout):
t.Fatalf("timeout in binding after %v", wait.ForeverTestTimeout)
}
}
func TestSchedulerNoPhantomPodAfterDelete(t *testing.T) {
stop := make(chan struct{})
defer close(stop)
queuedPodStore := clientcache.NewFIFO(clientcache.MetaNamespaceKeyFunc)
scache := schedulercache.New(10*time.Minute, stop)
firstPod := podWithPort("pod.Name", "", 8080)
node := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "machine1"}}
scache.AddNode(&node)
nodeLister := schedulertesting.FakeNodeLister([]*v1.Node{&node})
predicateMap := map[string]algorithm.FitPredicate{"PodFitsHostPorts": predicates.PodFitsHostPorts}
scheduler, bindingChan, errChan := setupTestSchedulerWithOnePodOnNode(t, queuedPodStore, scache, nodeLister, predicateMap, firstPod, &node)
// We use conflicted pod ports to incur fit predicate failure.
secondPod := podWithPort("bar", "", 8080)
queuedPodStore.Add(secondPod)
// queuedPodStore: [bar:8080]
// cache: [(assumed)foo:8080]
scheduler.scheduleOne()
select {
case err := <-errChan:
expectErr := &core.FitError{
Pod: secondPod,
NumAllNodes: 1,
FailedPredicates: core.FailedPredicateMap{node.Name: []algorithm.PredicateFailureReason{predicates.ErrPodNotFitsHostPorts}},
}
if !reflect.DeepEqual(expectErr, err) {
t.Errorf("err want=%v, get=%v", expectErr, err)
}
case <-time.After(wait.ForeverTestTimeout):
t.Fatalf("timeout in fitting after %v", wait.ForeverTestTimeout)
}
// We mimic the workflow of cache behavior when a pod is removed by user.
// Note: if the schedulercache timeout would be super short, the first pod would expire
// and would be removed itself (without any explicit actions on schedulercache). Even in that case,
// explicitly AddPod will as well correct the behavior.
firstPod.Spec.NodeName = node.Name
if err := scache.AddPod(firstPod); err != nil {
t.Fatalf("err: %v", err)
}
if err := scache.RemovePod(firstPod); err != nil {
t.Fatalf("err: %v", err)
}
queuedPodStore.Add(secondPod)
scheduler.scheduleOne()
select {
case b := <-bindingChan:
expectBinding := &v1.Binding{
ObjectMeta: metav1.ObjectMeta{Name: "bar"},
Target: v1.ObjectReference{Kind: "Node", Name: node.Name},
}
if !reflect.DeepEqual(expectBinding, b) {
t.Errorf("binding want=%v, get=%v", expectBinding, b)
}
case <-time.After(wait.ForeverTestTimeout):
t.Fatalf("timeout in binding after %v", wait.ForeverTestTimeout)
}
}
// Scheduler should preserve predicate constraint even if binding was longer
// than cache ttl
func TestSchedulerErrorWithLongBinding(t *testing.T) {
stop := make(chan struct{})
defer close(stop)
firstPod := podWithPort("foo", "", 8080)
conflictPod := podWithPort("bar", "", 8080)
pods := map[string]*v1.Pod{firstPod.Name: firstPod, conflictPod.Name: conflictPod}
for _, test := range []struct {
Expected map[string]bool
CacheTTL time.Duration
BindingDuration time.Duration
}{
{
Expected: map[string]bool{firstPod.Name: true},
CacheTTL: 100 * time.Millisecond,
BindingDuration: 300 * time.Millisecond,
},
{
Expected: map[string]bool{firstPod.Name: true},
CacheTTL: 10 * time.Second,
BindingDuration: 300 * time.Millisecond,
},
} {
queuedPodStore := clientcache.NewFIFO(clientcache.MetaNamespaceKeyFunc)
scache := schedulercache.New(test.CacheTTL, stop)
node := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "machine1"}}
scache.AddNode(&node)
nodeLister := schedulertesting.FakeNodeLister([]*v1.Node{&node})
predicateMap := map[string]algorithm.FitPredicate{"PodFitsHostPorts": predicates.PodFitsHostPorts}
scheduler, bindingChan := setupTestSchedulerLongBindingWithRetry(
queuedPodStore, scache, nodeLister, predicateMap, stop, test.BindingDuration)
scheduler.Run()
queuedPodStore.Add(firstPod)
queuedPodStore.Add(conflictPod)
resultBindings := map[string]bool{}
waitChan := time.After(5 * time.Second)
for finished := false; !finished; {
select {
case b := <-bindingChan:
resultBindings[b.Name] = true
p := pods[b.Name]
p.Spec.NodeName = b.Target.Name
scache.AddPod(p)
case <-waitChan:
finished = true
}
}
if !reflect.DeepEqual(resultBindings, test.Expected) {
t.Errorf("Result binding are not equal to expected. %v != %v", resultBindings, test.Expected)
}
}
}
// queuedPodStore: pods queued before processing.
// cache: scheduler cache that might contain assumed pods.
func setupTestSchedulerWithOnePodOnNode(t *testing.T, queuedPodStore *clientcache.FIFO, scache schedulercache.Cache,
nodeLister schedulertesting.FakeNodeLister, predicateMap map[string]algorithm.FitPredicate, pod *v1.Pod, node *v1.Node) (*Scheduler, chan *v1.Binding, chan error) {
scheduler, bindingChan, errChan := setupTestScheduler(queuedPodStore, scache, nodeLister, predicateMap)
queuedPodStore.Add(pod)
// queuedPodStore: [foo:8080]
// cache: []
scheduler.scheduleOne()
// queuedPodStore: []
// cache: [(assumed)foo:8080]
select {
case b := <-bindingChan:
expectBinding := &v1.Binding{
ObjectMeta: metav1.ObjectMeta{Name: pod.Name},
Target: v1.ObjectReference{Kind: "Node", Name: node.Name},
}
if !reflect.DeepEqual(expectBinding, b) {
t.Errorf("binding want=%v, get=%v", expectBinding, b)
}
case <-time.After(wait.ForeverTestTimeout):
t.Fatalf("timeout after %v", wait.ForeverTestTimeout)
}
return scheduler, bindingChan, errChan
}
func TestSchedulerFailedSchedulingReasons(t *testing.T) {
stop := make(chan struct{})
defer close(stop)
queuedPodStore := clientcache.NewFIFO(clientcache.MetaNamespaceKeyFunc)
scache := schedulercache.New(10*time.Minute, stop)
// Design the baseline for the pods, and we will make nodes that dont fit it later.
var cpu = int64(4)
var mem = int64(500)
podWithTooBigResourceRequests := podWithResources("bar", "", v1.ResourceList{
v1.ResourceCPU: *(resource.NewQuantity(cpu, resource.DecimalSI)),
v1.ResourceMemory: *(resource.NewQuantity(mem, resource.DecimalSI)),
}, v1.ResourceList{
v1.ResourceCPU: *(resource.NewQuantity(cpu, resource.DecimalSI)),
v1.ResourceMemory: *(resource.NewQuantity(mem, resource.DecimalSI)),
})
// create several nodes which cannot schedule the above pod
nodes := []*v1.Node{}
for i := 0; i < 100; i++ {
node := v1.Node{
ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("machine%v", i)},
Status: v1.NodeStatus{
Capacity: v1.ResourceList{
v1.ResourceCPU: *(resource.NewQuantity(cpu/2, resource.DecimalSI)),
v1.ResourceMemory: *(resource.NewQuantity(mem/5, resource.DecimalSI)),
v1.ResourcePods: *(resource.NewQuantity(10, resource.DecimalSI)),
},
Allocatable: v1.ResourceList{
v1.ResourceCPU: *(resource.NewQuantity(cpu/2, resource.DecimalSI)),
v1.ResourceMemory: *(resource.NewQuantity(mem/5, resource.DecimalSI)),
v1.ResourcePods: *(resource.NewQuantity(10, resource.DecimalSI)),
}},
}
scache.AddNode(&node)
nodes = append(nodes, &node)
}
nodeLister := schedulertesting.FakeNodeLister(nodes)
predicateMap := map[string]algorithm.FitPredicate{
"PodFitsResources": predicates.PodFitsResources,
}
// Create expected failure reasons for all the nodes. Hopefully they will get rolled up into a non-spammy summary.
failedPredicatesMap := core.FailedPredicateMap{}
for _, node := range nodes {
failedPredicatesMap[node.Name] = []algorithm.PredicateFailureReason{
predicates.NewInsufficientResourceError(v1.ResourceCPU, 4000, 0, 2000),
predicates.NewInsufficientResourceError(v1.ResourceMemory, 500, 0, 100),
}
}
scheduler, _, errChan := setupTestScheduler(queuedPodStore, scache, nodeLister, predicateMap)
queuedPodStore.Add(podWithTooBigResourceRequests)
scheduler.scheduleOne()
select {
case err := <-errChan:
expectErr := &core.FitError{
Pod: podWithTooBigResourceRequests,
NumAllNodes: len(nodes),
FailedPredicates: failedPredicatesMap,
}
if len(fmt.Sprint(expectErr)) > 150 {
t.Errorf("message is too spammy ! %v ", len(fmt.Sprint(expectErr)))
}
if !reflect.DeepEqual(expectErr, err) {
t.Errorf("\n err \nWANT=%+v,\nGOT=%+v", expectErr, err)
}
case <-time.After(wait.ForeverTestTimeout):
t.Fatalf("timeout after %v", wait.ForeverTestTimeout)
}
}
// queuedPodStore: pods queued before processing.
// scache: scheduler cache that might contain assumed pods.
func setupTestScheduler(queuedPodStore *clientcache.FIFO, scache schedulercache.Cache, nodeLister schedulertesting.FakeNodeLister, predicateMap map[string]algorithm.FitPredicate) (*Scheduler, chan *v1.Binding, chan error) {
algo := core.NewGenericScheduler(
scache,
nil,
nil,
predicateMap,
algorithm.EmptyPredicateMetadataProducer,
[]algorithm.PriorityConfig{},
algorithm.EmptyMetadataProducer,
[]algorithm.SchedulerExtender{})
bindingChan := make(chan *v1.Binding, 1)
errChan := make(chan error, 1)
configurator := &FakeConfigurator{
Config: &Config{
SchedulerCache: scache,
NodeLister: nodeLister,
Algorithm: algo,
Binder: fakeBinder{func(b *v1.Binding) error {
bindingChan <- b
return nil
}},
NextPod: func() *v1.Pod {
return clientcache.Pop(queuedPodStore).(*v1.Pod)
},
Error: func(p *v1.Pod, err error) {
errChan <- err
},
Recorder: &record.FakeRecorder{},
PodConditionUpdater: fakePodConditionUpdater{},
PodPreemptor: fakePodPreemptor{},
},
}
sched, _ := NewFromConfigurator(configurator, nil...)
return sched, bindingChan, errChan
}
func setupTestSchedulerLongBindingWithRetry(queuedPodStore *clientcache.FIFO, scache schedulercache.Cache, nodeLister schedulertesting.FakeNodeLister, predicateMap map[string]algorithm.FitPredicate, stop chan struct{}, bindingTime time.Duration) (*Scheduler, chan *v1.Binding) {
algo := core.NewGenericScheduler(
scache,
nil,
nil,
predicateMap,
algorithm.EmptyPredicateMetadataProducer,
[]algorithm.PriorityConfig{},
algorithm.EmptyMetadataProducer,
[]algorithm.SchedulerExtender{})
bindingChan := make(chan *v1.Binding, 2)
configurator := &FakeConfigurator{
Config: &Config{
SchedulerCache: scache,
NodeLister: nodeLister,
Algorithm: algo,
Binder: fakeBinder{func(b *v1.Binding) error {
time.Sleep(bindingTime)
bindingChan <- b
return nil
}},
WaitForCacheSync: func() bool {
return true
},
NextPod: func() *v1.Pod {
return clientcache.Pop(queuedPodStore).(*v1.Pod)
},
Error: func(p *v1.Pod, err error) {
queuedPodStore.AddIfNotPresent(p)
},
Recorder: &record.FakeRecorder{},
PodConditionUpdater: fakePodConditionUpdater{},
PodPreemptor: fakePodPreemptor{},
StopEverything: stop,
},
}
sched, _ := NewFromConfigurator(configurator, nil...)
return sched, bindingChan
}
| apache-2.0 |
Communote/communote-server | communote/webapp/src/main/webapp/javascript/blog/CreateNote.js | 48896 | // TODO rename to NoteEditorWidget and move to widget/note/editor
var CreateNoteWidget = new Class({
Extends: C_Widget,
widgetGroup: "blog",
// the current working mode of the widget (edit, comment, repost or create)
action: null,
ajaxLoadingOverlay: null,
/**
* Object that maps the source render style to the allowed target render styles (array of
* styles). If null all transitions are allowed.
*/
allowedRenderStyleTransitions: null,
autosaveDisabled: false,
// local reference to the blogUtils for defaultBlog handling
blogUtils: null,
// defines what should happen when cancel method is called. These defaults are intended
// for create mode and will differ slightly for edit and comment but can also be overridden
// by configuration.
cancelBehavior: {
// whether to discard the autosave and reset the editor. If there is no autosave the
// editor will only be reset if modified.
discardAutosave: true,
// whether to show a dialog to let the user confirm the removal of the autosave, if there
// is one
confirmDiscard: true,
// whether to show a dialog to let the user confirm the reset, if there are modifications
// but no autosave
confirmReset: true,
// defines what to do after handling the autosave/modification. Can be 'remove' to remove
// the editor, false to do nothing or renderStyle to set another renderStyle. In case of
// the latter actionOptions must hold the name of the new style.
action: false,
// can hold additional details to run the action. The allowed values depend on the action
actionOptions: undefined
},
// ComponentManager with all components for the current working mode/action
components: null,
// whether the editor is currently dirty. Will be reset after a successful autosave or submit.
dirty: false,
// the NoteTextEditor instance
editor: null,
// emitter for local events, mainly for notifying the components
eventEmitter: null,
/**
* JSON object holding initial note data which will be restored when resetting the note. This
* data is provided with the response metadata when refreshing the widget. In the edit case this
* will be the note to edit. Additionally the content can be provided with a static parameter to
* overwrite the content of the initialNote. In case there is an autosave, the autosave has
* precedence over the initial note when initializing the widget content after a refresh.
*/
initialNote: null,
/**
* A topic extracted from settings during initialization, can be null. Will only be set when in
* create mode and is used when resetting the editor.
*/
initialTargetTopic: null,
targetTopic: null,
// if the note was modified in some way. Will be reset with initContent after publishing or reverting
modified: false,
noTargetTopicChangeIfModifiedOrAutosaved: false,
// an array of note property objects to be included when sending the note
noteProperties: null,
parentPostId: null,
// css classes to be applied to the create note container (getWriteContainerElement)
// when the editor only supports plain text
plainTextEditorCssClass: 'cn-write-note-plaintext',
// note properties to pass along with every note. Can be set with the same-named static parameter.
predefinedNoteProperties: null,
// defines what should happen after a note was published successfully and the editor was
// cleared. If the editor is in comment or edit mode the action will default to 'remove'.
publishSuccessBehavior: {
// can be 'remove' to remove the editor, false to do nothing or renderStyle to set another
// renderStyle. In case of the latter actionOptions must hold the name of the new style.
action: false,
actionOptions: undefined
},
/**
* The render style of the widget
*/
renderStyle: null,
renderStyleCssClassPrefix: 'cn-write-note-render-style-',
// css classes to be applied to the create note container (getWriteContainerElement)
// when the editor only supports richtext
richTextEditorCssClass: null,
/**
* Supported render styles of the widget. The first is the default.
*/
supportedRenderStyles: [ 'full', 'minimal', 'simulate' ],
targetBlogIdChangeTracker: null,
topicWriteAccessEvaluator: null,
userInterfaceHidden: false,
init: function() {
var action, targetBlogId, targetBlogTitle, parentPostId, autosaveDisabled;
var filterGroupId, cancelBehavior, publishSuccessBehavior, renderStyle;
this.parent();
this.eventEmitter = new communote.classes.EventEmitter();
this.noTargetTopicChangeIfModifiedOrAutosaved = !!this
.getStaticParameter('noTargetTopicChangeIfModifiedOrAutosaved');
this.blogUtils = communote.utils.topicUtils;
action = this.getStaticParameter('action') || 'create';
this.setFilterParameter('action', action);
this.action = action;
if (action === 'create') {
targetBlogId = this.getStaticParameter('targetBlogId');
targetBlogTitle = this.getStaticParameter('targetBlogTitle');
this.setInitialTargetTopic(targetBlogId, targetBlogTitle);
// observe targetBlogId changes when in create mode and a repo is configured
filterGroupId = this.staticParams.filterWidgetGroupId;
if (filterGroupId && communote.filterGroupRepo[filterGroupId]) {
this.targetBlogIdChangeTracker = new communote.classes.FilterParameterChangedHandler(
filterGroupId, 'targetBlogId', this.onTargetBlogIdChanged.bind(this));
// check for targetBlogId which can be part of the widget settings (see above) or
// set in the filter store as initial parameter, but give setting preference
if (!this.initialTargetTopic) {
this.setInitialTargetTopic(this.targetBlogIdChangeTracker
.getCurrentValue(), null);
}
}
} else {
// set some other defaults for the cancelBehavior, mainly for backwards compatibility
this.cancelBehavior.confirmDiscard = false;
this.cancelBehavior.confirmReset = false;
this.cancelBehavior.action = 'remove';
this.publishSuccessBehavior.action = 'remove';
}
cancelBehavior = this.getStaticParameter('cancelBehavior');
if (cancelBehavior) {
if (typeof cancelBehavior == 'string') {
cancelBehavior = JSON.decode(cancelBehavior);
}
Object.merge(this.cancelBehavior, cancelBehavior);
}
publishSuccessBehavior = this.getStaticParameter('publishSuccessBehavior');
if (publishSuccessBehavior) {
if (typeof publishSuccessBehavior == 'string') {
publishSuccessBehavior = JSON.decode(publishSuccessBehavior);
}
Object.merge(this.publishSuccessBehavior, publishSuccessBehavior);
}
this.setRenderStyle(this.getStaticParameter('renderStyle'));
this.editor = this.createEditor();
if (!this.editor.supportsHtml()) {
if (this.renderStyle !== 'full') {
// check whether the editor in full render style would support HTML because the
// editor will switch to full if there is an autosave.
renderStyle = this.renderStyle;
this.renderStyle = 'full';
this.setFilterParameter('plaintextOnly', !this.createEditor().supportsHtml());
this.renderStyle = renderStyle;
} else {
this.setFilterParameter('plaintextOnly', true);
}
}
this.copyStaticParameter('repostNoteId');
if (this.getFilterParameter('repostNoteId')) {
// change action to repost (pure client-side feature)
this.action = 'repost';
}
this.copyStaticParameter('noteId');
parentPostId = this.getStaticParameter('parentPostId');
if (parentPostId) {
this.parentPostId = parentPostId;
this.setFilterParameter('parentPostId', parentPostId);
}
this.copyStaticParameter('authorNotification');
this.copyStaticParameter('inheritTags');
this.copyStaticParameter('copyAttachments');
autosaveDisabled = this.getStaticParameter('autosaveDisabled');
if (autosaveDisabled === 'true' || autosaveDisabled === true) {
this.autosaveDisabled = true;
// might have been set to true by subclass overriding the default or via static
// parameter
this.setFilterParameter('autosaveDisabled', true);
}
this.predefinedNoteProperties = this.getStaticParameter('predefinedNoteProperties');
this.initAutosaveHandler();
this.components = new communote.classes.NoteEditorComponentManager(this, action,
this.renderStyle, this.getAllStaticParameters());
this.topicWriteAccessEvaluator = new communote.classes.TopicWriteAccessEvaluator(this.blogUtils);
},
activateFullEditor: function() {
this.setRenderStyle('full');
if (this.action === 'create') {
this.editor.focus();
}
},
addEventListener: function(eventName, fn, context) {
this.eventEmitter.on(eventName, fn, context);
},
/**
* @override
*/
beforeRemove: function() {
this.stopAutosaveJob();
// TODO do autosave?
if (this.targetBlogIdChangeTracker) {
this.targetBlogIdChangeTracker.destroy();
}
this.cleanup();
this.eventEmitter.emit('widgetRemoving');
},
/**
* Cancel the edit, update or create operation. The actual behavior of this function is defined
* by the configurable cancelBehavior.
*
* @param Event [event] The event that triggered cancel.
*/
cancel: function(event) {
var remove, changeRenderStyle, hasAutosave, modified, postRemoveOperation;
var hasOnlineAutosave;
var behavior = this.cancelBehavior;
if (behavior.action) {
remove = behavior.action === 'remove';
changeRenderStyle = behavior.action === 'renderStyle'
&& this.supportedRenderStyles.contains(behavior.actionOptions);
// fallback to no action
if (!remove && !changeRenderStyle) {
behavior.action = false;
}
}
hasAutosave = this.hasAutosave();
modified = this.isModified();
if (behavior.discardAutosave && (hasAutosave || modified)) {
hasOnlineAutosave = this.autosaveHandler && this.autosaveHandler.hasOnlineAutosave();
postRemoveOperation = function() {
this.eventEmitter.emit('noteDiscarded', hasOnlineAutosave);
if (!remove) {
this.resetToNoAutosaveState();
if (changeRenderStyle) {
this.setRenderStyle(behavior.actionOptions);
}
} else {
this.widgetController.removeWidget(this);
}
}.bind(this);
if (hasAutosave) {
if (behavior.confirmDiscard || behavior.confirmReset) {
this.autosaveHandler.discardWithConfirm(event, postRemoveOperation);
} else {
this.autosaveHandler.discard(postRemoveOperation);
}
} else {
// only modified. Can call the same operations but have to stop the autosave job before
this.stopAutosaveJob();
if (behavior.confirmReset) {
showConfirmDialog(getJSMessage('create.note.dialog.discardChanges.title'),
getJSMessage('create.note.dialog.discardChanges.question'),
postRemoveOperation, {
triggeringEvent: event,
onCloseCallback: this.startAutosaveJob.bind(this)
});
} else {
postRemoveOperation();
}
}
} else {
// just run the action, if any
if (remove) {
this.widgetController.removeWidget(this);
} else if (changeRenderStyle) {
this.setRenderStyle(behavior.actionOptions);
}
}
},
/**
* Implementation of the 'approveMatchCallback' callback of the AutocompleterStaticDataSource
* that excludes the
*
* @@discussion suggestion when not used in a discussion context.
*/
checkDiscussionContextApproveMatchCallback: function(query, staticSearchDefinition) {
if (staticSearchDefinition.inputValue != '@discussion') {
return true;
}
// @@discussion should only be matched when in a discussion context: create note or edit
// a note that is not part of a discussion with more than one note
if (this.action === 'create' || this.action === 'repost'
|| (this.action == 'edit' && this.initialNote.numberOfDiscussionNotes == 1)) {
return false;
}
return true;
},
/**
* Cleanup any resources to avoid memory leaks
*/
cleanup: function() {
this.editor.cleanup();
},
/**
* Called after the content of the widget has been initialized after a refresh.
*
* @param {boolean} fromAutosave If true, the widget was initialized with an autosave
*/
contentInitializedAfterRefresh: function(fromAutosave) {
},
/**
* Create the NoteTextEditor to be used and return it.
*
* @return {NoteTextEditor} the editor
*/
createEditor: function() {
var minimal, options;
if (!this.editorRefreshCompleteCallback) {
this.editorRefreshCompleteCallback = this.emitEvent.bind(this, 'editorRefreshed');
}
minimal = this.renderStyle === 'minimal';
options = {
autoresizeMinHeight: Math.floor(46200 / this.domNode.clientWidth),
useExpander: true,
focusOnRefresh: this.action === 'comment',
expanderOptions: {
additionalLines: 0,
minLines: minimal ? 1 : 0
},
keyboardShortcuts: {
ctrlKey: true,
keyCode: 13,
callback: this.publishNote.bind(this),
cancelEvent: true
},
storeEditorSize: this.action === 'create'
};
if (minimal) {
return NoteTextEditorFactory.createPlainTextEditor(null, options);
} else {
options.tagAutocompleterOptions = this.prepareAutocompleterOptions(
this.setCurrentTopicBeforeRequestCallback.bind(this));
options.userAutocompleterOptions = this.prepareAutocompleterOptions(
this.setCurrentTopicBeforeRequestCallback.bind(this));
options.userAutocompleterOptions.staticDataSourceOptions = {};
options.userAutocompleterOptions.staticDataSourceOptions.approveMatchCallback = this.checkDiscussionContextApproveMatchCallback
.bind(this);
return NoteTextEditorFactory.createSupportedEditor(null, options);
}
},
/**
* Emit an event and notify all NoteEditorComponents or any other listener which registered for the
* event with addEventListener.
*
* @param {String} eventName The name of the event to emit.
* @param {*} [eventData] Any data to pass to the listener.
*/
emitEvent: function(eventName, eventData) {
this.eventEmitter.emit(eventName, eventData);
},
extractInitData: function(responseMetadata) {
var targetTopic, autosave, initObject, initialNote, autosaveLoaded, content;
if (responseMetadata) {
initObject = responseMetadata.initialNote;
}
if (initObject) {
targetTopic = initObject.targetBlog;
} else {
targetTopic = this.getTargetTopicForCreate();
initObject = {};
}
// use provided content
content = this.getStaticParameter('content');
if (content) {
content = content.replace(/<br\s*\/?>/ig, '\n');
initObject.content = unescapeXML(content);
}
// save initial note object as copy
initialNote = Object.clone(initObject);
// force invocation of resetTargetTopic when initializing with initialNote and no topic is
// set in 'create' mode
if (!initialNote.targetBlog && this.action === 'create') {
initialNote.forceResetTargetTopic = true;
}
// check for autosave and if available replace initObject with it to init with autosave
if (this.autosaveHandler) {
autosave = this.autosaveHandler.load(responseMetadata);
if (autosave) {
autosaveLoaded = true;
initObject = autosave.noteData;
}
}
// force the target topic of the parent or edited note, or in case of create of the autosave
if (this.action !== 'create' || !autosaveLoaded
|| (this.initialTargetTopic && !this.noTargetTopicChangeIfModifiedOrAutosaved)) {
initObject.targetBlog = targetTopic;
}
return {
initObject: initObject,
initialNote: initialNote,
isAutosave: autosaveLoaded
};
},
getListeningEvents: function() {
return [];
},
getNoteData: function(resetDirtyFlag) {
var data = {};
data.content = this.editor.getContent();
data.targetTopic = this.targetTopic;
data.isHtml = this.editor.supportsHtml();
data.noteId = this.getFilterParameter('noteId');
if (this.action != 'edit') {
data.parentNoteId = this.parentPostId;
}
data.properties = [];
// add properties extracted from init object. Components can overwrite them.
if (this.noteProperties) {
communote.utils.propertyUtils.mergeProperties(data.properties, this.noteProperties);
}
this.components.appendNoteData(data, resetDirtyFlag);
// add predefined properties and let them overwrite properties added by components
if (this.predefinedNoteProperties) {
communote.utils.propertyUtils.merge(data.properties, this.predefinedNoteProperties);
}
if (data.properties.length === 0) {
delete data.properties;
}
if (resetDirtyFlag) {
this.dirty = false;
}
return data;
},
/**
* Creates an object that holds all the information to be submitted when sending the note via
* REST API.
*
* @param {boolean} publish whether the note will be published or stored as an autosave
* @param {String} content the content of the note
* @return {Object} an object with all information for storing the note
*/
getNoteDataForRestRequest: function(publish, content) {
var i, name;
var data = {};
var writeContainerElem = this.getWriteContainerElement();
var hiddenInputs = writeContainerElem.getElements('input[type=hidden]');
for (i = 0; i < hiddenInputs.length; i++) {
name = hiddenInputs[i].getProperty('name');
if (name != 'topicId') {
data[name] = hiddenInputs[i].value;
}
}
data.properties = [];
// add properties extracted from init object. Components can overwrite them.
if (this.noteProperties) {
communote.utils.propertyUtils.mergeProperties(data.properties, this.noteProperties);
}
data.text = content;
data.isHtml = this.editor.supportsHtml();
data.topicId = this.getTargetTopicId();
data.noteId = this.getFilterParameter('noteId');
if (this.action != 'edit') {
data.parentNoteId = this.parentPostId;
}
this.components.appendNoteDataForRestRequest(data, publish, false);
data.publish = publish === true ? true : false;
if (this.autosaveHandler) {
data.autosaveNoteId = this.autosaveHandler.getNoteId();
data.noteVersion = this.autosaveHandler.getVersion();
}
// add predefined properties and let them overwrite properties added by components
if (this.predefinedNoteProperties) {
communote.utils.propertyUtils.merge(data.properties, this.predefinedNoteProperties);
}
if (data.properties.length === 0) {
delete data.properties;
}
return data;
},
getSendButtonElement: function() {
return this.domNode.getElementById(this.widgetId + '-send-button');
},
getTargetTopicForCreate: function() {
var topic, defaultTopic;
// check for initialTargetTopic, which is the one provided as static parameter or if not defined set defaultBlogId
if (this.initialTargetTopic) {
topic = this.initialTargetTopic;
} else if (this.blogUtils.isDefaultBlogEnabled()) {
defaultTopic = this.blogUtils.getDefaultBlog();
// TODO is cloning really necessary
topic = {
id: defaultTopic.id,
title: defaultTopic.title,
alias: defaultTopic.alias
};
}
return topic;
},
getTargetTopicId: function() {
return this.targetTopic && this.targetTopic.id;
},
/**
* Return the element that wraps the body of the widget including textarea and additional
* controls like the attachment upload. This element will receive render style CSS class
* constructed from the #renderStyleCssClassPrefix and the current render style. The default
* imlementation looks for child node with class 'control-write-note-body-wrapper'.
*
* @return {Element} the wrapper element or null if the widget does not need such a wrapper
*/
getWrapperElement: function() {
return this.domNode.getElement('.control-write-note-body-wrapper');
},
/**
* Return the element that contains the input element for the post data and some (optional)
* additional hidden inputs that provide data to be sent to the server when sending the note.
*/
getWriteContainerElement: function() {
return this.domNode.getElement('.cn-write-note-editor');
},
/**
* @return {Boolean} whether there is an autosave, no matter if it was loaded or created later
* on
*/
hasAutosave: function() {
if (this.autosaveHandler) {
return this.autosaveHandler.hasAutosave();
}
return false;
},
hideUserInterface: function(errorMsg) {
var errorContainer = this.domNode.getElement('.cn-write-note-no-editor-content');
errorContainer.set('text', errorMsg);
if (!this.userInterfaceHidden) {
this.domNode.getElement('.cn-write-note').addClass('cn-hidden');
this.domNode.getElement('.cn-write-note-no-editor').removeClass('cn-hidden');
this.userInterfaceHidden = true;
this.eventEmitter.emit('userInterfaceHidden');
}
},
initAutosaveHandler: function() {
var action, noteId, options, autosaveTimeout;
if (this.autosaveDisabled) {
return;
}
action = this.action;
if (action === 'edit') {
noteId = this.getFilterParameter('noteId');
} else if (action === 'comment') {
noteId = this.parentPostId;
} else if (action === 'repost') {
noteId = this.getFilterParameter('repostNoteId');
}
options = this.getStaticParameter('autosaveOptions') || {};
if (!options.defaultDiscardCompleteCallback) {
options.defaultDiscardCompleteCallback = this.resetToNoAutosaveState.bind(this);
}
// prefer new option
if (!options.autosaveTimeout) {
// check old option (value is in seconds)
autosaveTimeout = this.getStaticParameter('draftTimer');
if (autosaveTimeout != null) {
options.autosaveTimeout = autosaveTimeout * 1000;
}
}
this.autosaveHandler = new communote.classes.NoteEditorAutosaveHandler(this, action, noteId,
options);
},
initContent: function(note) {
if (!note) {
// clearAll
this.resetTargetTopic();
this.components.initContent(null);
this.editor.resetContent(null);
this.noteProperties = null;
} else {
if (note.forceResetTargetTopic) {
this.resetTargetTopic();
} else {
this.setTargetTopic(note.targetBlog);
}
this.components.initContent(note);
this.editor.resetContent(note.content);
this.noteProperties = note.properties;
}
this.dirty = false;
this.modified = false;
},
isDirty: function() {
return this.dirty || this.editor.isDirty() || this.components.isDirty();
},
isModified: function() {
if (!this.modified) {
if (this.editor.isDirty()) {
this.modified = true;
}
}
return this.modified || this.components.isModified();
},
/**
* Callback that is invoked when the title of the target topic got loaded via REST API and that
* request resulted in an error.
*/
loadTargetTopicInfoErrorCallback: function(topicId, response) {
// check if still the same topic
if (this.initialTargetTopic && this.initialTargetTopic.id == topicId) {
delete this.initialTargetTopic.loadingTitleAsync;
delete this.initialTargetTopic.loadingTitle;
if (response.httpStatusCode == 404) {
this.initialTargetTopic.notFound = true;
// don't know which request (refresh, topic-info GET or topic-rights) is faster ->
// don't hide the interface while still loading, the topic-rights check callback will do it
if (this.firstDOMLoadDone) {
this.hideUserInterface(response.message);
} else {
this.initialTargetTopic.notFoundErrorMessage = response.message;
}
} else if (response.httpStatusCode == 403) {
this.initialTargetTopic.noReadAccess = true;
} else {
this.blogUtils.defaultErrorCallback(response);
}
}
},
/**
* Callback that is invoked when the title of the target topic got loaded via REST API.
*/
loadTargetTopicInfoSuccessCallback: function(topicInfo) {
// check if still the same topic
if (this.initialTargetTopic && this.initialTargetTopic.id == topicInfo.topicId) {
this.initialTargetTopic.title = topicInfo.title;
if (this.initialTargetTopic.loadingTitleAsync) {
delete this.initialTargetTopic.loadingTitleAsync;
delete this.initialTargetTopic.loadingTitle;
// if the topic is current targetTopic notify subclasses
if (this.targetTopic == this.initialTargetTopic) {
this.targetTopicTitleChanged(this.initialTargetTopic);
}
}
}
},
notePublished: function(topicId, resultObj) {
var noteChangedDescr, noteId;
this.stopPublishNoteFeedback();
if (resultObj.status == 'ERROR') {
this.showErrorMessage(resultObj);
this.startAutosaveJob();
} else {
// noteUtils are using REST API version 3.0 which just returns the noteId
noteId = resultObj.result;
if (resultObj.status == 'WARNING') {
// show warning message
showNotification(NOTIFICATION_BOX_TYPES.warning, '', resultObj.message);
} else if (resultObj.status == 'OK') {
// show success message
showNotification(NOTIFICATION_BOX_TYPES.success, '', resultObj.message);
}
// inform widgets and also provide the action, but treat repost like create
if (noteId) {
noteChangedDescr = {
action: this.action === 'repost' ? 'create' : this.action,
noteId: noteId,
topicId: topicId
};
if (this.action == 'comment') {
noteChangedDescr.parentNoteId = this.parentPostId;
noteChangedDescr.discussionId = this.getStaticParameter('discussionId');
}
E('onNotesChanged', noteChangedDescr);
}
// TODO fire internal event?
if (this.autosaveHandler) {
this.autosaveHandler.notePublished();
}
// no need to clean up if removing it anyway
if (this.publishSuccessBehavior.action != 'remove') {
this.initContent(null);
this.startAutosaveJob();
if (this.publishSuccessBehavior.action == 'renderStyle') {
this.setRenderStyle(this.publishSuccessBehavior.actionOptions);
}
} else {
this.widgetController.removeWidget(this);
}
}
},
/**
* Callback of the targetBlogIdChangeTracker which observes the filter parameter store for
* changes of the parameter targetBlogId.
*/
onTargetBlogIdChanged: function(oldTopicId, newTopicId) {
// update the initialTargetTopic so it will be set the next time an autosave is discarded or note was sent
this.setInitialTargetTopic(newTopicId, null);
// update the target topic, but not if modified or there is an autosave, also do nothing
// if not yet refreshed since the responseMetadata might contain autosave data
// TODO also check whether content is empty?
if (this.firstDOMLoadDone) {
if (!this.noTargetTopicChangeIfModifiedOrAutosaved) {
// CNT pre 3 behavior: change topic even if modified but not if the default topic
// fallback would be set
if (this.initialTargetTopic || !this.hasAutosave()) {
this.resetTargetTopic();
} else {
// if there is an autosave and user switched to a context where there is no
// topic force an access check as if there would be no autosave by passing null
// and not the topic of the autosave. This will ensure the editor is shown
// and we have same behavior as when the widget is refreshed under same conditions.
this.showOrHideUserInterfaceForTopic(null);
}
} else if (!this.isModified() && !this.hasAutosave()) {
this.resetTargetTopic();
}
}
},
/**
* Prepares the options for an autocompleter.
*
* @param {Function} [beforeRequestCallback] A callback function to be passed to the DataSource
* @returns {Object} the prepared options object
*/
prepareAutocompleterOptions: function(beforeRequestCallback) {
var preparedOptions = {};
preparedOptions.autocompleterOptions = {};
if (beforeRequestCallback) {
preparedOptions.dataSourceOptions = {};
preparedOptions.dataSourceOptions.beforeRequestCallback = beforeRequestCallback;
}
return preparedOptions;
},
publishNote: function() {
// do nothing if there are still running uploads
if (this.getSendButtonElement().disabled
|| !this.components.canPublishNote()) {
// TODO show an error message?
return false;
}
// stop autosaves
this.stopAutosaveJob();
this.startPublishNoteFeedback();
this.publishNoteWhenAutosaveDone();
},
publishNoteWhenAutosaveDone: function() {
var content;
// TODO maybe have a more generic solution like letting the autosaveHandler disable publishing temporarily?
if (this.autosaveHandler && this.autosaveHandler.isAutosaveInProgress()) {
// wait for end of autosave
this.publishNoteWhenAutosaveDone.delay(1000, this);
} else {
content = this.editor.getContent();
this.sendNote(content);
}
},
refresh: function() {
this.cleanup();
this.eventEmitter.emit('widgetRefreshing');
this.parent();
},
refreshComplete: function(responseMetadata) {
var initData;
// set a marker flag to be able to react depending on the current working context (pre & post init)
this.initializingAfterRefresh = true;
initData = this.extractInitData(responseMetadata);
this.initialNote = initData.initialNote;
// TODO better name
this.refreshView(initData.isAutosave);
this.refreshEditor();
this.eventEmitter.emit('widgetRefreshed');
this.initContent(initData.initObject);
this.contentInitializedAfterRefresh(initData.isAutosave);
// TODO maybe let autosaveHandler.editorInitialized start job
if (this.autosaveHandler) {
this.autosaveHandler.editorInitialized();
this.startAutosaveJob();
}
init_tips(this.domNode);
// check access rights but not if an autosave is loaded as we might get stuck. The latter can
// only happen if the topic isn't overridden by the current initial topic (override option
// false or no topic set and default topic fallback would take effect)
if (this.action == 'create'
&& (!this.hasAutosave() || this.initialTargetTopic
&& !this.noTargetTopicChangeIfModifiedOrAutosaved)) {
this.showOrHideUserInterfaceForTopic(this.getTargetTopicId());
}
this.initializingAfterRefresh = false;
},
refreshEditor: function() {
var writeContainerElem, classToAdd, classToRemove;
// apply some CSS classes before refreshing the actual editor component as it might
// work on the resulting styles (like expanding textarea)
writeContainerElem = this.getWriteContainerElement();
if (this.editor.supportsHtml()) {
classToAdd = this.richTextEditorCssClass;
classToRemove = this.plainTextEditorCssClass;
this.domNode.getElement('.cn-write-note-editor-fields').removeClass('cn-border');
} else {
classToAdd = this.plainTextEditorCssClass;
classToRemove = this.richTextEditorCssClass;
// if using plain text editor add 'cn-border' class to textarea wrapper to
// get correct look
this.domNode.getElement('.cn-write-note-editor-fields').addClass('cn-border');
}
if (classToAdd) {
writeContainerElem.addClass(classToAdd);
}
if (classToRemove) {
writeContainerElem.removeClass(classToRemove);
}
this.editor.refresh(writeContainerElem, this.editorRefreshCompleteCallback);
},
refreshView: function(autosaveLoaded) {
this.ajaxLoadingOverlay = this.widgetController.createAjaxLoadingOverlay(this.domNode,
false);
if (autosaveLoaded && this.renderStyle !== 'full') {
this.setRenderStyle('full');
}
},
remove: function(deleteAutosave) {
var hasOnlineAutosave;
if (deleteAutosave) {
if (this.action != 'create') {
hasOnlineAutosave = this.autosaveHandler && this.autosaveHandler.hasOnlineAutosave();
this.eventEmitter.emit('noteDiscarded', hasOnlineAutosave);
if (this.autosaveHandler) {
this.autosaveHandler.discard(false);
}
}
}
this.widgetController.removeWidget(this);
},
removeEventListener: function(eventName, fn, context) {
this.eventEmitter.off(eventName, fn, context);
},
renderStyleChanged: function(oldStyle, newStyle) {
var oldEditor, content;
this.eventEmitter.emit('renderStyleChanged', {
oldStyle: oldStyle,
newStyle: newStyle
});
// ignore any style changes before the editor is set (e.g. during init)
if (newStyle === 'full' && this.editor) {
if (!instanceOf(this.editor, NoteTextEditorFactory.getSupportedEditorType())) {
oldEditor = this.editor;
this.editor = this.createEditor();
if (this.firstDOMLoadDone) {
content = oldEditor.getContent();
oldEditor.resetContent(null);
this.refreshEditor();
if (!oldEditor.supportsHtml()) {
this.editor.resetContentFromPlaintext(content);
} else {
this.editor.resetContent(content);
}
}
oldEditor.cleanup();
}
} else if (newStyle === 'simulate' && this.editor) {
this.editor.unFocus();
}
},
/**
* Reset the cache of an autocompleter.
*
* @param {Autocompleter} autocompleter The autocompleter whose cache should be reset. If null
* nothing will happen.
*/
resetAutocompleterCache: function(autocompleter) {
if (autocompleter) {
autocompleter.resetQuery(false);
}
},
/**
* Helper which replaces the target topic in 'create' mode with the topic returned by
* getTargetTopicForCreate.
*/
resetTargetTopic: function() {
if (this.action === 'create') {
this.targetTopic = this.getTargetTopicForCreate();
this.eventEmitter.emit('targetTopicReset', this.targetTopic);
this.targetTopicChanged();
}
},
/**
* Reset the editor to the initialNote. Should only be called if there is no autosave or the
* autosave was removed.
*/
resetToNoAutosaveState: function() {
// restore original note
this.initContent(this.initialNote);
this.startAutosaveJob();
},
/**
* Send the note.
* @param {String} content The text/HTML content of the note
* @param {boolean} [ignoreUncommittedOptions] if false a popup will warn the user when he
* publishes a note and there are uncommitted inputs in the blog and user input
* fields. If true there will be no warning.
*/
sendNote: function(content, ignoreUncommittedOptions) {
var warningMsg, cancelFunction, buttons;
var successCallback, errorCallback, data, options;
if (!ignoreUncommittedOptions) {
warningMsg = this.components.getUnconfirmedInputWarning();
if (warningMsg) {
cancelFunction = function() {
this.stopPublishNoteFeedback();
this.startAutosaveJob();
}.bind(this);
buttons = [];
buttons.push({
type: 'yes',
action: this.sendNote.bind(this, content, true)
});
buttons.push({
type: 'no',
action: cancelFunction
});
showDialog(this.getSendButtonElement().value, warningMsg, buttons, {
onCloseCallback: cancelFunction,
width: 300
});
return;
}
}
data = this.getNoteDataForRestRequest(true, content);
options = {};
options.defaultErrorMessage = getJSMessage('error.blogpost.create.failed');
// can use note published callback for success and error since state is evaluated there
successCallback = this.notePublished.bind(this, data.topicId);
errorCallback = successCallback;
if (this.action == 'edit') {
noteUtils.updateNote(data.noteId, data, successCallback, errorCallback, options);
} else {
noteUtils.createNote(data, successCallback, errorCallback, options);
}
},
/**
* AutocompleterRequestDataSource callback implementation that sets the current topic before
* sending the request.
*/
setCurrentTopicBeforeRequestCallback: function(request, postData, queryParam) {
postData['blogId'] = this.getTargetTopicId();
},
setInitialTargetTopic: function(id, title) {
var topicData, topic;
if (id != undefined) {
topic = {};
topic.id = id;
this.initialTargetTopic = topic;
if (!title) {
topic.title = ' ';
topic.loadingTitle = true;
if (this.blogUtils.getTopicInfo(id, this.loadTargetTopicInfoSuccessCallback
.bind(this), this.loadTargetTopicInfoErrorCallback.bind(this, id))) {
delete topic.loadingTitle;
} else {
topic.loadingTitleAsync = true;
}
} else {
topic.title = title;
}
} else {
this.initialTargetTopic = undefined;
}
},
setRenderStyle: function(newRenderStyle) {
var oldStyle, elem, transitions;
if (!this.supportedRenderStyles.contains(newRenderStyle)) {
// take the default render style if the provided is not supported
newRenderStyle = this.supportedRenderStyles[0];
}
// check if change is allowed
transitions = this.allowedRenderStyleTransitions;
if (newRenderStyle == this.renderStyle
|| transitions
&& (transitions[this.renderStyle] && !transitions[this.renderStyle]
.contains(newRenderStyle))) {
return;
}
oldStyle = this.renderStyle;
this.renderStyle = newRenderStyle;
this.setFilterParameter('renderStyle', newRenderStyle);
// set the new style css class to the wrapper element if it exists
elem = this.getWrapperElement();
if (elem && this.renderStyleCssClassPrefix) {
elem.removeClass(this.renderStyleCssClassPrefix + oldStyle);
elem.addClass(this.renderStyleCssClassPrefix + newRenderStyle);
}
this.renderStyleChanged(oldStyle, newRenderStyle);
},
setTargetTopic: function(newTargetTopic) {
// only allow changing of target topic when in a mode where notes are created
if (!this.targetTopic || this.action === 'create' || this.action === 'repost') {
// ignore if nothing changed
if ((!newTargetTopic && this.targetTopic) ||
(newTargetTopic && newTargetTopic.id != this.getTargetTopicId())) {
this.targetTopic = newTargetTopic;
this.targetTopicChanged();
this.dirty = true;
this.modified = true;
}
}
},
showErrorMessage: function(errObj) {
var message;
if (errObj.errors && typeOf(errObj.errors) == 'array' && errObj.errors.length > 0) {
// just take 1st error
message = errObj.errors[0].message;
} else {
message = errObj.message;
}
hideNotification();
showNotification(NOTIFICATION_BOX_TYPES.error, '', message, {
duration: ''
});
},
showOrHideUserInterfaceForTopic: function(topicId) {
var result = this.topicWriteAccessEvaluator.checkWriteAccess(topicId, this.initialTargetTopic);
if (result.writeAccess === true) {
// make sure the editor is shown, especially if it was hidden before
this.showUserInterface();
} else {
// if the user has write access to one of the subtopics show the interface but remove the topic
if (result.subtopicWriteAccess === true) {
this.setTargetTopic(null);
this.showUserInterface();
} else {
this.hideUserInterface(result.message || communote.i18n.getMessage('blogpost.create.no.writable.blog.selected'));
}
}
},
showUserInterface: function() {
if (this.userInterfaceHidden) {
this.domNode.getElement('.cn-write-note-no-editor').addClass('cn-hidden');
this.domNode.getElement('.cn-write-note').removeClass('cn-hidden');
this.userInterfaceHidden = false;
this.eventEmitter.emit('userInterfaceShown');
}
},
/**
* Starts the autosave draft job.
*/
startAutosaveJob: function() {
if (this.autosaveHandler) {
// TODO necessary to set dirty flag here?
this.dirty = false;
this.autosaveHandler.startAutomaticSave();
}
},
/**
* Disables the send button and shows an AJAX loading overlay
*/
startPublishNoteFeedback: function() {
// disable send button
this.getSendButtonElement().disabled = true;
this.ajaxLoadingOverlay.setStyle('display', '');
},
/**
* Stops the autosave job.
*/
stopAutosaveJob: function() {
// TODO necessary to set dirty flag here?
this.dirty = false;
if (this.autosaveHandler) {
this.autosaveHandler.stopAutomaticSave();
}
},
/**
* Re-enables the send button and hides the AJAX loading overlay
*/
stopPublishNoteFeedback: function() {
this.ajaxLoadingOverlay.setStyle('display', 'none');
this.getSendButtonElement().disabled = false;
},
/**
* Method that is invoked when the target topic was added, removed or replaced.
*/
targetTopicChanged: function() {
var newId = this.getTargetTopicId();
// don't check for write access here while still initializing because not all information
// might be available yet and it is done after init anyway
if (!this.initializingAfterRefresh) {
this.showOrHideUserInterfaceForTopic(newId);
}
this.eventEmitter.emit('targetTopicChanged', this.targetTopic);
// invalidate caches of autocompeters to let them restart a query for the same term
// after topic (request parameter) changed
this.resetAutocompleterCache(this.editor.getUserAutocompleter());
this.resetAutocompleterCache(this.editor.getTagAutocompleter());
},
/**
* Called when the title of the target topic changed.
*/
targetTopicTitleChanged: function(topicData) {
this.eventEmitter.emit('targetTopicTitleChanged', topicData.title);
}
});
| apache-2.0 |
mingjunli/GithubApp | app/src/main/java/com/anly/githubapp/ui/base/adapter/ArrayFragmentPagerAdapter.java | 834 | package com.anly.githubapp.ui.base.adapter;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.Arrays;
import java.util.List;
/**
* Created by mingjun on 16/6/28.
*/
public abstract class ArrayFragmentPagerAdapter<T> extends FragmentPagerAdapter {
protected List<T> mList;
public ArrayFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return mList != null ? mList.size() : 0;
}
public void setList(List<T> list){
this.mList = list;
notifyDataSetChanged();
}
public List<T> getList(){
return mList;
}
public void setList(T[] list){
setList(Arrays.asList(list));
}
}
| apache-2.0 |
oehme/analysing-gradle-performance | my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p231/Test4629.java | 2111 | package org.gradle.test.performance.mediummonolithicjavaproject.p231;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test4629 {
Production4629 objectUnderTest = new Production4629();
@Test
public void testProperty0() {
String value = "value";
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
String value = "value";
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
String value = "value";
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
} | apache-2.0 |
oehme/analysing-gradle-performance | my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p54/Production1090.java | 2129 | package org.gradle.test.performance.mediummonolithicjavaproject.p54;
import org.gradle.test.performance.mediummonolithicjavaproject.p50.Production1009;
import org.gradle.test.performance.mediummonolithicjavaproject.p52.Production1049;
public class Production1090 {
private Production1009 property0;
public Production1009 getProperty0() {
return property0;
}
public void setProperty0(Production1009 value) {
property0 = value;
}
private Production1049 property1;
public Production1049 getProperty1() {
return property1;
}
public void setProperty1(Production1049 value) {
property1 = value;
}
private Production1089 property2;
public Production1089 getProperty2() {
return property2;
}
public void setProperty2(Production1089 value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
} | apache-2.0 |
mrniko/redisson | redisson/src/main/java/org/redisson/cache/CachedValueReference.java | 763 | /**
* Copyright (c) 2013-2020 Nikita Koksharov
*
* 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.redisson.cache;
/**
*
* @author Nikita Koksharov
*
*/
public interface CachedValueReference {
CachedValue<?, ?> getOwner();
}
| apache-2.0 |
Esri/route-planner-csharp | RoutePlanner_DeveloperTools/Source/ArcLogisticsApp/Converters/ClusterSizeConverter.cs | 1933 | /*
| Version 10.1.84
| Copyright 2013 Esri
|
| 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 System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Globalization;
using ESRI.ArcLogistics.App.Mapping;
using System.ComponentModel;
namespace ESRI.ArcLogistics.App.Converters
{
/// <summary>
/// Converts drawing color to SolidColorBrush
/// </summary>
[ValueConversion(typeof(IDictionary<string, object>), typeof(object))]
[EditorBrowsable(EditorBrowsableState.Never)]
public class ClusterSizeConverter : IValueConverter
{
private const int EXPANDANBLE_CLUSTER_SIZE = 22;
private const int NONEXPANDANBLE_CLUSTER_SIZE = 28;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
IDictionary<string, object> attributes = value as IDictionary<string, object>;
if (attributes != null)
{
int count = (int)attributes[ALClusterer.COUNT_PROPERTY_NAME];
if (count > ALClusterer.CLUSTER_COUNT_TO_EXPAND)
return NONEXPANDANBLE_CLUSTER_SIZE;
}
return EXPANDANBLE_CLUSTER_SIZE;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
}
| apache-2.0 |
arkhipov/transaction-cdi | src/main/java/org/softus/cdi/transaction/impl/DefaultTransactionSupport.java | 3424 | /*
* Copyright 2012 The Softus Team.
*
* 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.softus.cdi.transaction.impl;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Typed;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.TransactionManager;
import javax.transaction.TransactionSynchronizationRegistry;
import org.softus.cdi.transaction.TransactionSupport;
/**
* <p>
* Transaction support that uses most popular JNDI locations for
* TransactionManager and TransactionSynchronizationRegistry to lookup them.
* </p>
*
* <p>
* JNDI locations for TransactionManager.
* <ul>
* <li>java:appserver/TransactionManager</li>
* <li>java:jboss/TransactionManager</li>
* <li>java:/TransactionManager</li>
* <li>java:pm/TransactionManager</li>
* <li>java:comp/TransactionManager</li>
* </ul>
* </p>
*
* <p>
* JNDI locations for TransactionSynchronizationRegistry.
* <ul>
* <li>java:comp/TransactionSynchronizationRegistry</li>
* </ul>
* </p>
*
* @author Vlad Arkhipov
*/
@ApplicationScoped
@Typed(TransactionSupport.class)
class DefaultTransactionSupport
extends AbstractTransactionSupport
{
private static final String[] TRANSACTION_MANAGER_JNDI_NAMES = {
"java:appserver/TransactionManager", // Glassfish
"java:jboss/TransactionManager", // JBoss
"java:/TransactionManager", // JBoss
"java:pm/TransactionManager", // TopLink
"java:comp/TransactionManager" // Some servlet containers
};
private static final String TRANSACTION_SYNCHRONIZATION_REGISTRY_JNDI_NAME =
"java:comp/TransactionSynchronizationRegistry";
/**
* Creates a new transaction support.
*/
public DefaultTransactionSupport()
{
}
/**
* {@inheritDoc}
*/
@Override
protected TransactionManager lookupTransactionManager()
{
InitialContext ctx;
try
{
ctx = new InitialContext();
}
catch (NamingException e)
{
throw new RuntimeException(e);
}
for (String jndiName : TRANSACTION_MANAGER_JNDI_NAMES)
{
try
{
return (TransactionManager) ctx.lookup(jndiName);
}
catch (NamingException e)
{
// Try next.
}
}
throw new RuntimeException();
}
/**
* {@inheritDoc}
*/
@Override
protected TransactionSynchronizationRegistry lookupSynchronizationRegistry()
{
try
{
return (TransactionSynchronizationRegistry) new InitialContext()
.lookup(TRANSACTION_SYNCHRONIZATION_REGISTRY_JNDI_NAME);
}
catch (NamingException e)
{
throw new RuntimeException(e);
}
}
}
| apache-2.0 |
BrianGladman/pthreads | build.vs/run_tests/run_tests.py | 2615 |
from __future__ import print_function
from os import chdir, walk
from os.path import join, dirname, normpath, split, splitext
import shutil
import string
import copy
import subprocess
import code
import sys
import re
from time import sleep
# timeout for running each test
test_time_limit = 60
vs_version = 19
if len(sys.argv) > 1:
vs_version = int(sys.argv[1])
build_dir_name = 'build.vs'
script_dir = dirname(__file__)
chdir(script_dir)
t = join(script_dir, '..\\..\\' + build_dir_name)
exe_dir = normpath(join(t, 'build_tests'))
def split_pnx(p):
h, t = split(p)
n, x = splitext(t)
if x == '.filters':
n, _ = splitext(x)
return (h, n, x)
exe = []
for root, dirs, files in walk(exe_dir, topdown=False):
for x in files:
h, t = splitext(x)
if t == '.exe':
exe.append(join(root, x))
build_fail = 0
run_ok = 0
run_fail = 0
timed_out_fail = 0
print(len(exe))
fails, timed_out = [], []
for ef in exe:
fdn, fx = splitext(ef)
fd, fn = split(fdn)
fd = fd[fd.find('tests') + 6 : fd.find('\\x64\\')]
fd = fd + ': ' + fn
print(fd)
try:
prc = subprocess.Popen( ef, stdout = subprocess.PIPE,
stderr = subprocess.STDOUT, creationflags = 0x08000000 )
except Exception as str:
print(fd, ' ... ERROR (', str, ')')
run_fail += 1
continue
for _ in range(test_time_limit):
sleep(1)
if prc.poll() is not None:
output = prc.communicate()[0]
break
else:
print(fd + '... ERROR (test timed out)')
prc.kill()
timed_out_fail += 1
timed_out += [fd]
continue
if output:
op = output.decode().replace('\n', '')
if prc.returncode:
t = fd + ' ...ERROR {}'.format(prc.returncode)
print(t, end=' ')
fails += [t + ' ' + op]
run_fail += 1
else:
run_ok += 1
if output:
op = output.decode().replace('\n', '')
if 'PASS' in op:
print(fd + ' ... PASS')
elif 'SKIPPED' in op:
print(fd + ' ... SKIPPED')
else:
print('output from ' + op)
else:
print()
# else:
# print("Build failure for {0}".format(i))
# build_fail += 1
print(build_fail + run_ok + run_fail, "tests:")
if build_fail > 0:
print("\t{0} failed to build".format(build_fail))
if run_ok > 0:
print("\t{0} ran correctly".format(run_ok))
if run_fail > 0:
print("\t{0} failed".format(run_fail))
if timed_out_fail > 0:
print("\t{0} timed out".format(timed_out_fail))
print('Failed:')
for t in fails:
print(t)
print('Timed out:')
for t in timed_out:
print(t)
if len(sys.argv) == 1:
try:
input(".. completed - press ENTER")
except:
pass
else:
sys.exit(build_fail + run_fail)
| apache-2.0 |
wavelets/smile | Smile/test/smile/mds/IsotonicMDSTest.java | 43361 | /******************************************************************************
* Confidential Proprietary *
* (c) Copyright Haifeng Li 2011, All Rights Reserved *
******************************************************************************/
package smile.mds;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import smile.math.Math;
/**
*
* @author Haifeng Li
*/
public class IsotonicMDSTest {
double[][] swiss = {
{0, 80.5395828149116, 87.3528682986426, 31.3811424266230, 27.2185598443415, 83.1457882276667, 98.6354505236327, 101.038458024655, 95.111377342566, 86.204967374276, 100.783741248279, 45.777326265303, 51.4295255665459, 44.2325773610356, 53.819323667248, 58.3449877881554, 18.9260561132001, 19.7833894972525, 22.6758924851923, 56.7144990280263, 43.8731455448547, 39.5378755119695, 35.4301058423483, 38.96405523043, 55.9127320026486, 41.6070054197607, 48.9555921218404, 44.3087756544908, 17.8600111982048, 32.9733164846971, 114.4407379389, 112.986054006678, 116.652053561007, 108.255623410518, 101.159466190762, 107.109196617284, 113.312929535865, 98.4551517189426, 24.5235723335733, 17.3507607902363, 7.90996839437428, 29.1451814199191, 21.8883553516476, 11.7002606808566, 58.9978338585409, 53.1034923521985, 52.9202881700393},
{80.5395828149116, 0, 11.1100675065456, 52.2083795956166, 80.6909065508624, 12.6977517695063, 28.2865710187714, 27.1912191709015, 16.5314518418680, 12.7914659050478, 25.3823344080090, 79.8551338362162, 86.0068305426959, 82.9902289429304, 87.1617484909521, 68.025433478957, 83.059145191845, 81.9459754960547, 92.777185234302, 87.6142111760415, 82.6346301498349, 81.5557625186596, 72.020691471271, 82.6826438861264, 87.0574729704464, 81.0821318170656, 84.629772538983, 79.5600050276519, 72.1379539493601, 79.381594844145, 44.6560958884675, 42.6617580509758, 47.7932589388922, 36.7127280381069, 24.7399353273205, 34.3396039581123, 43.0558288736844, 23.4429115085989, 82.0567389066858, 83.562865556418, 80.680570151679, 82.0976028882695, 80.7793717479902, 82.9105910001853, 81.5358816718137, 41.2589154001896, 40.865022941386},
{87.3528682986426, 11.1100675065456, 0, 60.1580160909583, 89.6933531539545, 9.3983455990935, 32.6666879251632, 30.2628088583991, 16.0260069886419, 15.3938429250139, 27.2520476294902, 89.5577712987544, 95.7273571138366, 92.7788278649822, 96.809846606634, 77.7820673420294, 91.1237619943338, 89.3876619002869, 99.5799804177527, 97.580959208239, 92.1780825359261, 90.7009062799264, 81.2423387157214, 91.7279128728, 96.637932510997, 90.6392238492806, 93.9584248484403, 89.1486533829872, 79.868038663786, 88.4964406063882, 47.0453621518636, 45.690681763353, 50.5585798851194, 39.5449566948808, 25.8122529043863, 37.1515221760832, 45.5625240740677, 26.300853598315, 90.5374419784434, 89.2963722667388, 87.3913176465489, 89.2997222840027, 89.0410854605895, 89.599400109599, 86.152269848217, 50.9414457980925, 47.3256262504787},
{31.3811424266230, 52.2083795956166, 60.1580160909583, 0, 30.9293081073599, 57.2395842053382, 68.2130955169167, 70.8811829754555, 66.0752601205625, 58.8507612525106, 70.7874678174040, 37.5266905015617, 44.2570898275067, 39.0670654132096, 46.2634034632127, 38.1654935773140, 30.9961433084828, 37.3975346781041, 45.5386034041449, 48.3942651561112, 38.3628935300767, 35.0133188943865, 26.3134357315802, 35.6951663394359, 47.1662686673432, 36.0325075452708, 41.956573978341, 36.1951999580055, 25.3346817623589, 30.8134532306913, 83.1954542027387, 81.9325216260308, 85.4087401850654, 77.3979075944563, 70.7203824933095, 76.383205614847, 82.1083802056769, 68.7456442256526, 31.8909469912701, 39.1622318056568, 32.2258048774581, 42.4549467082459, 28.9782677191029, 33.4289455412521, 63.7638212468481, 29.7317271614012, 35.5757445459684},
{27.2185598443415, 80.6909065508624, 89.6933531539545, 30.9293081073599, 0, 86.7531446115932, 92.0675083837941, 95.5561614967868, 93.5056153394009, 86.3493972185099, 96.3281500912376, 19.8834001116509, 25.6827198715401, 17.7139182565575, 28.2794200789196, 37.1442000856123, 11.9611705112836, 29.6525294030712, 33.5706732133867, 30.2653663450486, 17.9570292643299, 17.0648644881816, 14.2678099230400, 15.2109039836559, 31.5605386519305, 16.7751274212746, 26.0484164585873, 18.7172006453957, 23.1488660629414, 9.6692088611220, 105.511669970672, 104.065510136644, 106.992315611917, 100.548346580140, 96.758894164826, 99.8739705829302, 104.595363185946, 93.8818347711633, 10.7847855796951, 38.9374742375517, 28.0509108586513, 37.7871353770036, 10.1590403090056, 27.5032743505205, 70.8689099676297, 47.5577848516938, 57.4402202293828},
{83.1457882276667, 12.6977517695063, 9.3983455990935, 57.2395842053382, 86.7531446115932, 0, 35.7939715594679, 33.5941676485666, 20.365902877113, 13.7297523648462, 30.784600046127, 87.8413484641487, 94.4191717820062, 90.5840471606342, 95.3492134209821, 77.0157574785836, 87.8993907828717, 84.7333558877494, 95.5235384604235, 96.2569628650312, 90.1949311214328, 88.6300315920061, 78.899017104144, 89.7936907583155, 95.59873900842, 88.5245480078831, 92.9513856809031, 87.6268366426633, 75.5287501551561, 85.968778635037, 53.2649002627434, 50.9351754684324, 56.1976414095823, 44.4144357163299, 31.5538032572937, 42.4485582794045, 51.6489312570938, 30.5986535651489, 87.0620611977456, 84.321636606508, 83.1063926542357, 83.9736416978566, 86.094192603218, 85.3982224639366, 80.3921818338077, 48.3990661066926, 42.4672532664876},
{98.6354505236327, 28.2865710187714, 32.6666879251632, 68.2130955169167, 92.0675083837941, 35.7939715594679, 0, 5.5701077188866, 18.2099533222905, 25.7643338745639, 8.45444261912044, 85.3182213832426, 90.7539332480967, 89.1243872349202, 90.3892742530882, 68.944488539694, 96.6674841919453, 98.2453439100296, 108.670741232403, 90.1975614969717, 88.6667040100172, 89.7309249924462, 80.746170807042, 90.5755071749532, 90.7797471906592, 88.4800226039754, 91.3484214422997, 86.010272060958, 87.4626897596912, 89.2034892815298, 23.6600845307028, 18.9520157239276, 24.6061476058322, 11.6607075257036, 12.8641711742343, 12.5576311460402, 22.1210781834882, 11.8953940666125, 93.5745846905024, 101.741552966327, 98.080563314043, 97.5627229017313, 93.806259919048, 99.195261983625, 99.5018597816141, 53.568427268308, 59.4673893827533},
{101.038458024655, 27.1912191709015, 30.2628088583991, 70.8811829754555, 95.5561614967868, 33.5941676485666, 5.5701077188866, 0, 15.1894733285917, 23.9461562677604, 4.14155767797576, 89.5893386514266, 95.0728252446513, 93.2475356242727, 94.9406425088855, 73.565559876888, 99.9257204127146, 100.708254378675, 111.469592714785, 94.7275693766076, 92.90174863801, 93.6734199226227, 84.617553734435, 94.6647326093514, 95.1799747846153, 92.4468760964912, 95.4162459961615, 90.1691388447289, 90.1814282432919, 92.9170253505782, 24.2312298491018, 19.4363165234568, 25.4604713232100, 12.2331516789419, 10.2773342847258, 12.0677255520666, 22.5275387026635, 9.71796789457549, 97.0829109575934, 103.999648557098, 100.607621977661, 99.8954833813822, 97.1444599552646, 101.960728224155, 100.211787729788, 55.8840129196177, 60.4329289377902},
{95.111377342566, 16.5314518418680, 16.0260069886419, 66.0752601205625, 93.5056153394009, 20.365902877113, 18.2099533222905, 15.1894733285917, 0, 12.9897690510648, 11.9822201615560, 90.275481167369, 96.490465850259, 93.943321210185, 96.756459732671, 76.363413360064, 96.4633966849602, 95.4325080881772, 105.875967055796, 97.1329959385584, 93.3027523709778, 93.2851676313014, 83.4293167897233, 93.9934620066736, 97.1225148974222, 92.6338685362972, 95.9737052530536, 90.5226076734426, 85.3784756247147, 91.7156197166, 34.7524330083521, 32.0942378005772, 37.5723156060416, 25.0046815616596, 13.2854243439944, 23.150207342484, 33.1961458606267, 11.9229023312279, 94.4282928999566, 97.0590768552844, 94.6233190075258, 94.6205712305733, 94.0732693170595, 96.4000539418936, 92.3353610487336, 52.7669176662803, 52.8193676599787},
{86.204967374276, 12.7914659050478, 15.3938429250139, 58.8507612525106, 86.3493972185099, 13.7297523648462, 25.7643338745639, 23.9461562677604, 12.9897690510648, 0, 21.8580168359346, 85.0672063723736, 92.2278271456072, 88.3936790726577, 92.4995870261051, 73.4789248696522, 89.0442945954428, 85.3932836937426, 96.5450822155121, 93.0404836616835, 87.8688938134537, 88.0378872985943, 77.0799429164293, 88.4724386461682, 93.621580845444, 87.2788204549076, 92.0045781469596, 85.5392634992843, 76.0600841440502, 85.561547438087, 45.8515964825654, 42.3808919207701, 48.3090509118115, 35.1632819856168, 25.1697357951966, 33.3171487375496, 44.1843456441306, 19.9700400600500, 86.7111734437956, 87.262065641377, 85.4641772908392, 83.845164440175, 87.0678361968414, 87.6784631480274, 80.1428824038667, 44.4218696139638, 41.4314192370959},
{100.783741248279, 25.3823344080090, 27.2520476294902, 70.7874678174040, 96.3281500912376, 30.784600046127, 8.45444261912044, 4.14155767797576, 11.9822201615560, 21.8580168359346, 0, 90.947556866581, 96.543024605613, 94.5967885289982, 96.4230475560693, 75.135531541342, 100.237199182739, 100.810465726531, 111.389907980930, 96.4281748245812, 94.1496914493085, 94.62926661451, 85.51631949517, 95.6140580667927, 96.656629881245, 93.6230441718277, 96.6532591276673, 91.4435459723648, 90.2677821816843, 93.766199133803, 26.1635242274431, 22.0996583684002, 27.7923028912683, 14.7588109277137, 8.76368073357308, 14.4586479312555, 24.5351278782076, 9.80246907671735, 97.6011787838651, 103.376362868888, 100.330514301483, 99.960572727451, 97.541322525379, 101.673209844088, 99.76699303878, 56.6957882033578, 59.9729805829258},
{45.777326265303, 79.8551338362162, 89.5577712987544, 37.5266905015617, 19.8834001116509, 87.8413484641487, 85.3182213832426, 89.5893386514266, 90.275481167369, 85.0672063723736, 90.947556866581, 0, 12.2504081564656, 7.80116017012854, 11.8583304052468, 22.1204068678675, 29.2489042529801, 46.0688408797096, 49.2677064617382, 13.3608532661653, 4.78686745168487, 15.113570061372, 12.9643511214407, 10.9321727026241, 18.5565190701274, 12.0134965767673, 18.601655840274, 5.57853027239254, 37.7121147643566, 15.8147526063483, 96.5027776802305, 95.27562962269, 97.4429084130805, 92.559405788931, 91.3520114721072, 92.4412873125423, 95.8430153949676, 88.6985123888783, 24.5928851499778, 55.2925211941, 45.465811331153, 51.7703583143868, 26.1000478926764, 43.8737609511653, 82.3388268072845, 48.0676408824065, 62.8917013603544},
{51.4295255665459, 86.0068305426959, 95.7273571138366, 44.2570898275067, 25.6827198715401, 94.4191717820062, 90.7539332480967, 95.0728252446513, 96.490465850259, 92.2278271456072, 96.543024605613, 12.2504081564656, 0, 10.6707825392517, 8.46773287249899, 23.5020190621997, 33.6767115377972, 54.7416258435937, 57.1156230816053, 7.77077216240445, 11.9273467292605, 13.6276373594251, 23.1507429686393, 15.3207343166051, 7.5707925608882, 10.9641050706385, 9.86377716698831, 9.7689559319305, 46.7637263271438, 18.7677622533961, 99.9755650146574, 99.2066434267383, 100.750349379047, 97.3064031808801, 96.329499635366, 97.3116339396272, 99.4140135996933, 94.8628146324997, 32.0698066723203, 62.8626311889663, 52.5431489349468, 61.5292003848579, 30.0517886322928, 50.4311847967109, 92.9919614805495, 56.9649506275569, 72.6278431457248},
{44.2325773610356, 82.9902289429304, 92.7788278649822, 39.0670654132096, 17.7139182565575, 90.5840471606342, 89.1243872349202, 93.2475356242727, 93.943321210185, 88.3936790726577, 94.5967885289982, 7.80116017012854, 10.6707825392517, 0, 12.2699674001197, 25.2133476555574, 27.2297062048051, 45.5622914261344, 49.244881967571, 13.0425495973755, 6.04483250388297, 11.7242526414267, 15.9920011255627, 11.6349860335112, 16.9487728169328, 7.04343666117613, 16.8352873453351, 8.0494782439609, 37.8720332171379, 12.6597353842804, 100.633386110177, 99.2300987604064, 101.439562794799, 96.6336426923874, 95.1075922311148, 96.5343819579325, 99.8993038013779, 92.7452424655842, 23.5258602393196, 54.7946128738948, 44.794465059871, 51.6691406934545, 24.1286468746177, 43.0470486793230, 83.6929393676671, 51.3133510891659, 65.6031249255704},
{53.819323667248, 87.1617484909521, 96.809846606634, 46.2634034632127, 28.2794200789196, 95.3492134209821, 90.3892742530882, 94.9406425088855, 96.756459732671, 92.4995870261051, 96.4230475560693, 11.8583304052468, 8.46773287249899, 12.2699674001197, 0, 22.3437776573255, 35.8051728106429, 55.8888548818098, 57.4079167014446, 6.3545574196792, 11.0248854869336, 16.9180377112714, 23.3097061328538, 15.7957082778836, 11.1837560774545, 15.1742578072208, 17.1521893646263, 12.7679285712288, 47.5468148249701, 21.7999633027214, 100.230694400468, 99.259405599671, 100.788255268161, 97.0752264998645, 96.7045500480717, 97.4243686148389, 99.7203068587336, 94.9825252349083, 32.0968845840215, 63.270379325558, 53.864273874248, 61.5482737369619, 32.6221167308316, 51.0684726617117, 93.4287450413415, 58.2602102639529, 73.4049051494517},
{58.3449877881554, 68.025433478957, 77.7820673420294, 38.1654935773140, 37.1442000856123, 77.0157574785836, 68.944488539694, 73.565559876888, 76.363413360064, 73.4789248696522, 75.135531541342, 22.1204068678675, 23.5020190621997, 25.2133476555574, 22.3437776573255, 0, 44.3306891442035, 60.9705510882098, 66.1976019203113, 22.5355186317067, 24.7778308170832, 26.6831857168517, 26.2530683920947, 28.2322510615076, 22.6768604528934, 25.0772984988415, 26.5770502501688, 22.4241031035803, 49.6857887126691, 30.1315449321803, 78.3636401655768, 77.3788110531559, 78.8381887158755, 75.3369603846611, 75.2412812224779, 75.8714017268694, 77.8336533897774, 74.3032765091823, 40.9837333584924, 67.2522720805773, 58.6138243079224, 65.3470611427935, 40.3761427082875, 56.7794196870662, 91.6474745969577, 45.8913161720167, 62.6855397998613},
{18.9260561132001, 83.059145191845, 91.1237619943338, 30.9961433084828, 11.9611705112836, 87.8993907828717, 96.6674841919453, 99.9257204127146, 96.4633966849602, 89.0442945954428, 100.237199182739, 29.2489042529801, 33.6767115377972, 27.2297062048051, 35.8051728106429, 44.3306891442035, 0, 27.7815784288798, 27.9177810722844, 39.0667582479018, 26.5021678358583, 22.0558019577616, 21.8560197657304, 20.9740315628636, 38.2053661152462, 24.6571470369141, 31.9499233175919, 27.5039342640285, 21.6211840563832, 16.0729586573226, 110.654905449329, 109.471249193567, 112.411164925909, 105.51699199655, 100.447281695425, 104.859084489614, 109.735115619386, 98.1798395802315, 11.0377715142143, 30.9027523046087, 20.3279708775864, 36.9251188217452, 4.55509604728594, 18.1097349511250, 70.91517186047, 53.1529575846914, 59.4515004015878},
{19.7833894972525, 81.9459754960547, 89.3876619002869, 37.3975346781041, 29.6525294030712, 84.7333558877494, 98.2453439100296, 100.708254378675, 95.4325080881772, 85.3932836937426, 100.810465726531, 46.0688408797096, 54.7416258435937, 45.5622914261344, 55.8888548818098, 60.9705510882098, 27.7815784288798, 0, 17.1523059674202, 58.0425094219745, 44.9926038366307, 45.8905011957812, 35.8563927354663, 42.5519459014509, 60.8536284867221, 45.8474034161151, 55.3701408703283, 46.6094636313271, 13.3256331932107, 38.3199699895498, 115.442713065832, 113.154385244232, 117.419555866985, 108.078686613041, 102.328794090422, 106.809702274653, 114.237789281831, 97.3939341026945, 25.6735291691657, 20.9237281572859, 15.8357854241588, 11.4549596245469, 30.7288073312324, 21.3295944640305, 44.6758648489316, 48.0963865586595, 47.1485779212905},
{22.6758924851923, 92.777185234302, 99.5799804177527, 45.5386034041449, 33.5706732133867, 95.5235384604235, 108.670741232403, 111.469592714785, 105.875967055796, 96.5450822155121, 111.389907980930, 49.2677064617382, 57.1156230816053, 49.244881967571, 57.4079167014446, 66.1976019203113, 27.9177810722844, 17.1523059674202, 0, 60.7532394198038, 47.2386113259058, 48.0644036684114, 40.2869718395414, 43.0657926897903, 62.9452341325378, 49.5166275103626, 57.4360348561772, 49.6551598527283, 23.2289926600359, 41.5810353406454, 125.071713828507, 123.3822957316, 127.205041173689, 118.203790548358, 112.485087456071, 117.175245252570, 124.051787975829, 108.097189602690, 27.0098296921695, 19.2569364126280, 16.736932215911, 23.0814405962886, 31.9272986643092, 18.3081948864436, 54.6632975587825, 60.6438653121649, 59.5541132080732},
{56.7144990280263, 87.6142111760415, 97.580959208239, 48.3942651561112, 30.2653663450486, 96.2569628650312, 90.1975614969717, 94.7275693766076, 97.1329959385584, 93.0404836616835, 96.4281748245812, 13.3608532661653, 7.77077216240445, 13.0425495973755, 6.3545574196792, 22.5355186317067, 39.0667582479018, 58.0425094219745, 60.7532394198038, 0, 13.9266686612413, 19.7482252367143, 25.8571073401492, 19.7775023701174, 10.8366784579040, 16.3756557120623, 17.3011097909932, 14.0122946015276, 50.1521126175159, 24.2100722840722, 99.39424983368, 98.3495582094805, 99.8340903699733, 96.5632145281007, 96.659166145793, 96.8067063792587, 98.872010194999, 94.8036924386387, 35.5384073925661, 66.9943467764258, 57.1500166229197, 63.7291644382695, 35.7448863475603, 54.9772325603972, 94.760170958056, 58.0862126498191, 74.4360134612272},
{43.8731455448547, 82.6346301498349, 92.1780825359261, 38.3628935300767, 17.9570292643299, 90.1949311214328, 88.6667040100172, 92.90174863801, 93.3027523709778, 87.8688938134537, 94.1496914493085, 4.78686745168487, 11.9273467292605, 6.04483250388297, 11.0248854869336, 24.7778308170832, 26.5021678358583, 44.9926038366307, 47.2386113259058, 13.9266686612413, 0, 12.4480560731385, 13.5317441595679, 7.80005769209433, 18.1099116508060, 10.2239913927976, 18.050454287912, 6.78896899389001, 36.9112841824827, 13.4200186288991, 100.20524137988, 98.9699575628888, 101.135814131296, 96.134452201071, 94.6149570628238, 96.0901602662832, 99.535033530913, 92.149118281186, 21.9864071644277, 53.3285439516212, 43.6268277554076, 50.9460116201455, 23.5564768163662, 41.4868220041015, 82.9765756102287, 51.1304214729353, 64.9053926881272},
{39.5378755119695, 81.5557625186596, 90.7009062799264, 35.0133188943865, 17.0648644881816, 88.6300315920061, 89.7309249924462, 93.6734199226227, 93.2851676313014, 88.0378872985943, 94.62926661451, 15.113570061372, 13.6276373594251, 11.7242526414267, 16.9180377112714, 26.6831857168517, 22.0558019577616, 45.8905011957812, 48.0644036684114, 19.7482252367143, 12.4480560731385, 0, 17.5474898489784, 9.8240724753027, 16.5428050825729, 6.03855115073144, 12.5603184673001, 11.5299609713130, 37.0737589138194, 7.73733804353926, 100.921088480060, 100.041119545915, 102.041170122652, 97.3371645364709, 94.4964020479087, 97.2245421691457, 100.210097295632, 93.29858573419, 22.572328191837, 51.2377097458503, 41.1788780808803, 53.3138818695469, 18.144213953765, 38.5671738658668, 85.9297527053348, 53.6434348266403, 66.3014788673677},
{35.4301058423483, 72.020691471271, 81.2423387157214, 26.3134357315802, 14.2678099230400, 78.899017104144, 80.746170807042, 84.617553734435, 83.4293167897233, 77.0799429164293, 85.51631949517, 12.9643511214407, 23.1507429686393, 15.9920011255627, 23.3097061328538, 26.2530683920947, 21.8560197657304, 35.8563927354663, 40.2869718395414, 25.8571073401492, 13.5317441595679, 17.5474898489784, 0, 13.1104385891548, 28.5287153583893, 16.7468832921233, 25.606764731219, 13.9005899155396, 25.8354872220363, 13.5026515914468, 94.02470366877, 92.5938529277187, 95.384587853594, 88.9627585003972, 86.1193149067037, 88.5820320381058, 93.2078988069144, 83.1026840721766, 16.6084436356933, 43.9602377154628, 34.5086423957825, 41.4819044885839, 19.1104395553844, 33.4783527073839, 71.5375425912856, 39.8888969514074, 51.955520399665},
{38.96405523043, 82.6826438861264, 91.7279128728, 35.6951663394359, 15.2109039836559, 89.7936907583155, 90.5755071749532, 94.6647326093514, 93.9934620066736, 88.4724386461682, 95.6140580667927, 10.9321727026241, 15.3207343166051, 11.6349860335112, 15.7957082778836, 28.2322510615076, 20.9740315628636, 42.5519459014509, 43.0657926897903, 19.7775023701174, 7.80005769209433, 9.8240724753027, 13.1104385891548, 0, 20.4240054837439, 11.3714950644144, 17.4166472089206, 9.50159986528584, 34.2636483755014, 10.2766726132538, 102.168684536897, 101.263618343411, 103.416633091587, 98.1889891994006, 95.6995841161287, 98.0301463836508, 101.507229299198, 93.6330972466467, 18.5878024521459, 48.7644142792672, 38.9101580567337, 49.5412797573902, 17.9146001909057, 36.2850175692392, 82.2092427893604, 52.4106181989871, 64.622108445949},
{55.9127320026486, 87.0574729704464, 96.637932510997, 47.1662686673432, 31.5605386519305, 95.59873900842, 90.7797471906592, 95.1799747846153, 97.1225148974222, 93.621580845444, 96.656629881245, 18.5565190701274, 7.5707925608882, 16.9487728169328, 11.1837560774545, 22.6768604528934, 38.2053661152462, 60.8536284867221, 62.9452341325378, 10.8366784579040, 18.1099116508060, 16.5428050825729, 28.5287153583893, 20.4240054837439, 0, 15.5067372454685, 10.4074780806879, 15.9860063805817, 52.1756034943536, 23.3415937759186, 99.0057377125185, 98.501413187832, 99.6257998713185, 96.9556269640912, 96.181091696861, 97.203320930923, 98.5255987040931, 95.5826600383145, 37.4659632199681, 67.462820130795, 57.4147402676351, 67.6593703783888, 34.3738985278074, 54.7956430749745, 99.1625110613885, 60.9908263593797, 76.8589936181837},
{41.6070054197607, 81.0821318170656, 90.6392238492806, 36.0325075452708, 16.7751274212746, 88.5245480078831, 88.4800226039754, 92.4468760964912, 92.6338685362972, 87.2788204549076, 93.6230441718277, 12.0134965767673, 10.9641050706385, 7.04343666117613, 15.1742578072208, 25.0772984988415, 24.6571470369141, 45.8474034161151, 49.5166275103626, 16.3756557120623, 10.2239913927976, 6.03855115073144, 16.7468832921233, 11.3714950644144, 15.5067372454685, 0, 12.6067005992845, 8.81703464890549, 37.4851023741433, 8.79811911717499, 99.6594220332428, 98.5293991659342, 100.633805950088, 96.0035567049471, 93.7034689859452, 95.8274955323367, 98.913057277591, 92.054603361266, 23.6747143594173, 53.4632920797064, 43.1607472131797, 52.8634665908319, 20.8987463738857, 41.2861526422601, 84.8669670720004, 51.4941744277933, 65.337737946764},
{48.9555921218404, 84.629772538983, 93.9584248484403, 41.956573978341, 26.0484164585873, 92.9513856809031, 91.3484214422997, 95.4162459961615, 95.9737052530536, 92.0045781469596, 96.6532591276673, 18.601655840274, 9.86377716698831, 16.8352873453351, 17.1521893646263, 26.5770502501688, 31.9499233175919, 55.3701408703283, 57.4360348561772, 17.3011097909932, 18.050454287912, 12.5603184673001, 25.606764731219, 17.4166472089206, 10.4074780806879, 12.6067005992845, 0, 13.6310527839929, 47.1710716435402, 18.2970380116564, 99.7912446059272, 99.5163021821048, 100.911265971645, 97.754846427172, 95.7007607075304, 97.5246122781321, 99.2305900415794, 95.0578923603927, 33.5509105688653, 61.959687700956, 51.2059137209756, 63.403624502074, 27.8858046324649, 49.2278183550724, 94.4708335942898, 57.9067085923557, 72.9768655122978},
{44.3087756544908, 79.5600050276519, 89.1486533829872, 36.1951999580055, 18.7172006453957, 87.6268366426633, 86.010272060958, 90.1691388447289, 90.5226076734426, 85.5392634992843, 91.4435459723648, 5.57853027239254, 9.7689559319305, 8.0494782439609, 12.7679285712288, 22.4241031035803, 27.5039342640285, 46.6094636313271, 49.6551598527283, 14.0122946015276, 6.78896899389001, 11.5299609713130, 13.9005899155396, 9.50159986528584, 15.9860063805817, 8.81703464890549, 13.6310527839929, 0, 38.138007289317, 13.1815932269206, 96.5743760010905, 95.6383897815098, 97.671942747137, 93.108042617166, 91.3907544557982, 92.8614860962283, 95.9201105086936, 89.2587368272709, 25.0233890590383, 55.17331692041, 44.8198616686843, 53.2988742845475, 23.8640419878947, 43.2841183345578, 83.9261246573437, 48.8916567524562, 63.7415257112661},
{17.8600111982048, 72.1379539493601, 79.868038663786, 25.3346817623589, 23.1488660629414, 75.5287501551561, 87.4626897596912, 90.1814282432919, 85.3784756247147, 76.0600841440502, 90.2677821816843, 37.7121147643566, 46.7637263271438, 37.8720332171379, 47.5468148249701, 49.6857887126691, 21.6211840563832, 13.3256331932107, 23.2289926600359, 50.1521126175159, 36.9112841824827, 37.0737589138194, 25.8354872220363, 34.2636483755014, 52.1756034943536, 37.4851023741433, 47.1710716435402, 38.138007289317, 0, 29.86, 104.407913972074, 102.305954860898, 106.305886948936, 97.2751766896365, 91.6174524858665, 96.29527506581, 103.261803199441, 87.4493390483885, 18.7025559750532, 21.6050665354217, 14.2628047732555, 18.9847728456255, 23.3115872475471, 17.5444036661267, 50.3390941515638, 40.0301249061254, 41.2551439216978},
{32.9733164846971, 79.381594844145, 88.4964406063882, 30.8134532306913, 9.6692088611220, 85.968778635037, 89.2034892815298, 92.9170253505782, 91.7156197166, 85.561547438087, 93.766199133803, 15.8147526063483, 18.7677622533961, 12.6597353842804, 21.7999633027214, 30.1315449321803, 16.0729586573226, 38.3199699895498, 41.5810353406454, 24.2100722840722, 13.4200186288991, 7.73733804353926, 13.5026515914468, 10.2766726132538, 23.3415937759186, 8.79811911717499, 18.2970380116564, 13.1815932269206, 29.86, 0, 101.599961122040, 100.427418566844, 102.892613923449, 97.3102235122292, 93.9017806007958, 96.941279133298, 100.774697221078, 92.0068089871614, 16.2874307366140, 44.8929404249711, 34.4820881038257, 45.9448843724739, 12.2530363583889, 32.6365209542929, 78.5842070647786, 49.3360811171702, 60.8560013474431},
{114.4407379389, 44.6560958884675, 47.0453621518636, 83.1954542027387, 105.511669970672, 53.2649002627434, 23.6600845307028, 24.2312298491018, 34.7524330083521, 45.8515964825654, 26.1635242274431, 96.5027776802305, 99.9755650146574, 100.633386110177, 100.230694400468, 78.3636401655768, 110.654905449329, 115.442713065832, 125.071713828507, 99.39424983368, 100.20524137988, 100.921088480060, 94.02470366877, 102.168684536897, 99.0057377125185, 99.6594220332428, 99.7912446059272, 96.5743760010905, 104.407913972074, 101.599961122040, 0, 7.42232443376063, 5.36321731799113, 13.2416955107720, 22.0506258414586, 13.8820927817098, 2.04755952294433, 27.5342405016009, 108.467590090312, 119.514210033786, 114.523185862078, 116.213097798828, 107.245361671263, 115.482135414964, 119.292987639676, 69.861422831202, 78.7856865172856},
{112.986054006678, 42.6617580509758, 45.690681763353, 81.9325216260308, 104.065510136644, 50.9351754684324, 18.9520157239276, 19.4363165234568, 32.0942378005772, 42.3808919207701, 22.0996583684002, 95.27562962269, 99.2066434267383, 99.2300987604064, 99.259405599671, 77.3788110531559, 109.471249193567, 113.154385244232, 123.3822957316, 98.3495582094805, 98.9699575628888, 100.041119545915, 92.5938529277187, 101.263618343411, 98.501413187832, 98.5293991659342, 99.5163021821048, 95.6383897815098, 102.305954860898, 100.427418566844, 7.42232443376063, 0, 6.73738821799664, 8.40049998511994, 20.2803254411757, 9.91889106704978, 6.11460546560447, 23.9008891048011, 106.802544913499, 117.670820937053, 112.921307112520, 113.352316253352, 106.171154745533, 113.991187817305, 115.783442685040, 67.1193898959161, 75.73580725126},
{116.652053561007, 47.7932589388922, 50.5585798851194, 85.4087401850654, 106.992315611917, 56.1976414095823, 24.6061476058322, 25.4604713232100, 37.5723156060416, 48.3090509118115, 27.7923028912683, 97.4429084130805, 100.750349379047, 101.439562794799, 100.788255268161, 78.8381887158755, 112.411164925909, 117.419555866985, 127.205041173689, 99.8340903699733, 101.135814131296, 102.041170122652, 95.384587853594, 103.416633091587, 99.6257998713185, 100.633805950088, 100.911265971645, 97.671942747137, 106.305886948936, 102.892613923449, 5.36321731799113, 6.73738821799664, 0, 14.125919439102, 25.0363415857829, 16.0179149704323, 5.94151495832503, 30.0441158964613, 109.928496760394, 121.729224510797, 116.710104104143, 117.994857515063, 108.963300702576, 117.525582321467, 121.581312708821, 71.866577071682, 81.2366228987887},
{108.255623410518, 36.7127280381069, 39.5449566948808, 77.3979075944563, 100.548346580140, 44.4144357163299, 11.6607075257036, 12.2331516789419, 25.0046815616596, 35.1632819856168, 14.7588109277137, 92.559405788931, 97.3064031808801, 96.6336426923874, 97.0752264998645, 75.3369603846611, 105.51699199655, 108.078686613041, 118.203790548358, 96.5632145281007, 96.134452201071, 97.3371645364709, 88.9627585003972, 98.1889891994006, 96.9556269640912, 96.0035567049471, 97.754846427172, 93.108042617166, 97.2751766896365, 97.3102235122292, 13.2416955107720, 8.40049998511994, 14.125919439102, 0, 14.5628843296924, 5.08527285403645, 11.8667602992561, 16.8593267955752, 102.611917436524, 111.979412840039, 107.841585670835, 107.800192949735, 102.434564967105, 108.931887434305, 109.411079877680, 62.4512682016947, 69.4986107774825},
{101.159466190762, 24.7399353273205, 25.8122529043863, 70.7203824933095, 96.758894164826, 31.5538032572937, 12.8641711742343, 10.2773342847258, 13.2854243439944, 25.1697357951966, 8.76368073357308, 91.3520114721072, 96.329499635366, 95.1075922311148, 96.7045500480717, 75.2412812224779, 100.447281695425, 102.328794090422, 112.485087456071, 96.659166145793, 94.6149570628238, 94.4964020479087, 86.1193149067037, 95.6995841161287, 96.181091696861, 93.7034689859452, 95.7007607075304, 91.3907544557982, 91.6174524858665, 93.9017806007958, 22.0506258414586, 20.2803254411757, 25.0363415857829, 14.5628843296924, 0, 12.9408500493592, 20.5143267011130, 12.0657407563730, 98.5850901505902, 104.634386795164, 101.088723406718, 102.370991985035, 97.5750608506088, 102.458356906599, 102.883936549881, 58.1358245834700, 62.2644529406627},
{107.109196617284, 34.3396039581123, 37.1515221760832, 76.383205614847, 99.8739705829302, 42.4485582794045, 12.5576311460402, 12.0677255520666, 23.150207342484, 33.3171487375496, 14.4586479312555, 92.4412873125423, 97.3116339396272, 96.5343819579325, 97.4243686148389, 75.8714017268694, 104.859084489614, 106.809702274653, 117.175245252570, 96.8067063792587, 96.0901602662832, 97.2245421691457, 88.5820320381058, 98.0301463836508, 97.203320930923, 95.8274955323367, 97.5246122781321, 92.8614860962283, 96.29527506581, 96.941279133298, 13.8820927817098, 9.91889106704978, 16.0179149704323, 5.08527285403645, 12.9408500493592, 0, 12.2515305166334, 14.1740220121178, 102.183822594381, 111.056305088905, 106.802226568551, 106.667284581544, 101.806964889442, 108.206737775427, 107.318630255888, 60.6013770470606, 67.479055269024},
{113.312929535865, 43.0558288736844, 45.5625240740677, 82.1083802056769, 104.595363185946, 51.6489312570938, 22.1210781834882, 22.5275387026635, 33.1961458606267, 44.1843456441306, 24.5351278782076, 95.8430153949676, 99.4140135996933, 99.8993038013779, 99.7203068587336, 77.8336533897774, 109.735115619386, 114.237789281831, 124.051787975829, 98.872010194999, 99.535033530913, 100.210097295632, 93.2078988069144, 101.507229299198, 98.5255987040931, 98.913057277591, 99.2305900415794, 95.9201105086936, 103.261803199441, 100.774697221078, 2.04755952294433, 6.11460546560447, 5.94151495832503, 11.8667602992561, 20.5143267011130, 12.2515305166334, 0, 25.9308098600873, 107.547131993373, 118.366375715403, 113.421636383893, 114.942340327662, 106.353420725428, 114.453073790091, 117.801292013288, 68.5313862401746, 77.299979948251},
{98.4551517189426, 23.4429115085989, 26.300853598315, 68.7456442256526, 93.8818347711633, 30.5986535651489, 11.8953940666125, 9.71796789457549, 11.9229023312279, 19.9700400600500, 9.80246907671735, 88.6985123888783, 94.8628146324997, 92.7452424655842, 94.9825252349083, 74.3032765091823, 98.1798395802315, 97.3939341026945, 108.097189602690, 94.8036924386387, 92.149118281186, 93.29858573419, 83.1026840721766, 93.6330972466467, 95.5826600383145, 92.054603361266, 95.0578923603927, 89.2587368272709, 87.4493390483885, 92.0068089871614, 27.5342405016009, 23.9008891048011, 30.0441158964613, 16.8593267955752, 12.0657407563730, 14.1740220121178, 25.9308098600873, 0, 95.4159006665032, 101.146238684392, 97.7940289588275, 96.5653566244127, 95.5621242961875, 99.6445302061282, 94.7458711501456, 51.8673307583878, 55.442312361589},
{24.5235723335733, 82.0567389066858, 90.5374419784434, 31.8909469912701, 10.7847855796951, 87.0620611977456, 93.5745846905024, 97.0829109575934, 94.4282928999566, 86.7111734437956, 97.6011787838651, 24.5928851499778, 32.0698066723203, 23.5258602393196, 32.0968845840215, 40.9837333584924, 11.0377715142143, 25.6735291691657, 27.0098296921695, 35.5384073925661, 21.9864071644277, 22.572328191837, 16.6084436356933, 18.5878024521459, 37.4659632199681, 23.6747143594173, 33.5509105688653, 25.0233890590383, 18.7025559750532, 16.2874307366140, 108.467590090312, 106.802544913499, 109.928496760394, 102.611917436524, 98.5850901505902, 102.183822594381, 107.547131993373, 95.4159006665032, 0, 31.9261475909637, 22.8300240910955, 32.3824026285883, 12.1306430167572, 20.5890966290413, 67.3757255990613, 49.6848679177071, 56.5582363586419},
{17.3507607902363, 83.562865556418, 89.2963722667388, 39.1622318056568, 38.9374742375517, 84.321636606508, 101.741552966327, 103.999648557098, 97.0590768552844, 87.262065641377, 103.376362868888, 55.2925211941, 62.8626311889663, 54.7946128738948, 63.270379325558, 67.2522720805773, 30.9027523046087, 20.9237281572859, 19.2569364126280, 66.9943467764258, 53.3285439516212, 51.2377097458503, 43.9602377154628, 48.7644142792672, 67.462820130795, 53.4632920797064, 61.959687700956, 55.17331692041, 21.6050665354217, 44.8929404249711, 119.514210033786, 117.670820937053, 121.729224510797, 111.979412840039, 104.634386795164, 111.056305088905, 118.366375715403, 101.146238684392, 31.9261475909637, 0, 11.9651535719355, 24.3116618107442, 34.4100624817799, 13.4320363311004, 51.8806563181308, 57.9136391534844, 52.5190593975178},
{7.90996839437428, 80.680570151679, 87.3913176465489, 32.2258048774581, 28.0509108586513, 83.1063926542357, 98.080563314043, 100.607621977661, 94.6233190075258, 85.4641772908392, 100.330514301483, 45.465811331153, 52.5431489349468, 44.794465059871, 53.864273874248, 58.6138243079224, 20.3279708775864, 15.8357854241588, 16.736932215911, 57.1500166229197, 43.6268277554076, 41.1788780808803, 34.5086423957825, 38.9101580567337, 57.4147402676351, 43.1607472131797, 51.2059137209756, 44.8198616686843, 14.2628047732555, 34.4820881038257, 114.523185862078, 112.921307112520, 116.710104104143, 107.841585670835, 101.088723406718, 106.802226568551, 113.421636383893, 97.7940289588275, 22.8300240910955, 11.9651535719355, 0, 24.0854728000096, 23.7082791446364, 7.4809691885477, 55.0864266403258, 52.1912262741546, 50.955981984454},
{29.1451814199191, 82.0976028882695, 89.2997222840027, 42.4549467082459, 37.7871353770036, 83.9736416978566, 97.5627229017313, 99.8954833813822, 94.6205712305733, 83.845164440175, 99.960572727451, 51.7703583143868, 61.5292003848579, 51.6691406934545, 61.5482737369619, 65.3470611427935, 36.9251188217452, 11.4549596245469, 23.0814405962886, 63.7291644382695, 50.9460116201455, 53.3138818695469, 41.4819044885839, 49.5412797573902, 67.6593703783888, 52.8634665908319, 63.403624502074, 53.2988742845475, 18.9847728456255, 45.9448843724739, 116.213097798828, 113.352316253352, 117.994857515063, 107.800192949735, 102.370991985035, 106.667284581544, 114.942340327662, 96.5653566244127, 32.3824026285883, 24.3116618107442, 24.0854728000096, 0, 39.7089725377024, 28.4051562220664, 37.2174206521623, 48.5485334484987, 44.8161589161766},
{21.8883553516476, 80.7793717479902, 89.0410854605895, 28.9782677191029, 10.1590403090056, 86.094192603218, 93.806259919048, 97.1444599552646, 94.0732693170595, 87.0678361968414, 97.541322525379, 26.1000478926764, 30.0517886322928, 24.1286468746177, 32.6221167308316, 40.3761427082875, 4.55509604728594, 30.7288073312324, 31.9272986643092, 35.7448863475603, 23.5564768163662, 18.144213953765, 19.1104395553844, 17.9146001909057, 34.3738985278074, 20.8987463738857, 27.8858046324649, 23.8640419878947, 23.3115872475471, 12.2530363583889, 107.245361671263, 106.171154745533, 108.963300702576, 102.434564967105, 97.5750608506088, 101.806964889442, 106.353420725428, 95.5621242961875, 12.1306430167572, 34.4100624817799, 23.7082791446364, 39.7089725377024, 0, 21.7025897072216, 72.9758651884306, 51.3405453808196, 58.9812648219755},
{11.7002606808566, 82.9105910001853, 89.599400109599, 33.4289455412521, 27.5032743505205, 85.3982224639366, 99.195261983625, 101.960728224155, 96.4000539418936, 87.6784631480274, 101.673209844088, 43.8737609511653, 50.4311847967109, 43.0470486793230, 51.0684726617117, 56.7794196870662, 18.1097349511250, 21.3295944640305, 18.3081948864436, 54.9772325603972, 41.4868220041015, 38.5671738658668, 33.4783527073839, 36.2850175692392, 54.7956430749745, 41.2861526422601, 49.2278183550724, 43.2841183345578, 17.5444036661267, 32.6365209542929, 115.482135414964, 113.991187817305, 117.525582321467, 108.931887434305, 102.458356906599, 108.206737775427, 114.453073790091, 99.6445302061282, 20.5890966290413, 13.4320363311004, 7.4809691885477, 28.4051562220664, 21.7025897072216, 0, 60.856520603794, 55.5937802276478, 55.1556198405928},
{58.9978338585409, 81.5358816718137, 86.152269848217, 63.7638212468481, 70.8689099676297, 80.3921818338077, 99.5018597816141, 100.211787729788, 92.3353610487336, 80.1428824038667, 99.76699303878, 82.3388268072845, 92.9919614805495, 83.6929393676671, 93.4287450413415, 91.6474745969577, 70.91517186047, 44.6758648489316, 54.6632975587825, 94.760170958056, 82.9765756102287, 85.9297527053348, 71.5375425912856, 82.2092427893604, 99.1625110613885, 84.8669670720004, 94.4708335942898, 83.9261246573437, 50.3390941515638, 78.5842070647786, 119.292987639676, 115.783442685040, 121.581312708821, 109.411079877680, 102.883936549881, 107.318630255888, 117.801292013288, 94.7458711501456, 67.3757255990613, 51.8806563181308, 55.0864266403258, 37.2174206521623, 72.9758651884306, 60.856520603794, 0, 56.0682450233642, 41.9597438028404},
{53.1034923521985, 41.2589154001896, 50.9414457980925, 29.7317271614012, 47.5577848516938, 48.3990661066926, 53.568427268308, 55.8840129196177, 52.7669176662803, 44.4218696139638, 56.6957882033578, 48.0676408824065, 56.9649506275569, 51.3133510891659, 58.2602102639529, 45.8913161720167, 53.1529575846914, 48.0963865586595, 60.6438653121649, 58.0862126498191, 51.1304214729353, 53.6434348266403, 39.8888969514074, 52.4106181989871, 60.9908263593797, 51.4941744277933, 57.9067085923557, 48.8916567524562, 40.0301249061254, 49.3360811171702, 69.861422831202, 67.1193898959161, 71.866577071682, 62.4512682016947, 58.1358245834700, 60.6013770470606, 68.5313862401746, 51.8673307583878, 49.6848679177071, 57.9136391534844, 52.1912262741546, 48.5485334484987, 51.3405453808196, 55.5937802276478, 56.0682450233642, 0, 21.3735818242989},
{52.9202881700393, 40.865022941386, 47.3256262504787, 35.5757445459684, 57.4402202293828, 42.4672532664876, 59.4673893827533, 60.4329289377902, 52.8193676599787, 41.4314192370959, 59.9729805829258, 62.8917013603544, 72.6278431457248, 65.6031249255704, 73.4049051494517, 62.6855397998613, 59.4515004015878, 47.1485779212905, 59.5541132080732, 74.4360134612272, 64.9053926881272, 66.3014788673677, 51.955520399665, 64.622108445949, 76.8589936181837, 65.337737946764, 72.9768655122978, 63.7415257112661, 41.2551439216978, 60.8560013474431, 78.7856865172856, 75.73580725126, 81.2366228987887, 69.4986107774825, 62.2644529406627, 67.479055269024, 77.299979948251, 55.442312361589, 56.5582363586419, 52.5190593975178, 50.955981984454, 44.8161589161766, 58.9812648219755, 55.1556198405928, 41.9597438028404, 21.3735818242989, 0}
};
public IsotonicMDSTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of learn method, of class IsotonicMDS.
*/
@Test
public void testLearn_doubleArrArr() {
System.out.println("learn");
double[][] points = {
{40.22360360457568, 18.504098418635056},
{-41.96153329423929, 15.679459081085987},
{-49.154520492544854, 23.057549478935496},
{10.598081220086218, 7.779540233953462},
{35.757866842749806, -4.0940414119709745},
{-45.05078778030483, 26.197239791961866},
{-55.284584971795624, -3.4691421950369614},
{-58.547722578180036, -0.581590856322055},
{-55.23402255948884, 11.41947137100053},
{-46.739993491044444, 17.75826916762321},
{-59.27724694557147, 2.5924406005262988},
{27.6737865285104, -18.86395047195548},
{31.583645719051308, -26.40457138526285},
{32.20027300792993, -19.14462360613023},
{30.93647170723012, -28.139903505514962},
{10.820417446883258, -25.981714242664278},
{40.61994472140328, 1.7893356291367033},
{36.893123121307056, 25.2011449401249},
{50.35435388043603, 23.460119648230112},
{30.31641225177879, -30.621625333828987},
{31.57301393922658, -18.462236251192287},
{33.48847606238201, -16.246616010675815},
{25.404563654492463, -7.368448245974307},
{34.198667011206695, -14.51548898530616},
{30.374194968862504, -32.03010239329132},
{31.799691626843952, -17.620915345075993},
{33.202462089583705, -26.623087076374446},
{28.74143110010598, -18.88136294206028},
{29.619321505441754, 16.53977754459522},
{33.21904729286558, -10.485990318581562},
{-68.03569731150479, -17.717332618032408},
{-66.8523610229811, -14.04860419250387},
{-69.0945497414166, -19.49039719928254},
{-63.412123082772155, -8.958925369982111},
{-60.125050342241366, 0.6420002976226844},
{-63.01224683586109, -7.474379597257728},
{-67.2871126283525, -15.967072181468266},
{-56.75383978958709, 3.8275706756047425},
{37.38667411461407, 1.48236982754225},
{42.09168775562593, 30.160624244349172},
{39.515694105763124, 20.31157656136279},
{34.40756902634357, 33.374967724530244},
{37.50347081823464, -1.1747328861102793},
{42.17288961345579, 16.841661303971275},
{17.7129501323806, 65.0200551147668},
{-6.945057439388253, 11.751691969153283},
{-7.62133456223296, 30.975890997191055}
};
IsotonicMDS mds = new IsotonicMDS(swiss, 2);
double sign = Math.signum(points[0][0] / mds.getCoordinates()[0][0]);
for (int i = 0; i < points.length; i++) {
points[i][0] *= sign;
}
sign = Math.signum(points[0][1] / mds.getCoordinates()[0][1]);
for (int i = 0; i < points.length; i++) {
points[i][1] *= sign;
}
assertEquals(0.023190, mds.getStress(), 1E-6);
assertTrue(Math.equals(points, mds.getCoordinates(), 1E-6));
}
}
| apache-2.0 |
AntennaeSDK/MMS | mobile-server/src/main/java/com/github/antennaesdk/messageserver/services/IRegistrationService.java | 893 | /*
* Copyright 2015 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 com.github.antennaesdk.messageserver.services;
import com.github.antennaesdk.common.beans.AppDetails;
import java.util.List;
public interface IRegistrationService {
public void register(AppDetails appDetails);
public List<AppDetails> getAllRegistrations();
}
| apache-2.0 |
treeleafj/treeleaf | treeleaf-db/src/main/java/org/treeleaf/db/meta/annotation/Column.java | 936 | package org.treeleaf.db.meta.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 标于实体类中的属性上面,用于声明一个字段的信息
* Created by leaf on 2015/1/2 0002.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
/**
* 数据库表得列名称
*
* @return
*/
String value() default "";
/**
* 是否必须不为null和不为空窜空格
*
* @return
*/
boolean requrie() default false;
/**
* 是否主键,默认为false
*
* @return
*/
boolean primaryKey() default false;
/**
* 是否自动递增(对于例如Mysql的自增主键,会进行多一次查询查出主键值)
*
* @return
*/
boolean autoIncremen() default false;
}
| apache-2.0 |
Hanks10100/weex | android/playground/app/src/androidTest/java/com/alibaba/wasmWeex/uitest/TC_AG/AG_Input_Input_Color.java | 932 | package com.alibaba.wasmWeex.uitest.TC_AG;
import com.alibaba.wasmWeex.WXPageActivity;
import com.alibaba.wasmWeex.util.TestFlow;
import java.util.TreeMap;
import org.junit.Before;
import org.junit.Test;
public class AG_Input_Input_Color extends TestFlow {
public AG_Input_Input_Color() {
super(WXPageActivity.class);
}
@Before
public void setUp() throws InterruptedException {
super.setUp();
TreeMap testMap = new <String, Object> TreeMap();
testMap.put("testComponet", "AG_Input");
testMap.put("testChildCaseInit", "AG_Input_Input_Color");
testMap.put("step1",new TreeMap(){
{
put("click", "#FF0000");
put("screenshot", "AG_Input_Input_Color_01_#FF0000");
}
});
testMap.put("step2",new TreeMap(){
{
put("click", "#FF00FF");
put("screenshot", "AG_Input_Input_Color_02_#FF00FF");
}
});
super.setTestMap(testMap);
}
@Test
public void doTest(){
super.testByTestMap();
}
}
| apache-2.0 |
mtlynch/gofn-prosper | prosper/note_parser.go | 3366 | package prosper
import (
"fmt"
"github.com/mtlynch/gofn-prosper/prosper/thin"
)
type noteParser interface {
Parse(thin.NoteResult) (Note, error)
}
type defaultNoteParser struct{}
func (p defaultNoteParser) Parse(r thin.NoteResult) (Note, error) {
originationDate, err := parseProsperDate(r.OriginationDate)
if err != nil {
return Note{}, err
}
nextPaymentDueDate, err := parseProsperDate(r.NextPaymentDueDate)
if err != nil {
return Note{}, err
}
defaultReason, err := parseDefaultReason(r.NoteDefaultReason)
if err != nil {
return Note{}, err
}
rating, err := parseRating(r.Rating)
if err != nil {
return Note{}, err
}
noteStatus, err := parseNoteStatus(r.NoteStatus)
if err != nil {
return Note{}, err
}
return Note{
AgeInMonths: r.AgeInMonths,
AmountBorrowed: r.AmountBorrowed,
BorrowerRate: r.BorrowerRate,
DaysPastDue: r.DaysPastDue,
DebtSaleProceedsReceivedProRataShare: r.DebtSaleProceedsReceivedProRataShare,
InterestPaidProRataShare: r.InterestPaidProRataShare,
IsSold: r.IsSold,
LateFeesPaidProRataShare: r.LateFeesPaidProRataShare,
ListingNumber: ListingNumber(r.ListingNumber),
LoanNoteID: r.LoanNoteID,
LoanNumber: r.LoanNumber,
NextPaymentDueAmountProRataShare: r.NextPaymentDueAmountProRataShare,
NextPaymentDueDate: nextPaymentDueDate,
NoteDefaultReasonDescription: r.NoteDefaultReasonDescription,
NoteDefaultReason: defaultReason,
NoteOwnershipAmount: r.NoteOwnershipAmount,
NoteSaleFeesPaid: r.NoteSaleFeesPaid,
NoteSaleGrossAmountReceived: r.NoteSaleGrossAmountReceived,
NoteStatusDescription: r.NoteStatusDescription,
NoteStatus: noteStatus,
OriginationDate: originationDate,
PrincipalBalanceProRataShare: r.PrincipalBalanceProRataShare,
PrincipalPaidProRataShare: r.PrincipalPaidProRataShare,
ProsperFeesPaidProRataShare: r.ProsperFeesPaidProRataShare,
Rating: rating,
ServiceFeesPaidProRataShare: r.ServiceFeesPaidProRataShare,
Term: r.Term,
}, nil
}
func parseDefaultReason(defaultReason int64) (*DefaultReason, error) {
if defaultReason == 0 {
return nil, nil
}
if defaultReason < int64(DefaultReasonMin) || defaultReason > int64(DefaultReasonMax) {
return nil, fmt.Errorf("default reason out of range: %d, expected %d-%d", defaultReason, DefaultReasonMin, DefaultReasonMax)
}
dr := DefaultReason(defaultReason)
return &dr, nil
}
func parseRating(rating string) (Rating, error) {
stringToRating := map[string]Rating{
"AA": RatingAA,
"A": RatingA,
"B": RatingB,
"C": RatingC,
"D": RatingD,
"E": RatingE,
"HR": RatingHR,
"N/A": RatingNA,
}
parsed, ok := stringToRating[rating]
if !ok {
return RatingNA, fmt.Errorf("unrecognized Prosper rating value: %s", rating)
}
return parsed, nil
}
func parseNoteStatus(noteStatus int64) (NoteStatus, error) {
if noteStatus < int64(NoteStatusMin) || noteStatus > int64(NoteStatusMax) {
return NoteStatusInvalid, fmt.Errorf("note status out of range: %d, expected %d-%d", noteStatus, NoteStatusMax, NoteStatusMax)
}
return NoteStatus(noteStatus), nil
}
| apache-2.0 |
vsilaev/java-continuations | net.tascalate.javaflow.api/src/main/java/org/apache/commons/javaflow/api/ContinuableAnnotation.java | 1804 | /**
* Copyright 2013-2019 Valery Silaev (http://vsilaev.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.javaflow.api;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* Meta-annotation that is used to annotate other continuation-related
* annotations. It provides an option to declare and use own annotations instead
* of supplied {@link continuable} and {@link ccs} annotations, for ex:
*
* <pre>
* <code>
* import java.lang.annotation.Documented;
* import java.lang.annotation.ElementType;
* import java.lang.annotation.Retention;
* import java.lang.annotation.RetentionPolicy;
* import java.lang.annotation.Target;
*
* {@literal @}Documented
* {@literal @}Retention(RetentionPolicy.CLASS)
* {@literal @}Target({ElementType.METHOD})
* <b>{@literal @}ContinuableAnnotation</b>
* public {@literal @}interface ContinuableMethod {
* // The annotation to mark continuable methods
* }
*
* </code>
* </pre>
*
* @author Valery Silaev
*
*/
@Documented
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.ANNOTATION_TYPE)
public @interface ContinuableAnnotation {
}
| apache-2.0 |
vunvulear/Stuff | Azure/RunLegacyDotNetFrameworkUsingDocker/Web.Docker/Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs | 7398 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Web.Docker.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("00000000000000_CreateIdentitySchema")]
partial class CreateIdentitySchema
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rc2")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Web.Docker.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("Web.Docker.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("Web.Docker.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Web.Docker.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| apache-2.0 |
gbehrmann/JGlobus | ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleUtil.java | 23138 | /*
* Copyright 1999-2010 University of Chicago
*
* 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.globus.gsi.bc;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Security;
import java.security.cert.CertStore;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509CertSelector;
import java.security.cert.X509Certificate;
import java.util.Collection;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERBoolean;
import org.bouncycastle.asn1.DEREncodable;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERObject;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROutputStream;
import org.bouncycastle.asn1.DERString;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.TBSCertificateStructure;
import org.bouncycastle.asn1.x509.X509Extension;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.asn1.x509.X509Name;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.globus.gsi.GSIConstants;
import org.globus.gsi.TrustedCertificates;
import org.globus.gsi.TrustedCertificatesUtil;
import org.globus.gsi.proxy.ext.ProxyCertInfo;
import org.globus.gsi.proxy.ext.ProxyPolicy;
import org.globus.gsi.util.ProxyCertificateUtil;
import org.globus.util.I18n;
// COMMENT: BCB: removed methods createCertificateType(...) that took a TBSCertificateStructure as parameter
/**
* A collection of various utility functions.
*/
public class BouncyCastleUtil {
static {
Security.addProvider(new BouncyCastleProvider());
}
private static I18n i18n =
I18n.getI18n("org.globus.gsi.errors",
BouncyCastleUtil.class.getClassLoader());
/**
* Converts given <code>DERObject</code> into
* a DER-encoded byte array.
*
* @param obj DERObject to convert.
* @return the DER-encoded byte array
* @exception IOException if conversion fails
*/
public static byte[] toByteArray(DERObject obj)
throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DEROutputStream der = new DEROutputStream(bout);
der.writeObject(obj);
return bout.toByteArray();
}
/**
* Converts the DER-encoded byte array into a
* <code>DERObject</code>.
*
* @param data the DER-encoded byte array to convert.
* @return the DERObject.
* @exception IOException if conversion fails
*/
public static DERObject toDERObject(byte[] data)
throws IOException {
ByteArrayInputStream inStream = new ByteArrayInputStream(data);
ASN1InputStream derInputStream = new ASN1InputStream(inStream);
return derInputStream.readObject();
}
/**
* Replicates a given <code>DERObject</code>.
*
* @param obj the DERObject to replicate.
* @return a copy of the DERObject.
* @exception IOException if replication fails
*/
public static DERObject duplicate(DERObject obj)
throws IOException {
return toDERObject(toByteArray(obj));
}
/**
* Extracts the TBS certificate from the given certificate.
*
* @param cert the X.509 certificate to extract the TBS certificate from.
* @return the TBS certificate
* @exception IOException if extraction fails.
* @exception CertificateEncodingException if extraction fails.
*/
public static TBSCertificateStructure getTBSCertificateStructure(X509Certificate cert)
throws CertificateEncodingException, IOException {
DERObject obj = BouncyCastleUtil.toDERObject(cert.getTBSCertificate());
return TBSCertificateStructure.getInstance(obj);
}
/**
* Extracts the value of a certificate extension.
*
* @param ext the certificate extension to extract the value from.
* @exception IOException if extraction fails.
*/
public static DERObject getExtensionObject(X509Extension ext)
throws IOException {
return toDERObject(ext.getValue().getOctets());
}
/**
* Returns certificate type of the given certificate.
* Please see {@link #getCertificateType(TBSCertificateStructure,
* TrustedCertificates) getCertificateType} for details for
* determining the certificate type.
*
* @param cert the certificate to get the type of.
* @param trustedCerts the trusted certificates to double check the
* {@link GSIConstants#EEC GSIConstants.EEC}
* certificate against.
* @return the certificate type as determined by
* {@link #getCertificateType(TBSCertificateStructure,
* TrustedCertificates) getCertificateType}.
* @exception CertificateException if something goes wrong.
* @deprecated
*/
public static GSIConstants.CertificateType getCertificateType(X509Certificate cert,
TrustedCertificates trustedCerts)
throws CertificateException {
try {
return getCertificateType(cert, TrustedCertificatesUtil.createCertStore(trustedCerts));
} catch (Exception e) {
throw new CertificateException("", e);
}
}
/**
* Returns the certificate type of the given certificate.
* Please see {@link #getCertificateType(TBSCertificateStructure,
* TrustedCertificates) getCertificateType} for details for
* determining the certificate type.
*
* @param cert the certificate to get the type of.
* @param trustedCerts the trusted certificates to double check the
* {@link GSIConstants#EEC GSIConstants.EEC}
* certificate against.
* @return the certificate type as determined by
* {@link #getCertificateType(TBSCertificateStructure,
* TrustedCertificates) getCertificateType}.
* @exception CertificateException if something goes wrong.
*/
public static GSIConstants.CertificateType getCertificateType(X509Certificate cert, CertStore trustedCerts)
throws CertificateException {
try {
TBSCertificateStructure crt = getTBSCertificateStructure(cert);
GSIConstants.CertificateType type = getCertificateType(crt);
// check subject of the cert in trusted cert list
// to make sure the cert is not a ca cert
if (type == GSIConstants.CertificateType.EEC) {
X509CertSelector selector = new X509CertSelector();
selector.setSubject(cert.getSubjectX500Principal());
Collection c = trustedCerts.getCertificates(selector);
if (c != null && c.size() > 0) {
type = GSIConstants.CertificateType.CA;
}
}
return type;
} catch (Exception e) {
// but this should not happen
throw new CertificateException("", e);
}
}
/**
* Returns certificate type of the given certificate.
* Please see {@link #getCertificateType(TBSCertificateStructure)
* getCertificateType} for details for determining the certificate type.
*
* @param cert the certificate to get the type of.
* @return the certificate type as determined by
* {@link #getCertificateType(TBSCertificateStructure)
* getCertificateType}.
* @exception CertificateException if something goes wrong.
*/
public static GSIConstants.CertificateType getCertificateType(X509Certificate cert)
throws CertificateException {
try {
TBSCertificateStructure crt = getTBSCertificateStructure(cert);
return getCertificateType(crt);
} catch (IOException e) {
// but this should not happen
throw new CertificateException("", e);
}
}
public static GSIConstants.CertificateType getCertificateType(TBSCertificateStructure crt, TrustedCertificates trustedCerts)
throws CertificateException, IOException {
GSIConstants.CertificateType type = getCertificateType(crt);
// check subject of the cert in trusted cert list
// to make sure the cert is not a ca cert
if (type == GSIConstants.CertificateType.EEC) {
if (trustedCerts == null) {
trustedCerts = TrustedCertificates.getDefaultTrustedCertificates();
}
if (trustedCerts != null && trustedCerts.getCertificate(crt.getSubject().toString()) != null) {
type = GSIConstants.CertificateType.CA;
}
}
return type;
}
/**
* Returns certificate type of the given TBS certificate. <BR>
* The certificate type is {@link GSIConstants#CA GSIConstants.CA}
* <B>only</B> if the certificate contains a
* BasicConstraints extension and it is marked as CA.<BR>
* A certificate is a GSI-2 proxy when the subject DN of the certificate
* ends with <I>"CN=proxy"</I> (certificate type {@link
* GSIConstants#GSI_2_PROXY GSIConstants.GSI_2_PROXY}) or
* <I>"CN=limited proxy"</I> (certificate type {@link
* GSIConstants#GSI_2_LIMITED_PROXY GSIConstants.LIMITED_PROXY}) component
* and the issuer DN of the certificate matches the subject DN without
* the last proxy <I>CN</I> component.<BR>
* A certificate is a GSI-3 proxy when the subject DN of the certificate
* ends with a <I>CN</I> component, the issuer DN of the certificate
* matches the subject DN without the last <I>CN</I> component and
* the certificate contains {@link ProxyCertInfo ProxyCertInfo} critical
* extension.
* The certificate type is {@link GSIConstants#GSI_3_IMPERSONATION_PROXY
* GSIConstants.GSI_3_IMPERSONATION_PROXY} if the policy language of
* the {@link ProxyCertInfo ProxyCertInfo} extension is set to
* {@link ProxyPolicy#IMPERSONATION ProxyPolicy.IMPERSONATION} OID.
* The certificate type is {@link GSIConstants#GSI_3_LIMITED_PROXY
* GSIConstants.GSI_3_LIMITED_PROXY} if the policy language of
* the {@link ProxyCertInfo ProxyCertInfo} extension is set to
* {@link ProxyPolicy#LIMITED ProxyPolicy.LIMITED} OID.
* The certificate type is {@link GSIConstants#GSI_3_INDEPENDENT_PROXY
* GSIConstants.GSI_3_INDEPENDENT_PROXY} if the policy language of
* the {@link ProxyCertInfo ProxyCertInfo} extension is set to
* {@link ProxyPolicy#INDEPENDENT ProxyPolicy.INDEPENDENT} OID.
* The certificate type is {@link GSIConstants#GSI_3_RESTRICTED_PROXY
* GSIConstants.GSI_3_RESTRICTED_PROXY} if the policy language of
* the {@link ProxyCertInfo ProxyCertInfo} extension is set to
* any other OID then the above.<BR>
* The certificate type is {@link GSIConstants#EEC GSIConstants.EEC}
* if the certificate is not a CA certificate or a GSI-2 or GSI-3 proxy.
*
* @param crt the TBS certificate to get the type of.
* @return the certificate type. The certificate type is determined
* by rules described above.
* @exception IOException if something goes wrong.
* @exception CertificateException for proxy certificates, if
* the issuer DN of the certificate does not match
* the subject DN of the certificate without the
* last <I>CN</I> component. Also, for GSI-3 proxies
* when the <code>ProxyCertInfo</code> extension is
* not marked as critical.
*/
private static GSIConstants.CertificateType getCertificateType(TBSCertificateStructure crt)
throws CertificateException, IOException {
X509Extensions extensions = crt.getExtensions();
X509Extension ext = null;
if (extensions != null) {
ext = extensions.getExtension(X509Extensions.BasicConstraints);
if (ext != null) {
BasicConstraints basicExt = getBasicConstraints(ext);
if (basicExt.isCA()) {
return GSIConstants.CertificateType.CA;
}
}
}
GSIConstants.CertificateType type = GSIConstants.CertificateType.EEC;
// does not handle multiple AVAs
X509Name subject = crt.getSubject();
ASN1Set entry = X509NameHelper.getLastNameEntry(subject);
ASN1Sequence ava = (ASN1Sequence)entry.getObjectAt(0);
if (X509Name.CN.equals(ava.getObjectAt(0))) {
String value = ((DERString)ava.getObjectAt(1)).getString();
if (value.equalsIgnoreCase("proxy")) {
type = GSIConstants.CertificateType.GSI_2_PROXY;
} else if (value.equalsIgnoreCase("limited proxy")) {
type = GSIConstants.CertificateType.GSI_2_LIMITED_PROXY;
} else if (extensions != null) {
boolean gsi4 = true;
// GSI_4
ext = extensions.getExtension(ProxyCertInfo.OID);
if (ext == null) {
// GSI_3
ext = extensions.getExtension(ProxyCertInfo.OLD_OID);
gsi4 = false;
}
if (ext != null) {
if (ext.isCritical()) {
ProxyCertInfo proxyCertExt = getProxyCertInfo(ext);
ProxyPolicy proxyPolicy =
proxyCertExt.getProxyPolicy();
DERObjectIdentifier oid =
proxyPolicy.getPolicyLanguage();
if (ProxyPolicy.IMPERSONATION.equals(oid)) {
if (gsi4) {
type = GSIConstants.CertificateType.GSI_4_IMPERSONATION_PROXY;
} else {
type = GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY;
}
} else if (ProxyPolicy.INDEPENDENT.equals(oid)) {
if (gsi4) {
type = GSIConstants.CertificateType.GSI_4_INDEPENDENT_PROXY;
} else {
type = GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY;
}
} else if (ProxyPolicy.LIMITED.equals(oid)) {
if (gsi4) {
type = GSIConstants.CertificateType.GSI_4_LIMITED_PROXY;
} else {
type = GSIConstants.CertificateType.GSI_3_LIMITED_PROXY;
}
} else {
if (gsi4) {
type = GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY;
} else {
type = GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY;
}
}
} else {
String err = i18n.getMessage("proxyCertCritical");
throw new CertificateException(err);
}
}
}
if (ProxyCertificateUtil.isProxy(type)) {
X509NameHelper iss = new X509NameHelper(crt.getIssuer());
iss.add((ASN1Set)BouncyCastleUtil.duplicate(entry));
X509Name issuer = iss.getAsName();
if (!issuer.equals(subject)) {
String err = i18n.getMessage("proxyDNErr");
throw new CertificateException(err);
}
}
}
return type;
}
/**
* Gets a boolean array representing bits of the KeyUsage extension.
*
* @see java.security.cert.X509Certificate#getKeyUsage
* @exception IOException if failed to extract the KeyUsage extension value.
*/
public static boolean[] getKeyUsage(X509Extension ext)
throws IOException {
DERBitString bits = (DERBitString)getExtensionObject(ext);
// copied from X509CertificateObject
byte [] bytes = bits.getBytes();
int length = (bytes.length * 8) - bits.getPadBits();
boolean[] keyUsage = new boolean[(length < 9) ? 9 : length];
for (int i = 0; i != length; i++) {
keyUsage[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0;
}
return keyUsage;
}
/**
* Creates a <code>BasicConstraints</code> object from given
* extension.
*
* @param ext the extension.
* @return the <code>BasicConstraints</code> object.
* @exception IOException if something fails.
*/
public static BasicConstraints getBasicConstraints(X509Extension ext)
throws IOException {
DERObject obj = BouncyCastleUtil.getExtensionObject(ext);
if (obj instanceof ASN1Sequence) {
ASN1Sequence seq = (ASN1Sequence)obj;
int size = seq.size();
if (size == 0) {
return new BasicConstraints(false);
} else if (size == 1) {
DEREncodable value = seq.getObjectAt(0);
if (value instanceof DERInteger) {
int length = ((DERInteger)value).getValue().intValue();
return new BasicConstraints(false, length);
} else if (value instanceof DERBoolean) {
boolean ca = ((DERBoolean)value).isTrue();
return new BasicConstraints(ca);
}
}
}
return BasicConstraints.getInstance(obj);
}
/**
* Creates a <code>ProxyCertInfo</code> object from given
* extension.
*
* @param ext the extension.
* @return the <code>ProxyCertInfo</code> object.
* @exception IOException if something fails.
*/
public static ProxyCertInfo getProxyCertInfo(X509Extension ext)
throws IOException {
return ProxyCertInfo.getInstance(BouncyCastleUtil.getExtensionObject(ext));
}
/**
* Returns the subject DN of the given certificate in the Globus format.
*
* @param cert the certificate to get the subject of. The certificate
* must be of <code>X509CertificateObject</code> type.
* @return the subject DN of the certificate in the Globus format.
*/
public static String getIdentity(X509Certificate cert) {
if (cert == null) {
return null;
}
String subjectDN = cert.getSubjectX500Principal().getName(X500Principal.RFC2253);
X509Name name = new X509Name(true, subjectDN);
return X509NameHelper.toString(name);
}
public static String getIdentityPrefix(X509Certificate cert) {
if (cert == null) {
return null;
}
String subjectDN = cert.getSubjectX500Principal().getName(X500Principal.RFC2253);
LdapName ldapname = null;
try {
ldapname = new LdapName(subjectDN);
ldapname.remove(ldapname.size() - 1);
} catch (InvalidNameException e) {
return null;
}
X509Name name = new X509Name(true, ldapname.toString());
return X509NameHelper.toString(name);
}
/**
* Finds the identity certificate in the given chain and
* returns the subject DN of that certificate in the Globus format.
*
* @param chain the certificate chain to find the identity
* certificate in. The certificates must be
* of <code>X509CertificateObject</code> type.
* @return the subject DN of the identity certificate in
* the Globus format.
* @exception CertificateException if something goes wrong.
*/
public static String getIdentity(X509Certificate [] chain)
throws CertificateException {
return getIdentity(getIdentityCertificate(chain));
}
/**
* Finds the identity certificate in the given chain.
* The identity certificate is the first certificate in the
* chain that is not an impersonation proxy (full or limited)
*
* @param chain the certificate chain to find the identity
* certificate in.
* @return the identity certificate.
* @exception CertificateException if something goes wrong.
*/
public static X509Certificate getIdentityCertificate(X509Certificate [] chain)
throws CertificateException {
if (chain == null) {
throw new IllegalArgumentException(i18n.getMessage("certChainNull"));
}
GSIConstants.CertificateType certType;
for (int i=0;i<chain.length;i++) {
certType = getCertificateType(chain[i]);
if (!ProxyCertificateUtil.isImpersonationProxy(certType)) {
return chain[i];
}
}
return null;
}
/**
* Retrieves the actual value of the X.509 extension.
*
* @param certExtValue the DER-encoded OCTET string value of the extension.
* @return the decoded/actual value of the extension (the octets).
*/
public static byte[] getExtensionValue(byte [] certExtValue)
throws IOException {
ByteArrayInputStream inStream = new ByteArrayInputStream(certExtValue);
ASN1InputStream derInputStream = new ASN1InputStream(inStream);
DERObject object = derInputStream.readObject();
if (object instanceof ASN1OctetString) {
return ((ASN1OctetString)object).getOctets();
} else {
throw new IOException(i18n.getMessage("octectExp"));
}
}
/**
* Returns the actual value of the extension.
*
* @param cert the certificate that contains the extensions to retrieve.
* @param oid the oid of the extension to retrieve.
* @return the actual value of the extension (not octet string encoded)
* @exception IOException if decoding the extension fails.
*/
public static byte[] getExtensionValue(X509Certificate cert, String oid)
throws IOException {
if (cert == null) {
throw new IllegalArgumentException(i18n.getMessage("certNull"));
}
if (oid == null) {
throw new IllegalArgumentException(i18n.getMessage("oidNull"));
}
byte [] value = cert.getExtensionValue(oid);
if (value == null) {
return null;
}
return getExtensionValue(value);
}
public static int getProxyPathConstraint(X509Certificate cert)
throws IOException, CertificateEncodingException {
TBSCertificateStructure crt = getTBSCertificateStructure(cert);
return getProxyPathConstraint(crt);
}
public static int getProxyPathConstraint(TBSCertificateStructure crt)
throws IOException {
ProxyCertInfo proxyCertExt = getProxyCertInfo(crt);
return (proxyCertExt != null) ? proxyCertExt.getPathLenConstraint() :
-1;
}
public static ProxyCertInfo getProxyCertInfo(TBSCertificateStructure crt)
throws IOException {
X509Extensions extensions = crt.getExtensions();
if (extensions == null) {
return null;
}
X509Extension ext =
extensions.getExtension(ProxyCertInfo.OID);
if (ext == null) {
ext = extensions.getExtension(ProxyCertInfo.OLD_OID);
}
return (ext != null) ? BouncyCastleUtil.getProxyCertInfo(ext) : null;
}
}
| apache-2.0 |
jasdel/aws-sdk-go | private/protocol/ec2query/unmarshal_test.go | 86851 | // Code generated by models/protocol_tests/generate.go. DO NOT EDIT.
package ec2query_test
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/aws/aws-sdk-go/awstesting"
"github.com/aws/aws-sdk-go/awstesting/unit"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/ec2query"
"github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil"
"github.com/aws/aws-sdk-go/private/util"
)
var _ bytes.Buffer // always import bytes
var _ http.Request
var _ json.Marshaler
var _ time.Time
var _ xmlutil.XMLNode
var _ xml.Attr
var _ = ioutil.Discard
var _ = util.Trim("")
var _ = url.Values{}
var _ = io.EOF
var _ = aws.String
var _ = fmt.Println
var _ = reflect.Value{}
func init() {
protocol.RandReader = &awstesting.ZeroReader{}
}
// OutputService1ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService1ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService1ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService1ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService1ProtocolTest client from just a session.
// svc := outputservice1protocoltest.New(mySession)
//
// // Create a OutputService1ProtocolTest client with additional configuration
// svc := outputservice1protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService1ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService1ProtocolTest {
c := p.ClientConfig("outputservice1protocoltest", cfgs...)
return newOutputService1ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService1ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService1ProtocolTest {
svc := &OutputService1ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService1ProtocolTest",
ServiceID: "OutputService1ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService1ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService1TestCaseOperation1 = "OperationName"
// OutputService1TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService1TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService1TestCaseOperation1 for more information on using the OutputService1TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService1TestCaseOperation1Request method.
// req, resp := client.OutputService1TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *request.Request, output *OutputService1TestShapeOutputService1TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService1TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{}
}
output = &OutputService1TestShapeOutputService1TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService1TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService1TestCaseOperation1 for usage and error information.
func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (*OutputService1TestShapeOutputService1TestCaseOperation1Output, error) {
req, out := c.OutputService1TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService1TestCaseOperation1WithContext is the same as OutputService1TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService1TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1WithContext(ctx aws.Context, input *OutputService1TestShapeOutputService1TestCaseOperation1Input, opts ...request.Option) (*OutputService1TestShapeOutputService1TestCaseOperation1Output, error) {
req, out := c.OutputService1TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService1TestShapeOutputService1TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService1TestShapeOutputService1TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Char *string `type:"character"`
Double *float64 `type:"double"`
FalseBool *bool `type:"boolean"`
Float *float64 `type:"float"`
Long *int64 `type:"long"`
Num *int64 `locationName:"FooNum" type:"integer"`
Str *string `type:"string"`
TrueBool *bool `type:"boolean"`
}
// SetChar sets the Char field's value.
func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetChar(v string) *OutputService1TestShapeOutputService1TestCaseOperation1Output {
s.Char = &v
return s
}
// SetDouble sets the Double field's value.
func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetDouble(v float64) *OutputService1TestShapeOutputService1TestCaseOperation1Output {
s.Double = &v
return s
}
// SetFalseBool sets the FalseBool field's value.
func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetFalseBool(v bool) *OutputService1TestShapeOutputService1TestCaseOperation1Output {
s.FalseBool = &v
return s
}
// SetFloat sets the Float field's value.
func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetFloat(v float64) *OutputService1TestShapeOutputService1TestCaseOperation1Output {
s.Float = &v
return s
}
// SetLong sets the Long field's value.
func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetLong(v int64) *OutputService1TestShapeOutputService1TestCaseOperation1Output {
s.Long = &v
return s
}
// SetNum sets the Num field's value.
func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetNum(v int64) *OutputService1TestShapeOutputService1TestCaseOperation1Output {
s.Num = &v
return s
}
// SetStr sets the Str field's value.
func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetStr(v string) *OutputService1TestShapeOutputService1TestCaseOperation1Output {
s.Str = &v
return s
}
// SetTrueBool sets the TrueBool field's value.
func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetTrueBool(v bool) *OutputService1TestShapeOutputService1TestCaseOperation1Output {
s.TrueBool = &v
return s
}
// OutputService2ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService2ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService2ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService2ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService2ProtocolTest client from just a session.
// svc := outputservice2protocoltest.New(mySession)
//
// // Create a OutputService2ProtocolTest client with additional configuration
// svc := outputservice2protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService2ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService2ProtocolTest {
c := p.ClientConfig("outputservice2protocoltest", cfgs...)
return newOutputService2ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService2ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService2ProtocolTest {
svc := &OutputService2ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService2ProtocolTest",
ServiceID: "OutputService2ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService2ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService2TestCaseOperation1 = "OperationName"
// OutputService2TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService2TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService2TestCaseOperation1 for more information on using the OutputService2TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService2TestCaseOperation1Request method.
// req, resp := client.OutputService2TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *request.Request, output *OutputService2TestShapeOutputService2TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService2TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{}
}
output = &OutputService2TestShapeOutputService2TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService2TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService2TestCaseOperation1 for usage and error information.
func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (*OutputService2TestShapeOutputService2TestCaseOperation1Output, error) {
req, out := c.OutputService2TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService2TestCaseOperation1WithContext is the same as OutputService2TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService2TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1WithContext(ctx aws.Context, input *OutputService2TestShapeOutputService2TestCaseOperation1Input, opts ...request.Option) (*OutputService2TestShapeOutputService2TestCaseOperation1Output, error) {
req, out := c.OutputService2TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService2TestShapeOutputService2TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService2TestShapeOutputService2TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
// Blob is automatically base64 encoded/decoded by the SDK.
Blob []byte `type:"blob"`
}
// SetBlob sets the Blob field's value.
func (s *OutputService2TestShapeOutputService2TestCaseOperation1Output) SetBlob(v []byte) *OutputService2TestShapeOutputService2TestCaseOperation1Output {
s.Blob = v
return s
}
// OutputService3ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService3ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService3ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService3ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService3ProtocolTest client from just a session.
// svc := outputservice3protocoltest.New(mySession)
//
// // Create a OutputService3ProtocolTest client with additional configuration
// svc := outputservice3protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService3ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService3ProtocolTest {
c := p.ClientConfig("outputservice3protocoltest", cfgs...)
return newOutputService3ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService3ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService3ProtocolTest {
svc := &OutputService3ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService3ProtocolTest",
ServiceID: "OutputService3ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService3ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService3TestCaseOperation1 = "OperationName"
// OutputService3TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService3TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService3TestCaseOperation1 for more information on using the OutputService3TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService3TestCaseOperation1Request method.
// req, resp := client.OutputService3TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *request.Request, output *OutputService3TestShapeOutputService3TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService3TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{}
}
output = &OutputService3TestShapeOutputService3TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService3TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService3TestCaseOperation1 for usage and error information.
func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (*OutputService3TestShapeOutputService3TestCaseOperation1Output, error) {
req, out := c.OutputService3TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService3TestCaseOperation1WithContext is the same as OutputService3TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService3TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1WithContext(ctx aws.Context, input *OutputService3TestShapeOutputService3TestCaseOperation1Input, opts ...request.Option) (*OutputService3TestShapeOutputService3TestCaseOperation1Output, error) {
req, out := c.OutputService3TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService3TestShapeOutputService3TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService3TestShapeOutputService3TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
ListMember []*string `type:"list"`
}
// SetListMember sets the ListMember field's value.
func (s *OutputService3TestShapeOutputService3TestCaseOperation1Output) SetListMember(v []*string) *OutputService3TestShapeOutputService3TestCaseOperation1Output {
s.ListMember = v
return s
}
// OutputService4ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService4ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService4ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService4ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService4ProtocolTest client from just a session.
// svc := outputservice4protocoltest.New(mySession)
//
// // Create a OutputService4ProtocolTest client with additional configuration
// svc := outputservice4protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService4ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService4ProtocolTest {
c := p.ClientConfig("outputservice4protocoltest", cfgs...)
return newOutputService4ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService4ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService4ProtocolTest {
svc := &OutputService4ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService4ProtocolTest",
ServiceID: "OutputService4ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService4ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService4TestCaseOperation1 = "OperationName"
// OutputService4TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService4TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService4TestCaseOperation1 for more information on using the OutputService4TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService4TestCaseOperation1Request method.
// req, resp := client.OutputService4TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *request.Request, output *OutputService4TestShapeOutputService4TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService4TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{}
}
output = &OutputService4TestShapeOutputService4TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService4TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService4TestCaseOperation1 for usage and error information.
func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (*OutputService4TestShapeOutputService4TestCaseOperation1Output, error) {
req, out := c.OutputService4TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService4TestCaseOperation1WithContext is the same as OutputService4TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService4TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1WithContext(ctx aws.Context, input *OutputService4TestShapeOutputService4TestCaseOperation1Input, opts ...request.Option) (*OutputService4TestShapeOutputService4TestCaseOperation1Output, error) {
req, out := c.OutputService4TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService4TestShapeOutputService4TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService4TestShapeOutputService4TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
ListMember []*string `locationNameList:"item" type:"list"`
}
// SetListMember sets the ListMember field's value.
func (s *OutputService4TestShapeOutputService4TestCaseOperation1Output) SetListMember(v []*string) *OutputService4TestShapeOutputService4TestCaseOperation1Output {
s.ListMember = v
return s
}
// OutputService5ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService5ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService5ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService5ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService5ProtocolTest client from just a session.
// svc := outputservice5protocoltest.New(mySession)
//
// // Create a OutputService5ProtocolTest client with additional configuration
// svc := outputservice5protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService5ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService5ProtocolTest {
c := p.ClientConfig("outputservice5protocoltest", cfgs...)
return newOutputService5ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService5ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService5ProtocolTest {
svc := &OutputService5ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService5ProtocolTest",
ServiceID: "OutputService5ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService5ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService5TestCaseOperation1 = "OperationName"
// OutputService5TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService5TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService5TestCaseOperation1 for more information on using the OutputService5TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService5TestCaseOperation1Request method.
// req, resp := client.OutputService5TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *request.Request, output *OutputService5TestShapeOutputService5TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService5TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{}
}
output = &OutputService5TestShapeOutputService5TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService5TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService5TestCaseOperation1 for usage and error information.
func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (*OutputService5TestShapeOutputService5TestCaseOperation1Output, error) {
req, out := c.OutputService5TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService5TestCaseOperation1WithContext is the same as OutputService5TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService5TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1WithContext(ctx aws.Context, input *OutputService5TestShapeOutputService5TestCaseOperation1Input, opts ...request.Option) (*OutputService5TestShapeOutputService5TestCaseOperation1Output, error) {
req, out := c.OutputService5TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService5TestShapeOutputService5TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService5TestShapeOutputService5TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
ListMember []*string `type:"list" flattened:"true"`
}
// SetListMember sets the ListMember field's value.
func (s *OutputService5TestShapeOutputService5TestCaseOperation1Output) SetListMember(v []*string) *OutputService5TestShapeOutputService5TestCaseOperation1Output {
s.ListMember = v
return s
}
// OutputService6ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService6ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService6ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService6ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService6ProtocolTest client from just a session.
// svc := outputservice6protocoltest.New(mySession)
//
// // Create a OutputService6ProtocolTest client with additional configuration
// svc := outputservice6protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService6ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService6ProtocolTest {
c := p.ClientConfig("outputservice6protocoltest", cfgs...)
return newOutputService6ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService6ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService6ProtocolTest {
svc := &OutputService6ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService6ProtocolTest",
ServiceID: "OutputService6ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService6ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService6TestCaseOperation1 = "OperationName"
// OutputService6TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService6TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService6TestCaseOperation1 for more information on using the OutputService6TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService6TestCaseOperation1Request method.
// req, resp := client.OutputService6TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *request.Request, output *OutputService6TestShapeOutputService6TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService6TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{}
}
output = &OutputService6TestShapeOutputService6TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService6TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService6TestCaseOperation1 for usage and error information.
func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (*OutputService6TestShapeOutputService6TestCaseOperation1Output, error) {
req, out := c.OutputService6TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService6TestCaseOperation1WithContext is the same as OutputService6TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService6TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1WithContext(ctx aws.Context, input *OutputService6TestShapeOutputService6TestCaseOperation1Input, opts ...request.Option) (*OutputService6TestShapeOutputService6TestCaseOperation1Output, error) {
req, out := c.OutputService6TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService6TestShapeOutputService6TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService6TestShapeOutputService6TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Map map[string]*OutputService6TestShapeStructureType `type:"map"`
}
// SetMap sets the Map field's value.
func (s *OutputService6TestShapeOutputService6TestCaseOperation1Output) SetMap(v map[string]*OutputService6TestShapeStructureType) *OutputService6TestShapeOutputService6TestCaseOperation1Output {
s.Map = v
return s
}
type OutputService6TestShapeStructureType struct {
_ struct{} `type:"structure"`
Foo *string `locationName:"foo" type:"string"`
}
// SetFoo sets the Foo field's value.
func (s *OutputService6TestShapeStructureType) SetFoo(v string) *OutputService6TestShapeStructureType {
s.Foo = &v
return s
}
// OutputService7ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService7ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService7ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService7ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService7ProtocolTest client from just a session.
// svc := outputservice7protocoltest.New(mySession)
//
// // Create a OutputService7ProtocolTest client with additional configuration
// svc := outputservice7protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService7ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService7ProtocolTest {
c := p.ClientConfig("outputservice7protocoltest", cfgs...)
return newOutputService7ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService7ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService7ProtocolTest {
svc := &OutputService7ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService7ProtocolTest",
ServiceID: "OutputService7ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService7ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService7TestCaseOperation1 = "OperationName"
// OutputService7TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService7TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService7TestCaseOperation1 for more information on using the OutputService7TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService7TestCaseOperation1Request method.
// req, resp := client.OutputService7TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *request.Request, output *OutputService7TestShapeOutputService7TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService7TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{}
}
output = &OutputService7TestShapeOutputService7TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService7TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService7TestCaseOperation1 for usage and error information.
func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (*OutputService7TestShapeOutputService7TestCaseOperation1Output, error) {
req, out := c.OutputService7TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService7TestCaseOperation1WithContext is the same as OutputService7TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService7TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1WithContext(ctx aws.Context, input *OutputService7TestShapeOutputService7TestCaseOperation1Input, opts ...request.Option) (*OutputService7TestShapeOutputService7TestCaseOperation1Output, error) {
req, out := c.OutputService7TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService7TestShapeOutputService7TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService7TestShapeOutputService7TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Map map[string]*string `type:"map" flattened:"true"`
}
// SetMap sets the Map field's value.
func (s *OutputService7TestShapeOutputService7TestCaseOperation1Output) SetMap(v map[string]*string) *OutputService7TestShapeOutputService7TestCaseOperation1Output {
s.Map = v
return s
}
// OutputService8ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService8ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService8ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService8ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService8ProtocolTest client from just a session.
// svc := outputservice8protocoltest.New(mySession)
//
// // Create a OutputService8ProtocolTest client with additional configuration
// svc := outputservice8protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService8ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService8ProtocolTest {
c := p.ClientConfig("outputservice8protocoltest", cfgs...)
return newOutputService8ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService8ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService8ProtocolTest {
svc := &OutputService8ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService8ProtocolTest",
ServiceID: "OutputService8ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService8ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService8TestCaseOperation1 = "OperationName"
// OutputService8TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService8TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService8TestCaseOperation1 for more information on using the OutputService8TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService8TestCaseOperation1Request method.
// req, resp := client.OutputService8TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *request.Request, output *OutputService8TestShapeOutputService8TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService8TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{}
}
output = &OutputService8TestShapeOutputService8TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService8TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService8TestCaseOperation1 for usage and error information.
func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (*OutputService8TestShapeOutputService8TestCaseOperation1Output, error) {
req, out := c.OutputService8TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService8TestCaseOperation1WithContext is the same as OutputService8TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService8TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1WithContext(ctx aws.Context, input *OutputService8TestShapeOutputService8TestCaseOperation1Input, opts ...request.Option) (*OutputService8TestShapeOutputService8TestCaseOperation1Output, error) {
req, out := c.OutputService8TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService8TestShapeOutputService8TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService8TestShapeOutputService8TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Map map[string]*string `locationNameKey:"foo" locationNameValue:"bar" type:"map" flattened:"true"`
}
// SetMap sets the Map field's value.
func (s *OutputService8TestShapeOutputService8TestCaseOperation1Output) SetMap(v map[string]*string) *OutputService8TestShapeOutputService8TestCaseOperation1Output {
s.Map = v
return s
}
// OutputService9ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService9ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService9ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService9ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService9ProtocolTest client from just a session.
// svc := outputservice9protocoltest.New(mySession)
//
// // Create a OutputService9ProtocolTest client with additional configuration
// svc := outputservice9protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService9ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService9ProtocolTest {
c := p.ClientConfig("outputservice9protocoltest", cfgs...)
return newOutputService9ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService9ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService9ProtocolTest {
svc := &OutputService9ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService9ProtocolTest",
ServiceID: "OutputService9ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService9ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService9TestCaseOperation1 = "OperationName"
// OutputService9TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService9TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService9TestCaseOperation1 for more information on using the OutputService9TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService9TestCaseOperation1Request method.
// req, resp := client.OutputService9TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1Request(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (req *request.Request, output *OutputService9TestShapeOutputService9TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService9TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService9TestShapeOutputService9TestCaseOperation1Input{}
}
output = &OutputService9TestShapeOutputService9TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService9TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService9TestCaseOperation1 for usage and error information.
func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (*OutputService9TestShapeOutputService9TestCaseOperation1Output, error) {
req, out := c.OutputService9TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService9TestCaseOperation1WithContext is the same as OutputService9TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService9TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1WithContext(ctx aws.Context, input *OutputService9TestShapeOutputService9TestCaseOperation1Input, opts ...request.Option) (*OutputService9TestShapeOutputService9TestCaseOperation1Output, error) {
req, out := c.OutputService9TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService9TestShapeOutputService9TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService9TestShapeOutputService9TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Foo *string `type:"string"`
}
// SetFoo sets the Foo field's value.
func (s *OutputService9TestShapeOutputService9TestCaseOperation1Output) SetFoo(v string) *OutputService9TestShapeOutputService9TestCaseOperation1Output {
s.Foo = &v
return s
}
// OutputService10ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService10ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService10ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService10ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService10ProtocolTest client from just a session.
// svc := outputservice10protocoltest.New(mySession)
//
// // Create a OutputService10ProtocolTest client with additional configuration
// svc := outputservice10protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService10ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService10ProtocolTest {
c := p.ClientConfig("outputservice10protocoltest", cfgs...)
return newOutputService10ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService10ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService10ProtocolTest {
svc := &OutputService10ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService10ProtocolTest",
ServiceID: "OutputService10ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService10ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService10ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService10TestCaseOperation1 = "OperationName"
// OutputService10TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService10TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService10TestCaseOperation1 for more information on using the OutputService10TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService10TestCaseOperation1Request method.
// req, resp := client.OutputService10TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1Request(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (req *request.Request, output *OutputService10TestShapeOutputService10TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService10TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService10TestShapeOutputService10TestCaseOperation1Input{}
}
output = &OutputService10TestShapeOutputService10TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService10TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService10TestCaseOperation1 for usage and error information.
func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (*OutputService10TestShapeOutputService10TestCaseOperation1Output, error) {
req, out := c.OutputService10TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService10TestCaseOperation1WithContext is the same as OutputService10TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService10TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1WithContext(ctx aws.Context, input *OutputService10TestShapeOutputService10TestCaseOperation1Input, opts ...request.Option) (*OutputService10TestShapeOutputService10TestCaseOperation1Output, error) {
req, out := c.OutputService10TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService10TestShapeOutputService10TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService10TestShapeOutputService10TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
StructMember *OutputService10TestShapeTimeContainer `type:"structure"`
TimeArg *time.Time `type:"timestamp"`
TimeCustom *time.Time `type:"timestamp" timestampFormat:"rfc822"`
TimeFormat *time.Time `type:"timestamp" timestampFormat:"unixTimestamp"`
}
// SetStructMember sets the StructMember field's value.
func (s *OutputService10TestShapeOutputService10TestCaseOperation1Output) SetStructMember(v *OutputService10TestShapeTimeContainer) *OutputService10TestShapeOutputService10TestCaseOperation1Output {
s.StructMember = v
return s
}
// SetTimeArg sets the TimeArg field's value.
func (s *OutputService10TestShapeOutputService10TestCaseOperation1Output) SetTimeArg(v time.Time) *OutputService10TestShapeOutputService10TestCaseOperation1Output {
s.TimeArg = &v
return s
}
// SetTimeCustom sets the TimeCustom field's value.
func (s *OutputService10TestShapeOutputService10TestCaseOperation1Output) SetTimeCustom(v time.Time) *OutputService10TestShapeOutputService10TestCaseOperation1Output {
s.TimeCustom = &v
return s
}
// SetTimeFormat sets the TimeFormat field's value.
func (s *OutputService10TestShapeOutputService10TestCaseOperation1Output) SetTimeFormat(v time.Time) *OutputService10TestShapeOutputService10TestCaseOperation1Output {
s.TimeFormat = &v
return s
}
type OutputService10TestShapeTimeContainer struct {
_ struct{} `type:"structure"`
Bar *time.Time `locationName:"bar" type:"timestamp" timestampFormat:"unixTimestamp"`
Foo *time.Time `locationName:"foo" type:"timestamp"`
}
// SetBar sets the Bar field's value.
func (s *OutputService10TestShapeTimeContainer) SetBar(v time.Time) *OutputService10TestShapeTimeContainer {
s.Bar = &v
return s
}
// SetFoo sets the Foo field's value.
func (s *OutputService10TestShapeTimeContainer) SetFoo(v time.Time) *OutputService10TestShapeTimeContainer {
s.Foo = &v
return s
}
// OutputService11ProtocolTest provides the API operation methods for making requests to
// . See this package's package overview docs
// for details on the service.
//
// OutputService11ProtocolTest methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type OutputService11ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService11ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a OutputService11ProtocolTest client from just a session.
// svc := outputservice11protocoltest.New(mySession)
//
// // Create a OutputService11ProtocolTest client with additional configuration
// svc := outputservice11protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService11ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService11ProtocolTest {
c := p.ClientConfig("outputservice11protocoltest", cfgs...)
return newOutputService11ProtocolTestClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService11ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *OutputService11ProtocolTest {
svc := &OutputService11ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "OutputService11ProtocolTest",
ServiceID: "OutputService11ProtocolTest",
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler)
return svc
}
// newRequest creates a new request for a OutputService11ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService11ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService11TestCaseOperation1 = "OperationName"
// OutputService11TestCaseOperation1Request generates a "aws/request.Request" representing the
// client's request for the OutputService11TestCaseOperation1 operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See OutputService11TestCaseOperation1 for more information on using the OutputService11TestCaseOperation1
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the OutputService11TestCaseOperation1Request method.
// req, resp := client.OutputService11TestCaseOperation1Request(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1Request(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (req *request.Request, output *OutputService11TestShapeOutputService11TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService11TestCaseOperation1,
HTTPPath: "/",
}
if input == nil {
input = &OutputService11TestShapeOutputService11TestCaseOperation1Input{}
}
output = &OutputService11TestShapeOutputService11TestCaseOperation1Output{}
req = c.newRequest(op, input, output)
return
}
// OutputService11TestCaseOperation1 API operation for .
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for 's
// API operation OutputService11TestCaseOperation1 for usage and error information.
func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (*OutputService11TestShapeOutputService11TestCaseOperation1Output, error) {
req, out := c.OutputService11TestCaseOperation1Request(input)
return out, req.Send()
}
// OutputService11TestCaseOperation1WithContext is the same as OutputService11TestCaseOperation1 with the addition of
// the ability to pass a context and additional request options.
//
// See OutputService11TestCaseOperation1 for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1WithContext(ctx aws.Context, input *OutputService11TestShapeOutputService11TestCaseOperation1Input, opts ...request.Option) (*OutputService11TestShapeOutputService11TestCaseOperation1Output, error) {
req, out := c.OutputService11TestCaseOperation1Request(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type OutputService11TestShapeOutputService11TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService11TestShapeOutputService11TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
FooEnum *string `type:"string" enum:"OutputService11TestShapeEC2EnumType"`
ListEnums []*string `type:"list"`
}
// SetFooEnum sets the FooEnum field's value.
func (s *OutputService11TestShapeOutputService11TestCaseOperation1Output) SetFooEnum(v string) *OutputService11TestShapeOutputService11TestCaseOperation1Output {
s.FooEnum = &v
return s
}
// SetListEnums sets the ListEnums field's value.
func (s *OutputService11TestShapeOutputService11TestCaseOperation1Output) SetListEnums(v []*string) *OutputService11TestShapeOutputService11TestCaseOperation1Output {
s.ListEnums = v
return s
}
const (
// EC2EnumTypeFoo is a OutputService11TestShapeEC2EnumType enum value
EC2EnumTypeFoo = "foo"
// EC2EnumTypeBar is a OutputService11TestShapeEC2EnumType enum value
EC2EnumTypeBar = "bar"
)
// OutputService11TestShapeEC2EnumType_Values returns all elements of the OutputService11TestShapeEC2EnumType enum
func OutputService11TestShapeEC2EnumType_Values() []string {
return []string{
EC2EnumTypeFoo,
EC2EnumTypeBar,
}
}
//
// Tests begin here
//
func TestOutputService1ProtocolTestScalarMembersCase1(t *testing.T) {
svc := NewOutputService1ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><Str>myname</Str><FooNum>123</FooNum><FalseBool>false</FalseBool><TrueBool>true</TrueBool><Float>1.2</Float><Double>1.3</Double><Long>200</Long><Char>a</Char><RequestId>request-id</RequestId></OperationNameResponse>"))
req, out := svc.OutputService1TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "a", *out.Char; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := 1.3, *out.Double; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := false, *out.FalseBool; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := 1.2, *out.Float; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := int64(200), *out.Long; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := int64(123), *out.Num; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "myname", *out.Str; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := true, *out.TrueBool; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService2ProtocolTestBlobCase1(t *testing.T) {
svc := NewOutputService2ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><Blob>dmFsdWU=</Blob><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService2TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "value", string(out.Blob); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService3ProtocolTestListsCase1(t *testing.T) {
svc := NewOutputService3ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><ListMember><member>abc</member><member>123</member></ListMember><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService3TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "abc", *out.ListMember[0]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "123", *out.ListMember[1]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService4ProtocolTestListWithCustomMemberNameCase1(t *testing.T) {
svc := NewOutputService4ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><ListMember><item>abc</item><item>123</item></ListMember><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService4TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "abc", *out.ListMember[0]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "123", *out.ListMember[1]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService5ProtocolTestFlattenedListCase1(t *testing.T) {
svc := NewOutputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><ListMember>abc</ListMember><ListMember>123</ListMember><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService5TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "abc", *out.ListMember[0]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "123", *out.ListMember[1]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService6ProtocolTestNormalMapCase1(t *testing.T) {
svc := NewOutputService6ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><Map><entry><key>qux</key><value><foo>bar</foo></value></entry><entry><key>baz</key><value><foo>bam</foo></value></entry></Map><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService6TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "bam", *out.Map["baz"].Foo; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "bar", *out.Map["qux"].Foo; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService7ProtocolTestFlattenedMapCase1(t *testing.T) {
svc := NewOutputService7ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><Map><key>qux</key><value>bar</value></Map><Map><key>baz</key><value>bam</value></Map><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService7TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "bam", *out.Map["baz"]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "bar", *out.Map["qux"]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService8ProtocolTestNamedMapCase1(t *testing.T) {
svc := NewOutputService8ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><Map><foo>qux</foo><bar>bar</bar></Map><Map><foo>baz</foo><bar>bam</bar></Map><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService8TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "bam", *out.Map["baz"]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "bar", *out.Map["qux"]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService9ProtocolTestEmptyStringCase1(t *testing.T) {
svc := NewOutputService9ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><Foo/><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService9TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "", *out.Foo; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService10ProtocolTestTimestampMembersCase1(t *testing.T) {
svc := NewOutputService10ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><StructMember><foo>2014-04-29T18:30:38Z</foo><bar>1398796238</bar></StructMember><TimeArg>2014-04-29T18:30:38Z</TimeArg><TimeCustom>Tue, 29 Apr 2014 18:30:38 GMT</TimeCustom><TimeFormat>1398796238</TimeFormat><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService10TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := time.Unix(1.398796238e+09, 0).UTC().String(), out.StructMember.Bar.UTC().String(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := time.Unix(1.398796238e+09, 0).UTC().String(), out.StructMember.Foo.UTC().String(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := time.Unix(1.398796238e+09, 0).UTC().String(), out.TimeArg.UTC().String(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := time.Unix(1.398796238e+09, 0).UTC().String(), out.TimeCustom.UTC().String(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := time.Unix(1.398796238e+09, 0).UTC().String(), out.TimeFormat.UTC().String(); e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
func TestOutputService11ProtocolTestEnumOutputCase1(t *testing.T) {
svc := NewOutputService11ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><FooEnum>foo</FooEnum><ListEnums><member>foo</member><member>bar</member></ListEnums></OperationNameResponse>"))
req, out := svc.OutputService11TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
req.Handlers.UnmarshalMeta.Run(req)
req.Handlers.Unmarshal.Run(req)
if req.Error != nil {
t.Errorf("expect not error, got %v", req.Error)
}
// assert response
if out == nil {
t.Errorf("expect not to be nil")
}
if e, a := "foo", *out.FooEnum; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "foo", *out.ListEnums[0]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
if e, a := "bar", *out.ListEnums[1]; e != a {
t.Errorf("expect %v, got %v", e, a)
}
}
| apache-2.0 |