code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2019 The ZAP Development 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.zaproxy.zap.extension.ascanrulesBeta;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Duplicated from Replacer addon. */
class HexString {
private static final Pattern HEX_VALUE = Pattern.compile("\\\\?\\\\x\\p{XDigit}{2}");
private static final String ESCAPED_ESCAPE_CHAR = "\\\\";
static String compile(String binaryRegex) {
Matcher matcher = HEX_VALUE.matcher(binaryRegex);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String value = matcher.group();
if (!value.startsWith(ESCAPED_ESCAPE_CHAR)) {
value = convertByte(value.substring(2));
}
matcher.appendReplacement(sb, value);
}
matcher.appendTail(sb);
return sb.toString();
}
private static String convertByte(String value) {
return Matcher.quoteReplacement(
new String(
new byte[] {(byte) Integer.parseInt(value, 16)},
StandardCharsets.US_ASCII));
}
}
| kingthorin/zap-extensions | addOns/ascanrulesBeta/src/main/java/org/zaproxy/zap/extension/ascanrulesBeta/HexString.java | Java | apache-2.0 | 1,851 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.query.aggregation.post;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.apache.druid.java.util.common.guava.Comparators;
import org.apache.druid.math.expr.Expr;
import org.apache.druid.math.expr.ExprMacroTable;
import org.apache.druid.math.expr.Parser;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.query.aggregation.PostAggregator;
import org.apache.druid.query.cache.CacheKeyBuilder;
import org.apache.druid.utils.CollectionUtils;
import javax.annotation.Nullable;
import java.util.Comparator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class ExpressionPostAggregator implements PostAggregator
{
private static final Comparator<Comparable> DEFAULT_COMPARATOR = Comparator.nullsFirst(
(Comparable o1, Comparable o2) -> {
if (o1 instanceof Long && o2 instanceof Long) {
return Long.compare((long) o1, (long) o2);
} else if (o1 instanceof Number && o2 instanceof Number) {
return Double.compare(((Number) o1).doubleValue(), ((Number) o2).doubleValue());
} else {
return o1.compareTo(o2);
}
}
);
private final String name;
private final String expression;
private final Comparator<Comparable> comparator;
private final String ordering;
private final ExprMacroTable macroTable;
private final Map<String, Function<Object, Object>> finalizers;
private final Supplier<Expr> parsed;
private final Supplier<Set<String>> dependentFields;
/**
* Constructor for serialization.
*/
@JsonCreator
public ExpressionPostAggregator(
@JsonProperty("name") String name,
@JsonProperty("expression") String expression,
@JsonProperty("ordering") @Nullable String ordering,
@JacksonInject ExprMacroTable macroTable
)
{
this(name, expression, ordering, macroTable, ImmutableMap.of());
}
/**
* Constructor for {@link #decorate(Map)}.
*/
private ExpressionPostAggregator(
final String name,
final String expression,
@Nullable final String ordering,
final ExprMacroTable macroTable,
final Map<String, Function<Object, Object>> finalizers
)
{
this(
name,
expression,
ordering,
macroTable,
finalizers,
Suppliers.memoize(() -> Parser.parse(expression, macroTable))
);
}
private ExpressionPostAggregator(
final String name,
final String expression,
@Nullable final String ordering,
final ExprMacroTable macroTable,
final Map<String, Function<Object, Object>> finalizers,
final Supplier<Expr> parsed
)
{
this(
name,
expression,
ordering,
macroTable,
finalizers,
parsed,
Suppliers.memoize(() -> parsed.get().analyzeInputs().getRequiredBindings()));
}
private ExpressionPostAggregator(
final String name,
final String expression,
@Nullable final String ordering,
final ExprMacroTable macroTable,
final Map<String, Function<Object, Object>> finalizers,
final Supplier<Expr> parsed,
final Supplier<Set<String>> dependentFields
)
{
Preconditions.checkArgument(expression != null, "expression cannot be null");
this.name = name;
this.expression = expression;
this.ordering = ordering;
this.comparator = ordering == null ? DEFAULT_COMPARATOR : Ordering.valueOf(ordering);
this.macroTable = macroTable;
this.finalizers = finalizers;
this.parsed = parsed;
this.dependentFields = dependentFields;
}
@Override
public Set<String> getDependentFields()
{
return dependentFields.get();
}
@Override
public Comparator getComparator()
{
return comparator;
}
@Override
public Object compute(Map<String, Object> values)
{
// Maps.transformEntries is lazy, will only finalize values we actually read.
final Map<String, Object> finalizedValues = Maps.transformEntries(
values,
(String k, Object v) -> {
final Function<Object, Object> finalizer = finalizers.get(k);
return finalizer != null ? finalizer.apply(v) : v;
}
);
return parsed.get().eval(Parser.withMap(finalizedValues)).value();
}
@Override
@JsonProperty
public String getName()
{
return name;
}
@Override
public ExpressionPostAggregator decorate(final Map<String, AggregatorFactory> aggregators)
{
return new ExpressionPostAggregator(
name,
expression,
ordering,
macroTable,
CollectionUtils.mapValues(aggregators, aggregatorFactory -> obj -> aggregatorFactory.finalizeComputation(obj)),
parsed,
dependentFields
);
}
@JsonProperty("expression")
public String getExpression()
{
return expression;
}
@JsonProperty("ordering")
public String getOrdering()
{
return ordering;
}
@Override
public String toString()
{
return "ExpressionPostAggregator{" +
"name='" + name + '\'' +
", expression='" + expression + '\'' +
", ordering=" + ordering +
'}';
}
@Override
public byte[] getCacheKey()
{
return new CacheKeyBuilder(PostAggregatorIds.EXPRESSION)
.appendString(expression)
.appendString(ordering)
.build();
}
public enum Ordering implements Comparator<Comparable>
{
/**
* Ensures the following order: numeric > NaN > Infinite.
*
* The name may be referenced via Ordering.valueOf(String) in the constructor {@link
* ExpressionPostAggregator#ExpressionPostAggregator(String, String, String, ExprMacroTable, Map)}.
*/
@SuppressWarnings("unused")
numericFirst {
@Override
public int compare(Comparable lhs, Comparable rhs)
{
if (lhs instanceof Long && rhs instanceof Long) {
return Long.compare(((Number) lhs).longValue(), ((Number) rhs).longValue());
} else if (lhs instanceof Number && rhs instanceof Number) {
double d1 = ((Number) lhs).doubleValue();
double d2 = ((Number) rhs).doubleValue();
if (Double.isFinite(d1) && !Double.isFinite(d2)) {
return 1;
}
if (!Double.isFinite(d1) && Double.isFinite(d2)) {
return -1;
}
return Double.compare(d1, d2);
} else {
return Comparators.<Comparable>naturalNullsFirst().compare(lhs, rhs);
}
}
}
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ExpressionPostAggregator that = (ExpressionPostAggregator) o;
if (!comparator.equals(that.comparator)) {
return false;
}
if (!Objects.equals(name, that.name)) {
return false;
}
if (!Objects.equals(expression, that.expression)) {
return false;
}
if (!Objects.equals(ordering, that.ordering)) {
return false;
}
return true;
}
@Override
public int hashCode()
{
int result = name != null ? name.hashCode() : 0;
result = 31 * result + expression.hashCode();
result = 31 * result + comparator.hashCode();
result = 31 * result + (ordering != null ? ordering.hashCode() : 0);
return result;
}
}
| deltaprojects/druid | processing/src/main/java/org/apache/druid/query/aggregation/post/ExpressionPostAggregator.java | Java | apache-2.0 | 8,546 |
/*
* 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.ignite.yardstick;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteSpring;
import org.apache.ignite.Ignition;
import org.apache.ignite.cache.eviction.lru.LruEvictionPolicy;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.ConnectorConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.configuration.NearCacheConfiguration;
import org.apache.ignite.configuration.TransactionConfiguration;
import org.apache.ignite.internal.util.IgniteUtils;
import org.apache.ignite.lang.IgniteBiTuple;
import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.UrlResource;
import org.yardstickframework.BenchmarkConfiguration;
import org.yardstickframework.BenchmarkServer;
import org.yardstickframework.BenchmarkUtils;
import static org.apache.ignite.cache.CacheMemoryMode.OFFHEAP_VALUES;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER;
/**
* Standalone Ignite node.
*/
public class IgniteNode implements BenchmarkServer {
/** Grid instance. */
private Ignite ignite;
/** Client mode. */
private boolean clientMode;
/** */
public IgniteNode() {
// No-op.
}
/** */
public IgniteNode(boolean clientMode) {
this.clientMode = clientMode;
}
/** */
public IgniteNode(boolean clientMode, Ignite ignite) {
this.clientMode = clientMode;
this.ignite = ignite;
}
/** {@inheritDoc} */
@Override public void start(BenchmarkConfiguration cfg) throws Exception {
IgniteBenchmarkArguments args = new IgniteBenchmarkArguments();
BenchmarkUtils.jcommander(cfg.commandLineArguments(), args, "<ignite-node>");
IgniteBiTuple<IgniteConfiguration, ? extends ApplicationContext> tup = loadConfiguration(args.configuration());
IgniteConfiguration c = tup.get1();
assert c != null;
ApplicationContext appCtx = tup.get2();
assert appCtx != null;
for (CacheConfiguration cc : c.getCacheConfiguration()) {
// IgniteNode can not run in CLIENT_ONLY mode,
// except the case when it's used inside IgniteAbstractBenchmark.
boolean cl = args.isClientOnly() && (args.isNearCache() || clientMode);
if (cl)
c.setClientMode(true);
if (args.isNearCache()) {
NearCacheConfiguration nearCfg = new NearCacheConfiguration();
if (args.getNearCacheSize() != 0)
nearCfg.setNearEvictionPolicy(new LruEvictionPolicy(args.getNearCacheSize()));
cc.setNearConfiguration(nearCfg);
}
cc.setWriteSynchronizationMode(args.syncMode());
if (args.orderMode() != null)
cc.setAtomicWriteOrderMode(args.orderMode());
cc.setBackups(args.backups());
if (args.restTcpPort() != 0) {
ConnectorConfiguration ccc = new ConnectorConfiguration();
ccc.setPort(args.restTcpPort());
if (args.restTcpHost() != null)
ccc.setHost(args.restTcpHost());
c.setConnectorConfiguration(ccc);
}
if (args.isOffHeap()) {
cc.setOffHeapMaxMemory(0);
if (args.isOffheapValues())
cc.setMemoryMode(OFFHEAP_VALUES);
else
cc.setEvictionPolicy(new LruEvictionPolicy(50000));
}
cc.setReadThrough(args.isStoreEnabled());
cc.setWriteThrough(args.isStoreEnabled());
cc.setWriteBehindEnabled(args.isWriteBehind());
BenchmarkUtils.println(cfg, "Cache configured with the following parameters: " + cc);
}
TransactionConfiguration tc = c.getTransactionConfiguration();
tc.setDefaultTxConcurrency(args.txConcurrency());
tc.setDefaultTxIsolation(args.txIsolation());
TcpCommunicationSpi commSpi = (TcpCommunicationSpi)c.getCommunicationSpi();
if (commSpi == null)
commSpi = new TcpCommunicationSpi();
c.setCommunicationSpi(commSpi);
ignite = IgniteSpring.start(c, appCtx);
BenchmarkUtils.println("Configured marshaller: " + ignite.cluster().localNode().attribute(ATTR_MARSHALLER));
}
/**
* @param springCfgPath Spring configuration file path.
* @return Tuple with grid configuration and Spring application context.
* @throws Exception If failed.
*/
private static IgniteBiTuple<IgniteConfiguration, ? extends ApplicationContext> loadConfiguration(String springCfgPath)
throws Exception {
URL url;
try {
url = new URL(springCfgPath);
}
catch (MalformedURLException e) {
url = IgniteUtils.resolveIgniteUrl(springCfgPath);
if (url == null)
throw new IgniteCheckedException("Spring XML configuration path is invalid: " + springCfgPath +
". Note that this path should be either absolute or a relative local file system path, " +
"relative to META-INF in classpath or valid URL to IGNITE_HOME.", e);
}
GenericApplicationContext springCtx;
try {
springCtx = new GenericApplicationContext();
new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(url));
springCtx.refresh();
}
catch (BeansException e) {
throw new Exception("Failed to instantiate Spring XML application context [springUrl=" +
url + ", err=" + e.getMessage() + ']', e);
}
Map<String, IgniteConfiguration> cfgMap;
try {
cfgMap = springCtx.getBeansOfType(IgniteConfiguration.class);
}
catch (BeansException e) {
throw new Exception("Failed to instantiate bean [type=" + IgniteConfiguration.class + ", err=" +
e.getMessage() + ']', e);
}
if (cfgMap == null || cfgMap.isEmpty())
throw new Exception("Failed to find ignite configuration in: " + url);
return new IgniteBiTuple<>(cfgMap.values().iterator().next(), springCtx);
}
/** {@inheritDoc} */
@Override public void stop() throws Exception {
Ignition.stopAll(true);
}
/** {@inheritDoc} */
@Override public String usage() {
return BenchmarkUtils.usage(new IgniteBenchmarkArguments());
}
/**
* @return Ignite.
*/
public Ignite ignite() {
return ignite;
}
}
| DoudTechData/ignite | modules/yardstick/src/main/java/org/apache/ignite/yardstick/IgniteNode.java | Java | apache-2.0 | 7,875 |
/******************************************************************************
* Copyright (c) 2006, 2010 VMware Inc.
* 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 and 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.
*
* Contributors:
* VMware Inc.
*****************************************************************************/
package org.eclipse.gemini.blueprint.service.importer.support.internal.aop;
import org.eclipse.gemini.blueprint.service.importer.ServiceReferenceProxy;
import org.eclipse.gemini.blueprint.service.importer.support.internal.util.ServiceComparatorUtil;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceReference;
import org.springframework.util.Assert;
/**
* Simple {@link ServiceReference} proxy which simply does delegation, without any extra features. It's main purpose is
* to allow the consistent behaviour between dynamic and static proxies.
*
* @author Costin Leau
*
*/
public class StaticServiceReferenceProxy implements ServiceReferenceProxy {
private static final int HASH_CODE = StaticServiceReferenceProxy.class.hashCode() * 13;
private final ServiceReference target;
/**
* Constructs a new <code>StaticServiceReferenceProxy</code> instance.
*
* @param target service reference
*/
public StaticServiceReferenceProxy(ServiceReference target) {
Assert.notNull(target);
this.target = target;
}
public Bundle getBundle() {
return target.getBundle();
}
public Object getProperty(String key) {
return target.getProperty(key);
}
public String[] getPropertyKeys() {
return target.getPropertyKeys();
}
public Bundle[] getUsingBundles() {
return target.getUsingBundles();
}
public boolean isAssignableTo(Bundle bundle, String className) {
return target.isAssignableTo(bundle, className);
}
public ServiceReference getTargetServiceReference() {
return target;
}
public boolean equals(Object obj) {
if (obj instanceof StaticServiceReferenceProxy) {
StaticServiceReferenceProxy other = (StaticServiceReferenceProxy) obj;
return (target.equals(other.target));
}
return false;
}
public int hashCode() {
return HASH_CODE + target.hashCode();
}
public int compareTo(Object other) {
return ServiceComparatorUtil.compare(target, other);
}
} | eclipse/gemini.blueprint | core/src/main/java/org/eclipse/gemini/blueprint/service/importer/support/internal/aop/StaticServiceReferenceProxy.java | Java | apache-2.0 | 2,728 |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Functional tests for 3d convolutional operations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import math
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import test_util
from tensorflow.python.ops import gradient_checker
from tensorflow.python.ops import gradients_impl
from tensorflow.python.ops import nn_ops
import tensorflow.python.ops.nn_grad # pylint: disable=unused-import
from tensorflow.python.platform import test
def GetTestConfigs():
"""Get all the valid tests configs to run.
Returns:
all the valid test configs as tuples of data_format and use_gpu.
"""
test_configs = [("NDHWC", False), ("NDHWC", True)]
if test.is_gpu_available(cuda_only=True):
# "NCDHW" format is only supported on CUDA.
test_configs += [("NCDHW", True)]
return test_configs
class Conv3DTest(test.TestCase):
def _DtypesToTest(self, use_gpu):
if use_gpu:
if not test_util.CudaSupportsHalfMatMulAndConv():
return [dtypes.float64, dtypes.float32]
else:
# It is important that float32 comes before float16 here,
# as we will be using its gradients as reference for fp16 gradients.
return [dtypes.float64, dtypes.float32, dtypes.float16]
else:
return [dtypes.float64, dtypes.float32, dtypes.float16]
def _SetupValuesForDevice(self, tensor_in_sizes, filter_in_sizes, stride,
padding, data_format, dtype, use_gpu):
total_size_tensor = 1
total_size_filter = 1
for s in tensor_in_sizes:
total_size_tensor *= s
for s in filter_in_sizes:
total_size_filter *= s
# Initializes the input tensor with array containing numbers from 0 to 1.
# We keep the input tensor values fairly small to avoid overflowing float16
# during the conv3d.
x1 = [f * 1.0 / total_size_tensor for f in range(1, total_size_tensor + 1)]
x2 = [f * 1.0 / total_size_filter for f in range(1, total_size_filter + 1)]
with self.cached_session(use_gpu=use_gpu):
t1 = constant_op.constant(x1, shape=tensor_in_sizes, dtype=dtype)
t2 = constant_op.constant(x2, shape=filter_in_sizes, dtype=dtype)
if isinstance(stride, collections.Iterable):
strides = [1] + list(stride) + [1]
else:
strides = [1, stride, stride, stride, 1]
if data_format == "NCDHW":
t1 = test_util.NHWCToNCHW(t1)
strides = test_util.NHWCToNCHW(strides)
conv = nn_ops.conv3d(t1, t2, strides, padding=padding,
data_format=data_format)
if data_format == "NCDHW":
conv = test_util.NCHWToNHWC(conv)
return conv
def _VerifyValues(self, tensor_in_sizes, filter_in_sizes, stride, padding,
expected):
results = []
for data_format, use_gpu in GetTestConfigs():
for dtype in self._DtypesToTest(use_gpu):
result = self._SetupValuesForDevice(
tensor_in_sizes,
filter_in_sizes,
stride,
padding,
data_format,
dtype,
use_gpu=use_gpu)
results.append(result)
with self.cached_session() as sess:
values = self.evaluate(results)
for value in values:
print("expected = ", expected)
print("actual = ", value)
tol = 1e-6
if value.dtype == np.float16:
tol = 1e-3
self.assertAllClose(expected, value.flatten(), atol=tol, rtol=tol)
def _ComputeReferenceDilatedConv(self, tensor_in_sizes, filter_in_sizes,
stride, dilation, padding, data_format,
use_gpu):
total_size_tensor = 1
total_size_filter = 1
for s in tensor_in_sizes:
total_size_tensor *= s
for s in filter_in_sizes:
total_size_filter *= s
# Initializes the input tensor with array containing incrementing
# numbers from 1.
x1 = [f * 1.0 for f in range(1, total_size_tensor + 1)]
x2 = [f * 1.0 for f in range(1, total_size_filter + 1)]
with self.cached_session(use_gpu=use_gpu):
t1 = constant_op.constant(x1, shape=tensor_in_sizes)
t2 = constant_op.constant(x2, shape=filter_in_sizes)
if isinstance(stride, collections.Iterable):
strides = list(stride)
else:
strides = [stride, stride, stride]
if data_format == "NCDHW":
t1 = test_util.NHWCToNCHW(t1)
full_strides = [1, 1] + strides
full_dilation = [1, 1] + dilation
else:
full_strides = [1] + strides + [1]
full_dilation = [1] + dilation + [1]
expected = nn_ops.convolution(
t1,
t2,
padding=padding,
strides=strides,
dilation_rate=dilation,
data_format=data_format)
computed = nn_ops.conv3d(
t1,
t2,
strides=full_strides,
dilations=full_dilation,
padding=padding,
data_format=data_format)
if data_format == "NCDHW":
expected = test_util.NCHWToNHWC(expected)
computed = test_util.NCHWToNHWC(computed)
return expected, computed
def _VerifyDilatedConvValues(self, tensor_in_sizes, filter_in_sizes, stride,
padding, dilations):
expected_results = []
computed_results = []
default_dilations = (
dilations[0] == 1 and dilations[1] == 1 and dilations[2] == 1)
for data_format, use_gpu in GetTestConfigs():
# If any dilation rate is larger than 1, only do test on the GPU
# because we currently do not have a CPU implementation for arbitrary
# dilation rates.
if default_dilations or use_gpu:
expected, computed = self._ComputeReferenceDilatedConv(
tensor_in_sizes, filter_in_sizes, stride, dilations, padding,
data_format, use_gpu)
expected_results.append(expected)
computed_results.append(computed)
tolerance = 1e-2 if use_gpu else 1e-5
with self.cached_session() as sess:
expected_values = self.evaluate(expected_results)
computed_values = self.evaluate(computed_results)
for e_value, c_value in zip(expected_values, computed_values):
print("expected = ", e_value)
print("actual = ", c_value)
self.assertAllClose(
e_value.flatten(), c_value.flatten(), atol=tolerance, rtol=1e-6)
def testConv3D1x1x1Filter(self):
expected_output = [
0.18518519, 0.22222222, 0.25925926, 0.40740741, 0.5, 0.59259259,
0.62962963, 0.77777778, 0.92592593, 0.85185185, 1.05555556, 1.25925926,
1.07407407, 1.33333333, 1.59259259, 1.2962963, 1.61111111, 1.92592593
]
# These are equivalent to the Conv2D1x1 case.
self._VerifyValues(
tensor_in_sizes=[1, 2, 3, 1, 3],
filter_in_sizes=[1, 1, 1, 3, 3],
stride=1,
padding="VALID",
expected=expected_output)
self._VerifyValues(
tensor_in_sizes=[1, 2, 1, 3, 3],
filter_in_sizes=[1, 1, 1, 3, 3],
stride=1,
padding="VALID",
expected=expected_output)
self._VerifyValues(
tensor_in_sizes=[1, 1, 2, 3, 3],
filter_in_sizes=[1, 1, 1, 3, 3],
stride=1,
padding="VALID",
expected=expected_output)
def testConv3D1x1x1Filter2x1x1Dilation(self):
if test.is_gpu_available(cuda_only=True):
self._VerifyDilatedConvValues(
tensor_in_sizes=[1, 3, 6, 1, 1],
filter_in_sizes=[1, 1, 1, 1, 1],
stride=1,
padding="VALID",
dilations=[2, 1, 1])
# Expected values computed using scipy's correlate function.
def testConv3D2x2x2Filter(self):
expected_output = [
3.77199074, 3.85069444, 3.92939815, 4.2650463, 4.35763889, 4.45023148,
6.73032407, 6.89236111, 7.05439815, 7.22337963, 7.39930556, 7.57523148,
9.68865741, 9.93402778, 10.17939815, 10.18171296, 10.44097222,
10.70023148
]
# expected_shape = [1, 3, 1, 2, 5]
self._VerifyValues(
tensor_in_sizes=[1, 4, 2, 3, 3], # b, z, y, x, fin
filter_in_sizes=[2, 2, 2, 3, 3], # z, y, x, fin, fout
stride=1,
padding="VALID",
expected=expected_output)
def testConv3D2x2x2Filter1x2x1Dilation(self):
if test.is_gpu_available(cuda_only=True):
self._VerifyDilatedConvValues(
tensor_in_sizes=[1, 4, 6, 3, 1],
filter_in_sizes=[2, 2, 2, 1, 1],
stride=1,
padding="VALID",
dilations=[1, 2, 1])
def testConv3DStrides(self):
expected_output = [
0.06071429, 0.08988095, 0.10238095, 0.11488095, 0.12738095, 0.13988095,
0.08452381, 0.26071429, 0.35238095, 0.36488095, 0.37738095, 0.38988095,
0.40238095, 0.23452381, 0.46071429, 0.61488095, 0.62738095, 0.63988095,
0.65238095, 0.66488095, 0.38452381, 1.12738095, 1.48988095, 1.50238095,
1.51488095, 1.52738095, 1.53988095, 0.88452381, 1.32738095, 1.75238095,
1.76488095, 1.77738095, 1.78988095, 1.80238095, 1.03452381, 1.52738095,
2.01488095, 2.02738095, 2.03988095, 2.05238095, 2.06488095, 1.18452381,
2.19404762, 2.88988095, 2.90238095, 2.91488095, 2.92738095, 2.93988095,
1.68452381, 2.39404762, 3.15238095, 3.16488095, 3.17738095, 3.18988095,
3.20238095, 1.83452381, 2.59404762, 3.41488095, 3.42738095, 3.43988095,
3.45238095, 3.46488095, 1.98452381
]
self._VerifyValues(
tensor_in_sizes=[1, 5, 8, 7, 1],
filter_in_sizes=[1, 2, 3, 1, 1],
stride=[2, 3, 1], # different stride for each spatial dimension
padding="SAME",
expected=expected_output)
def testConv3D2x2x2FilterStride2(self):
expected_output = [
3.77199074, 3.85069444, 3.92939815, 9.68865741, 9.93402778, 10.17939815
]
self._VerifyValues(
tensor_in_sizes=[1, 4, 2, 3, 3],
filter_in_sizes=[2, 2, 2, 3, 3],
stride=2,
padding="VALID",
expected=expected_output)
def testConv3DStride3(self):
expected_output = [
1.51140873, 1.57167659, 1.63194444, 1.56349206, 1.62673611, 1.68998016,
1.6155754, 1.68179563, 1.74801587, 1.9280754, 2.01215278, 2.09623016,
1.98015873, 2.0672123, 2.15426587, 2.03224206, 2.12227183, 2.21230159,
4.4280754, 4.65500992, 4.88194444, 4.48015873, 4.71006944, 4.93998016,
4.53224206, 4.76512897, 4.99801587, 4.84474206, 5.09548611, 5.34623016,
4.8968254, 5.15054563, 5.40426587, 4.94890873, 5.20560516, 5.46230159
]
self._VerifyValues(
tensor_in_sizes=[1, 6, 7, 8, 2],
filter_in_sizes=[3, 2, 1, 2, 3],
stride=3,
padding="VALID",
expected=expected_output)
def testConv3D2x2x2FilterStride2Same(self):
expected_output = [
3.77199074, 3.85069444, 3.92939815, 2.0162037, 2.06597222, 2.11574074,
9.68865741, 9.93402778, 10.17939815, 4.59953704, 4.73263889, 4.86574074
]
self._VerifyValues(
tensor_in_sizes=[1, 4, 2, 3, 3],
filter_in_sizes=[2, 2, 2, 3, 3],
stride=2,
padding="SAME",
expected=expected_output)
def testKernelSmallerThanStride(self):
expected_output = [
0.03703704, 0.11111111, 0.25925926, 0.33333333, 0.7037037, 0.77777778,
0.92592593, 1.
]
self._VerifyValues(
tensor_in_sizes=[1, 3, 3, 3, 1],
filter_in_sizes=[1, 1, 1, 1, 1],
stride=2,
padding="SAME",
expected=expected_output)
self._VerifyValues(
tensor_in_sizes=[1, 3, 3, 3, 1],
filter_in_sizes=[1, 1, 1, 1, 1],
stride=2,
padding="VALID",
expected=expected_output)
expected_output = [
0.54081633, 0.58017493, 0.28061224, 0.81632653, 0.85568513, 0.40306122,
0.41873178, 0.4340379, 0.19642857, 2.46938776, 2.50874636, 1.1377551,
2.74489796, 2.78425656, 1.26020408, 1.16873178, 1.1840379, 0.51785714,
1.09511662, 1.10604956, 0.44642857, 1.17164723, 1.18258017, 0.47704082,
0.3691691, 0.37244898, 0.125
]
self._VerifyValues(
tensor_in_sizes=[1, 7, 7, 7, 1],
filter_in_sizes=[2, 2, 2, 1, 1],
stride=3,
padding="SAME",
expected=expected_output)
expected_output = [
0.540816, 0.580175, 0.816327, 0.855685, 2.469388, 2.508746, 2.744898,
2.784257
]
self._VerifyValues(
tensor_in_sizes=[1, 7, 7, 7, 1],
filter_in_sizes=[2, 2, 2, 1, 1],
stride=3,
padding="VALID",
expected=expected_output)
def testKernelSizeMatchesInputSize(self):
self._VerifyValues(
tensor_in_sizes=[1, 2, 1, 2, 1],
filter_in_sizes=[2, 1, 2, 1, 2],
stride=1,
padding="VALID",
expected=[1.5625, 1.875])
def _ConstructAndTestGradientForConfig(
self, batch, input_shape, filter_shape, in_depth, out_depth, stride,
padding, test_input, data_format, use_gpu):
input_planes, input_rows, input_cols = input_shape
filter_planes, filter_rows, filter_cols = filter_shape
input_shape = [batch, input_planes, input_rows, input_cols, in_depth]
filter_shape = [
filter_planes, filter_rows, filter_cols, in_depth, out_depth
]
if isinstance(stride, collections.Iterable):
strides = [1] + list(stride) + [1]
else:
strides = [1, stride, stride, stride, 1]
if padding == "VALID":
output_planes = int(
math.ceil((input_planes - filter_planes + 1.0) / strides[1]))
output_rows = int(
math.ceil((input_rows - filter_rows + 1.0) / strides[2]))
output_cols = int(
math.ceil((input_cols - filter_cols + 1.0) / strides[3]))
else:
output_planes = int(math.ceil(float(input_planes) / strides[1]))
output_rows = int(math.ceil(float(input_rows) / strides[2]))
output_cols = int(math.ceil(float(input_cols) / strides[3]))
output_shape = [batch, output_planes, output_rows, output_cols, out_depth]
input_size = 1
for x in input_shape:
input_size *= x
filter_size = 1
for x in filter_shape:
filter_size *= x
input_data = [x * 1.0 / input_size for x in range(0, input_size)]
filter_data = [x * 1.0 / filter_size for x in range(0, filter_size)]
for data_type in self._DtypesToTest(use_gpu=use_gpu):
# TODO(mjanusz): Modify gradient_checker to also provide max relative
# error and synchronize the tolerance levels between the tests for forward
# and backward computations.
if data_type == dtypes.float64:
tolerance = 1e-8
elif data_type == dtypes.float32:
tolerance = 5e-3
elif data_type == dtypes.float16:
tolerance = 1e-3
with self.cached_session(use_gpu=use_gpu):
orig_input_tensor = constant_op.constant(
input_data, shape=input_shape, dtype=data_type, name="input")
filter_tensor = constant_op.constant(
filter_data, shape=filter_shape, dtype=data_type, name="filter")
if data_format == "NCDHW":
input_tensor = test_util.NHWCToNCHW(orig_input_tensor)
new_strides = test_util.NHWCToNCHW(strides)
else:
input_tensor = orig_input_tensor
new_strides = strides
conv = nn_ops.conv3d(
input_tensor,
filter_tensor,
new_strides,
padding,
data_format=data_format,
name="conv")
if data_format == "NCDHW":
conv = test_util.NCHWToNHWC(conv)
self.assertEqual(conv.shape, tensor_shape.TensorShape(output_shape))
if test_input:
jacob_t, jacob_n = gradient_checker.compute_gradient(
orig_input_tensor, input_shape, conv, output_shape)
else:
jacob_t, jacob_n = gradient_checker.compute_gradient(
filter_tensor, filter_shape, conv, output_shape)
if data_type != dtypes.float16:
reference_jacob_t = jacob_t
err = np.fabs(jacob_t - jacob_n).max()
else:
# Compare fp16 theoretical gradients to fp32 theoretical gradients,
# since fp16 numerical gradients are too imprecise.
err = np.fabs(jacob_t - reference_jacob_t).max()
print("conv3d gradient error = ", err)
self.assertLess(err, tolerance)
def ConstructAndTestGradient(self, **kwargs):
for data_format, use_gpu in GetTestConfigs():
self._ConstructAndTestGradientForConfig(data_format=data_format,
use_gpu=use_gpu, **kwargs)
@test_util.run_deprecated_v1
def testInputGradientValidPaddingStrideOne(self):
self.ConstructAndTestGradient(
batch=2,
input_shape=(3, 5, 4),
filter_shape=(3, 3, 3),
in_depth=2,
out_depth=3,
stride=1,
padding="VALID",
test_input=True)
@test_util.run_deprecated_v1
def testFilterGradientValidPaddingStrideOne(self):
self.ConstructAndTestGradient(
batch=4,
input_shape=(4, 6, 5),
filter_shape=(2, 2, 2),
in_depth=2,
out_depth=3,
stride=1,
padding="VALID",
test_input=False)
@test_util.run_deprecated_v1
def testInputGradientValidPaddingStrideTwo(self):
self.ConstructAndTestGradient(
batch=2,
input_shape=(6, 3, 5),
filter_shape=(3, 3, 3),
in_depth=2,
out_depth=3,
stride=2,
padding="VALID",
test_input=True)
@test_util.run_deprecated_v1
def testFilterGradientValidPaddingStrideTwo(self):
self.ConstructAndTestGradient(
batch=2,
input_shape=(7, 6, 5),
filter_shape=(2, 2, 2),
in_depth=2,
out_depth=3,
stride=2,
padding="VALID",
test_input=False)
@test_util.run_deprecated_v1
def testInputGradientValidPaddingStrideThree(self):
self.ConstructAndTestGradient(
batch=2,
input_shape=(3, 7, 6),
filter_shape=(3, 3, 3),
in_depth=2,
out_depth=3,
stride=3,
padding="VALID",
test_input=True)
@test_util.run_deprecated_v1
def testFilterGradientValidPaddingStrideThree(self):
self.ConstructAndTestGradient(
batch=2,
input_shape=(4, 4, 7),
filter_shape=(4, 4, 4),
in_depth=2,
out_depth=3,
stride=3,
padding="VALID",
test_input=False)
@test_util.run_deprecated_v1
def testInputGradientSamePaddingStrideOne(self):
self.ConstructAndTestGradient(
batch=2,
input_shape=(3, 2, 2),
filter_shape=(3, 2, 1),
in_depth=2,
out_depth=1,
stride=1,
padding="SAME",
test_input=True)
@test_util.run_deprecated_v1
def testFilterGradientSamePaddingStrideOne(self):
self.ConstructAndTestGradient(
batch=2,
input_shape=(3, 6, 5),
filter_shape=(2, 2, 2),
in_depth=2,
out_depth=3,
stride=1,
padding="SAME",
test_input=False)
@test_util.run_deprecated_v1
def testInputGradientSamePaddingStrideTwo(self):
self.ConstructAndTestGradient(
batch=2,
input_shape=(6, 3, 4),
filter_shape=(3, 3, 3),
in_depth=2,
out_depth=3,
stride=2,
padding="SAME",
test_input=True)
@test_util.run_deprecated_v1
def testFilterGradientSamePaddingStrideTwo(self):
self.ConstructAndTestGradient(
batch=4,
input_shape=(7, 3, 5),
filter_shape=(2, 2, 2),
in_depth=2,
out_depth=3,
stride=2,
padding="SAME",
test_input=False)
@test_util.run_deprecated_v1
def testInputGradientSamePaddingStrideThree(self):
self.ConstructAndTestGradient(
batch=2,
input_shape=(9, 3, 6),
filter_shape=(3, 3, 3),
in_depth=2,
out_depth=3,
stride=3,
padding="SAME",
test_input=True)
@test_util.run_deprecated_v1
def testFilterGradientSamePaddingStrideThree(self):
self.ConstructAndTestGradient(
batch=2,
input_shape=(9, 4, 7),
filter_shape=(4, 4, 4),
in_depth=2,
out_depth=3,
stride=3,
padding="SAME",
test_input=False)
@test_util.run_deprecated_v1
def testInputGradientSamePaddingDifferentStrides(self):
self.ConstructAndTestGradient(
batch=1,
input_shape=(5, 8, 7),
filter_shape=(1, 2, 3),
in_depth=2,
out_depth=3,
stride=[2, 3, 1],
padding="SAME",
test_input=True)
@test_util.run_deprecated_v1
def testFilterGradientKernelSizeMatchesInputSize(self):
self.ConstructAndTestGradient(
batch=2,
input_shape=(5, 4, 3),
filter_shape=(5, 4, 3),
in_depth=2,
out_depth=3,
stride=1,
padding="VALID",
test_input=False)
@test_util.run_deprecated_v1
def testInputGradientKernelSizeMatchesInputSize(self):
self.ConstructAndTestGradient(
batch=2,
input_shape=(5, 4, 3),
filter_shape=(5, 4, 3),
in_depth=2,
out_depth=3,
stride=1,
padding="VALID",
test_input=True)
def disabledtestFilterGradientSamePaddingDifferentStrides(self):
self.ConstructAndTestGradient(
batch=1,
input_shape=(5, 8, 7),
filter_shape=(1, 2, 3),
in_depth=2,
out_depth=3,
stride=[2, 3, 1],
padding="SAME",
test_input=False)
# Test the fast path in gemm_pack_rhs/mkldnn_gemm_pack, when channel
# dimension is a multiple of packet size.
@test_util.run_deprecated_v1
def testInputGradientValidPaddingStrideOneFastPath(self):
self.ConstructAndTestGradient(
batch=2,
input_shape=(3, 5, 4),
filter_shape=(2, 2, 2),
in_depth=8,
out_depth=2,
stride=1,
padding="VALID",
test_input=True)
@test_util.run_deprecated_v1
def testFilterGradientValidPaddingStrideOneFastPath(self):
self.ConstructAndTestGradient(
batch=2,
input_shape=(4, 6, 5),
filter_shape=(2, 2, 2),
in_depth=8,
out_depth=2,
stride=1,
padding="VALID",
test_input=False)
# Testing for backprops
def _RunAndVerifyBackprop(self, input_sizes, filter_sizes, output_sizes,
strides, dilations, padding, data_format, use_gpu,
err, mode):
total_input_size = 1
total_filter_size = 1
for s in input_sizes:
total_input_size *= s
for s in filter_sizes:
total_filter_size *= s
# Initializes the input tensor with array containing incrementing
# numbers from 1.
x1 = [f * 1.0 for f in range(1, total_input_size + 1)]
x2 = [f * 1.0 for f in range(1, total_filter_size + 1)]
default_dilations = (
dilations[0] == 1 and dilations[1] == 1 and dilations[2] == 1)
# If any dilation rate is larger than 1, only do test on the GPU
# because we currently do not have a CPU implementation for arbitrary
# dilation rates.
if default_dilations or use_gpu:
with self.cached_session(use_gpu=use_gpu) as sess:
if data_format == "NCDHW":
input_sizes = test_util.NHWCToNCHW(input_sizes)
t1 = constant_op.constant(x1, shape=input_sizes)
t2 = constant_op.constant(x2, shape=filter_sizes)
full_strides = [1] + strides + [1]
full_dilations = [1] + dilations + [1]
if data_format == "NCDHW":
full_strides = test_util.NHWCToNCHW(full_strides)
full_dilations = test_util.NHWCToNCHW(full_dilations)
actual = nn_ops.conv3d(
t1,
t2,
strides=full_strides,
dilations=full_dilations,
padding=padding,
data_format=data_format)
expected = nn_ops.convolution(
t1,
t2,
padding=padding,
strides=strides,
dilation_rate=dilations,
data_format=data_format)
if data_format == "NCDHW":
actual = test_util.NCHWToNHWC(actual)
expected = test_util.NCHWToNHWC(expected)
actual_grad = gradients_impl.gradients(actual, t1
if mode == "input" else t2)[0]
expected_grad = gradients_impl.gradients(expected, t1
if mode == "input" else t2)[0]
# "values" consists of two tensors for two backprops
actual_value = self.evaluate(actual_grad)
expected_value = self.evaluate(expected_grad)
self.assertShapeEqual(actual_value, actual_grad)
self.assertShapeEqual(expected_value, expected_grad)
print("expected = ", expected_value)
print("actual = ", actual_value)
self.assertArrayNear(expected_value.flatten(), actual_value.flatten(),
err)
def testConv3D2x2Depth3ValidBackpropFilterStride1x1Dilation2x1(self):
if test.is_gpu_available(cuda_only=True):
for (data_format, use_gpu) in GetTestConfigs():
self._RunAndVerifyBackprop(
input_sizes=[1, 3, 6, 1, 1],
filter_sizes=[2, 2, 1, 1, 1],
output_sizes=[1, 1, 5, 1, 1],
strides=[1, 1, 1],
dilations=[2, 1, 1],
padding="VALID",
data_format=data_format,
use_gpu=use_gpu,
err=1e-5,
mode="filter")
def testConv3D2x2Depth3ValidBackpropInputStride1x1Dilation2x1(self):
if test.is_gpu_available(cuda_only=True):
for (data_format, use_gpu) in GetTestConfigs():
self._RunAndVerifyBackprop(
input_sizes=[1, 3, 6, 1, 1],
filter_sizes=[2, 2, 1, 1, 1],
output_sizes=[1, 1, 5, 1, 1],
strides=[1, 1, 1],
dilations=[2, 1, 1],
padding="VALID",
data_format=data_format,
use_gpu=use_gpu,
err=1e-5,
mode="input")
if __name__ == "__main__":
test.main()
| hfp/tensorflow-xsmm | tensorflow/python/kernel_tests/conv_ops_3d_test.py | Python | apache-2.0 | 27,016 |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Sql.AdvancedThreatProtection.Model;
using Microsoft.Azure.Commands.Sql.Common;
using Microsoft.Azure.Commands.Sql.ThreatDetection.Model;
using Microsoft.Azure.Commands.Sql.ThreatDetection.Services;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
using Microsoft.Azure.Management.Sql.Models;
using System.Linq;
namespace Microsoft.Azure.Commands.Sql.AdvancedThreatProtection.Services
{
/// <summary>
/// The SqlAdvancedThreatProtectionAdapter class is responsible for transforming the data that was received form the endpoints to the cmdlets model of AdvancedThreatProtection policy and vice versa
/// </summary>
public class SqlAdvancedThreatProtectionAdapter
{
/// <summary>
/// Gets or sets the Azure subscription
/// </summary>
private IAzureSubscription Subscription { get; set; }
/// <summary>
/// The Threat Detection endpoints communicator used by this adapter
/// </summary>
private SqlThreatDetectionAdapter SqlThreatDetectionAdapter { get; set; }
/// <summary>
/// The Azure endpoints communicator used by this adapter
/// </summary>
private AzureEndpointsCommunicator AzureCommunicator { get; set; }
/// <summary>
/// Gets or sets the Azure profile
/// </summary>
public IAzureContext Context { get; set; }
public SqlAdvancedThreatProtectionAdapter(IAzureContext context)
{
Context = context;
Subscription = context.Subscription;
SqlThreatDetectionAdapter = new SqlThreatDetectionAdapter(Context);
}
/// <summary>
/// Provides a server Advanced Threat Protection policy model for the given database
/// </summary>
public ServerAdvancedThreatProtectionPolicyModel GetServerAdvancedThreatProtectionPolicy(string resourceGroup, string serverName)
{
// Currently Advanced Threat Protection policy is a TD policy until the backend will support Advanced Threat Protection APIs
var threatDetectionPolicy = SqlThreatDetectionAdapter.GetServerThreatDetectionPolicy(resourceGroup, serverName);
var serverAdvancedThreatProtectionPolicyModel = new ServerAdvancedThreatProtectionPolicyModel()
{
ResourceGroupName = resourceGroup,
ServerName = serverName,
IsEnabled = (threatDetectionPolicy.ThreatDetectionState == ThreatDetectionStateType.Enabled)
};
return serverAdvancedThreatProtectionPolicyModel;
}
/// <summary>
/// Sets a server Advanced Threat Protection policy model for the given database
/// </summary>
public ServerAdvancedThreatProtectionPolicyModel SetServerAdvancedThreatProtection(ServerAdvancedThreatProtectionPolicyModel model)
{
// Currently Advanced Threat Protection policy is a TD policy until the backend will support Advanced Threat Protection APIs
var threatDetectionPolicy = SqlThreatDetectionAdapter.GetServerThreatDetectionPolicy(model.ResourceGroupName, model.ServerName);
threatDetectionPolicy.ThreatDetectionState = model.IsEnabled ? ThreatDetectionStateType.Enabled : ThreatDetectionStateType.Disabled;
SqlThreatDetectionAdapter.SetServerThreatDetectionPolicy(threatDetectionPolicy, AzureEnvironment.Endpoint.StorageEndpointSuffix);
return model;
}
}
}
| AzureAutomationTeam/azure-powershell | src/ResourceManager/Sql/Commands.Sql/AdvancedThreatProtection/Services/SqlAdvancedThreatProtectionAdapter.cs | C# | apache-2.0 | 4,342 |
/*
* Copyright 2012-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 org.springframework.boot.actuate.endpoint;
import java.util.Collection;
import org.springframework.boot.actuate.metrics.Metric;
/**
* Interface to expose specific {@link Metric}s via a {@link MetricsEndpoint}.
*
* @author Dave Syer
* @see VanillaPublicMetrics
* @see SystemPublicMetrics
*/
public interface PublicMetrics {
/**
* @return an indication of current state through metrics
*/
Collection<Metric<?>> metrics();
}
| 10045125/spring-boot | spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/PublicMetrics.java | Java | apache-2.0 | 1,069 |
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.engine.view.compilation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.threeten.bp.Instant;
import com.google.common.collect.Sets;
import com.opengamma.engine.ComputationTargetResolver;
import com.opengamma.engine.depgraph.DependencyGraph;
import com.opengamma.engine.depgraph.DependencyGraphBuilder;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.resolver.CompiledFunctionResolver;
import com.opengamma.engine.function.resolver.ComputationTargetResults;
import com.opengamma.engine.function.resolver.DefaultCompiledFunctionResolver;
import com.opengamma.engine.function.resolver.ResolutionRule;
import com.opengamma.engine.target.ComputationTargetReference;
import com.opengamma.engine.view.ViewCalculationConfiguration;
import com.opengamma.engine.view.ViewDefinition;
import com.opengamma.id.UniqueId;
import com.opengamma.id.VersionCorrection;
/**
* Holds context relating to the partially-completed compilation of a view definition, for passing to different stages of the compilation.
*/
/* package */class ViewCompilationContext {
private final ViewDefinition _viewDefinition;
private final ViewCompilationServices _services;
private final Collection<DependencyGraphBuilder> _builders;
private final VersionCorrection _resolverVersionCorrection;
private final Collection<DependencyGraph> _graphs;
private final ConcurrentMap<ComputationTargetReference, UniqueId> _activeResolutions;
private final CompiledFunctionResolver _functions;
private final Collection<ResolutionRule> _rules;
private final ComputationTargetResolver.AtVersionCorrection _targetResolver;
private Set<UniqueId> _expiredResolutions;
/* package */ViewCompilationContext(final ViewDefinition viewDefinition, final ViewCompilationServices compilationServices,
final Instant valuationTime, final VersionCorrection resolverVersionCorrection, final ConcurrentMap<ComputationTargetReference, UniqueId> resolutions) {
_viewDefinition = viewDefinition;
_services = compilationServices;
_builders = new LinkedList<DependencyGraphBuilder>();
_expiredResolutions = Sets.newSetFromMap(new ConcurrentHashMap<UniqueId, Boolean>());
_functions = compilationServices.getFunctionResolver().compile(valuationTime);
_rules = _functions.getAllResolutionRules();
_targetResolver = TargetResolutionLogger.of(compilationServices.getFunctionCompilationContext().getRawComputationTargetResolver().atVersionCorrection(resolverVersionCorrection), resolutions,
_expiredResolutions);
for (final ViewCalculationConfiguration calcConfig : viewDefinition.getAllCalculationConfigurations()) {
_builders.add(createBuilder(calcConfig));
}
_resolverVersionCorrection = resolverVersionCorrection;
_graphs = new ArrayList<DependencyGraph>(_builders.size());
_activeResolutions = resolutions;
}
public DependencyGraphBuilder createBuilder(final ViewCalculationConfiguration calcConfig) {
final DependencyGraphBuilder builder = _services.getDependencyGraphBuilder().newInstance();
builder.setCalculationConfigurationName(calcConfig.getName());
builder.setMarketDataAvailabilityProvider(_services.getMarketDataAvailabilityProvider());
final FunctionCompilationContext compilationContext = _services.getFunctionCompilationContext().clone();
compilationContext.setViewCalculationConfiguration(calcConfig);
compilationContext.setComputationTargetResolver(_targetResolver);
final Collection<ResolutionRule> transformedRules = calcConfig.getResolutionRuleTransform().transform(_rules);
compilationContext.setComputationTargetResults(new ComputationTargetResults(transformedRules));
final DefaultCompiledFunctionResolver functionResolver = new DefaultCompiledFunctionResolver(compilationContext, transformedRules);
functionResolver.compileRules();
builder.setFunctionResolver(functionResolver);
compilationContext.init();
builder.setCompilationContext(compilationContext);
return builder;
}
public ViewDefinition getViewDefinition() {
return _viewDefinition;
}
public ViewCompilationServices getServices() {
return _services;
}
public CompiledFunctionResolver getCompiledFunctionResolver() {
return _functions;
}
public Collection<DependencyGraphBuilder> getBuilders() {
return _builders;
}
public Collection<DependencyGraph> getGraphs() {
return _graphs;
}
public VersionCorrection getResolverVersionCorrection() {
return _resolverVersionCorrection;
}
public ConcurrentMap<ComputationTargetReference, UniqueId> getActiveResolutions() {
return _activeResolutions;
}
public boolean hasExpiredResolutions() {
return !_expiredResolutions.isEmpty();
}
public Set<UniqueId> takeExpiredResolutions() {
final Set<UniqueId> result = _expiredResolutions;
_expiredResolutions = Sets.newSetFromMap(new ConcurrentHashMap<UniqueId, Boolean>());
return result;
}
}
| jeorme/OG-Platform | projects/OG-Engine/src/main/java/com/opengamma/engine/view/compilation/ViewCompilationContext.java | Java | apache-2.0 | 5,308 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.datanode;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import org.apache.hadoop.fs.ChecksumException;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.DataTransferProtocol;
import org.apache.hadoop.hdfs.protocol.FSConstants;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.net.SocketOutputStream;
import org.apache.hadoop.util.ChecksumUtil;
import org.apache.hadoop.util.CrcConcat;
import org.apache.hadoop.util.DataChecksum;
import org.apache.hadoop.util.StringUtils;
/**
* Read from blocks with separate checksum files.
* Block file name:
* blk_(blockId)
*
* Checksum file name:
* blk_(blockId)_(generation_stamp).meta
*
* The on disk file format is:
* Data file keeps just data in the block:
*
* +---------------+
* | |
* | Data |
* | . |
* | . |
* | . |
* | . |
* | . |
* | . |
* | |
* +---------------+
*
* Checksum file:
* +----------------------+
* | Checksum Header |
* +----------------------+
* | Checksum for Chunk 1 |
* +----------------------+
* | Checksum for Chunk 2 |
* +----------------------+
* | . |
* | . |
* | . |
* +----------------------+
* | Checksum for last |
* | Chunk (Partial) |
* +----------------------+
*
*/
public class BlockWithChecksumFileReader extends DatanodeBlockReader {
private InputStreamWithChecksumFactory streamFactory;
private DataInputStream checksumIn; // checksum datastream
private BlockDataFile.Reader blockDataFileReader;
boolean useTransferTo = false;
MemoizedBlock memoizedBlock;
BlockWithChecksumFileReader(int namespaceId, Block block,
boolean isFinalized, boolean ignoreChecksum,
boolean verifyChecksum, boolean corruptChecksumOk,
InputStreamWithChecksumFactory streamFactory) throws IOException {
super(namespaceId, block, isFinalized, ignoreChecksum, verifyChecksum,
corruptChecksumOk);
this.streamFactory = streamFactory;
this.checksumIn = streamFactory.getChecksumStream();
this.block = block;
}
@Override
public void fadviseStream(int advise, long offset, long len)
throws IOException {
blockDataFileReader.posixFadviseIfPossible(offset, len, advise);
}
private void initializeNullChecksum() {
checksumIn = null;
// This only decides the buffer size. Use BUFFER_SIZE?
checksum = DataChecksum.newDataChecksum(DataChecksum.CHECKSUM_NULL,
16 * 1024);
}
public DataChecksum getChecksumToSend(long blockLength) throws IOException {
if (!corruptChecksumOk || checksumIn != null) {
// read and handle the common header here. For now just a version
try {
BlockMetadataHeader header = BlockMetadataHeader.readHeader(checksumIn);
short version = header.getVersion();
if (version != FSDataset.FORMAT_VERSION_NON_INLINECHECKSUM) {
LOG.warn("Wrong version (" + version + ") for metadata file for "
+ block + " ignoring ...");
}
checksum = header.getChecksum();
} catch (IOException ioe) {
if (blockLength == 0) {
initializeNullChecksum();
} else {
throw ioe;
}
}
} else {
LOG.warn("Could not find metadata file for " + block);
initializeNullChecksum();
}
super.getChecksumInfo(blockLength);
return checksum;
}
public void initialize(long offset, long blockLength)
throws IOException {
// seek to the right offsets
if (offset > 0) {
long checksumSkip = (offset / bytesPerChecksum) * checksumSize;
// note blockInStream is seeked when created below
if (checksumSkip > 0) {
// Should we use seek() for checksum file as well?
IOUtils.skipFully(checksumIn, checksumSkip);
}
}
blockDataFileReader = streamFactory.getBlockDataFileReader();
memoizedBlock = new MemoizedBlock(blockLength, streamFactory, block);
}
public boolean prepareTransferTo() throws IOException {
useTransferTo = true;
return useTransferTo;
}
@Override
public void sendChunks(OutputStream out, byte[] buf, long offset,
int checksumOff, int numChunks, int len, BlockCrcUpdater crcUpdater,
int packetVersion) throws IOException {
if (packetVersion != DataTransferProtocol.PACKET_VERSION_CHECKSUM_FIRST) {
throw new IOException("packet version " + packetVersion
+ " is not supported by non-inline checksum blocks.");
}
int checksumLen = numChunks * checksumSize;
if (checksumSize > 0 && checksumIn != null) {
try {
checksumIn.readFully(buf, checksumOff, checksumLen);
if (dnData != null) {
dnData.recordReadChunkCheckSumTime();
}
if (crcUpdater != null) {
long tempOffset = offset;
long remain = len;
for (int i = 0; i < checksumLen; i += checksumSize) {
long chunkSize = (remain > bytesPerChecksum) ? bytesPerChecksum
: remain;
crcUpdater.updateBlockCrc(tempOffset, (int) chunkSize,
DataChecksum.getIntFromBytes(buf, checksumOff + i));
remain -= chunkSize;
}
}
} catch (IOException e) {
LOG.warn(" Could not read or failed to veirfy checksum for data"
+ " at offset " + offset + " for block " + block + " got : "
+ StringUtils.stringifyException(e));
IOUtils.closeStream(checksumIn);
checksumIn = null;
if (corruptChecksumOk) {
if (checksumOff < checksumLen) {
// Just fill the array with zeros.
Arrays.fill(buf, checksumOff, checksumLen, (byte) 0);
if (dnData != null) {
dnData.recordReadChunkCheckSumTime();
}
}
} else {
throw e;
}
}
}
int dataOff = checksumOff + checksumLen;
if (!useTransferTo) {
// normal transfer
blockDataFileReader.readFully(buf, dataOff, len, offset, true);
if (dnData != null) {
dnData.recordReadChunkDataTime();
}
if (verifyChecksum) {
int dOff = dataOff;
int cOff = checksumOff;
int dLeft = len;
for (int i = 0; i < numChunks; i++) {
checksum.reset();
int dLen = Math.min(dLeft, bytesPerChecksum);
checksum.update(buf, dOff, dLen);
if (!checksum.compare(buf, cOff)) {
throw new ChecksumException("Checksum failed at "
+ (offset + len - dLeft), len);
}
dLeft -= dLen;
dOff += dLen;
cOff += checksumSize;
}
if (dnData != null) {
dnData.recordVerifyCheckSumTime();
}
}
// only recompute checksum if we can't trust the meta data due to
// concurrent writes
if (memoizedBlock.hasBlockChanged(len, offset)) {
ChecksumUtil.updateChunkChecksum(buf, checksumOff, dataOff, len,
checksum);
if (dnData != null) {
dnData.recordUpdateChunkCheckSumTime();
}
}
try {
out.write(buf, 0, dataOff + len);
if (dnData != null) {
dnData.recordSendChunkToClientTime();
}
} catch (IOException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("IOException when reading block " + block + " offset " + offset, e);
}
throw BlockSender.ioeToSocketException(e);
}
} else {
try {
// use transferTo(). Checks on out and blockIn are already done.
SocketOutputStream sockOut = (SocketOutputStream) out;
if (memoizedBlock.hasBlockChanged(len, offset)) {
blockDataFileReader.readFully(buf, dataOff, len, offset, true);
if (dnData != null) {
dnData.recordReadChunkDataTime();
}
ChecksumUtil.updateChunkChecksum(buf, checksumOff, dataOff, len,
checksum);
if (dnData != null) {
dnData.recordUpdateChunkCheckSumTime();
}
sockOut.write(buf, 0, dataOff + len);
if (dnData != null) {
dnData.recordSendChunkToClientTime();
}
} else {
// first write the packet
sockOut.write(buf, 0, dataOff);
// no need to flush. since we know out is not a buffered stream.
blockDataFileReader.transferToSocketFully(sockOut,offset, len);
if (dnData != null) {
dnData.recordTransferChunkToClientTime();
}
}
} catch (IOException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("IOException when reading block " + block + " offset "
+ offset, e);
}
/*
* exception while writing to the client (well, with transferTo(), it
* could also be while reading from the local file).
*/
throw BlockSender.ioeToSocketException(e);
}
}
}
@Override
public int getPreferredPacketVersion() {
return DataTransferProtocol.PACKET_VERSION_CHECKSUM_FIRST;
}
public void close() throws IOException {
IOException ioe = null;
// close checksum file
if (checksumIn != null) {
try {
checksumIn.close();
} catch (IOException e) {
ioe = e;
}
checksumIn = null;
}
// throw IOException if there is any
if (ioe != null) {
throw ioe;
}
}
/**
* helper class used to track if a block's meta data is verifiable or not
*/
class MemoizedBlock {
// visible block length
private long blockLength;
private final Block block;
private final InputStreamWithChecksumFactory isf;
private MemoizedBlock(long blockLength,
InputStreamWithChecksumFactory isf, Block block) {
this.blockLength = blockLength;
this.isf = isf;
this.block = block;
}
// logic: if we are starting or ending on a partial chunk and the block
// has more data than we were told at construction, the block has 'changed'
// in a way that we care about (ie, we can't trust crc data)
boolean hasBlockChanged(long dataLen, long offset) throws IOException {
if (isFinalized) {
// We would treat it an error case for a finalized block at open time
// has an unmatched size when closing. There might be false positive
// for append() case. We made the trade-off to avoid false negative.
// always return true so it data integrity is guaranteed by checksum
// checking.
return false;
}
// check if we are using transferTo since we tell if the file has changed
// (blockInPosition >= 0 => we are using transferTo and File Channels
if (useTransferTo) {
long currentLength = blockDataFileReader.size();
return (offset % bytesPerChecksum != 0 || dataLen
% bytesPerChecksum != 0)
&& currentLength > blockLength;
} else {
FSDatasetInterface ds = null;
if (isf instanceof DatanodeBlockReader.BlockInputStreamFactory) {
ds = ((DatanodeBlockReader.BlockInputStreamFactory) isf).getDataset();
}
// offset is the offset into the block
return (offset % bytesPerChecksum != 0 || dataLen % bytesPerChecksum != 0)
&& ds != null
&& ds.getOnDiskLength(namespaceId, block) > blockLength;
}
}
}
public static interface InputStreamWithChecksumFactory extends
BlockSender.InputStreamFactory {
public InputStream createStream(long offset) throws IOException;
public DataInputStream getChecksumStream() throws IOException;
}
/** Find the metadata file for the specified block file.
* Return the generation stamp from the name of the metafile.
*/
static long getGenerationStampFromSeperateChecksumFile(String[] listdir, String blockName) {
for (int j = 0; j < listdir.length; j++) {
String path = listdir[j];
if (!path.startsWith(blockName)) {
continue;
}
String[] vals = StringUtils.split(path, '_');
if (vals.length != 3) { // blk, blkid, genstamp.meta
continue;
}
String[] str = StringUtils.split(vals[2], '.');
if (str.length != 2) {
continue;
}
return Long.parseLong(str[0]);
}
DataNode.LOG.warn("Block " + blockName +
" does not have a metafile!");
return Block.GRANDFATHER_GENERATION_STAMP;
}
/**
* Find generation stamp from block file and meta file.
* @param blockFile
* @param metaFile
* @return
* @throws IOException
*/
static long parseGenerationStampInMetaFile(File blockFile, File metaFile
) throws IOException {
String metaname = metaFile.getName();
String gs = metaname.substring(blockFile.getName().length() + 1,
metaname.length() - FSDataset.METADATA_EXTENSION.length());
try {
return Long.parseLong(gs);
} catch(NumberFormatException nfe) {
throw (IOException)new IOException("blockFile=" + blockFile
+ ", metaFile=" + metaFile).initCause(nfe);
}
}
/**
* This class provides the input stream and length of the metadata
* of a block
*
*/
static class MetaDataInputStream extends FilterInputStream {
MetaDataInputStream(InputStream stream, long len) {
super(stream);
length = len;
}
private long length;
public long getLength() {
return length;
}
}
static protected File getMetaFile(FSDatasetInterface dataset, int namespaceId,
Block b) throws IOException {
return BlockWithChecksumFileWriter.getMetaFile(dataset.getBlockFile(namespaceId, b), b);
}
/**
* Does the meta file exist for this block?
* @param namespaceId - parent namespace id
* @param b - the block
* @return true of the metafile for specified block exits
* @throws IOException
*/
static public boolean metaFileExists(FSDatasetInterface dataset, int namespaceId, Block b) throws IOException {
return getMetaFile(dataset, namespaceId, b).exists();
}
/**
* Returns metaData of block b as an input stream (and its length)
* @param namespaceId - parent namespace id
* @param b - the block
* @return the metadata input stream;
* @throws IOException
*/
static public MetaDataInputStream getMetaDataInputStream(
FSDatasetInterface dataset, int namespace, Block b) throws IOException {
File checksumFile = getMetaFile(dataset, namespace, b);
return new MetaDataInputStream(new FileInputStream(checksumFile),
checksumFile.length());
}
static byte[] getMetaData(FSDatasetInterface dataset, int namespaceId,
Block block) throws IOException {
MetaDataInputStream checksumIn = null;
try {
checksumIn = getMetaDataInputStream(dataset, namespaceId, block);
long fileSize = checksumIn.getLength();
if (fileSize >= 1L << 31 || fileSize <= 0) {
throw new IOException("Unexpected size for checksumFile of block"
+ block);
}
byte[] buf = new byte[(int) fileSize];
IOUtils.readFully(checksumIn, buf, 0, buf.length);
return buf;
} finally {
IOUtils.closeStream(checksumIn);
}
}
/**
* Calculate CRC Checksum of the whole block. Implemented by concatenating
* checksums of all the chunks.
*
* @param datanode
* @param ri
* @param namespaceId
* @param block
* @return
* @throws IOException
*/
static public int getBlockCrc(DataNode datanode, ReplicaToRead ri,
int namespaceId, Block block) throws IOException {
InputStream rawStreamIn = null;
DataInputStream streamIn = null;
try {
int bytesPerCRC;
int checksumSize;
long crcPerBlock;
rawStreamIn = BlockWithChecksumFileReader.getMetaDataInputStream(
datanode.data, namespaceId, block);
streamIn = new DataInputStream(new BufferedInputStream(rawStreamIn,
FSConstants.BUFFER_SIZE));
final BlockMetadataHeader header = BlockMetadataHeader
.readHeader(streamIn);
final DataChecksum checksum = header.getChecksum();
if (checksum.getChecksumType() != DataChecksum.CHECKSUM_CRC32) {
throw new IOException("File Checksum now is only supported for CRC32");
}
bytesPerCRC = checksum.getBytesPerChecksum();
checksumSize = checksum.getChecksumSize();
crcPerBlock = (((BlockWithChecksumFileReader.MetaDataInputStream) rawStreamIn)
.getLength() - BlockMetadataHeader.getHeaderSize()) / checksumSize;
int blockCrc = 0;
byte[] buffer = new byte[checksumSize];
for (int i = 0; i < crcPerBlock; i++) {
IOUtils.readFully(streamIn, buffer, 0, buffer.length);
int intChecksum = ((buffer[0] & 0xff) << 24)
| ((buffer[1] & 0xff) << 16) | ((buffer[2] & 0xff) << 8)
| ((buffer[3] & 0xff));
if (i == 0) {
blockCrc = intChecksum;
} else {
int chunkLength;
if (i != crcPerBlock - 1 || ri.getBytesVisible() % bytesPerCRC == 0) {
chunkLength = bytesPerCRC;
} else {
chunkLength = (int) ri.getBytesVisible() % bytesPerCRC;
}
blockCrc = CrcConcat.concatCrc(blockCrc, intChecksum, chunkLength);
}
}
return blockCrc;
} finally {
if (streamIn != null) {
IOUtils.closeStream(streamIn);
}
if (rawStreamIn != null) {
IOUtils.closeStream(rawStreamIn);
}
}
}
static long readBlockAccelerator(Socket s, File dataFile, Block block,
long startOffset, long length, DataNode datanode) throws IOException {
File checksumFile = BlockWithChecksumFileWriter.getMetaFile(dataFile, block);
FileInputStream datain = new FileInputStream(dataFile);
FileInputStream metain = new FileInputStream(checksumFile);
FileChannel dch = datain.getChannel();
FileChannel mch = metain.getChannel();
// read in type of crc and bytes-per-checksum from metadata file
int versionSize = 2; // the first two bytes in meta file is the version
byte[] cksumHeader = new byte[versionSize + DataChecksum.HEADER_LEN];
int numread = metain.read(cksumHeader);
if (numread != versionSize + DataChecksum.HEADER_LEN) {
String msg = "readBlockAccelerator: metafile header should be atleast " +
(versionSize + DataChecksum.HEADER_LEN) + " bytes " +
" but could read only " + numread + " bytes.";
LOG.warn(msg);
throw new IOException(msg);
}
DataChecksum ckHdr = DataChecksum.newDataChecksum(cksumHeader, versionSize);
int type = ckHdr.getChecksumType();
int bytesPerChecksum = ckHdr.getBytesPerChecksum();
long cheaderSize = DataChecksum.getChecksumHeaderSize();
// align the startOffset with the previous bytesPerChecksum boundary.
long delta = startOffset % bytesPerChecksum;
startOffset -= delta;
length += delta;
// align the length to encompass the entire last checksum chunk
delta = length % bytesPerChecksum;
if (delta != 0) {
delta = bytesPerChecksum - delta;
length += delta;
}
// find the offset in the metafile
long startChunkNumber = startOffset / bytesPerChecksum;
long numChunks = length / bytesPerChecksum;
long checksumSize = ckHdr.getChecksumSize();
long startMetaOffset = versionSize + cheaderSize + startChunkNumber * checksumSize;
long metaLength = numChunks * checksumSize;
// get a connection back to the client
SocketOutputStream out = new SocketOutputStream(s, datanode.socketWriteTimeout);
try {
// write out the checksum type and bytesperchecksum to client
// skip the first two bytes that describe the version
long val = mch.transferTo(versionSize, cheaderSize, out);
if (val != cheaderSize) {
String msg = "readBlockAccelerator for block " + block +
" at offset " + 0 +
" but could not transfer checksum header.";
LOG.warn(msg);
throw new IOException(msg);
}
if (LOG.isDebugEnabled()) {
LOG.debug("readBlockAccelerator metaOffset " + startMetaOffset +
" mlength " + metaLength);
}
// write out the checksums back to the client
val = mch.transferTo(startMetaOffset, metaLength, out);
if (val != metaLength) {
String msg = "readBlockAccelerator for block " + block +
" at offset " + startMetaOffset +
" but could not transfer checksums of size " +
metaLength + ". Transferred only " + val;
LOG.warn(msg);
throw new IOException(msg);
}
if (LOG.isDebugEnabled()) {
LOG.debug("readBlockAccelerator dataOffset " + startOffset +
" length " + length);
}
// send data block back to client
long read = dch.transferTo(startOffset, length, out);
if (read != length) {
String msg = "readBlockAccelerator for block " + block +
" at offset " + startOffset +
" but block size is only " + length +
" and could transfer only " + read;
LOG.warn(msg);
throw new IOException(msg);
}
return read;
} catch ( SocketException ignored ) {
// Its ok for remote side to close the connection anytime.
datanode.myMetrics.blocksRead.inc();
return -1;
} catch ( IOException ioe ) {
/* What exactly should we do here?
* Earlier version shutdown() datanode if there is disk error.
*/
LOG.warn(datanode.getDatanodeInfo() +
":readBlockAccelerator:Got exception while serving " +
block + " to " +
s.getInetAddress() + ":\n" +
StringUtils.stringifyException(ioe) );
throw ioe;
} finally {
IOUtils.closeStream(out);
IOUtils.closeStream(datain);
IOUtils.closeStream(metain);
}
}
public static boolean isMetaFilename(String name) {
return name.startsWith(Block.BLOCK_FILE_PREFIX)
&& name.endsWith(Block.METADATA_EXTENSION);
}
/**
* Returns array of two longs: the first one is the block id, and the second
* one is genStamp. The method workds under assumption that metafile name has
* the following format: "blk_<blkid>_<gensmp>.meta"
*/
public static long[] parseMetafileName(String path) {
String[] groundSeparated = StringUtils.split(path, '_');
if (groundSeparated.length != 3) { // blk, blkid, genstamp.meta
throw new IllegalArgumentException("Not a valid meta file name");
}
String[] dotSeparated = StringUtils.split(groundSeparated[2], '.');
if (dotSeparated.length != 2) {
throw new IllegalArgumentException("Not a valid meta file name");
}
return new long[] { Long.parseLong(groundSeparated[1]),
Long.parseLong(dotSeparated[0]) };
}
}
| shakamunyi/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/server/datanode/BlockWithChecksumFileReader.java | Java | apache-2.0 | 24,443 |
/**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.model.forex.forward;
import java.util.Collections;
import java.util.Set;
import com.google.common.collect.Iterables;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.forex.derivative.Forex;
import com.opengamma.analytics.financial.forex.method.ForexForwardPointsMethod;
import com.opengamma.analytics.financial.interestrate.YieldCurveBundle;
import com.opengamma.analytics.math.curve.DoublesCurve;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValueProperties.Builder;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.analytics.fxforwardcurve.FXForwardCurveDefinition;
import com.opengamma.financial.analytics.model.CalculationPropertyNamesAndValues;
import com.opengamma.financial.analytics.model.forex.ForexVisitors;
import com.opengamma.financial.analytics.model.fx.FXForwardPointsPVFunction;
import com.opengamma.financial.security.FinancialSecurity;
import com.opengamma.util.money.CurrencyAmount;
import com.opengamma.util.money.MultipleCurrencyAmount;
/**
* Calculates the present value of an FX forward using the FX forward rates directly.
* @deprecated Use {@link FXForwardPointsPVFunction}
*/
@Deprecated
public class FXForwardPointsMethodPresentValueFunction extends FXForwardPointsMethodFunction {
private static final ForexForwardPointsMethod CALCULATOR = ForexForwardPointsMethod.getInstance();
public FXForwardPointsMethodPresentValueFunction() {
super(ValueRequirementNames.PRESENT_VALUE);
}
@Override
protected Set<ComputedValue> getResult(final Forex fxForward, final YieldCurveBundle data, final DoublesCurve forwardPoints, final ComputationTarget target,
final Set<ValueRequirement> desiredValues, final FunctionInputs inputs, final FunctionExecutionContext executionContext,
final FXForwardCurveDefinition fxForwardCurveDefinition) {
final MultipleCurrencyAmount mca = CALCULATOR.presentValue(fxForward, data, forwardPoints);
if (mca.size() != 1) {
throw new OpenGammaRuntimeException("Expecting a single value for present value");
}
final CurrencyAmount ca = mca.getCurrencyAmounts()[0];
final String currency = ((FinancialSecurity) target.getSecurity()).accept(ForexVisitors.getReceiveCurrencyVisitor()).getCode();
if (!ca.getCurrency().getCode().equals(currency)) {
throw new OpenGammaRuntimeException("Property currency did not match result currency");
}
final ValueProperties properties = getResultProperties(Iterables.getOnlyElement(desiredValues), currency).get();
final ValueSpecification spec = new ValueSpecification(ValueRequirementNames.PRESENT_VALUE, target.toSpecification(), properties);
return Collections.singleton(new ComputedValue(spec, ca.getAmount()));
}
@Override
protected ValueProperties.Builder getResultProperties(final ComputationTarget target) {
return createValueProperties()
.with(ValuePropertyNames.CALCULATION_METHOD, CalculationPropertyNamesAndValues.FORWARD_POINTS)
.withAny(ValuePropertyNames.PAY_CURVE)
.withAny(ValuePropertyNames.RECEIVE_CURVE)
.withAny(ValuePropertyNames.PAY_CURVE_CALCULATION_CONFIG)
.withAny(ValuePropertyNames.RECEIVE_CURVE_CALCULATION_CONFIG)
.withAny(ValuePropertyNames.FORWARD_CURVE_NAME)
.withAny(ValuePropertyNames.CURRENCY);
}
@Override
protected ValueProperties.Builder getResultProperties(final ComputationTarget target, final String payCurveName, final String receiveCurveName,
final String payCurveCalculationConfig, final String receiveCurveCalculationConfig, final String forwardCurveName) {
return createValueProperties()
.with(ValuePropertyNames.CALCULATION_METHOD, CalculationPropertyNamesAndValues.FORWARD_POINTS)
.with(ValuePropertyNames.PAY_CURVE, payCurveName)
.with(ValuePropertyNames.RECEIVE_CURVE, receiveCurveName)
.with(ValuePropertyNames.PAY_CURVE_CALCULATION_CONFIG, payCurveCalculationConfig)
.with(ValuePropertyNames.RECEIVE_CURVE_CALCULATION_CONFIG, receiveCurveCalculationConfig)
.with(ValuePropertyNames.FORWARD_CURVE_NAME, forwardCurveName)
.with(ValuePropertyNames.CURRENCY, ((FinancialSecurity) target.getSecurity()).accept(ForexVisitors.getReceiveCurrencyVisitor()).getCode());
}
protected ValueProperties.Builder getResultProperties(final ValueRequirement desiredValue, final String currency) {
final String payCurveName = desiredValue.getConstraint(ValuePropertyNames.PAY_CURVE);
final String receiveCurveName = desiredValue.getConstraint(ValuePropertyNames.RECEIVE_CURVE);
final String payCurveCalculationConfig = desiredValue.getConstraint(ValuePropertyNames.PAY_CURVE_CALCULATION_CONFIG);
final String receiveCurveCalculationConfig = desiredValue.getConstraint(ValuePropertyNames.RECEIVE_CURVE_CALCULATION_CONFIG);
final String forwardCurveName = desiredValue.getConstraint(ValuePropertyNames.FORWARD_CURVE_NAME);
return createValueProperties()
.with(ValuePropertyNames.CALCULATION_METHOD, CalculationPropertyNamesAndValues.FORWARD_POINTS)
.with(ValuePropertyNames.PAY_CURVE, payCurveName)
.with(ValuePropertyNames.RECEIVE_CURVE, receiveCurveName)
.with(ValuePropertyNames.PAY_CURVE_CALCULATION_CONFIG, payCurveCalculationConfig)
.with(ValuePropertyNames.RECEIVE_CURVE_CALCULATION_CONFIG, receiveCurveCalculationConfig)
.with(ValuePropertyNames.FORWARD_CURVE_NAME, forwardCurveName)
.with(ValuePropertyNames.CURRENCY, currency);
}
@Override
protected Builder getResultProperties(final ValueRequirement desiredValue, final ComputationTarget target) {
throw new UnsupportedOperationException();
}
}
| jeorme/OG-Platform | projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/forex/forward/FXForwardPointsMethodPresentValueFunction.java | Java | apache-2.0 | 6,310 |
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.xml;
import java.util.HashMap;
import java.util.Map;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
/**
* Support class for implementing custom {@link NamespaceHandler NamespaceHandlers}.
* Parsing and decorating of individual {@link Node Nodes} is done via {@link BeanDefinitionParser}
* and {@link BeanDefinitionDecorator} strategy interfaces, respectively.
*
* <p>Provides the {@link #registerBeanDefinitionParser} and {@link #registerBeanDefinitionDecorator}
* methods for registering a {@link BeanDefinitionParser} or {@link BeanDefinitionDecorator}
* to handle a specific element.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 2.0
* @see #registerBeanDefinitionParser(String, BeanDefinitionParser)
* @see #registerBeanDefinitionDecorator(String, BeanDefinitionDecorator)
*/
public abstract class NamespaceHandlerSupport implements NamespaceHandler {
/**
* Stores the {@link BeanDefinitionParser} implementations keyed by the
* local name of the {@link Element Elements} they handle.
*/
private final Map<String, BeanDefinitionParser> parsers =
new HashMap<String, BeanDefinitionParser>();
/**
* Stores the {@link BeanDefinitionDecorator} implementations keyed by the
* local name of the {@link Element Elements} they handle.
*/
private final Map<String, BeanDefinitionDecorator> decorators =
new HashMap<String, BeanDefinitionDecorator>();
/**
* Stores the {@link BeanDefinitionDecorator} implementations keyed by the local
* name of the {@link Attr Attrs} they handle.
*/
private final Map<String, BeanDefinitionDecorator> attributeDecorators =
new HashMap<String, BeanDefinitionDecorator>();
/**
* Parses the supplied {@link Element} by delegating to the {@link BeanDefinitionParser} that is
* registered for that {@link Element}.
*/
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
return findParserForElement(element, parserContext).parse(element, parserContext);
}
/**
* Locates the {@link BeanDefinitionParser} from the register implementations using
* the local name of the supplied {@link Element}.
*/
private BeanDefinitionParser findParserForElement(Element element, ParserContext parserContext) {
String localName = parserContext.getDelegate().getLocalName(element);
BeanDefinitionParser parser = this.parsers.get(localName);
if (parser == null) {
parserContext.getReaderContext().fatal(
"Cannot locate BeanDefinitionParser for element [" + localName + "]", element);
}
return parser;
}
/**
* Decorates the supplied {@link Node} by delegating to the {@link BeanDefinitionDecorator} that
* is registered to handle that {@link Node}.
*/
@Override
public BeanDefinitionHolder decorate(
Node node, BeanDefinitionHolder definition, ParserContext parserContext) {
return findDecoratorForNode(node, parserContext).decorate(node, definition, parserContext);
}
/**
* Locates the {@link BeanDefinitionParser} from the register implementations using
* the local name of the supplied {@link Node}. Supports both {@link Element Elements}
* and {@link Attr Attrs}.
*/
private BeanDefinitionDecorator findDecoratorForNode(Node node, ParserContext parserContext) {
BeanDefinitionDecorator decorator = null;
String localName = parserContext.getDelegate().getLocalName(node);
if (node instanceof Element) {
decorator = this.decorators.get(localName);
}
else if (node instanceof Attr) {
decorator = this.attributeDecorators.get(localName);
}
else {
parserContext.getReaderContext().fatal(
"Cannot decorate based on Nodes of type [" + node.getClass().getName() + "]", node);
}
if (decorator == null) {
parserContext.getReaderContext().fatal("Cannot locate BeanDefinitionDecorator for " +
(node instanceof Element ? "element" : "attribute") + " [" + localName + "]", node);
}
return decorator;
}
/**
* Subclasses can call this to register the supplied {@link BeanDefinitionParser} to
* handle the specified element. The element name is the local (non-namespace qualified)
* name.
*/
protected final void registerBeanDefinitionParser(String elementName, BeanDefinitionParser parser) {
this.parsers.put(elementName, parser);
}
/**
* Subclasses can call this to register the supplied {@link BeanDefinitionDecorator} to
* handle the specified element. The element name is the local (non-namespace qualified)
* name.
*/
protected final void registerBeanDefinitionDecorator(String elementName, BeanDefinitionDecorator dec) {
this.decorators.put(elementName, dec);
}
/**
* Subclasses can call this to register the supplied {@link BeanDefinitionDecorator} to
* handle the specified attribute. The attribute name is the local (non-namespace qualified)
* name.
*/
protected final void registerBeanDefinitionDecoratorForAttribute(String attrName, BeanDefinitionDecorator dec) {
this.attributeDecorators.put(attrName, dec);
}
}
| sunpy1106/SpringBeanLifeCycle | src/main/java/org/springframework/beans/factory/xml/NamespaceHandlerSupport.java | Java | apache-2.0 | 5,803 |
/**
* Derby - Class org.apache.derbyTesting.functionTests.tests.lang.PrecedenceTest
*
* 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.derbyTesting.functionTests.tests.lang;
import java.sql.SQLException;
import java.sql.Statement;
import junit.framework.Test;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.TestConfiguration;
/**
* Test case for precedence.sql.It tests precedence of operators other than and,
* or, and not that return boolean.
*/
public class PrecedenceTest extends BaseJDBCTestCase {
public PrecedenceTest(String name) {
super(name);
}
public static Test suite(){
return TestConfiguration.defaultSuite(PrecedenceTest.class);
}
public void testPrecedence() throws SQLException{
String sql = "create table t1(c11 int)";
Statement st = createStatement();
st.executeUpdate(sql);
sql = "insert into t1 values(1)";
assertEquals(1, st.executeUpdate(sql));
sql = "select c11 from t1 where 1 in (1,2,3) = (1=1)";
JDBC.assertSingleValueResultSet(st.executeQuery(sql), "1");
sql = "select c11 from t1 where 'acme widgets' " +
"like 'acme%' in ('1=1')";
JDBC.assertSingleValueResultSet(st.executeQuery(sql), "1");
sql = "select c11 from t1 where 1 between -100 " +
"and 100 is not null";
JDBC.assertSingleValueResultSet(st.executeQuery(sql), "1");
sql = "select c11 from t1 where exists(select *" +
" from (values 1) as t) not in ('1=2')";
JDBC.assertEmpty(st.executeQuery(sql));
st.close();
}
}
| scnakandala/derby | java/testing/org/apache/derbyTesting/functionTests/tests/lang/PrecedenceTest.java | Java | apache-2.0 | 2,454 |
// Copyright JS Foundation and other contributors, http://js.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.
const obj = {};
var a = { a : (o) = 1 } = obj;
assert (a === obj);
assert (o === 1);
| jerryscript-project/jerryscript | tests/jerry/regression-test-issue-3935.js | JavaScript | apache-2.0 | 716 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs.s3native;
import static org.apache.hadoop.fs.s3native.NativeS3FileSystem.PATH_DELIMITER;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.s3.S3Credentials;
import org.apache.hadoop.fs.s3.S3Exception;
import org.jets3t.service.S3Service;
import org.jets3t.service.S3ServiceException;
import org.jets3t.service.ServiceException;
import org.jets3t.service.StorageObjectsChunk;
import org.jets3t.service.impl.rest.httpclient.RestS3Service;
import org.jets3t.service.model.MultipartPart;
import org.jets3t.service.model.MultipartUpload;
import org.jets3t.service.model.S3Bucket;
import org.jets3t.service.model.S3Object;
import org.jets3t.service.model.StorageObject;
import org.jets3t.service.security.AWSCredentials;
import org.jets3t.service.utils.MultipartUtils;
@InterfaceAudience.Private
@InterfaceStability.Unstable
class Jets3tNativeFileSystemStore implements NativeFileSystemStore {
private S3Service s3Service;
private S3Bucket bucket;
private long multipartBlockSize;
private boolean multipartEnabled;
private long multipartCopyBlockSize;
static final long MAX_PART_SIZE = (long)5 * 1024 * 1024 * 1024;
public static final Log LOG =
LogFactory.getLog(Jets3tNativeFileSystemStore.class);
@Override
public void initialize(URI uri, Configuration conf) throws IOException {
S3Credentials s3Credentials = new S3Credentials();
s3Credentials.initialize(uri, conf);
try {
AWSCredentials awsCredentials =
new AWSCredentials(s3Credentials.getAccessKey(),
s3Credentials.getSecretAccessKey());
this.s3Service = new RestS3Service(awsCredentials);
} catch (S3ServiceException e) {
handleS3ServiceException(e);
}
multipartEnabled =
conf.getBoolean("fs.s3n.multipart.uploads.enabled", false);
multipartBlockSize = Math.min(
conf.getLong("fs.s3n.multipart.uploads.block.size", 64 * 1024 * 1024),
MAX_PART_SIZE);
multipartCopyBlockSize = Math.min(
conf.getLong("fs.s3n.multipart.copy.block.size", MAX_PART_SIZE),
MAX_PART_SIZE);
bucket = new S3Bucket(uri.getHost());
}
@Override
public void storeFile(String key, File file, byte[] md5Hash)
throws IOException {
if (multipartEnabled && file.length() >= multipartBlockSize) {
storeLargeFile(key, file, md5Hash);
return;
}
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
S3Object object = new S3Object(key);
object.setDataInputStream(in);
object.setContentType("binary/octet-stream");
object.setContentLength(file.length());
if (md5Hash != null) {
object.setMd5Hash(md5Hash);
}
s3Service.putObject(bucket, object);
} catch (S3ServiceException e) {
handleS3ServiceException(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
}
}
public void storeLargeFile(String key, File file, byte[] md5Hash)
throws IOException {
S3Object object = new S3Object(key);
object.setDataInputFile(file);
object.setContentType("binary/octet-stream");
object.setContentLength(file.length());
if (md5Hash != null) {
object.setMd5Hash(md5Hash);
}
List<StorageObject> objectsToUploadAsMultipart =
new ArrayList<StorageObject>();
objectsToUploadAsMultipart.add(object);
MultipartUtils mpUtils = new MultipartUtils(multipartBlockSize);
try {
mpUtils.uploadObjects(bucket.getName(), s3Service,
objectsToUploadAsMultipart, null);
} catch (ServiceException e) {
handleServiceException(e);
} catch (Exception e) {
throw new S3Exception(e);
}
}
@Override
public void storeEmptyFile(String key) throws IOException {
try {
S3Object object = new S3Object(key);
object.setDataInputStream(new ByteArrayInputStream(new byte[0]));
object.setContentType("binary/octet-stream");
object.setContentLength(0);
s3Service.putObject(bucket, object);
} catch (S3ServiceException e) {
handleS3ServiceException(e);
}
}
@Override
public FileMetadata retrieveMetadata(String key) throws IOException {
StorageObject object = null;
try {
if(LOG.isDebugEnabled()) {
LOG.debug("Getting metadata for key: " + key + " from bucket:" + bucket.getName());
}
object = s3Service.getObjectDetails(bucket.getName(), key);
return new FileMetadata(key, object.getContentLength(),
object.getLastModifiedDate().getTime());
} catch (ServiceException e) {
// Following is brittle. Is there a better way?
if ("NoSuchKey".equals(e.getErrorCode())) {
return null; //return null if key not found
}
handleServiceException(e);
return null; //never returned - keep compiler happy
} finally {
if (object != null) {
object.closeDataInputStream();
}
}
}
/**
* @param key
* The key is the object name that is being retrieved from the S3 bucket
* @return
* This method returns null if the key is not found
* @throws IOException
*/
@Override
public InputStream retrieve(String key) throws IOException {
try {
if(LOG.isDebugEnabled()) {
LOG.debug("Getting key: " + key + " from bucket:" + bucket.getName());
}
S3Object object = s3Service.getObject(bucket.getName(), key);
return object.getDataInputStream();
} catch (ServiceException e) {
handleServiceException(key, e);
return null; //return null if key not found
}
}
/**
*
* @param key
* The key is the object name that is being retrieved from the S3 bucket
* @return
* This method returns null if the key is not found
* @throws IOException
*/
@Override
public InputStream retrieve(String key, long byteRangeStart)
throws IOException {
try {
if(LOG.isDebugEnabled()) {
LOG.debug("Getting key: " + key + " from bucket:" + bucket.getName() + " with byteRangeStart: " + byteRangeStart);
}
S3Object object = s3Service.getObject(bucket, key, null, null, null,
null, byteRangeStart, null);
return object.getDataInputStream();
} catch (ServiceException e) {
handleServiceException(key, e);
return null; //return null if key not found
}
}
@Override
public PartialListing list(String prefix, int maxListingLength)
throws IOException {
return list(prefix, maxListingLength, null, false);
}
@Override
public PartialListing list(String prefix, int maxListingLength, String priorLastKey,
boolean recurse) throws IOException {
return list(prefix, recurse ? null : PATH_DELIMITER, maxListingLength, priorLastKey);
}
/**
*
* @return
* This method returns null if the list could not be populated
* due to S3 giving ServiceException
* @throws IOException
*/
private PartialListing list(String prefix, String delimiter,
int maxListingLength, String priorLastKey) throws IOException {
try {
if (prefix.length() > 0 && !prefix.endsWith(PATH_DELIMITER)) {
prefix += PATH_DELIMITER;
}
StorageObjectsChunk chunk = s3Service.listObjectsChunked(bucket.getName(),
prefix, delimiter, maxListingLength, priorLastKey);
FileMetadata[] fileMetadata =
new FileMetadata[chunk.getObjects().length];
for (int i = 0; i < fileMetadata.length; i++) {
StorageObject object = chunk.getObjects()[i];
fileMetadata[i] = new FileMetadata(object.getKey(),
object.getContentLength(), object.getLastModifiedDate().getTime());
}
return new PartialListing(chunk.getPriorLastKey(), fileMetadata,
chunk.getCommonPrefixes());
} catch (S3ServiceException e) {
handleS3ServiceException(e);
return null; //never returned - keep compiler happy
} catch (ServiceException e) {
handleServiceException(e);
return null; //return null if list could not be populated
}
}
@Override
public void delete(String key) throws IOException {
try {
if(LOG.isDebugEnabled()) {
LOG.debug("Deleting key:" + key + "from bucket" + bucket.getName());
}
s3Service.deleteObject(bucket, key);
} catch (ServiceException e) {
handleServiceException(key, e);
}
}
public void rename(String srcKey, String dstKey) throws IOException {
try {
s3Service.renameObject(bucket.getName(), srcKey, new S3Object(dstKey));
} catch (ServiceException e) {
handleServiceException(e);
}
}
@Override
public void copy(String srcKey, String dstKey) throws IOException {
try {
if(LOG.isDebugEnabled()) {
LOG.debug("Copying srcKey: " + srcKey + "to dstKey: " + dstKey + "in bucket: " + bucket.getName());
}
if (multipartEnabled) {
S3Object object = s3Service.getObjectDetails(bucket, srcKey, null,
null, null, null);
if (multipartCopyBlockSize > 0 &&
object.getContentLength() > multipartCopyBlockSize) {
copyLargeFile(object, dstKey);
return;
}
}
s3Service.copyObject(bucket.getName(), srcKey, bucket.getName(),
new S3Object(dstKey), false);
} catch (ServiceException e) {
handleServiceException(srcKey, e);
}
}
public void copyLargeFile(S3Object srcObject, String dstKey) throws IOException {
try {
long partCount = srcObject.getContentLength() / multipartCopyBlockSize +
(srcObject.getContentLength() % multipartCopyBlockSize > 0 ? 1 : 0);
MultipartUpload multipartUpload = s3Service.multipartStartUpload
(bucket.getName(), dstKey, srcObject.getMetadataMap());
List<MultipartPart> listedParts = new ArrayList<MultipartPart>();
for (int i = 0; i < partCount; i++) {
long byteRangeStart = i * multipartCopyBlockSize;
long byteLength;
if (i < partCount - 1) {
byteLength = multipartCopyBlockSize;
} else {
byteLength = srcObject.getContentLength() % multipartCopyBlockSize;
if (byteLength == 0) {
byteLength = multipartCopyBlockSize;
}
}
MultipartPart copiedPart = s3Service.multipartUploadPartCopy
(multipartUpload, i + 1, bucket.getName(), srcObject.getKey(),
null, null, null, null, byteRangeStart,
byteRangeStart + byteLength - 1, null);
listedParts.add(copiedPart);
}
Collections.reverse(listedParts);
s3Service.multipartCompleteUpload(multipartUpload, listedParts);
} catch (ServiceException e) {
handleServiceException(e);
}
}
@Override
public void purge(String prefix) throws IOException {
try {
S3Object[] objects = s3Service.listObjects(bucket.getName(), prefix, null);
for (S3Object object : objects) {
s3Service.deleteObject(bucket, object.getKey());
}
} catch (S3ServiceException e) {
handleS3ServiceException(e);
}
}
@Override
public void dump() throws IOException {
StringBuilder sb = new StringBuilder("S3 Native Filesystem, ");
sb.append(bucket.getName()).append("\n");
try {
S3Object[] objects = s3Service.listObjects(bucket.getName());
for (S3Object object : objects) {
sb.append(object.getKey()).append("\n");
}
} catch (S3ServiceException e) {
handleS3ServiceException(e);
}
System.out.println(sb);
}
private void handleServiceException(String key, ServiceException e) throws IOException {
if ("NoSuchKey".equals(e.getErrorCode())) {
throw new FileNotFoundException("Key '" + key + "' does not exist in S3");
} else {
handleServiceException(e);
}
}
private void handleS3ServiceException(S3ServiceException e) throws IOException {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
}
else {
if(LOG.isDebugEnabled()) {
LOG.debug("S3 Error code: " + e.getS3ErrorCode() + "; S3 Error message: " + e.getS3ErrorMessage());
}
throw new S3Exception(e);
}
}
private void handleServiceException(ServiceException e) throws IOException {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
}
else {
if(LOG.isDebugEnabled()) {
LOG.debug("Got ServiceException with Error code: " + e.getErrorCode() + ";and Error message: " + e.getErrorMessage());
}
}
}
}
| songweijia/fffs | sources/hadoop-2.4.1-src/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/s3native/Jets3tNativeFileSystemStore.java | Java | apache-2.0 | 14,116 |
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Can't test the system lib because this test enables debug mode
// MODULES_DEFINES: _LIBCPP_DEBUG=1
// UNSUPPORTED: with_system_cxx_lib
// UNSUPPORTED: c++98, c++03
// UNSUPPORTED: windows
// UNSUPPORTED: with_system_cxx_lib
// <list>
// Call prev(forward_iterator, -1)
#define _LIBCPP_DEBUG 0
#include <iterator>
#include "test_macros.h"
#include "debug_mode_helper.h"
#include "test_iterators.h"
int main(int, char**)
{
int a[] = {1, 2, 3};
bidirectional_iterator<int *> bidi(a+1);
std::prev(bidi, -1); // should work fine
std::prev(bidi, 0); // should work fine
std::prev(bidi, 1); // should work fine
forward_iterator<int *> it(a+1);
std::prev(it, -1); // should work fine
std::prev(it, 0); // should work fine
EXPECT_DEATH( std::prev(it, 1) ); // can't go backwards on a FwdIter
return 0;
}
| llvm-mirror/libcxx | test/libcxx/iterators/prev.debug1.pass.cpp | C++ | apache-2.0 | 1,215 |
# Copyright 2014-2015 Canonical Limited.
#
# 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.
# Bootstrap charm-helpers, installing its dependencies if necessary using
# only standard libraries.
import subprocess
import sys
try:
import six # flake8: noqa
except ImportError:
if sys.version_info.major == 2:
subprocess.check_call(['apt-get', 'install', '-y', 'python-six'])
else:
subprocess.check_call(['apt-get', 'install', '-y', 'python3-six'])
import six # flake8: noqa
try:
import yaml # flake8: noqa
except ImportError:
if sys.version_info.major == 2:
subprocess.check_call(['apt-get', 'install', '-y', 'python-yaml'])
else:
subprocess.check_call(['apt-get', 'install', '-y', 'python3-yaml'])
import yaml # flake8: noqa
| CanonicalBootStack/charm-hacluster | tests/charmhelpers/__init__.py | Python | apache-2.0 | 1,285 |
/*
* 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.commons.io.output;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import junit.framework.TestCase;
import org.junit.Assert;
/**
* @version $Id$
*/
public class TeeOutputStreamTest extends TestCase {
private static class ExceptionOnCloseByteArrayOutputStream extends ByteArrayOutputStream {
@Override
public void close() throws IOException {
throw new IOException();
}
}
private static class RecordCloseByteArrayOutputStream extends ByteArrayOutputStream {
boolean closed;
@Override
public void close() throws IOException {
super.close();
closed = true;
}
}
public TeeOutputStreamTest(final String name) {
super(name);
}
/**
* Tests that the branch {@code OutputStream} is closed when closing the main {@code OutputStream} throws an
* exception on {@link TeeOutputStream#close()}.
*/
public void testCloseBranchIOException() {
final ByteArrayOutputStream badOs = new ExceptionOnCloseByteArrayOutputStream();
final RecordCloseByteArrayOutputStream goodOs = new RecordCloseByteArrayOutputStream();
final TeeOutputStream tos = new TeeOutputStream(goodOs, badOs);
try {
tos.close();
Assert.fail("Expected " + IOException.class.getName());
} catch (final IOException e) {
Assert.assertTrue(goodOs.closed);
}
}
/**
* Tests that the main {@code OutputStream} is closed when closing the branch {@code OutputStream} throws an
* exception on {@link TeeOutputStream#close()}.
*/
public void testCloseMainIOException() {
final ByteArrayOutputStream badOs = new ExceptionOnCloseByteArrayOutputStream();
final RecordCloseByteArrayOutputStream goodOs = new RecordCloseByteArrayOutputStream();
final TeeOutputStream tos = new TeeOutputStream(badOs, goodOs);
try {
tos.close();
Assert.fail("Expected " + IOException.class.getName());
} catch (final IOException e) {
Assert.assertTrue(goodOs.closed);
}
}
public void testTee() throws IOException {
final ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
final ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
final TeeOutputStream tos = new TeeOutputStream(baos1, baos2);
for (int i = 0; i < 20; i++) {
tos.write(i);
}
assertByteArrayEquals("TeeOutputStream.write(int)", baos1.toByteArray(), baos2.toByteArray());
final byte[] array = new byte[10];
for (int i = 20; i < 30; i++) {
array[i - 20] = (byte) i;
}
tos.write(array);
assertByteArrayEquals("TeeOutputStream.write(byte[])", baos1.toByteArray(), baos2.toByteArray());
for (int i = 25; i < 35; i++) {
array[i - 25] = (byte) i;
}
tos.write(array, 5, 5);
assertByteArrayEquals("TeeOutputStream.write(byte[], int, int)", baos1.toByteArray(), baos2.toByteArray());
tos.flush();
tos.close();
}
private void assertByteArrayEquals(final String msg, final byte[] array1, final byte[] array2) {
assertEquals(msg + ": array size mismatch", array1.length, array2.length);
for (int i = 0; i < array1.length; i++) {
assertEquals(msg + ": array[ " + i + "] mismatch", array1[i], array2[i]);
}
}
}
| MuShiiii/commons-io | src/test/java/org/apache/commons/io/output/TeeOutputStreamTest.java | Java | apache-2.0 | 4,322 |
/*
* 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.cassandra.auth;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.Iterables;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.schema.KeyspaceParams;
import org.apache.cassandra.schema.SchemaConstants;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.service.StorageService;
import static org.apache.cassandra.auth.AuthTestUtils.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CassandraRoleManagerTest
{
@BeforeClass
public static void setupClass()
{
SchemaLoader.prepareServer();
// create the system_auth keyspace so the IRoleManager can function as normal
SchemaLoader.createKeyspace(SchemaConstants.AUTH_KEYSPACE_NAME,
KeyspaceParams.simple(1),
Iterables.toArray(AuthKeyspace.metadata().tables, TableMetadata.class));
// We start StorageService because confirmFastRoleSetup confirms that CassandraRoleManager will
// take a faster path once the cluster is already setup, which includes checking MessagingService
// and issuing queries with QueryProcessor.process, which uses TokenMetadata
DatabaseDescriptor.daemonInitialization();
StorageService.instance.initServer(0);
AuthCacheService.initializeAndRegisterCaches();
}
@Before
public void setup() throws Exception
{
ColumnFamilyStore.getIfExists(SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES).truncateBlocking();
ColumnFamilyStore.getIfExists(SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLE_MEMBERS).truncateBlocking();
}
@Test
public void getGrantedRolesImplMinimizesReads()
{
// IRoleManager::getRoleDetails was not in the initial API, so a default impl
// was added which uses the existing methods on IRoleManager as primitive to
// construct the Role objects. While this will work for any IRoleManager impl
// it is inefficient, so CassandraRoleManager has its own implementation which
// collects all of the necessary info with a single query for each granted role.
// This just tests that that is the case, i.e. we perform 1 read per role in the
// transitive set of granted roles
IRoleManager roleManager = new AuthTestUtils.LocalCassandraRoleManager();
roleManager.setup();
for (RoleResource r : ALL_ROLES)
roleManager.createRole(AuthenticatedUser.ANONYMOUS_USER, r, new RoleOptions());
// simple role with no grants
fetchRolesAndCheckReadCount(roleManager, ROLE_A);
// single level of grants
grantRolesTo(roleManager, ROLE_A, ROLE_B, ROLE_C);
fetchRolesAndCheckReadCount(roleManager, ROLE_A);
// multi level role hierarchy
grantRolesTo(roleManager, ROLE_B, ROLE_B_1, ROLE_B_2, ROLE_B_3);
grantRolesTo(roleManager, ROLE_C, ROLE_C_1, ROLE_C_2, ROLE_C_3);
fetchRolesAndCheckReadCount(roleManager, ROLE_A);
// Check that when granted roles appear multiple times in parallel levels of the hierarchy, we don't
// do redundant reads. E.g. here role_b_1, role_b_2 and role_b3 are granted to both role_b and role_c
// but we only want to actually read them once
grantRolesTo(roleManager, ROLE_C, ROLE_B_1, ROLE_B_2, ROLE_B_3);
fetchRolesAndCheckReadCount(roleManager, ROLE_A);
}
private void fetchRolesAndCheckReadCount(IRoleManager roleManager, RoleResource primaryRole)
{
long before = getRolesReadCount();
Set<Role> granted = roleManager.getRoleDetails(primaryRole);
long after = getRolesReadCount();
assertEquals(granted.size(), after - before);
}
@Test
public void confirmFastRoleSetup()
{
IRoleManager roleManager = new AuthTestUtils.LocalCassandraRoleManager();
roleManager.setup();
for (RoleResource r : ALL_ROLES)
roleManager.createRole(AuthenticatedUser.ANONYMOUS_USER, r, new RoleOptions());
CassandraRoleManager crm = new CassandraRoleManager();
assertTrue("Expected the role manager to have existing roles before CassandraRoleManager setup", CassandraRoleManager.hasExistingRoles());
}
@Test
public void warmCacheLoadsAllEntries()
{
IRoleManager roleManager = new AuthTestUtils.LocalCassandraRoleManager();
roleManager.setup();
for (RoleResource r : ALL_ROLES)
roleManager.createRole(AuthenticatedUser.ANONYMOUS_USER, r, new RoleOptions());
// Multi level role hierarchy
grantRolesTo(roleManager, ROLE_B, ROLE_B_1, ROLE_B_2, ROLE_B_3);
grantRolesTo(roleManager, ROLE_C, ROLE_C_1, ROLE_C_2, ROLE_C_3);
// Use CassandraRoleManager to get entries for pre-warming a cache, then verify those entries
CassandraRoleManager crm = new CassandraRoleManager();
crm.setup();
Map<RoleResource, Set<Role>> cacheEntries = crm.bulkLoader().get();
Set<Role> roleBRoles = cacheEntries.get(ROLE_B);
assertRoleSet(roleBRoles, ROLE_B, ROLE_B_1, ROLE_B_2, ROLE_B_3);
Set<Role> roleCRoles = cacheEntries.get(ROLE_C);
assertRoleSet(roleCRoles, ROLE_C, ROLE_C_1, ROLE_C_2, ROLE_C_3);
for (RoleResource r : ALL_ROLES)
{
// We already verified ROLE_B and ROLE_C
if (r.equals(ROLE_B) || r.equals(ROLE_C))
continue;
// Check the cache entries for the roles without any further grants
assertRoleSet(cacheEntries.get(r), r);
}
}
@Test
public void warmCacheWithEmptyTable()
{
CassandraRoleManager crm = new CassandraRoleManager();
crm.setup();
Map<RoleResource, Set<Role>> cacheEntries = crm.bulkLoader().get();
assertTrue(cacheEntries.isEmpty());
}
private void assertRoleSet(Set<Role> actual, RoleResource...expected)
{
assertEquals(expected.length, actual.size());
for (RoleResource expectedRole : expected)
assertTrue(actual.stream().anyMatch(role -> role.resource.equals(expectedRole)));
}
}
| belliottsmith/cassandra | test/unit/org/apache/cassandra/auth/CassandraRoleManagerTest.java | Java | apache-2.0 | 7,254 |
aws_iam_user 'test-kitchen-user' do
aws_access_key node['aws_test']['key_id']
aws_secret_access_key node['aws_test']['access_key']
action :create
end
aws_iam_user 'test-kitchen-user' do
aws_access_key node['aws_test']['key_id']
aws_secret_access_key node['aws_test']['access_key']
action :delete
end
| vishnuzimbra/zimbra | test/fixtures/cookbooks/aws_test/recipes/iam_user.rb | Ruby | apache-2.0 | 313 |
import {verifyNoBrowserErrors} from 'angular2/src/testing/e2e_util';
import {Promise} from 'angular2/src/core/facade/async';
describe('WebWorkers Kitchen Sink', function() {
afterEach(() => {
verifyNoBrowserErrors();
browser.ignoreSynchronization = false;
});
var selector = "hello-app .greeting";
var URL = "playground/src/web_workers/kitchen_sink/index.html";
it('should greet', () => {
// This test can't wait for Angular 2 as Testability is not available when using WebWorker
browser.ignoreSynchronization = true;
browser.get(URL);
browser.wait(protractor.until.elementLocated(by.css(selector)), 15000);
expect(element.all(by.css(selector)).first().getText()).toEqual("hello world!");
});
it('should change greeting', () => {
// This test can't wait for Angular 2 as Testability is not available when using WebWorker
browser.ignoreSynchronization = true;
browser.get(URL);
browser.wait(protractor.until.elementLocated(by.css(selector)), 15000);
element(by.css("hello-app .changeButton")).click();
var elem = element(by.css(selector));
browser.wait(protractor.until.elementTextIs(elem, "howdy world!"), 5000);
expect(elem.getText()).toEqual("howdy world!");
});
it("should display correct key names", () => {
// This test can't wait for Angular 2 as Testability is not available when using WebWorker
browser.ignoreSynchronization = true;
browser.get(URL);
browser.wait(protractor.until.elementLocated(by.css(".sample-area")), 15000);
var area = element.all(by.css(".sample-area")).first();
expect(area.getText()).toEqual('(none)');
area.sendKeys('u');
browser.wait(protractor.until.elementTextIs(area, "U"), 5000);
expect(area.getText()).toEqual("U");
});
});
| hankduan/angular | modules/playground/e2e_test/web_workers/kitchen_sink/kitchen_sink_spec.ts | TypeScript | apache-2.0 | 1,788 |
<?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_CloudKMS_KeyOperationAttestation extends Google_Model
{
protected $certChainsType = 'Google_Service_CloudKMS_CertificateChains';
protected $certChainsDataType = '';
public $content;
public $format;
/**
* @param Google_Service_CloudKMS_CertificateChains
*/
public function setCertChains(Google_Service_CloudKMS_CertificateChains $certChains)
{
$this->certChains = $certChains;
}
/**
* @return Google_Service_CloudKMS_CertificateChains
*/
public function getCertChains()
{
return $this->certChains;
}
public function setContent($content)
{
$this->content = $content;
}
public function getContent()
{
return $this->content;
}
public function setFormat($format)
{
$this->format = $format;
}
public function getFormat()
{
return $this->format;
}
}
| tsugiproject/tsugi | vendor/google/apiclient-services/src/Google/Service/CloudKMS/KeyOperationAttestation.php | PHP | apache-2.0 | 1,447 |
/**
* Copyright 2015-2017 Red Hat, Inc, and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.swarm.datasources.runtime.drivers;
import org.wildfly.swarm.config.datasources.DataSource;
import org.wildfly.swarm.datasources.runtime.DriverInfo;
/**
* Auto-detection for Apache Hive
*
* @author Kylin Soong
*/
public class Hive2DriverInfo extends DriverInfo {
public static final String DEFAULT_CONNETION_URL = "jdbc:hive2://localhost:10000/default";
public static final String DEFAULT_USER_NAME = "sa";
public static final String DEFAULT_PASSWORD = "sa";
protected Hive2DriverInfo() {
super("hive2", "org.apache.hive.jdbc", "org.apache.hive.jdbc.HiveDriver");
}
@Override
protected void configureDefaultDS(DataSource datasource) {
datasource.connectionUrl(DEFAULT_CONNETION_URL);
datasource.userName(DEFAULT_USER_NAME);
datasource.password(DEFAULT_PASSWORD);
}
}
| swarmsandbox/wildfly-swarm | fractions/javaee/datasources/src/main/java/org/wildfly/swarm/datasources/runtime/drivers/Hive2DriverInfo.java | Java | apache-2.0 | 1,490 |
// Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.trading.api;
import java.io.Serializable;
import com.leansoft.nano.annotation.*;
import java.util.List;
/**
*
* Indicates whether Contact Seller is enabled for Classified Ads.
* Added for EbayMotors Pro users.
*
*/
public class EBayMotorsProBestOfferEnabledDefinitionType implements Serializable {
private static final long serialVersionUID = -1L;
@AnyElement
@Order(value=0)
public List<Object> any;
} | uaraven/nano | sample/webservice/eBayDemoApp/src/com/ebay/trading/api/EBayMotorsProBestOfferEnabledDefinitionType.java | Java | apache-2.0 | 509 |
package useridentitymapping
import (
"fmt"
kapi "k8s.io/kubernetes/pkg/api"
kerrs "k8s.io/kubernetes/pkg/api/errors"
"k8s.io/kubernetes/pkg/api/rest"
"k8s.io/kubernetes/pkg/runtime"
"k8s.io/kubernetes/pkg/util"
"k8s.io/kubernetes/pkg/util/fielderrors"
"k8s.io/kubernetes/pkg/util/sets"
"github.com/openshift/origin/pkg/user/api"
"github.com/openshift/origin/pkg/user/registry/identity"
"github.com/openshift/origin/pkg/user/registry/user"
)
// REST implements the RESTStorage interface in terms of an image registry and
// image repository registry. It only supports the Create method and is used
// to simplify adding a new Image and tag to an ImageRepository.
type REST struct {
userRegistry user.Registry
identityRegistry identity.Registry
}
// NewREST returns a new REST.
func NewREST(userRegistry user.Registry, identityRegistry identity.Registry) *REST {
return &REST{userRegistry: userRegistry, identityRegistry: identityRegistry}
}
// New returns a new UserIdentityMapping for use with Create.
func (r *REST) New() runtime.Object {
return &api.UserIdentityMapping{}
}
// Get returns the mapping for the named identity
func (s *REST) Get(ctx kapi.Context, name string) (runtime.Object, error) {
_, _, _, _, mapping, err := s.getRelatedObjects(ctx, name)
return mapping, err
}
// Create associates a user and identity if they both exist, and the identity is not already mapped to a user
func (s *REST) Create(ctx kapi.Context, obj runtime.Object) (runtime.Object, error) {
mapping, ok := obj.(*api.UserIdentityMapping)
if !ok {
return nil, kerrs.NewBadRequest("invalid type")
}
Strategy.PrepareForCreate(mapping)
createdMapping, _, err := s.createOrUpdate(ctx, obj, true)
return createdMapping, err
}
// Update associates an identity with a user.
// Both the identity and user must already exist.
// If the identity is associated with another user already, it is disassociated.
func (s *REST) Update(ctx kapi.Context, obj runtime.Object) (runtime.Object, bool, error) {
mapping, ok := obj.(*api.UserIdentityMapping)
if !ok {
return nil, false, kerrs.NewBadRequest("invalid type")
}
Strategy.PrepareForUpdate(mapping, nil)
return s.createOrUpdate(ctx, mapping, false)
}
func (s *REST) createOrUpdate(ctx kapi.Context, obj runtime.Object, forceCreate bool) (runtime.Object, bool, error) {
mapping := obj.(*api.UserIdentityMapping)
identity, identityErr, oldUser, oldUserErr, oldMapping, oldMappingErr := s.getRelatedObjects(ctx, mapping.Name)
// Ensure we didn't get any errors other than NotFound errors
if !(oldMappingErr == nil || kerrs.IsNotFound(oldMappingErr)) {
return nil, false, oldMappingErr
}
if !(identityErr == nil || kerrs.IsNotFound(identityErr)) {
return nil, false, identityErr
}
if !(oldUserErr == nil || kerrs.IsNotFound(oldUserErr)) {
return nil, false, oldUserErr
}
// If we expect to be creating, fail if the mapping already existed
if forceCreate && oldMappingErr == nil {
return nil, false, kerrs.NewAlreadyExists("UserIdentityMapping", oldMapping.Name)
}
// Allow update to create if missing
creating := forceCreate || kerrs.IsNotFound(oldMappingErr)
if creating {
// Pre-create checks with no access to oldMapping
if err := rest.BeforeCreate(Strategy, ctx, mapping); err != nil {
return nil, false, err
}
// Ensure resource version is not specified
if len(mapping.ResourceVersion) > 0 {
return nil, false, kerrs.NewNotFound("UserIdentityMapping", mapping.Name)
}
} else {
// Pre-update checks with access to oldMapping
if err := rest.BeforeUpdate(Strategy, ctx, mapping, oldMapping); err != nil {
return nil, false, err
}
// Ensure resource versions match
if len(mapping.ResourceVersion) > 0 && mapping.ResourceVersion != oldMapping.ResourceVersion {
return nil, false, kerrs.NewConflict("UserIdentityMapping", mapping.Name, fmt.Errorf("the resource was updated to %s", oldMapping.ResourceVersion))
}
// If we're "updating" to the user we're already pointing to, we're already done
if mapping.User.Name == oldMapping.User.Name {
return oldMapping, false, nil
}
}
// Validate identity
if kerrs.IsNotFound(identityErr) {
errs := fielderrors.ValidationErrorList([]error{
fielderrors.NewFieldInvalid("identity.name", mapping.Identity.Name, "referenced identity does not exist"),
})
return nil, false, kerrs.NewInvalid("UserIdentityMapping", mapping.Name, errs)
}
// Get new user
newUser, err := s.userRegistry.GetUser(ctx, mapping.User.Name)
if kerrs.IsNotFound(err) {
errs := fielderrors.ValidationErrorList([]error{
fielderrors.NewFieldInvalid("user.name", mapping.User.Name, "referenced user does not exist"),
})
return nil, false, kerrs.NewInvalid("UserIdentityMapping", mapping.Name, errs)
}
if err != nil {
return nil, false, err
}
// Update the new user to point at the identity. If this fails, Update is re-entrant
if addIdentityToUser(identity, newUser) {
if _, err := s.userRegistry.UpdateUser(ctx, newUser); err != nil {
return nil, false, err
}
}
// Update the identity to point at the new user. If this fails. Update is re-entrant
if setIdentityUser(identity, newUser) {
if updatedIdentity, err := s.identityRegistry.UpdateIdentity(ctx, identity); err != nil {
return nil, false, err
} else {
identity = updatedIdentity
}
}
// At this point, the mapping for the identity has been updated to the new user
// Everything past this point is cleanup
// Update the old user to no longer point at the identity.
// If this fails, log the error, but continue, because Update is no longer re-entrant
if oldUser != nil && removeIdentityFromUser(identity, oldUser) {
if _, err := s.userRegistry.UpdateUser(ctx, oldUser); err != nil {
util.HandleError(fmt.Errorf("error removing identity reference %s from user %s: %v", identity.Name, oldUser.Name, err))
}
}
updatedMapping, err := mappingFor(newUser, identity)
return updatedMapping, creating, err
}
// Delete deletes the user association for the named identity
func (s *REST) Delete(ctx kapi.Context, name string) (runtime.Object, error) {
identity, _, user, _, _, mappingErr := s.getRelatedObjects(ctx, name)
if mappingErr != nil {
return nil, mappingErr
}
// Disassociate the identity with the user first
// If this fails, Delete is re-entrant
if removeIdentityFromUser(identity, user) {
if _, err := s.userRegistry.UpdateUser(ctx, user); err != nil {
return nil, err
}
}
// Remove the user association from the identity last.
// If this fails, log the error, but continue, because Delete is no longer re-entrant
// At this point, the mapping for the identity no longer exists
if unsetIdentityUser(identity) {
if _, err := s.identityRegistry.UpdateIdentity(ctx, identity); err != nil {
util.HandleError(fmt.Errorf("error removing user reference %s from identity %s: %v", user.Name, identity.Name, err))
}
}
return &kapi.Status{Status: kapi.StatusSuccess}, nil
}
// getRelatedObjects returns the identity, user, and mapping for the named identity
// a nil mappingErr means all objects were retrieved without errors, and correctly reference each other
func (s *REST) getRelatedObjects(ctx kapi.Context, name string) (
identity *api.Identity, identityErr error,
user *api.User, userErr error,
mapping *api.UserIdentityMapping, mappingErr error,
) {
// Initialize errors to NotFound
identityErr = kerrs.NewNotFound("Identity", name)
userErr = kerrs.NewNotFound("User", "")
mappingErr = kerrs.NewNotFound("UserIdentityMapping", name)
// Get identity
identity, identityErr = s.identityRegistry.GetIdentity(ctx, name)
if identityErr != nil {
return
}
if !hasUserMapping(identity) {
return
}
// Get user
user, userErr = s.userRegistry.GetUser(ctx, identity.User.Name)
if userErr != nil {
return
}
// Ensure relational integrity
if !identityReferencesUser(identity, user) {
return
}
if !userReferencesIdentity(user, identity) {
return
}
mapping, mappingErr = mappingFor(user, identity)
return
}
// hasUserMapping returns true if the given identity references a user
func hasUserMapping(identity *api.Identity) bool {
return len(identity.User.Name) > 0
}
// identityReferencesUser returns true if the identity's user name and uid match the given user
func identityReferencesUser(identity *api.Identity, user *api.User) bool {
return identity.User.Name == user.Name && identity.User.UID == user.UID
}
// userReferencesIdentity returns true if the user's identity list contains the given identity
func userReferencesIdentity(user *api.User, identity *api.Identity) bool {
return sets.NewString(user.Identities...).Has(identity.Name)
}
// addIdentityToUser adds the given identity to the user's list of identities
// returns true if the user's identity list was modified
func addIdentityToUser(identity *api.Identity, user *api.User) bool {
identities := sets.NewString(user.Identities...)
if identities.Has(identity.Name) {
return false
}
identities.Insert(identity.Name)
user.Identities = identities.List()
return true
}
// removeIdentityFromUser removes the given identity from the user's list of identities
// returns true if the user's identity list was modified
func removeIdentityFromUser(identity *api.Identity, user *api.User) bool {
identities := sets.NewString(user.Identities...)
if !identities.Has(identity.Name) {
return false
}
identities.Delete(identity.Name)
user.Identities = identities.List()
return true
}
// setIdentityUser sets the identity to reference the given user
// returns true if the identity's user reference was modified
func setIdentityUser(identity *api.Identity, user *api.User) bool {
if identityReferencesUser(identity, user) {
return false
}
identity.User = kapi.ObjectReference{
Name: user.Name,
UID: user.UID,
}
return true
}
// unsetIdentityUser clears the identity's user reference
// returns true if the identity's user reference was modified
func unsetIdentityUser(identity *api.Identity) bool {
if !hasUserMapping(identity) {
return false
}
identity.User = kapi.ObjectReference{}
return true
}
// mappingFor returns a UserIdentityMapping for the given user and identity
// The name and resource version of the identity mapping match the identity
func mappingFor(user *api.User, identity *api.Identity) (*api.UserIdentityMapping, error) {
return &api.UserIdentityMapping{
ObjectMeta: kapi.ObjectMeta{
Name: identity.Name,
ResourceVersion: identity.ResourceVersion,
UID: identity.UID,
},
Identity: kapi.ObjectReference{
Name: identity.Name,
UID: identity.UID,
},
User: kapi.ObjectReference{
Name: user.Name,
UID: user.UID,
},
}, nil
}
| vongalpha/origin | pkg/user/registry/useridentitymapping/rest.go | GO | apache-2.0 | 10,722 |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System.Management.Automation;
using Microsoft.Azure.Commands.TrafficManager.Models;
using Microsoft.Azure.Commands.TrafficManager.Utilities;
using ProjectResources = Microsoft.Azure.Commands.TrafficManager.Properties.Resources;
namespace Microsoft.Azure.Commands.TrafficManager
{
[Cmdlet(VerbsCommon.Remove, "AzureRmTrafficManagerEndpointConfig"), OutputType(typeof(TrafficManagerProfile))]
public class RemoveAzureTrafficManagerEndpointConfig : TrafficManagerBaseCmdlet
{
[Parameter(Mandatory = true, HelpMessage = "The name of the endpoint.")]
[ValidateNotNullOrEmpty]
public string EndpointName { get; set; }
[Parameter(Mandatory = true, ValueFromPipeline = true, HelpMessage = "The profile.")]
[ValidateNotNullOrEmpty]
public TrafficManagerProfile TrafficManagerProfile { get; set; }
public override void ExecuteCmdlet()
{
if (this.TrafficManagerProfile.Endpoints == null)
{
throw new PSArgumentException(string.Format(ProjectResources.Error_EndpointNotFound, this.EndpointName));
}
int endpointsRemoved = this.TrafficManagerProfile.Endpoints.RemoveAll(endpoint => string.Equals(this.EndpointName, endpoint.Name));
if (endpointsRemoved == 0)
{
throw new PSArgumentException(string.Format(ProjectResources.Error_EndpointNotFound, this.EndpointName));
}
this.WriteVerbose(ProjectResources.Success);
this.WriteObject(this.TrafficManagerProfile);
}
}
}
| dulems/azure-powershell | src/ResourceManager/TrafficManager/Commands.TrafficManager2/Endpoint/RemoveAzureTrafficManagerEndpointConfig.cs | C# | apache-2.0 | 2,353 |
cask 'hunt-x' do
version :latest
sha256 :no_check
url 'http://huntx.mobilefirst.in/Apps/Hunt%20X.zip'
name 'Hunt X'
homepage 'http://huntx.mobilefirst.in/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'Hunt X.app'
end
| jppelteret/homebrew-cask | Casks/hunt-x.rb | Ruby | bsd-2-clause | 307 |
// This file was procedurally generated from the following sources:
// - src/dstr-binding-for-await/obj-ptrn-prop-ary.case
// - src/dstr-binding-for-await/default/for-await-of-async-func-var.template
/*---
description: Object binding pattern with "nested" array binding pattern not using initializer (for-await-of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation
features: [destructuring-binding, async-iteration]
flags: [generated, async]
info: |
IterationStatement :
for await ( var ForBinding of AssignmentExpression ) Statement
[...]
2. Return ? ForIn/OfBodyEvaluation(ForBinding, Statement, keyResult,
varBinding, labelSet, async).
13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation
[...]
4. Let destructuring be IsDestructuring of lhs.
[...]
6. Repeat
[...]
j. If destructuring is false, then
[...]
k. Else
i. If lhsKind is assignment, then
[...]
ii. Else if lhsKind is varBinding, then
1. Assert: lhs is a ForBinding.
2. Let status be the result of performing BindingInitialization
for lhs passing nextValue and undefined as the arguments.
[...]
13.3.3.7 Runtime Semantics: KeyedBindingInitialization
[...]
3. If Initializer is present and v is undefined, then
[...]
4. Return the result of performing BindingInitialization for BindingPattern
passing v and environment as arguments.
---*/
var iterCount = 0;
async function fn() {
for await (var { w: [x, y, z] = [4, 5, 6] } of [{ w: [7, undefined, ] }]) {
assert.sameValue(x, 7);
assert.sameValue(y, undefined);
assert.sameValue(z, undefined);
assert.throws(ReferenceError, function() {
w;
});
iterCount += 1;
}
}
fn()
.then(() => assert.sameValue(iterCount, 1, 'iteration occurred as expected'), $DONE)
.then($DONE, $DONE);
| sebastienros/jint | Jint.Tests.Test262/test/language/statements/for-await-of/async-func-dstr-var-obj-ptrn-prop-ary.js | JavaScript | bsd-2-clause | 1,967 |
class Evernote < Cask
url 'https://www.evernote.com/about/download/get.php?file=EvernoteMac'
appcast 'http://update.evernote.com/public/ENMac/EvernoteMacUpdate.xml'
homepage 'https://evernote.com/'
version 'latest'
sha256 :no_check
link 'Evernote.app'
end
| tonyseek/homebrew-cask | Casks/evernote.rb | Ruby | bsd-2-clause | 268 |
/*
* Copyright 2010-2017 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bx#license-bsd-2-clause
*/
#include "test.h"
#include <bx/handlealloc.h>
#include <bx/hash.h>
TEST_CASE("HandleListT", "")
{
bx::HandleListT<32> list;
list.pushBack(16);
REQUIRE(list.getFront() == 16);
REQUIRE(list.getBack() == 16);
list.pushFront(7);
REQUIRE(list.getFront() == 7);
REQUIRE(list.getBack() == 16);
uint16_t expected0[] = { 15, 31, 7, 16, 17, 11, 13 };
list.pushBack(17);
list.pushBack(11);
list.pushBack(13);
list.pushFront(31);
list.pushFront(15);
uint16_t count = 0;
for (uint16_t it = list.getFront(); it != UINT16_MAX; it = list.getNext(it), ++count)
{
REQUIRE(it == expected0[count]);
}
REQUIRE(count == BX_COUNTOF(expected0) );
list.remove(17);
list.remove(31);
list.remove(16);
list.pushBack(16);
uint16_t expected1[] = { 15, 7, 11, 13, 16 };
count = 0;
for (uint16_t it = list.getFront(); it != UINT16_MAX; it = list.getNext(it), ++count)
{
REQUIRE(it == expected1[count]);
}
REQUIRE(count == BX_COUNTOF(expected1) );
list.popBack();
list.popFront();
list.popBack();
list.popBack();
REQUIRE(list.getFront() == 7);
REQUIRE(list.getBack() == 7);
list.popBack();
REQUIRE(list.getFront() == UINT16_MAX);
REQUIRE(list.getBack() == UINT16_MAX);
}
TEST_CASE("HandleAllocLruT", "")
{
bx::HandleAllocLruT<16> lru;
uint16_t handle[4] =
{
lru.alloc(),
lru.alloc(),
lru.alloc(),
lru.alloc(),
};
lru.touch(handle[1]);
uint16_t expected0[] = { handle[1], handle[3], handle[2], handle[0] };
uint16_t count = 0;
for (uint16_t it = lru.getFront(); it != UINT16_MAX; it = lru.getNext(it), ++count)
{
REQUIRE(it == expected0[count]);
}
}
TEST_CASE("HandleHashTable", "")
{
typedef bx::HandleHashMapT<512> HashMap;
HashMap hm;
REQUIRE(512 == hm.getMaxCapacity() );
bx::StringView sv0("test0");
bool ok = hm.insert(bx::hash<bx::HashMurmur2A>(sv0), 0);
REQUIRE(ok);
ok = hm.insert(bx::hash<bx::HashMurmur2A>(sv0), 0);
REQUIRE(!ok);
REQUIRE(1 == hm.getNumElements() );
bx::StringView sv1("test1");
ok = hm.insert(bx::hash<bx::HashMurmur2A>(sv1), 0);
REQUIRE(ok);
REQUIRE(2 == hm.getNumElements() );
hm.removeByHandle(0);
REQUIRE(0 == hm.getNumElements() );
ok = hm.insert(bx::hash<bx::HashMurmur2A>(sv0), 0);
REQUIRE(ok);
hm.removeByKey(bx::hash<bx::HashMurmur2A>(sv0) );
REQUIRE(0 == hm.getNumElements() );
for (uint32_t ii = 0, num = hm.getMaxCapacity(); ii < num; ++ii)
{
ok = hm.insert(ii, uint16_t(ii) );
REQUIRE(ok);
}
}
| mmicko/bx | tests/handle_test.cpp | C++ | bsd-2-clause | 2,557 |
class Libwebsockets < Formula
desc "C websockets server library"
homepage "https://libwebsockets.org"
url "https://github.com/warmcat/libwebsockets/archive/v3.1.0.tar.gz"
sha256 "db948be74c78fc13f1f1a55e76707d7baae3a1c8f62b625f639e8f2736298324"
head "https://github.com/warmcat/libwebsockets.git"
bottle do
sha256 "c3dee13c27c98c87853ec9d1cbd3db27473c3fee1b0870260dc6c47294dd95e4" => :mojave
sha256 "fce83552c866222ad1386145cdd9745b82efc0c0a97b89b9069b98928241e893" => :high_sierra
sha256 "a57218f16bde1f484648fd7893d99d3dafc5c0ade4902c7ce442019b9782dc66" => :sierra
end
depends_on "cmake" => :build
depends_on "libevent"
depends_on "libuv"
depends_on "openssl"
def install
system "cmake", ".", *std_cmake_args,
"-DLWS_IPV6=ON",
"-DLWS_WITH_HTTP2=ON",
"-DLWS_WITH_LIBEVENT=ON",
"-DLWS_WITH_LIBUV=ON",
"-DLWS_WITH_PLUGINS=ON",
"-DLWS_WITHOUT_TESTAPPS=ON",
"-DLWS_UNIX_SOCK=ON"
system "make"
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <openssl/ssl.h>
#include <libwebsockets.h>
int main()
{
struct lws_context_creation_info info;
memset(&info, 0, sizeof(info));
struct lws_context *context;
context = lws_create_context(&info);
lws_context_destroy(context);
return 0;
}
EOS
system ENV.cc, "test.c", "-I#{Formula["openssl"].opt_prefix}/include", "-L#{lib}", "-lwebsockets", "-o", "test"
system "./test"
end
end
| adamliter/homebrew-core | Formula/libwebsockets.rb | Ruby | bsd-2-clause | 1,637 |
#ifndef SM_PYTHON_ID_HPP
#define SM_PYTHON_ID_HPP
#include <numpy_eigen/boost_python_headers.hpp>
#include <boost/python/to_python_converter.hpp>
#include <Python.h>
#include <boost/cstdint.hpp>
namespace sm { namespace python {
// to use: sm::python::Id_python_converter<FrameId>::register_converter();
// adapted from http://misspent.wordpress.com/2009/09/27/how-to-write-boost-python-converters/
template<typename ID_T>
struct Id_python_converter
{
typedef ID_T id_t;
// The "Convert from C to Python" API
static PyObject * convert(id_t const & id){
PyObject * i = PyInt_FromLong(id.getId());
// It seems that the call to "incref(.)" caused a memory leak!
// I will check this in hoping it doesn't cause any instability.
return i;//boost::python::incref(i);
}
// The "Convert from Python to C" API
// Two functions: convertible() and construct()
static void * convertible(PyObject* obj_ptr)
{
if (!(PyInt_Check(obj_ptr) || PyLong_Check(obj_ptr)))
return 0;
return obj_ptr;
}
static void construct(
PyObject* obj_ptr,
boost::python::converter::rvalue_from_python_stage1_data* data)
{
// Get the value.
boost::uint64_t value;
if ( PyInt_Check(obj_ptr) ) {
value = PyInt_AsUnsignedLongLongMask(obj_ptr);
} else {
value = PyLong_AsUnsignedLongLong(obj_ptr);
}
void* storage = ((boost::python::converter::rvalue_from_python_storage<id_t>*)
data)->storage.bytes;
new (storage) id_t(value);
// Stash the memory chunk pointer for later use by boost.python
data->convertible = storage;
}
// The registration function.
static void register_converter()
{
// This code checks if the type has already been registered.
// http://stackoverflow.com/questions/9888289/checking-whether-a-converter-has-already-been-registered
boost::python::type_info info = boost::python::type_id<id_t>();
const boost::python::converter::registration* reg = boost::python::converter::registry::query(info);
if (reg == NULL || reg->m_to_python == NULL) {
// This is the code to register the type.
boost::python::to_python_converter<id_t,Id_python_converter>();
boost::python::converter::registry::push_back(
&convertible,
&construct,
boost::python::type_id<id_t>());
}
}
};
}}
#endif /* SM_PYTHON_ID_HPP */
| ethz-asl/Schweizer-Messer | sm_python/include/sm/python/Id.hpp | C++ | bsd-3-clause | 2,754 |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/message_center/views/message_popup_collection.h"
#include "base/containers/cxx20_erase.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "ui/display/display.h"
#include "ui/events/base_event_utils.h"
#include "ui/gfx/animation/linear_animation.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/public/cpp/message_center_constants.h"
#include "ui/message_center/views/desktop_message_popup_collection.h"
#include "ui/message_center/views/message_popup_view.h"
#include "ui/views/test/views_test_base.h"
using message_center::MessageCenter;
using message_center::Notification;
namespace message_center {
namespace {
class MockMessagePopupView;
class MockMessagePopupCollection : public DesktopMessagePopupCollection {
public:
explicit MockMessagePopupCollection(gfx::NativeWindow context)
: DesktopMessagePopupCollection(), context_(context) {}
MockMessagePopupCollection(const MockMessagePopupCollection&) = delete;
MockMessagePopupCollection& operator=(const MockMessagePopupCollection&) =
delete;
~MockMessagePopupCollection() override = default;
void SetAnimationValue(double current) {
animation()->SetCurrentValue(current);
if (current == 1.0)
animation()->End();
else
AnimationProgressed(animation());
}
void RemovePopup(MockMessagePopupView* popup) {
base::Erase(popups_, popup);
}
bool IsAnimating() { return animation()->is_animating(); }
void set_is_primary_display(bool is_primary_display) {
is_primary_display_ = is_primary_display;
}
void set_is_fullscreen(bool is_fullscreen) { is_fullscreen_ = is_fullscreen; }
void set_new_popup_height(int new_popup_height) {
new_popup_height_ = new_popup_height;
}
std::vector<MockMessagePopupView*>& popups() { return popups_; }
bool popup_timer_started() const { return popup_timer_started_; }
protected:
MessagePopupView* CreatePopup(const Notification& notification) override;
void ConfigureWidgetInitParamsForContainer(
views::Widget* widget,
views::Widget::InitParams* init_params) override {
// Provides an aura window context for widget creation.
init_params->context = context_;
}
void RestartPopupTimers() override {
MessagePopupCollection::RestartPopupTimers();
popup_timer_started_ = true;
}
void PausePopupTimers() override {
MessagePopupCollection::PausePopupTimers();
popup_timer_started_ = false;
}
bool IsPrimaryDisplayForNotification() const override {
return is_primary_display_;
}
bool BlockForMixedFullscreen(
const Notification& notification) const override {
return is_fullscreen_;
}
private:
gfx::NativeWindow context_;
std::vector<MockMessagePopupView*> popups_;
bool popup_timer_started_ = false;
bool is_primary_display_ = true;
bool is_fullscreen_ = false;
int new_popup_height_ = 84;
};
class MockMessagePopupView : public MessagePopupView {
public:
MockMessagePopupView(const std::string& id,
int init_height,
MockMessagePopupCollection* popup_collection)
: MessagePopupView(popup_collection),
popup_collection_(popup_collection),
id_(id),
title_(base::UTF16ToUTF8(
MessageCenter::Get()->FindVisibleNotificationById(id)->title())) {
auto* view = new views::View;
view->SetPreferredSize(gfx::Size(kNotificationWidth, init_height));
AddChildView(view);
}
~MockMessagePopupView() override = default;
void Close() override {
popup_collection_->RemovePopup(this);
MessagePopupView::Close();
}
void UpdateContents(const Notification& notification) override {
if (height_after_update_.has_value())
SetPreferredHeight(height_after_update_.value());
popup_collection_->NotifyPopupResized();
updated_ = true;
title_ = base::UTF16ToUTF8(notification.title());
}
void AutoCollapse() override {
if (expandable_)
children().front()->SetPreferredSize(gfx::Size(kNotificationWidth, 42));
}
void SetPreferredHeight(int height) {
children().front()->SetPreferredSize(gfx::Size(kNotificationWidth, height));
}
void SetHovered(bool is_hovered) {
if (is_hovered) {
ui::MouseEvent enter_event(ui::ET_MOUSE_ENTERED, gfx::Point(),
gfx::Point(), ui::EventTimeForNow(), 0, 0);
OnMouseEntered(enter_event);
} else {
ui::MouseEvent exit_event(ui::ET_MOUSE_EXITED, gfx::Point(), gfx::Point(),
ui::EventTimeForNow(), 0, 0);
OnMouseExited(exit_event);
}
}
void SimulateFocused() { OnDidChangeFocus(nullptr, children().front()); }
void Activate() {
SetCanActivate(true);
GetWidget()->Activate();
}
const std::string& id() const { return id_; }
bool updated() const { return updated_; }
const std::string& title() const { return title_; }
void set_expandable(bool expandable) { expandable_ = expandable; }
void set_height_after_update(absl::optional<int> height_after_update) {
height_after_update_ = height_after_update;
}
private:
const raw_ptr<MockMessagePopupCollection> popup_collection_;
std::string id_;
bool updated_ = false;
bool expandable_ = false;
std::string title_;
absl::optional<int> height_after_update_;
};
MessagePopupView* MockMessagePopupCollection::CreatePopup(
const Notification& notification) {
auto* popup =
new MockMessagePopupView(notification.id(), new_popup_height_, this);
popups_.push_back(popup);
return popup;
}
} // namespace
class MessagePopupCollectionTest : public views::ViewsTestBase,
public MessageCenterObserver {
public:
MessagePopupCollectionTest() = default;
MessagePopupCollectionTest(const MessagePopupCollectionTest&) = delete;
MessagePopupCollectionTest& operator=(const MessagePopupCollectionTest&) =
delete;
~MessagePopupCollectionTest() override = default;
// views::ViewTestBase:
void SetUp() override {
views::ViewsTestBase::SetUp();
MessageCenter::Initialize();
MessageCenter::Get()->DisableTimersForTest();
MessageCenter::Get()->AddObserver(this);
popup_collection_ =
std::make_unique<MockMessagePopupCollection>(GetContext());
// This size fits test machines resolution and also can keep a few popups
// w/o ill effects of hitting the screen overflow. This allows us to assume
// and verify normal layout of the toast stack.
SetDisplayInfo(gfx::Rect(0, 0, 1920, 1070), // taskbar at the bottom.
gfx::Rect(0, 0, 1920, 1080));
}
void TearDown() override {
MessageCenter::Get()->RemoveAllNotifications(
false /* by_user */, MessageCenter::RemoveType::ALL);
AnimateUntilIdle();
popup_collection_.reset();
MessageCenter::Get()->RemoveObserver(this);
MessageCenter::Shutdown();
views::ViewsTestBase::TearDown();
}
// MessageCenterObserver:
void OnNotificationDisplayed(const std::string& notification_id,
const DisplaySource source) override {
last_displayed_id_ = notification_id;
}
protected:
std::unique_ptr<Notification> CreateNotification(const std::string& id) {
return CreateNotification(id, "test title");
}
std::unique_ptr<Notification> CreateNotification(const std::string& id,
const std::string& title) {
return std::make_unique<Notification>(
NOTIFICATION_TYPE_BASE_FORMAT, id, base::UTF8ToUTF16(title),
u"test message", gfx::Image(), std::u16string() /* display_source */,
GURL(), NotifierId(), RichNotificationData(),
new NotificationDelegate());
}
std::string AddNotification() {
std::string id = base::NumberToString(id_++);
MessageCenter::Get()->AddNotification(CreateNotification(id));
return id;
}
void Update() { popup_collection_->Update(); }
void SetAnimationValue(double current) {
popup_collection_->SetAnimationValue(current);
}
bool IsAnimating() const { return popup_collection_->IsAnimating(); }
void AnimateUntilIdle() {
while (popup_collection_->IsAnimating()) {
popup_collection_->SetAnimationValue(1.0);
}
}
void AnimateToMiddle() {
EXPECT_TRUE(popup_collection_->IsAnimating());
popup_collection_->SetAnimationValue(0.5);
}
void AnimateToEnd() {
EXPECT_TRUE(popup_collection_->IsAnimating());
popup_collection_->SetAnimationValue(1.0);
}
MockMessagePopupView* GetPopup(const std::string& id) {
for (auto* popup : popup_collection_->popups()) {
if (popup->id() == id)
return popup;
}
return nullptr;
}
MockMessagePopupView* GetPopupAt(size_t index) {
return popup_collection_->popups()[index];
}
size_t GetPopupCounts() const { return popup_collection_->popups().size(); }
void SetDisplayInfo(const gfx::Rect& work_area,
const gfx::Rect& display_bounds) {
display::Display dummy_display;
dummy_display.set_bounds(display_bounds);
dummy_display.set_work_area(work_area);
work_area_ = work_area;
popup_collection_->RecomputeAlignment(dummy_display);
}
bool IsPopupTimerStarted() const {
return popup_collection_->popup_timer_started();
}
MockMessagePopupCollection* popup_collection() const {
return popup_collection_.get();
}
const gfx::Rect& work_area() const { return work_area_; }
const std::string& last_displayed_id() const { return last_displayed_id_; }
private:
int id_ = 0;
std::unique_ptr<MockMessagePopupCollection> popup_collection_;
gfx::Rect work_area_;
std::string last_displayed_id_;
};
TEST_F(MessagePopupCollectionTest, Nothing) {
EXPECT_FALSE(IsAnimating());
Update();
// If no popups are available, nothing changes.
EXPECT_FALSE(IsAnimating());
}
TEST_F(MessagePopupCollectionTest, FadeInFadeOutNotification) {
// Add a notification.
std::string id = AddNotification();
EXPECT_TRUE(IsAnimating());
EXPECT_EQ(1u, GetPopupCounts());
// The popup will fade in from right.
const int before_x = GetPopup(id)->GetBoundsInScreen().x();
EXPECT_EQ(0.0f, GetPopup(id)->GetOpacity());
AnimateToMiddle();
EXPECT_GT(before_x, GetPopup(id)->GetBoundsInScreen().x());
EXPECT_LT(0.0f, GetPopup(id)->GetOpacity());
AnimateToEnd();
EXPECT_EQ(1.0f, GetPopup(id)->GetOpacity());
EXPECT_FALSE(IsAnimating());
EXPECT_TRUE(work_area().Contains(GetPopup(id)->GetBoundsInScreen()));
EXPECT_EQ(id, last_displayed_id());
// The popup will fade out because of timeout.
MessageCenter::Get()->MarkSinglePopupAsShown(id, false);
EXPECT_TRUE(IsAnimating());
AnimateToMiddle();
EXPECT_GT(1.0f, GetPopup(id)->GetOpacity());
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_FALSE(GetPopup(id));
}
TEST_F(MessagePopupCollectionTest, FadeInMultipleNotifications) {
std::vector<std::string> ids;
for (size_t i = 0; i < kMaxVisiblePopupNotifications; ++i)
ids.push_back(AddNotification());
for (size_t i = 0; i < ids.size(); ++i) {
EXPECT_EQ(ids[i], last_displayed_id());
EXPECT_EQ(i + 1, GetPopupCounts());
AnimateToMiddle();
EXPECT_LT(0.0f, GetPopupAt(i)->GetOpacity());
AnimateToEnd();
EXPECT_EQ(1.0f, GetPopupAt(i)->GetOpacity());
EXPECT_TRUE(work_area().Contains(GetPopupAt(i)->GetBoundsInScreen()));
}
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
for (size_t i = 0; i < ids.size(); ++i)
EXPECT_EQ(ids[i], GetPopupAt(i)->id());
for (size_t i = 0; i < ids.size() - 1; ++i) {
EXPECT_GT(GetPopupAt(i)->GetBoundsInScreen().x(),
GetPopupAt(i + 1)->GetBoundsInScreen().bottom());
}
}
TEST_F(MessagePopupCollectionTest, FadeInMultipleNotificationsInverse) {
popup_collection()->set_inverse();
std::vector<std::string> ids;
for (size_t i = 0; i < kMaxVisiblePopupNotifications; ++i)
ids.push_back(AddNotification());
for (size_t i = 0; i < ids.size(); ++i) {
EXPECT_EQ(ids[i], last_displayed_id());
EXPECT_EQ(i + 1, GetPopupCounts());
const int before_x = GetPopupAt(i)->GetBoundsInScreen().x();
AnimateToMiddle();
EXPECT_LT(0.0f, GetPopupAt(i)->GetOpacity());
EXPECT_GT(before_x, GetPopupAt(i)->GetBoundsInScreen().x());
AnimateToEnd();
EXPECT_EQ(1.0f, GetPopupAt(i)->GetOpacity());
EXPECT_TRUE(work_area().Contains(GetPopupAt(i)->GetBoundsInScreen()));
if (i + 1 < ids.size()) {
const int before_y = GetPopupAt(i)->GetBoundsInScreen().y();
AnimateToMiddle();
EXPECT_GT(before_y, GetPopupAt(i)->GetBoundsInScreen().y());
AnimateToEnd();
}
}
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
for (size_t i = 0; i < ids.size(); ++i)
EXPECT_EQ(ids[i], GetPopupAt(i)->id());
for (size_t i = 0; i < ids.size() - 1; ++i) {
EXPECT_GT(GetPopupAt(i + 1)->GetBoundsInScreen().x(),
GetPopupAt(i)->GetBoundsInScreen().bottom());
}
}
TEST_F(MessagePopupCollectionTest, UpdateContents) {
std::string id = AddNotification();
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_FALSE(GetPopup(id)->updated());
auto updated_notification = CreateNotification(id);
updated_notification->set_message(u"updated");
MessageCenter::Get()->UpdateNotification(id, std::move(updated_notification));
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id)->updated());
}
TEST_F(MessagePopupCollectionTest, UpdateContentsCausesPopupClose) {
std::string id = AddNotification();
AnimateToEnd();
RunPendingMessages();
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_FALSE(GetPopup(id)->updated());
GetPopup(id)->set_height_after_update(2048);
auto updated_notification = CreateNotification(id);
updated_notification->set_message(u"updated");
MessageCenter::Get()->UpdateNotification(id, std::move(updated_notification));
RunPendingMessages();
EXPECT_EQ(0u, GetPopupCounts());
}
TEST_F(MessagePopupCollectionTest, MessageCenterVisibility) {
// It only applies to a platform with MessageCenterView i.e. Chrome OS.
MessageCenter::Get()->SetHasMessageCenterView(true);
for (size_t i = 0; i < kMaxVisiblePopupNotifications; ++i)
AddNotification();
AnimateUntilIdle();
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
EXPECT_EQ(3u, GetPopupCounts());
EXPECT_EQ(3u, MessageCenter::Get()->GetPopupNotifications().size());
// The notification should be hidden when MessageCenterView is visible.
MessageCenter::Get()->SetVisibility(Visibility::VISIBILITY_MESSAGE_CENTER);
// It should not animate in order to show ARC++ notifications properly.
EXPECT_FALSE(IsAnimating());
MessageCenter::Get()->SetVisibility(Visibility::VISIBILITY_TRANSIENT);
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(0u, GetPopupCounts());
EXPECT_EQ(0u, MessageCenter::Get()->GetPopupNotifications().size());
}
TEST_F(MessagePopupCollectionTest, ShowCustomOnPrimaryDisplay) {
// TODO(yoshiki): Support custom popup notification on multiple display
// (crbug.com/715370).
popup_collection()->set_is_primary_display(true);
auto custom = CreateNotification("id");
custom->set_type(NOTIFICATION_TYPE_CUSTOM);
MessageCenter::Get()->AddNotification(std::move(custom));
EXPECT_TRUE(IsAnimating());
EXPECT_EQ(1u, GetPopupCounts());
}
TEST_F(MessagePopupCollectionTest, NotShowCustomOnSubDisplay) {
// Disables popup of custom notification on non-primary displays, since
// currently custom notification supports only on one display at the same
// time.
// TODO(yoshiki): Support custom popup notification on multiple display
// (crbug.com/715370).
popup_collection()->set_is_primary_display(false);
auto custom = CreateNotification("id");
custom->set_type(NOTIFICATION_TYPE_CUSTOM);
MessageCenter::Get()->AddNotification(std::move(custom));
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(0u, GetPopupCounts());
}
TEST_F(MessagePopupCollectionTest, MixedFullscreenShow) {
popup_collection()->set_is_fullscreen(false);
AddNotification();
EXPECT_TRUE(IsAnimating());
EXPECT_EQ(1u, GetPopupCounts());
}
TEST_F(MessagePopupCollectionTest, MixedFullscreenBlock) {
popup_collection()->set_is_fullscreen(true);
AddNotification();
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(0u, GetPopupCounts());
}
TEST_F(MessagePopupCollectionTest, NotificationsMoveDown) {
std::vector<std::string> ids;
for (size_t i = 0; i < kMaxVisiblePopupNotifications + 1; ++i)
ids.push_back(AddNotification());
AnimateUntilIdle();
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
EXPECT_FALSE(IsAnimating());
gfx::Rect dismissed = GetPopup(ids.front())->GetBoundsInScreen();
MessageCenter::Get()->MarkSinglePopupAsShown(ids.front(), false);
EXPECT_TRUE(IsAnimating());
AnimateToMiddle();
EXPECT_GT(1.0f, GetPopup(ids[0])->GetOpacity());
EXPECT_EQ(ids[0], GetPopup(ids[0])->id());
AnimateToEnd();
EXPECT_EQ(ids[1], GetPopup(ids[1])->id());
EXPECT_TRUE(IsAnimating());
gfx::Rect before = GetPopup(ids[1])->GetBoundsInScreen();
AnimateToMiddle();
gfx::Rect moving = GetPopup(ids[1])->GetBoundsInScreen();
EXPECT_GT(moving.bottom(), before.bottom());
EXPECT_GT(dismissed.bottom(), moving.bottom());
AnimateToEnd();
gfx::Rect after = GetPopup(ids[1])->GetBoundsInScreen();
EXPECT_EQ(dismissed, after);
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
EXPECT_TRUE(IsAnimating());
EXPECT_EQ(0.f, GetPopup(ids.back())->GetOpacity());
AnimateToMiddle();
EXPECT_LT(0.0f, GetPopup(ids.back())->GetOpacity());
AnimateToEnd();
EXPECT_EQ(1.0f, GetPopup(ids.back())->GetOpacity());
EXPECT_FALSE(IsAnimating());
}
TEST_F(MessagePopupCollectionTest, NotificationsMoveDownInverse) {
popup_collection()->set_inverse();
std::vector<std::string> ids;
for (size_t i = 0; i < kMaxVisiblePopupNotifications; ++i)
ids.push_back(AddNotification());
std::string dismissed_id = ids[kMaxVisiblePopupNotifications - 1];
std::string new_bottom_id = ids[kMaxVisiblePopupNotifications - 2];
AnimateUntilIdle();
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
EXPECT_FALSE(IsAnimating());
gfx::Rect dismissed = GetPopup(dismissed_id)->GetBoundsInScreen();
MessageCenter::Get()->MarkSinglePopupAsShown(dismissed_id, false);
EXPECT_TRUE(IsAnimating());
AnimateToMiddle();
EXPECT_GT(1.0f, GetPopup(dismissed_id)->GetOpacity());
EXPECT_EQ(dismissed_id, GetPopup(dismissed_id)->id());
AnimateToEnd();
EXPECT_EQ(ids[1], GetPopup(new_bottom_id)->id());
EXPECT_TRUE(IsAnimating());
gfx::Rect before = GetPopup(new_bottom_id)->GetBoundsInScreen();
AnimateToMiddle();
gfx::Rect moving = GetPopup(new_bottom_id)->GetBoundsInScreen();
EXPECT_GT(moving.bottom(), before.bottom());
EXPECT_GT(dismissed.bottom(), moving.bottom());
AnimateToEnd();
gfx::Rect after = GetPopup(new_bottom_id)->GetBoundsInScreen();
EXPECT_EQ(dismissed, after);
EXPECT_EQ(kMaxVisiblePopupNotifications - 1, GetPopupCounts());
EXPECT_FALSE(IsAnimating());
}
TEST_F(MessagePopupCollectionTest, NotificationsMoveUpForInverse) {
popup_collection()->set_inverse();
std::vector<std::string> ids;
for (size_t i = 0; i < kMaxVisiblePopupNotifications + 1; ++i)
ids.push_back(AddNotification());
AnimateUntilIdle();
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
EXPECT_FALSE(IsAnimating());
gfx::Rect dismissed = GetPopup(ids.front())->GetBoundsInScreen();
MessageCenter::Get()->MarkSinglePopupAsShown(ids.front(), false);
EXPECT_TRUE(IsAnimating());
// FADE_OUT
AnimateToMiddle();
EXPECT_GT(1.0f, GetPopup(ids[0])->GetOpacity());
EXPECT_EQ(ids[0], GetPopup(ids[0])->id());
AnimateToEnd();
EXPECT_EQ(ids[1], GetPopup(ids[1])->id());
EXPECT_TRUE(IsAnimating());
gfx::Rect before = GetPopup(ids[1])->GetBoundsInScreen();
// MOVE_UP_FOR_INVERSE
AnimateToMiddle();
gfx::Rect moving = GetPopup(ids[1])->GetBoundsInScreen();
EXPECT_LT(moving.bottom(), before.bottom());
EXPECT_LT(dismissed.bottom(), moving.bottom());
AnimateToEnd();
gfx::Rect after = GetPopup(ids[1])->GetBoundsInScreen();
EXPECT_EQ(dismissed, after);
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
EXPECT_TRUE(IsAnimating());
EXPECT_EQ(0.f, GetPopup(ids.back())->GetOpacity());
// FADE_IN
AnimateToMiddle();
EXPECT_LT(0.0f, GetPopup(ids.back())->GetOpacity());
AnimateToEnd();
EXPECT_EQ(1.0f, GetPopup(ids.back())->GetOpacity());
EXPECT_FALSE(IsAnimating());
}
TEST_F(MessagePopupCollectionTest, PopupResized) {
std::vector<std::string> ids;
for (size_t i = 0; i < kMaxVisiblePopupNotifications; ++i)
ids.push_back(AddNotification());
AnimateUntilIdle();
std::vector<gfx::Rect> previous_bounds;
for (const auto& id : ids)
previous_bounds.push_back(GetPopup(id)->GetBoundsInScreen());
const int changed_height = 256;
GetPopup(ids[1])->SetPreferredHeight(changed_height);
EXPECT_TRUE(IsAnimating());
AnimateToMiddle();
EXPECT_EQ(previous_bounds[0], GetPopup(ids[0])->GetBoundsInScreen());
EXPECT_EQ(previous_bounds[1].bottom(),
GetPopup(ids[1])->GetBoundsInScreen().bottom());
EXPECT_GT(previous_bounds[1].y(), GetPopup(ids[1])->GetBoundsInScreen().y());
EXPECT_GT(previous_bounds[2].bottom(),
GetPopup(ids[2])->GetBoundsInScreen().bottom());
EXPECT_GT(previous_bounds[2].y(), GetPopup(ids[2])->GetBoundsInScreen().y());
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(previous_bounds[0], GetPopup(ids[0])->GetBoundsInScreen());
EXPECT_EQ(changed_height, GetPopup(ids[1])->GetBoundsInScreen().height());
}
TEST_F(MessagePopupCollectionTest, ExpandLatest) {
std::string id = AddNotification();
AnimateToEnd();
GetPopup(id)->set_expandable(true);
const int top_y = GetPopup(id)->GetBoundsInScreen().y();
AddNotification();
EXPECT_TRUE(IsAnimating());
EXPECT_EQ(1u, GetPopupCounts());
AnimateToMiddle();
EXPECT_LT(top_y, GetPopup(id)->GetBoundsInScreen().y());
AnimateToEnd();
EXPECT_LT(top_y, GetPopup(id)->GetBoundsInScreen().y());
EXPECT_TRUE(IsAnimating());
EXPECT_EQ(2u, GetPopupCounts());
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
}
TEST_F(MessagePopupCollectionTest, ExpandLatestWithMoveDown) {
std::vector<std::string> ids;
for (size_t i = 0; i < kMaxVisiblePopupNotifications + 1; ++i)
ids.push_back(AddNotification());
AnimateUntilIdle();
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
GetPopup(ids[1])->set_expandable(true);
const int top_y = GetPopup(ids[1])->GetBoundsInScreen().y();
MessageCenter::Get()->MarkSinglePopupAsShown(ids.front(), false);
AnimateToEnd();
EXPECT_TRUE(IsAnimating());
EXPECT_EQ(kMaxVisiblePopupNotifications - 1, GetPopupCounts());
AnimateToMiddle();
EXPECT_LT(top_y, GetPopup(ids[2])->GetBoundsInScreen().y());
AnimateToEnd();
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
EXPECT_TRUE(IsAnimating());
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
}
TEST_F(MessagePopupCollectionTest, HoverClose) {
std::string id0 = AddNotification();
AnimateToEnd();
popup_collection()->set_new_popup_height(256);
std::string id1 = AddNotification();
AnimateToEnd();
popup_collection()->set_new_popup_height(84);
std::string id2 = AddNotification();
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_TRUE(IsPopupTimerStarted());
GetPopup(id0)->SetHovered(true);
EXPECT_FALSE(IsPopupTimerStarted());
const int first_popup_top = GetPopup(id0)->GetBoundsInScreen().y();
MessageCenter::Get()->RemoveNotification(id0, true);
EXPECT_TRUE(IsAnimating());
AnimateToEnd();
EXPECT_TRUE(IsAnimating());
AnimateToMiddle();
GetPopup(id1)->SetHovered(true);
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(first_popup_top, GetPopup(id1)->GetBoundsInScreen().y());
EXPECT_FALSE(IsPopupTimerStarted());
GetPopup(id1)->SetHovered(false);
EXPECT_TRUE(IsAnimating());
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_TRUE(IsPopupTimerStarted());
EXPECT_GT(first_popup_top, GetPopup(id1)->GetBoundsInScreen().y());
}
// Popup timers should be paused if a notification has focus.
// Once the focus is lost or the notification is resumed, popup timers
// should restart.
TEST_F(MessagePopupCollectionTest, FocusedClose) {
std::string id0 = AddNotification();
AnimateToEnd();
popup_collection()->set_new_popup_height(256);
std::string id1 = AddNotification();
AnimateToEnd();
popup_collection()->set_new_popup_height(84);
std::string id2 = AddNotification();
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_TRUE(IsPopupTimerStarted());
GetPopup(id0)->Activate();
// Activating a popup should not pause timers.
EXPECT_TRUE(IsPopupTimerStarted());
// If the popup gets keyboard focus the timers should pause.
GetPopup(id0)->SimulateFocused();
EXPECT_FALSE(IsPopupTimerStarted());
const int first_popup_top = GetPopup(id0)->GetBoundsInScreen().y();
MessageCenter::Get()->RemoveNotification(id0, true);
AnimateToEnd();
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_GT(first_popup_top, GetPopup(id1)->GetBoundsInScreen().y());
EXPECT_TRUE(IsPopupTimerStarted());
}
TEST_F(MessagePopupCollectionTest, SlideOutClose) {
std::vector<std::string> ids;
for (size_t i = 0; i < kMaxVisiblePopupNotifications; ++i)
ids.push_back(AddNotification());
AnimateUntilIdle();
GetPopup(ids[1])->SetOpacity(0);
MessageCenter::Get()->RemoveNotification(ids[1], true);
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_TRUE(IsPopupTimerStarted());
}
TEST_F(MessagePopupCollectionTest, TooTallNotification) {
SetDisplayInfo(gfx::Rect(0, 0, 800, 470), // taskbar at the bottom.
gfx::Rect(0, 0, 800, 480));
std::string id0 = AddNotification();
std::string id1 = AddNotification();
AnimateUntilIdle();
EXPECT_EQ(2u, GetPopupCounts());
popup_collection()->set_new_popup_height(400);
std::string id2 = AddNotification();
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(2u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id0));
EXPECT_TRUE(GetPopup(id1));
EXPECT_FALSE(GetPopup(id2));
MessageCenter::Get()->MarkSinglePopupAsShown(id0, false);
AnimateUntilIdle();
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_FALSE(GetPopup(id2));
MessageCenter::Get()->MarkSinglePopupAsShown(id1, false);
AnimateUntilIdle();
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id2));
}
TEST_F(MessagePopupCollectionTest, TooTallNotificationInverse) {
popup_collection()->set_inverse();
SetDisplayInfo(gfx::Rect(0, 0, 800, 470), // taskbar at the bottom.
gfx::Rect(0, 0, 800, 480));
// 2 popus shall fit. 3 popups shall not.
popup_collection()->set_new_popup_height(200);
std::string id0 = AddNotification();
std::string id1 = AddNotification();
AnimateUntilIdle();
EXPECT_EQ(2u, GetPopupCounts());
std::string id2 = AddNotification();
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(2u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id0));
EXPECT_TRUE(GetPopup(id1));
EXPECT_FALSE(GetPopup(id2));
MessageCenter::Get()->MarkSinglePopupAsShown(id0, false);
AnimateUntilIdle();
EXPECT_EQ(2u, GetPopupCounts());
EXPECT_FALSE(GetPopup(id0));
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(GetPopup(id2));
}
TEST_F(MessagePopupCollectionTest, DisplaySizeChanged) {
std::string id0 = AddNotification();
AnimateToEnd();
std::string id1 = AddNotification();
AnimateToEnd();
popup_collection()->set_new_popup_height(400);
std::string id2 = AddNotification();
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_TRUE(GetPopup(id0));
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(GetPopup(id2));
SetDisplayInfo(gfx::Rect(0, 0, 800, 470), // taskbar at the bottom.
gfx::Rect(0, 0, 800, 480));
popup_collection()->ResetBounds();
EXPECT_TRUE(GetPopup(id0));
EXPECT_TRUE(work_area().Contains(GetPopup(id0)->GetBoundsInScreen()));
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(work_area().Contains(GetPopup(id1)->GetBoundsInScreen()));
EXPECT_FALSE(GetPopup(id2));
MessageCenter::Get()->MarkSinglePopupAsShown(id0, false);
MessageCenter::Get()->MarkSinglePopupAsShown(id1, false);
AnimateUntilIdle();
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id2));
}
TEST_F(MessagePopupCollectionTest, PopupResizedAndOverflown) {
SetDisplayInfo(gfx::Rect(0, 0, 800, 470), // taskbar at the bottom.
gfx::Rect(0, 0, 800, 480));
std::string id0 = AddNotification();
std::string id1 = AddNotification();
std::string id2 = AddNotification();
AnimateUntilIdle();
EXPECT_TRUE(GetPopup(id0));
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(GetPopup(id2));
const int changed_height = 300;
GetPopup(id1)->SetPreferredHeight(changed_height);
AnimateUntilIdle();
RunPendingMessages();
EXPECT_TRUE(GetPopup(id0));
EXPECT_TRUE(work_area().Contains(GetPopup(id0)->GetBoundsInScreen()));
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(work_area().Contains(GetPopup(id1)->GetBoundsInScreen()));
EXPECT_FALSE(GetPopup(id2));
MessageCenter::Get()->MarkSinglePopupAsShown(id0, false);
AnimateUntilIdle();
EXPECT_EQ(2u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id2));
}
TEST_F(MessagePopupCollectionTest, DismissOnClick) {
MessageCenter::Get()->SetHasMessageCenterView(true);
std::string id1 = AddNotification();
std::string id2 = AddNotification();
AnimateUntilIdle();
EXPECT_EQ(2u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(GetPopup(id2));
MessageCenter::Get()->ClickOnNotification(id2);
AnimateUntilIdle();
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id1));
EXPECT_FALSE(GetPopup(id2));
MessageCenter::Get()->ClickOnNotificationButton(id1, 0);
AnimateUntilIdle();
EXPECT_EQ(0u, GetPopupCounts());
EXPECT_FALSE(GetPopup(id1));
EXPECT_FALSE(GetPopup(id2));
}
TEST_F(MessagePopupCollectionTest, NotDismissedOnClick) {
MessageCenter::Get()->SetHasMessageCenterView(false);
std::string id1 = AddNotification();
std::string id2 = AddNotification();
AnimateUntilIdle();
EXPECT_EQ(2u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(GetPopup(id2));
MessageCenter::Get()->ClickOnNotification(id2);
AnimateUntilIdle();
EXPECT_EQ(2u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(GetPopup(id2));
MessageCenter::Get()->ClickOnNotificationButton(id1, 0);
AnimateUntilIdle();
EXPECT_EQ(2u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(GetPopup(id2));
}
TEST_F(MessagePopupCollectionTest, DefaultPositioning) {
std::string id0 = AddNotification();
std::string id1 = AddNotification();
std::string id2 = AddNotification();
std::string id3 = AddNotification();
AnimateUntilIdle();
gfx::Rect r0 = GetPopup(id0)->GetBoundsInScreen();
gfx::Rect r1 = GetPopup(id1)->GetBoundsInScreen();
gfx::Rect r2 = GetPopup(id2)->GetBoundsInScreen();
// The 4th toast is not shown yet.
EXPECT_FALSE(GetPopup(id3));
// 3 toasts are shown, equal size, vertical stack.
EXPECT_EQ(r0.width(), r1.width());
EXPECT_EQ(r1.width(), r2.width());
EXPECT_EQ(r0.height(), r1.height());
EXPECT_EQ(r1.height(), r2.height());
EXPECT_GT(r0.y(), r1.y());
EXPECT_GT(r1.y(), r2.y());
EXPECT_EQ(r0.x(), r1.x());
EXPECT_EQ(r1.x(), r2.x());
}
TEST_F(MessagePopupCollectionTest, DefaultPositioningInverse) {
popup_collection()->set_inverse();
std::string id0 = AddNotification();
std::string id1 = AddNotification();
std::string id2 = AddNotification();
std::string id3 = AddNotification();
AnimateUntilIdle();
// This part is inverted.
gfx::Rect r0 = GetPopup(id2)->GetBoundsInScreen();
gfx::Rect r1 = GetPopup(id1)->GetBoundsInScreen();
gfx::Rect r2 = GetPopup(id0)->GetBoundsInScreen();
// The 4th toast is not shown yet.
EXPECT_FALSE(GetPopup(id3));
// 3 toasts are shown, equal size, vertical stack.
EXPECT_EQ(r0.width(), r1.width());
EXPECT_EQ(r1.width(), r2.width());
EXPECT_EQ(r0.height(), r1.height());
EXPECT_EQ(r1.height(), r2.height());
EXPECT_GT(r0.y(), r1.y());
EXPECT_GT(r1.y(), r2.y());
EXPECT_EQ(r0.x(), r1.x());
EXPECT_EQ(r1.x(), r2.x());
}
TEST_F(MessagePopupCollectionTest, DefaultPositioningWithRightTaskbar) {
// If taskbar is on the right we show the toasts bottom to top as usual.
// Simulate a taskbar at the right.
SetDisplayInfo(gfx::Rect(0, 0, 590, 400), // Work-area.
gfx::Rect(0, 0, 600, 400)); // Display-bounds.
std::string id0 = AddNotification();
std::string id1 = AddNotification();
AnimateUntilIdle();
gfx::Rect r0 = GetPopup(id0)->GetBoundsInScreen();
gfx::Rect r1 = GetPopup(id1)->GetBoundsInScreen();
// 2 toasts are shown, equal size, vertical stack.
EXPECT_EQ(r0.width(), r1.width());
EXPECT_EQ(r0.height(), r1.height());
EXPECT_GT(r0.y(), r1.y());
EXPECT_EQ(r0.x(), r1.x());
}
TEST_F(MessagePopupCollectionTest, TopDownPositioningWithTopTaskbar) {
// Simulate a taskbar at the top.
SetDisplayInfo(gfx::Rect(0, 10, 600, 390), // Work-area.
gfx::Rect(0, 0, 600, 400)); // Display-bounds.
std::string id0 = AddNotification();
std::string id1 = AddNotification();
AnimateUntilIdle();
gfx::Rect r0 = GetPopup(id0)->GetBoundsInScreen();
gfx::Rect r1 = GetPopup(id1)->GetBoundsInScreen();
// 2 toasts are shown, equal size, vertical stack.
EXPECT_EQ(r0.width(), r1.width());
EXPECT_EQ(r0.height(), r1.height());
EXPECT_LT(r0.y(), r1.y());
EXPECT_EQ(r0.x(), r1.x());
}
TEST_F(MessagePopupCollectionTest, TopDownPositioningWithLeftAndTopTaskbar) {
// If there "seems" to be a taskbar on left and top (like in Unity), it is
// assumed that the actual taskbar is the top one.
// Simulate a taskbar at the top and left.
SetDisplayInfo(gfx::Rect(10, 10, 590, 390), // Work-area.
gfx::Rect(0, 0, 600, 400)); // Display-bounds.
std::string id0 = AddNotification();
std::string id1 = AddNotification();
AnimateUntilIdle();
gfx::Rect r0 = GetPopup(id0)->GetBoundsInScreen();
gfx::Rect r1 = GetPopup(id1)->GetBoundsInScreen();
// 2 toasts are shown, equal size, vertical stack.
EXPECT_EQ(r0.width(), r1.width());
EXPECT_EQ(r0.height(), r1.height());
EXPECT_LT(r0.y(), r1.y());
EXPECT_EQ(r0.x(), r1.x());
}
TEST_F(MessagePopupCollectionTest, TopDownPositioningWithBottomAndTopTaskbar) {
// If there "seems" to be a taskbar on bottom and top (like in Gnome), it is
// assumed that the actual taskbar is the top one.
// Simulate a taskbar at the top and bottom.
SetDisplayInfo(gfx::Rect(0, 10, 580, 400), // Work-area.
gfx::Rect(0, 0, 600, 400)); // Display-bounds.
std::string id0 = AddNotification();
std::string id1 = AddNotification();
AnimateUntilIdle();
gfx::Rect r0 = GetPopup(id0)->GetBoundsInScreen();
gfx::Rect r1 = GetPopup(id1)->GetBoundsInScreen();
// 2 toasts are shown, equal size, vertical stack.
EXPECT_EQ(r0.width(), r1.width());
EXPECT_EQ(r0.height(), r1.height());
EXPECT_LT(r0.y(), r1.y());
EXPECT_EQ(r0.x(), r1.x());
}
TEST_F(MessagePopupCollectionTest, LeftPositioningWithLeftTaskbar) {
// Simulate a taskbar at the left.
SetDisplayInfo(gfx::Rect(10, 0, 590, 400), // Work-area.
gfx::Rect(0, 0, 600, 400)); // Display-bounds.
std::string id0 = AddNotification();
std::string id1 = AddNotification();
AnimateUntilIdle();
gfx::Rect r0 = GetPopup(id0)->GetBoundsInScreen();
gfx::Rect r1 = GetPopup(id1)->GetBoundsInScreen();
EXPECT_EQ(r0.width(), r1.width());
EXPECT_EQ(r0.height(), r1.height());
EXPECT_GT(r0.y(), r1.y());
EXPECT_EQ(r0.x(), r1.x());
// Ensure that toasts are on the left.
EXPECT_LT(r1.x(), work_area().CenterPoint().x());
EXPECT_TRUE(work_area().Contains(r0));
EXPECT_TRUE(work_area().Contains(r1));
}
TEST_F(MessagePopupCollectionTest, PopupWidgetClosedOutsideDuringFadeOut) {
std::string id = AddNotification();
AnimateUntilIdle();
MessageCenter::Get()->MarkSinglePopupAsShown(id, false);
AnimateToMiddle();
// On Windows it might be possible that the widget is closed outside
// MessagePopupCollection? https://crbug.com/871199
GetPopup(id)->GetWidget()->CloseNow();
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
}
// Notification removing may occur while the animation triggered by the previous
// operation is running. As result, notification is removed from the message
// center but its popup is still kept. At this moment, a new notification with
// the same notification id may be added to the message center. This can happen
// on Chrome OS when an external display is connected with the Chromebook device
// (see https://crbug.com/921402). This test case emulates the procedure of
// the external display connection that is mentioned in the link above. Verifies
// that under this circumstance the notification popup is updated.
TEST_F(MessagePopupCollectionTest, RemoveNotificationWhileAnimating) {
const std::string notification_id("test_id");
const std::string old_notification_title("old_title");
const std::string new_notification_title("new_title");
// Create a notification and add it to message center.
auto old_notification =
CreateNotification(notification_id, old_notification_title);
MessageCenter::Get()->AddNotification(std::move(old_notification));
AnimateToMiddle();
// On real device, MessageCenter::RemoveNotification is called before the
// animation ends. As result, notification is removed while popup keeps still.
EXPECT_TRUE(IsAnimating());
MessageCenter::Get()->RemoveNotification(notification_id, false);
EXPECT_FALSE(MessageCenter::Get()->HasPopupNotifications());
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_EQ(old_notification_title, GetPopup(notification_id)->title());
// On real device, the new notification with the same notification id is
// created and added to message center before the animation ends.
auto new_notification =
CreateNotification(notification_id, new_notification_title);
EXPECT_TRUE(IsAnimating());
MessageCenter::Get()->AddNotification(std::move(new_notification));
AnimateUntilIdle();
// Verifies that the new notification popup is shown.
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_EQ(new_notification_title, GetPopup(notification_id)->title());
}
} // namespace message_center
| chromium/chromium | ui/message_center/views/message_popup_collection_unittest.cc | C++ | bsd-3-clause | 38,889 |
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/thread_local.h"
#include <pthread.h>
#include "base/logging.h"
namespace base {
// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
int error = pthread_key_create(&slot, NULL);
CHECK(error == 0);
}
// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
int error = pthread_key_delete(slot);
DCHECK(error == 0);
}
// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
return pthread_getspecific(slot);
}
// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
int error = pthread_setspecific(slot, value);
CHECK(error == 0);
}
} // namespace base
| balena/sandboxed | chrome/base/thread_local_posix.cc | C++ | bsd-3-clause | 826 |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/paint/paint_invalidator.h"
#include "base/trace_event/trace_event.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/renderer/core/accessibility/ax_object_cache.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/layout_shift_tracker.h"
#include "third_party/blink/renderer/core/layout/layout_table.h"
#include "third_party/blink/renderer/core/layout/layout_table_section.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.h"
#include "third_party/blink/renderer/core/layout/ng/legacy_layout_tree_walking.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
#include "third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.h"
#include "third_party/blink/renderer/core/page/link_highlight.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/paint/clip_path_clipper.h"
#include "third_party/blink/renderer/core/paint/object_paint_properties.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/paint/pre_paint_tree_walk.h"
#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
namespace blink {
void PaintInvalidator::UpdatePaintingLayer(const LayoutObject& object,
PaintInvalidatorContext& context) {
if (object.HasLayer() &&
To<LayoutBoxModelObject>(object).HasSelfPaintingLayer()) {
context.painting_layer = To<LayoutBoxModelObject>(object).Layer();
} else if (object.IsColumnSpanAll() ||
object.IsFloatingWithNonContainingBlockParent()) {
// See |LayoutObject::PaintingLayer| for the special-cases of floating under
// inline and multicolumn.
// Post LayoutNG the |LayoutObject::IsFloatingWithNonContainingBlockParent|
// check can be removed as floats will be painted by the correct layer.
context.painting_layer = object.PaintingLayer();
}
auto* layout_block_flow = DynamicTo<LayoutBlockFlow>(object);
if (layout_block_flow && !object.IsLayoutNGBlockFlow() &&
layout_block_flow->ContainsFloats())
context.painting_layer->SetNeedsPaintPhaseFloat();
if (object.IsFloating() &&
(object.IsInLayoutNGInlineFormattingContext() ||
IsLayoutNGContainingBlock(object.ContainingBlock())))
context.painting_layer->SetNeedsPaintPhaseFloat();
if (!context.painting_layer->NeedsPaintPhaseDescendantOutlines() &&
((object != context.painting_layer->GetLayoutObject() &&
object.StyleRef().HasOutline()) ||
// If this is a block-in-inline, it may need to paint outline.
// See |StyleForContinuationOutline|.
(layout_block_flow && layout_block_flow->StyleForContinuationOutline())))
context.painting_layer->SetNeedsPaintPhaseDescendantOutlines();
}
void PaintInvalidator::UpdateFromTreeBuilderContext(
const PaintPropertyTreeBuilderFragmentContext& tree_builder_context,
PaintInvalidatorContext& context) {
DCHECK_EQ(tree_builder_context.current.paint_offset,
context.fragment_data->PaintOffset());
// For performance, we ignore subpixel movement of composited layers for paint
// invalidation. This will result in imperfect pixel-snapped painting.
// See crbug.com/833083 for details.
if (!RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled() &&
tree_builder_context.current
.directly_composited_container_paint_offset_subpixel_delta ==
tree_builder_context.current.paint_offset -
tree_builder_context.old_paint_offset) {
context.old_paint_offset = tree_builder_context.current.paint_offset;
} else {
context.old_paint_offset = tree_builder_context.old_paint_offset;
}
context.transform_ = tree_builder_context.current.transform;
}
void PaintInvalidator::UpdateLayoutShiftTracking(
const LayoutObject& object,
const PaintPropertyTreeBuilderFragmentContext& tree_builder_context,
PaintInvalidatorContext& context) {
if (!object.ShouldCheckGeometryForPaintInvalidation())
return;
if (tree_builder_context.this_or_ancestor_opacity_is_zero ||
context.inside_opaque_layout_shift_root) {
object.GetMutableForPainting().SetShouldSkipNextLayoutShiftTracking(true);
return;
}
auto& layout_shift_tracker = object.GetFrameView()->GetLayoutShiftTracker();
if (!layout_shift_tracker.NeedsToTrack(object)) {
object.GetMutableForPainting().SetShouldSkipNextLayoutShiftTracking(true);
return;
}
PropertyTreeStateOrAlias property_tree_state(
*tree_builder_context.current.transform,
*tree_builder_context.current.clip, *tree_builder_context.current_effect);
// Adjust old_paint_offset so that LayoutShiftTracker will see the change of
// offset caused by change of paint offset translations and scroll offset
// below the layout shift root. For more details, see
// renderer/core/layout/layout-shift-tracker-old-paint-offset.md.
PhysicalOffset adjusted_old_paint_offset =
context.old_paint_offset -
tree_builder_context.current
.additional_offset_to_layout_shift_root_delta -
PhysicalOffset::FromVector2dFRound(
tree_builder_context.translation_2d_to_layout_shift_root_delta +
tree_builder_context.current
.scroll_offset_to_layout_shift_root_delta);
PhysicalOffset new_paint_offset = tree_builder_context.current.paint_offset;
if (object.IsText()) {
const auto& text = To<LayoutText>(object);
LogicalOffset new_starting_point;
LayoutUnit logical_height;
text.LogicalStartingPointAndHeight(new_starting_point, logical_height);
LogicalOffset old_starting_point = text.PreviousLogicalStartingPoint();
if (new_starting_point == old_starting_point)
return;
text.SetPreviousLogicalStartingPoint(new_starting_point);
if (old_starting_point == LayoutText::UninitializedLogicalStartingPoint())
return;
// If the layout shift root has changed, LayoutShiftTracker can't use the
// current paint property tree to map the old rect.
if (tree_builder_context.current.layout_shift_root_changed)
return;
layout_shift_tracker.NotifyTextPrePaint(
text, property_tree_state, old_starting_point, new_starting_point,
adjusted_old_paint_offset,
tree_builder_context.translation_2d_to_layout_shift_root_delta,
tree_builder_context.current.scroll_offset_to_layout_shift_root_delta,
tree_builder_context.current.pending_scroll_anchor_adjustment,
new_paint_offset, logical_height);
return;
}
DCHECK(object.IsBox());
const auto& box = To<LayoutBox>(object);
PhysicalRect new_rect = box.PhysicalVisualOverflowRectAllowingUnset();
new_rect.Move(new_paint_offset);
PhysicalRect old_rect = box.PreviousPhysicalVisualOverflowRect();
old_rect.Move(adjusted_old_paint_offset);
// TODO(crbug.com/1178618): We may want to do better than this. For now, just
// don't report anything inside multicol containers.
const auto* block_flow = DynamicTo<LayoutBlockFlow>(&box);
if (block_flow && block_flow->IsFragmentationContextRoot() &&
block_flow->IsLayoutNGObject())
context.inside_opaque_layout_shift_root = true;
bool should_create_containing_block_scope =
// TODO(crbug.com/1178618): Support multiple-fragments when switching to
// LayoutNGFragmentTraversal.
context.fragment_data == &box.FirstFragment() && block_flow &&
block_flow->ChildrenInline() && block_flow->FirstChild();
if (should_create_containing_block_scope) {
// For layout shift tracking of contained LayoutTexts.
context.containing_block_scope_.emplace(
PhysicalSizeToBeNoop(box.PreviousSize()),
PhysicalSizeToBeNoop(box.Size()), old_rect, new_rect);
}
bool should_report_layout_shift = [&]() -> bool {
if (box.ShouldSkipNextLayoutShiftTracking()) {
box.GetMutableForPainting().SetShouldSkipNextLayoutShiftTracking(false);
return false;
}
// If the layout shift root has changed, LayoutShiftTracker can't use the
// current paint property tree to map the old rect.
if (tree_builder_context.current.layout_shift_root_changed)
return false;
if (new_rect.IsEmpty() || old_rect.IsEmpty())
return false;
// Track self-painting layers separately because their ancestors'
// PhysicalVisualOverflowRect may not cover them.
if (object.HasLayer() &&
To<LayoutBoxModelObject>(object).HasSelfPaintingLayer())
return true;
// Always track if the parent doesn't need to track (e.g. it has visibility:
// hidden), while this object needs (e.g. it has visibility: visible).
// This also includes non-anonymous child with an anonymous parent.
if (object.Parent()->ShouldSkipNextLayoutShiftTracking())
return true;
// Report if the parent is in a different transform space.
const auto* parent_context = context.ParentContext();
if (!parent_context || !parent_context->transform_ ||
parent_context->transform_ != tree_builder_context.current.transform)
return true;
// Report if this object has local movement (i.e. delta of paint offset is
// different from that of the parent).
return parent_context->fragment_data->PaintOffset() -
parent_context->old_paint_offset !=
new_paint_offset - context.old_paint_offset;
}();
if (should_report_layout_shift) {
layout_shift_tracker.NotifyBoxPrePaint(
box, property_tree_state, old_rect, new_rect, adjusted_old_paint_offset,
tree_builder_context.translation_2d_to_layout_shift_root_delta,
tree_builder_context.current.scroll_offset_to_layout_shift_root_delta,
tree_builder_context.current.pending_scroll_anchor_adjustment,
new_paint_offset);
}
}
bool PaintInvalidator::InvalidatePaint(
const LayoutObject& object,
const NGPrePaintInfo* pre_paint_info,
const PaintPropertyTreeBuilderContext* tree_builder_context,
PaintInvalidatorContext& context) {
TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("blink.invalidation"),
"PaintInvalidator::InvalidatePaint()", "object",
object.DebugName().Ascii());
if (object.IsSVGHiddenContainer() || object.IsLayoutTableCol())
context.subtree_flags |= PaintInvalidatorContext::kSubtreeNoInvalidation;
if (context.subtree_flags & PaintInvalidatorContext::kSubtreeNoInvalidation)
return false;
object.GetMutableForPainting().EnsureIsReadyForPaintInvalidation();
UpdatePaintingLayer(object, context);
// Assert that the container state in the invalidation context is consistent
// with what the LayoutObject tree says. We cannot do this if we're fragment-
// traversing an "orphaned" object (an object that has a fragment inside a
// fragmentainer, even though not all its ancestor objects have it; this may
// happen to OOFs, and also to floats, if they are inside a non-atomic
// inline). In such cases we'll just have to live with the inconsitency, which
// means that we'll lose any paint effects from such "missing" ancestors.
DCHECK_EQ(context.painting_layer, object.PaintingLayer()) << object;
if (AXObjectCache* cache = object.GetDocument().ExistingAXObjectCache())
cache->InvalidateBoundingBox(&object);
if (!object.ShouldCheckForPaintInvalidation() && !context.NeedsSubtreeWalk())
return false;
if (object.SubtreeShouldDoFullPaintInvalidation()) {
context.subtree_flags |=
PaintInvalidatorContext::kSubtreeFullInvalidation |
PaintInvalidatorContext::kSubtreeFullInvalidationForStackedContents;
}
if (object.SubtreeShouldCheckForPaintInvalidation()) {
context.subtree_flags |=
PaintInvalidatorContext::kSubtreeInvalidationChecking;
}
if (UNLIKELY(object.ContainsInlineWithOutlineAndContinuation()) &&
// Need this only if the subtree needs to check geometry change.
PrePaintTreeWalk::ObjectRequiresTreeBuilderContext(object)) {
// Force subtree invalidation checking to ensure invalidation of focus rings
// when continuation's geometry changes.
context.subtree_flags |=
PaintInvalidatorContext::kSubtreeInvalidationChecking;
}
if (pre_paint_info) {
FragmentData& fragment_data = *pre_paint_info->fragment_data;
context.fragment_data = &fragment_data;
if (tree_builder_context) {
DCHECK_EQ(tree_builder_context->fragments.size(), 1u);
const auto& fragment_tree_builder_context =
tree_builder_context->fragments[0];
UpdateFromTreeBuilderContext(fragment_tree_builder_context, context);
UpdateLayoutShiftTracking(object, fragment_tree_builder_context, context);
} else {
context.old_paint_offset = fragment_data.PaintOffset();
}
object.InvalidatePaint(context);
} else {
unsigned tree_builder_index = 0;
for (auto* fragment_data = &object.GetMutableForPainting().FirstFragment();
fragment_data;
fragment_data = fragment_data->NextFragment(), tree_builder_index++) {
context.fragment_data = fragment_data;
DCHECK(!tree_builder_context ||
tree_builder_index < tree_builder_context->fragments.size());
if (tree_builder_context) {
const auto& fragment_tree_builder_context =
tree_builder_context->fragments[tree_builder_index];
UpdateFromTreeBuilderContext(fragment_tree_builder_context, context);
UpdateLayoutShiftTracking(object, fragment_tree_builder_context,
context);
} else {
context.old_paint_offset = fragment_data->PaintOffset();
}
object.InvalidatePaint(context);
}
}
auto reason = static_cast<const DisplayItemClient&>(object)
.GetPaintInvalidationReason();
if (object.ShouldDelayFullPaintInvalidation() &&
(!IsFullPaintInvalidationReason(reason) ||
// Delay invalidation if the client has never been painted.
reason == PaintInvalidationReason::kJustCreated))
pending_delayed_paint_invalidations_.push_back(&object);
if (auto* local_frame = DynamicTo<LocalFrame>(object.GetFrame()->Top())) {
if (auto* mf_checker =
local_frame->View()->GetMobileFriendlinessChecker()) {
if (tree_builder_context &&
(!pre_paint_info || pre_paint_info->is_last_for_node))
mf_checker->NotifyInvalidatePaint(object);
}
}
return reason != PaintInvalidationReason::kNone;
}
void PaintInvalidator::ProcessPendingDelayedPaintInvalidations() {
for (const auto& target : pending_delayed_paint_invalidations_)
target->GetMutableForPainting().SetShouldDelayFullPaintInvalidation();
}
} // namespace blink
| chromium/chromium | third_party/blink/renderer/core/paint/paint_invalidator.cc | C++ | bsd-3-clause | 15,422 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/html_viewer/layout_test_content_handler_impl.h"
#include <utility>
#include "base/bind.h"
#include "base/macros.h"
#include "components/html_viewer/global_state.h"
#include "components/html_viewer/html_document_application_delegate.h"
#include "components/html_viewer/html_widget.h"
#include "components/html_viewer/layout_test_blink_settings_impl.h"
#include "components/html_viewer/web_test_delegate_impl.h"
#include "components/test_runner/web_frame_test_proxy.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebTestingSupport.h"
#include "third_party/WebKit/public/web/WebView.h"
namespace html_viewer {
class TestHTMLFrame : public HTMLFrame {
public:
explicit TestHTMLFrame(HTMLFrame::CreateParams* params)
: HTMLFrame(params), test_interfaces_(nullptr) {}
void set_test_interfaces(test_runner::WebTestInterfaces* test_interfaces) {
test_interfaces_ = test_interfaces;
}
protected:
~TestHTMLFrame() override {}
private:
// blink::WebFrameClient::
void didClearWindowObject(blink::WebLocalFrame* frame) override {
HTMLFrame::didClearWindowObject(frame);
blink::WebTestingSupport::injectInternalsObject(frame);
DCHECK(test_interfaces_);
test_interfaces_->BindTo(frame);
}
test_runner::WebTestInterfaces* test_interfaces_;
DISALLOW_COPY_AND_ASSIGN(TestHTMLFrame);
};
LayoutTestContentHandlerImpl::LayoutTestContentHandlerImpl(
GlobalState* global_state,
mojo::ApplicationImpl* app,
mojo::InterfaceRequest<mojo::ContentHandler> request,
test_runner::WebTestInterfaces* test_interfaces,
WebTestDelegateImpl* test_delegate)
: ContentHandlerImpl(global_state, app, std::move(request)),
test_interfaces_(test_interfaces),
test_delegate_(test_delegate),
web_widget_proxy_(nullptr),
app_refcount_(app->app_lifetime_helper()->CreateAppRefCount()) {}
LayoutTestContentHandlerImpl::~LayoutTestContentHandlerImpl() {
}
void LayoutTestContentHandlerImpl::StartApplication(
mojo::InterfaceRequest<mojo::Application> request,
mojo::URLResponsePtr response,
const mojo::Callback<void()>& destruct_callback) {
test_interfaces_->SetTestIsRunning(true);
test_interfaces_->ConfigureForTestWithURL(GURL(), false);
// HTMLDocumentApplicationDelegate deletes itself.
HTMLDocumentApplicationDelegate* delegate =
new HTMLDocumentApplicationDelegate(
std::move(request), std::move(response), global_state(),
app()->app_lifetime_helper()->CreateAppRefCount(), destruct_callback);
delegate->set_html_factory(this);
}
HTMLWidgetRootLocal* LayoutTestContentHandlerImpl::CreateHTMLWidgetRootLocal(
HTMLWidgetRootLocal::CreateParams* params) {
web_widget_proxy_ = new WebWidgetProxy(params);
return web_widget_proxy_;
}
HTMLFrame* LayoutTestContentHandlerImpl::CreateHTMLFrame(
HTMLFrame::CreateParams* params) {
params->manager->global_state()->set_blink_settings(
new LayoutTestBlinkSettingsImpl());
// The test harness isn't correctly set-up for iframes yet. So return a normal
// HTMLFrame for iframes.
if (params->parent || !params->window || params->window->id() != params->id)
return new HTMLFrame(params);
using ProxyType =
test_runner::WebFrameTestProxy<TestHTMLFrame, HTMLFrame::CreateParams*>;
ProxyType* proxy = new ProxyType(params);
proxy->set_test_interfaces(test_interfaces_);
web_widget_proxy_->SetInterfaces(test_interfaces_);
web_widget_proxy_->SetDelegate(test_delegate_);
proxy->set_base_proxy(web_widget_proxy_);
test_delegate_->set_test_proxy(web_widget_proxy_);
test_interfaces_->SetWebView(web_widget_proxy_->web_view(),
web_widget_proxy_);
web_widget_proxy_->set_widget(web_widget_proxy_->web_view());
test_interfaces_->BindTo(web_widget_proxy_->web_view()->mainFrame());
return proxy;
}
} // namespace html_viewer
| js0701/chromium-crosswalk | components/html_viewer/layout_test_content_handler_impl.cc | C++ | bsd-3-clause | 4,105 |
/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "platform/graphics/GeneratedImage.h"
#include "platform/geometry/FloatRect.h"
#include "platform/graphics/paint/SkPictureBuilder.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkPicture.h"
namespace blink {
void GeneratedImage::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
{
Image::computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
intrinsicRatio = FloatSize();
}
void GeneratedImage::drawPattern(GraphicsContext& destContext, const FloatRect& srcRect, const FloatSize& scale,
const FloatPoint& phase, SkXfermode::Mode compositeOp, const FloatRect& destRect,
const FloatSize& repeatSpacing)
{
FloatRect tileRect = srcRect;
tileRect.expand(FloatSize(repeatSpacing));
SkPictureBuilder builder(tileRect, nullptr, &destContext);
builder.context().beginRecording(tileRect);
drawTile(builder.context(), srcRect);
RefPtr<const SkPicture> tilePicture = builder.endRecording();
AffineTransform patternTransform;
patternTransform.translate(phase.x(), phase.y());
patternTransform.scale(scale.width(), scale.height());
patternTransform.translate(tileRect.x(), tileRect.y());
RefPtr<Pattern> picturePattern = Pattern::createPicturePattern(tilePicture);
picturePattern->setPatternSpaceTransform(patternTransform);
SkPaint fillPaint = destContext.fillPaint();
picturePattern->applyToPaint(fillPaint);
fillPaint.setColor(SK_ColorBLACK);
fillPaint.setXfermodeMode(compositeOp);
destContext.drawRect(destRect, fillPaint);
}
PassRefPtr<SkImage> GeneratedImage::imageForCurrentFrame()
{
return nullptr;
}
} // namespace blink
| js0701/chromium-crosswalk | third_party/WebKit/Source/platform/graphics/GeneratedImage.cpp | C++ | bsd-3-clause | 3,311 |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Benchmarks.Data
{
[Table("fortune")]
public class Fortune : IComparable<Fortune>, IComparable
{
[Column("id")]
public int Id { get; set; }
[Column("message")]
[StringLength(2048)]
[Required]
public string Message { get; set; }
public int CompareTo(object obj)
{
return CompareTo((Fortune)obj);
}
public int CompareTo(Fortune other)
{
// Performance critical, using culture insensitive comparison
return String.CompareOrdinal(Message, other.Message);
}
}
}
| sumeetchhetri/FrameworkBenchmarks | frameworks/CSharp/aspnetcore/Benchmarks/Data/Fortune.cs | C# | bsd-3-clause | 902 |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Text.Json;
using System.Threading.Tasks;
using Benchmarks.Configuration;
using Benchmarks.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Benchmarks.Middleware
{
public class MultipleUpdatesRawMiddleware
{
private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.DbMultiUpdateRaw));
private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
private readonly RequestDelegate _next;
public MultipleUpdatesRawMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
{
var count = MiddlewareHelpers.GetMultipleQueriesQueryCount(httpContext);
var db = httpContext.RequestServices.GetService<RawDb>();
var rows = await db.LoadMultipleUpdatesRows(count);
var result = JsonSerializer.Serialize(rows, _serializerOptions);
httpContext.Response.StatusCode = StatusCodes.Status200OK;
httpContext.Response.ContentType = "application/json";
httpContext.Response.ContentLength = result.Length;
await httpContext.Response.WriteAsync(result);
return;
}
await _next(httpContext);
}
}
public static class MultipleUpdatesRawMiddlewareExtensions
{
public static IApplicationBuilder UseMultipleUpdatesRaw(this IApplicationBuilder builder)
{
return builder.UseMiddleware<MultipleUpdatesRawMiddleware>();
}
}
}
| sumeetchhetri/FrameworkBenchmarks | frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MultipleUpdatesRawMiddleware.cs | C# | bsd-3-clause | 2,038 |
/*
* Copyright (c) 2010-2014 ARM Limited
* Copyright (c) 2012-2013 AMD
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2004-2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Kevin Lim
* Korey Sewell
*/
#ifndef __CPU_O3_FETCH_IMPL_HH__
#define __CPU_O3_FETCH_IMPL_HH__
#include <algorithm>
#include <cstring>
#include <list>
#include <map>
#include <queue>
#include "arch/isa_traits.hh"
#include "arch/tlb.hh"
#include "arch/utility.hh"
#include "arch/vtophys.hh"
#include "base/random.hh"
#include "base/types.hh"
#include "config/the_isa.hh"
#include "cpu/base.hh"
//#include "cpu/checker/cpu.hh"
#include "cpu/o3/fetch.hh"
#include "cpu/exetrace.hh"
#include "debug/Activity.hh"
#include "debug/Drain.hh"
#include "debug/Fetch.hh"
#include "debug/O3PipeView.hh"
#include "mem/packet.hh"
#include "params/DerivO3CPU.hh"
#include "sim/byteswap.hh"
#include "sim/core.hh"
#include "sim/eventq.hh"
#include "sim/full_system.hh"
#include "sim/system.hh"
#include "cpu/o3/isa_specific.hh"
using namespace std;
template<class Impl>
DefaultFetch<Impl>::DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params)
: cpu(_cpu),
decodeToFetchDelay(params->decodeToFetchDelay),
renameToFetchDelay(params->renameToFetchDelay),
iewToFetchDelay(params->iewToFetchDelay),
commitToFetchDelay(params->commitToFetchDelay),
fetchWidth(params->fetchWidth),
decodeWidth(params->decodeWidth),
retryPkt(NULL),
retryTid(InvalidThreadID),
cacheBlkSize(cpu->cacheLineSize()),
fetchBufferSize(params->fetchBufferSize),
fetchBufferMask(fetchBufferSize - 1),
fetchQueueSize(params->fetchQueueSize),
numThreads(params->numThreads),
numFetchingThreads(params->smtNumFetchingThreads),
finishTranslationEvent(this)
{
if (numThreads > Impl::MaxThreads)
fatal("numThreads (%d) is larger than compiled limit (%d),\n"
"\tincrease MaxThreads in src/cpu/o3/impl.hh\n",
numThreads, static_cast<int>(Impl::MaxThreads));
if (fetchWidth > Impl::MaxWidth)
fatal("fetchWidth (%d) is larger than compiled limit (%d),\n"
"\tincrease MaxWidth in src/cpu/o3/impl.hh\n",
fetchWidth, static_cast<int>(Impl::MaxWidth));
if (fetchBufferSize > cacheBlkSize)
fatal("fetch buffer size (%u bytes) is greater than the cache "
"block size (%u bytes)\n", fetchBufferSize, cacheBlkSize);
if (cacheBlkSize % fetchBufferSize)
fatal("cache block (%u bytes) is not a multiple of the "
"fetch buffer (%u bytes)\n", cacheBlkSize, fetchBufferSize);
std::string policy = params->smtFetchPolicy;
// Convert string to lowercase
std::transform(policy.begin(), policy.end(), policy.begin(),
(int(*)(int)) tolower);
// Figure out fetch policy
if (policy == "singlethread") {
fetchPolicy = SingleThread;
if (numThreads > 1)
panic("Invalid Fetch Policy for a SMT workload.");
} else if (policy == "roundrobin") {
fetchPolicy = RoundRobin;
DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
} else if (policy == "branch") {
fetchPolicy = Branch;
DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
} else if (policy == "iqcount") {
fetchPolicy = IQ;
DPRINTF(Fetch, "Fetch policy set to IQ count\n");
} else if (policy == "lsqcount") {
fetchPolicy = LSQ;
DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
} else {
fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
" RoundRobin,LSQcount,IQcount}\n");
}
// Get the size of an instruction.
instSize = sizeof(TheISA::MachInst);
for (int i = 0; i < Impl::MaxThreads; i++) {
decoder[i] = NULL;
fetchBuffer[i] = NULL;
fetchBufferPC[i] = 0;
fetchBufferValid[i] = false;
}
branchPred = params->branchPred;
for (ThreadID tid = 0; tid < numThreads; tid++) {
decoder[tid] = new TheISA::Decoder(params->isa[tid]);
// Create space to buffer the cache line data,
// which may not hold the entire cache line.
fetchBuffer[tid] = new uint8_t[fetchBufferSize];
}
}
template <class Impl>
std::string
DefaultFetch<Impl>::name() const
{
return cpu->name() + ".fetch";
}
template <class Impl>
void
DefaultFetch<Impl>::regProbePoints()
{
ppFetch = new ProbePointArg<DynInstPtr>(cpu->getProbeManager(), "Fetch");
ppFetchRequestSent = new ProbePointArg<RequestPtr>(cpu->getProbeManager(),
"FetchRequest");
}
template <class Impl>
void
DefaultFetch<Impl>::regStats()
{
icacheStallCycles
.name(name() + ".icacheStallCycles")
.desc("Number of cycles fetch is stalled on an Icache miss")
.prereq(icacheStallCycles);
fetchedInsts
.name(name() + ".Insts")
.desc("Number of instructions fetch has processed")
.prereq(fetchedInsts);
fetchedBranches
.name(name() + ".Branches")
.desc("Number of branches that fetch encountered")
.prereq(fetchedBranches);
predictedBranches
.name(name() + ".predictedBranches")
.desc("Number of branches that fetch has predicted taken")
.prereq(predictedBranches);
fetchCycles
.name(name() + ".Cycles")
.desc("Number of cycles fetch has run and was not squashing or"
" blocked")
.prereq(fetchCycles);
fetchSquashCycles
.name(name() + ".SquashCycles")
.desc("Number of cycles fetch has spent squashing")
.prereq(fetchSquashCycles);
fetchTlbCycles
.name(name() + ".TlbCycles")
.desc("Number of cycles fetch has spent waiting for tlb")
.prereq(fetchTlbCycles);
fetchIdleCycles
.name(name() + ".IdleCycles")
.desc("Number of cycles fetch was idle")
.prereq(fetchIdleCycles);
fetchBlockedCycles
.name(name() + ".BlockedCycles")
.desc("Number of cycles fetch has spent blocked")
.prereq(fetchBlockedCycles);
fetchedCacheLines
.name(name() + ".CacheLines")
.desc("Number of cache lines fetched")
.prereq(fetchedCacheLines);
fetchMiscStallCycles
.name(name() + ".MiscStallCycles")
.desc("Number of cycles fetch has spent waiting on interrupts, or "
"bad addresses, or out of MSHRs")
.prereq(fetchMiscStallCycles);
fetchPendingDrainCycles
.name(name() + ".PendingDrainCycles")
.desc("Number of cycles fetch has spent waiting on pipes to drain")
.prereq(fetchPendingDrainCycles);
fetchNoActiveThreadStallCycles
.name(name() + ".NoActiveThreadStallCycles")
.desc("Number of stall cycles due to no active thread to fetch from")
.prereq(fetchNoActiveThreadStallCycles);
fetchPendingTrapStallCycles
.name(name() + ".PendingTrapStallCycles")
.desc("Number of stall cycles due to pending traps")
.prereq(fetchPendingTrapStallCycles);
fetchPendingQuiesceStallCycles
.name(name() + ".PendingQuiesceStallCycles")
.desc("Number of stall cycles due to pending quiesce instructions")
.prereq(fetchPendingQuiesceStallCycles);
fetchIcacheWaitRetryStallCycles
.name(name() + ".IcacheWaitRetryStallCycles")
.desc("Number of stall cycles due to full MSHR")
.prereq(fetchIcacheWaitRetryStallCycles);
fetchIcacheSquashes
.name(name() + ".IcacheSquashes")
.desc("Number of outstanding Icache misses that were squashed")
.prereq(fetchIcacheSquashes);
fetchTlbSquashes
.name(name() + ".ItlbSquashes")
.desc("Number of outstanding ITLB misses that were squashed")
.prereq(fetchTlbSquashes);
fetchNisnDist
.init(/* base value */ 0,
/* last value */ fetchWidth,
/* bucket size */ 1)
.name(name() + ".rateDist")
.desc("Number of instructions fetched each cycle (Total)")
.flags(Stats::pdf);
idleRate
.name(name() + ".idleRate")
.desc("Percent of cycles fetch was idle")
.prereq(idleRate);
idleRate = fetchIdleCycles * 100 / cpu->numCycles;
branchRate
.name(name() + ".branchRate")
.desc("Number of branch fetches per cycle")
.flags(Stats::total);
branchRate = fetchedBranches / cpu->numCycles;
fetchRate
.name(name() + ".rate")
.desc("Number of inst fetches per cycle")
.flags(Stats::total);
fetchRate = fetchedInsts / cpu->numCycles;
}
template<class Impl>
void
DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
{
timeBuffer = time_buffer;
// Create wires to get information from proper places in time buffer.
fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
fromRename = timeBuffer->getWire(-renameToFetchDelay);
fromIEW = timeBuffer->getWire(-iewToFetchDelay);
fromCommit = timeBuffer->getWire(-commitToFetchDelay);
}
template<class Impl>
void
DefaultFetch<Impl>::setActiveThreads(std::list<ThreadID> *at_ptr)
{
activeThreads = at_ptr;
}
template<class Impl>
void
DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *ftb_ptr)
{
// Create wire to write information to proper place in fetch time buf.
toDecode = ftb_ptr->getWire(0);
}
template<class Impl>
void
DefaultFetch<Impl>::startupStage()
{
assert(priorityList.empty());
resetStage();
// Fetch needs to start fetching instructions at the very beginning,
// so it must start up in active state.
switchToActive();
}
template<class Impl>
void
DefaultFetch<Impl>::resetStage()
{
numInst = 0;
interruptPending = false;
cacheBlocked = false;
priorityList.clear();
// Setup PC and nextPC with initial state.
for (ThreadID tid = 0; tid < numThreads; ++tid) {
fetchStatus[tid] = Running;
pc[tid] = cpu->pcState(tid);
fetchOffset[tid] = 0;
macroop[tid] = NULL;
delayedCommit[tid] = false;
memReq[tid] = NULL;
stalls[tid].decode = false;
stalls[tid].drain = false;
fetchBufferPC[tid] = 0;
fetchBufferValid[tid] = false;
fetchQueue[tid].clear();
priorityList.push_back(tid);
}
wroteToTimeBuffer = false;
_status = Inactive;
}
template<class Impl>
void
DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
{
ThreadID tid = cpu->contextToThread(pkt->req->contextId());
DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n", tid);
assert(!cpu->switchedOut());
// Only change the status if it's still waiting on the icache access
// to return.
if (fetchStatus[tid] != IcacheWaitResponse ||
pkt->req != memReq[tid]) {
++fetchIcacheSquashes;
delete pkt->req;
delete pkt;
return;
}
memcpy(fetchBuffer[tid], pkt->getConstPtr<uint8_t>(), fetchBufferSize);
fetchBufferValid[tid] = true;
// Wake up the CPU (if it went to sleep and was waiting on
// this completion event).
cpu->wakeCPU();
DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
tid);
switchToActive();
// Only switch to IcacheAccessComplete if we're not stalled as well.
if (checkStall(tid)) {
fetchStatus[tid] = Blocked;
} else {
fetchStatus[tid] = IcacheAccessComplete;
}
pkt->req->setAccessLatency();
cpu->ppInstAccessComplete->notify(pkt);
// Reset the mem req to NULL.
delete pkt->req;
delete pkt;
memReq[tid] = NULL;
}
template <class Impl>
void
DefaultFetch<Impl>::drainResume()
{
for (ThreadID i = 0; i < numThreads; ++i)
stalls[i].drain = false;
}
template <class Impl>
void
DefaultFetch<Impl>::drainSanityCheck() const
{
assert(isDrained());
assert(retryPkt == NULL);
assert(retryTid == InvalidThreadID);
assert(!cacheBlocked);
assert(!interruptPending);
for (ThreadID i = 0; i < numThreads; ++i) {
assert(!memReq[i]);
assert(fetchStatus[i] == Idle || stalls[i].drain);
}
branchPred->drainSanityCheck();
}
template <class Impl>
bool
DefaultFetch<Impl>::isDrained() const
{
/* Make sure that threads are either idle of that the commit stage
* has signaled that draining has completed by setting the drain
* stall flag. This effectively forces the pipeline to be disabled
* until the whole system is drained (simulation may continue to
* drain other components).
*/
for (ThreadID i = 0; i < numThreads; ++i) {
// Verify fetch queues are drained
if (!fetchQueue[i].empty())
return false;
// Return false if not idle or drain stalled
if (fetchStatus[i] != Idle) {
if (fetchStatus[i] == Blocked && stalls[i].drain)
continue;
else
return false;
}
}
/* The pipeline might start up again in the middle of the drain
* cycle if the finish translation event is scheduled, so make
* sure that's not the case.
*/
return !finishTranslationEvent.scheduled();
}
template <class Impl>
void
DefaultFetch<Impl>::takeOverFrom()
{
assert(cpu->getInstPort().isConnected());
resetStage();
}
template <class Impl>
void
DefaultFetch<Impl>::drainStall(ThreadID tid)
{
assert(cpu->isDraining());
assert(!stalls[tid].drain);
DPRINTF(Drain, "%i: Thread drained.\n", tid);
stalls[tid].drain = true;
}
template <class Impl>
void
DefaultFetch<Impl>::wakeFromQuiesce()
{
DPRINTF(Fetch, "Waking up from quiesce\n");
// Hopefully this is safe
// @todo: Allow other threads to wake from quiesce.
fetchStatus[0] = Running;
}
template <class Impl>
inline void
DefaultFetch<Impl>::switchToActive()
{
if (_status == Inactive) {
DPRINTF(Activity, "Activating stage.\n");
cpu->activateStage(O3CPU::FetchIdx);
_status = Active;
}
}
template <class Impl>
inline void
DefaultFetch<Impl>::switchToInactive()
{
if (_status == Active) {
DPRINTF(Activity, "Deactivating stage.\n");
cpu->deactivateStage(O3CPU::FetchIdx);
_status = Inactive;
}
}
template <class Impl>
void
DefaultFetch<Impl>::deactivateThread(ThreadID tid)
{
// Update priority list
auto thread_it = std::find(priorityList.begin(), priorityList.end(), tid);
if (thread_it != priorityList.end()) {
priorityList.erase(thread_it);
}
}
template <class Impl>
bool
DefaultFetch<Impl>::lookupAndUpdateNextPC(
DynInstPtr &inst, TheISA::PCState &nextPC)
{
// Do branch prediction check here.
// A bit of a misnomer...next_PC is actually the current PC until
// this function updates it.
bool predict_taken;
if (!inst->isControl()) {
TheISA::advancePC(nextPC, inst->staticInst);
inst->setPredTarg(nextPC);
inst->setPredTaken(false);
return false;
}
ThreadID tid = inst->threadNumber;
predict_taken = branchPred->predict(inst->staticInst, inst->seqNum,
nextPC, tid);
if (predict_taken) {
DPRINTF(Fetch, "[tid:%i]: [sn:%i]: Branch predicted to be taken to %s.\n",
tid, inst->seqNum, nextPC);
} else {
DPRINTF(Fetch, "[tid:%i]: [sn:%i]:Branch predicted to be not taken.\n",
tid, inst->seqNum);
}
DPRINTF(Fetch, "[tid:%i]: [sn:%i] Branch predicted to go to %s.\n",
tid, inst->seqNum, nextPC);
inst->setPredTarg(nextPC);
inst->setPredTaken(predict_taken);
++fetchedBranches;
if (predict_taken) {
++predictedBranches;
}
return predict_taken;
}
template <class Impl>
bool
DefaultFetch<Impl>::fetchCacheLine(Addr vaddr, ThreadID tid, Addr pc)
{
Fault fault = NoFault;
assert(!cpu->switchedOut());
// @todo: not sure if these should block translation.
//AlphaDep
if (cacheBlocked) {
DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
tid);
return false;
} else if (checkInterrupt(pc) && !delayedCommit[tid]) {
// Hold off fetch from getting new instructions when:
// Cache is blocked, or
// while an interrupt is pending and we're not in PAL mode, or
// fetch is switched out.
DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n",
tid);
return false;
}
// Align the fetch address to the start of a fetch buffer segment.
Addr fetchBufferBlockPC = fetchBufferAlignPC(vaddr);
DPRINTF(Fetch, "[tid:%i] Fetching cache line %#x for addr %#x\n",
tid, fetchBufferBlockPC, vaddr);
// Setup the memReq to do a read of the first instruction's address.
// Set the appropriate read size and flags as well.
// Build request here.
RequestPtr mem_req =
new Request(tid, fetchBufferBlockPC, fetchBufferSize,
Request::INST_FETCH, cpu->instMasterId(), pc,
cpu->thread[tid]->contextId());
mem_req->taskId(cpu->taskId());
memReq[tid] = mem_req;
// Initiate translation of the icache block
fetchStatus[tid] = ItlbWait;
FetchTranslation *trans = new FetchTranslation(this);
cpu->itb->translateTiming(mem_req, cpu->thread[tid]->getTC(),
trans, BaseTLB::Execute);
return true;
}
template <class Impl>
void
DefaultFetch<Impl>::finishTranslation(const Fault &fault, RequestPtr mem_req)
{
ThreadID tid = cpu->contextToThread(mem_req->contextId());
Addr fetchBufferBlockPC = mem_req->getVaddr();
assert(!cpu->switchedOut());
// Wake up CPU if it was idle
cpu->wakeCPU();
if (fetchStatus[tid] != ItlbWait || mem_req != memReq[tid] ||
mem_req->getVaddr() != memReq[tid]->getVaddr()) {
DPRINTF(Fetch, "[tid:%i] Ignoring itlb completed after squash\n",
tid);
++fetchTlbSquashes;
delete mem_req;
return;
}
// If translation was successful, attempt to read the icache block.
if (fault == NoFault) {
// Check that we're not going off into random memory
// If we have, just wait around for commit to squash something and put
// us on the right track
if (!cpu->system->isMemAddr(mem_req->getPaddr())) {
warn("Address %#x is outside of physical memory, stopping fetch\n",
mem_req->getPaddr());
fetchStatus[tid] = NoGoodAddr;
delete mem_req;
memReq[tid] = NULL;
return;
}
// Build packet here.
PacketPtr data_pkt = new Packet(mem_req, MemCmd::ReadReq);
data_pkt->dataDynamic(new uint8_t[fetchBufferSize]);
fetchBufferPC[tid] = fetchBufferBlockPC;
fetchBufferValid[tid] = false;
DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
fetchedCacheLines++;
// Access the cache.
if (!cpu->getInstPort().sendTimingReq(data_pkt)) {
assert(retryPkt == NULL);
assert(retryTid == InvalidThreadID);
DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
fetchStatus[tid] = IcacheWaitRetry;
retryPkt = data_pkt;
retryTid = tid;
cacheBlocked = true;
} else {
DPRINTF(Fetch, "[tid:%i]: Doing Icache access.\n", tid);
DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
"response.\n", tid);
lastIcacheStall[tid] = curTick();
fetchStatus[tid] = IcacheWaitResponse;
// Notify Fetch Request probe when a packet containing a fetch
// request is successfully sent
ppFetchRequestSent->notify(mem_req);
}
} else {
// Don't send an instruction to decode if we can't handle it.
if (!(numInst < fetchWidth) || !(fetchQueue[tid].size() < fetchQueueSize)) {
assert(!finishTranslationEvent.scheduled());
finishTranslationEvent.setFault(fault);
finishTranslationEvent.setReq(mem_req);
cpu->schedule(finishTranslationEvent,
cpu->clockEdge(Cycles(1)));
return;
}
DPRINTF(Fetch, "[tid:%i] Got back req with addr %#x but expected %#x\n",
tid, mem_req->getVaddr(), memReq[tid]->getVaddr());
// Translation faulted, icache request won't be sent.
delete mem_req;
memReq[tid] = NULL;
// Send the fault to commit. This thread will not do anything
// until commit handles the fault. The only other way it can
// wake up is if a squash comes along and changes the PC.
TheISA::PCState fetchPC = pc[tid];
DPRINTF(Fetch, "[tid:%i]: Translation faulted, building noop.\n", tid);
// We will use a nop in ordier to carry the fault.
DynInstPtr instruction = buildInst(tid,
decoder[tid]->decode(TheISA::NoopMachInst, fetchPC.instAddr()),
NULL, fetchPC, fetchPC, false);
instruction->setPredTarg(fetchPC);
instruction->fault = fault;
wroteToTimeBuffer = true;
DPRINTF(Activity, "Activity this cycle.\n");
cpu->activityThisCycle();
fetchStatus[tid] = TrapPending;
DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n", tid);
DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %s.\n",
tid, fault->name(), pc[tid]);
}
_status = updateFetchStatus();
}
template <class Impl>
inline void
DefaultFetch<Impl>::doSquash(const TheISA::PCState &newPC,
const DynInstPtr squashInst, ThreadID tid)
{
DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %s.\n",
tid, newPC);
pc[tid] = newPC;
fetchOffset[tid] = 0;
if (squashInst && squashInst->pcState().instAddr() == newPC.instAddr())
macroop[tid] = squashInst->macroop;
else
macroop[tid] = NULL;
decoder[tid]->reset();
// Clear the icache miss if it's outstanding.
if (fetchStatus[tid] == IcacheWaitResponse) {
DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
tid);
memReq[tid] = NULL;
} else if (fetchStatus[tid] == ItlbWait) {
DPRINTF(Fetch, "[tid:%i]: Squashing outstanding ITLB miss.\n",
tid);
memReq[tid] = NULL;
}
// Get rid of the retrying packet if it was from this thread.
if (retryTid == tid) {
assert(cacheBlocked);
if (retryPkt) {
delete retryPkt->req;
delete retryPkt;
}
retryPkt = NULL;
retryTid = InvalidThreadID;
}
fetchStatus[tid] = Squashing;
// Empty fetch queue
fetchQueue[tid].clear();
// microops are being squashed, it is not known wheather the
// youngest non-squashed microop was marked delayed commit
// or not. Setting the flag to true ensures that the
// interrupts are not handled when they cannot be, though
// some opportunities to handle interrupts may be missed.
delayedCommit[tid] = true;
++fetchSquashCycles;
}
template<class Impl>
void
DefaultFetch<Impl>::squashFromDecode(const TheISA::PCState &newPC,
const DynInstPtr squashInst,
const InstSeqNum seq_num, ThreadID tid)
{
DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n", tid);
doSquash(newPC, squashInst, tid);
// Tell the CPU to remove any instructions that are in flight between
// fetch and decode.
cpu->removeInstsUntil(seq_num, tid);
}
template<class Impl>
bool
DefaultFetch<Impl>::checkStall(ThreadID tid) const
{
bool ret_val = false;
if (stalls[tid].drain) {
assert(cpu->isDraining());
DPRINTF(Fetch,"[tid:%i]: Drain stall detected.\n",tid);
ret_val = true;
}
return ret_val;
}
template<class Impl>
typename DefaultFetch<Impl>::FetchStatus
DefaultFetch<Impl>::updateFetchStatus()
{
//Check Running
list<ThreadID>::iterator threads = activeThreads->begin();
list<ThreadID>::iterator end = activeThreads->end();
while (threads != end) {
ThreadID tid = *threads++;
if (fetchStatus[tid] == Running ||
fetchStatus[tid] == Squashing ||
fetchStatus[tid] == IcacheAccessComplete) {
if (_status == Inactive) {
DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
if (fetchStatus[tid] == IcacheAccessComplete) {
DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
"completion\n",tid);
}
cpu->activateStage(O3CPU::FetchIdx);
}
return Active;
}
}
// Stage is switching from active to inactive, notify CPU of it.
if (_status == Active) {
DPRINTF(Activity, "Deactivating stage.\n");
cpu->deactivateStage(O3CPU::FetchIdx);
}
return Inactive;
}
template <class Impl>
void
DefaultFetch<Impl>::squash(const TheISA::PCState &newPC,
const InstSeqNum seq_num, DynInstPtr squashInst,
ThreadID tid)
{
DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n", tid);
doSquash(newPC, squashInst, tid);
// Tell the CPU to remove any instructions that are not in the ROB.
cpu->removeInstsNotInROB(tid);
}
template <class Impl>
void
DefaultFetch<Impl>::tick()
{
list<ThreadID>::iterator threads = activeThreads->begin();
list<ThreadID>::iterator end = activeThreads->end();
bool status_change = false;
wroteToTimeBuffer = false;
for (ThreadID i = 0; i < numThreads; ++i) {
issuePipelinedIfetch[i] = false;
}
while (threads != end) {
ThreadID tid = *threads++;
// Check the signals for each thread to determine the proper status
// for each thread.
bool updated_status = checkSignalsAndUpdate(tid);
status_change = status_change || updated_status;
}
DPRINTF(Fetch, "Running stage.\n");
if (FullSystem) {
if (fromCommit->commitInfo[0].interruptPending) {
interruptPending = true;
}
if (fromCommit->commitInfo[0].clearInterrupt) {
interruptPending = false;
}
}
for (threadFetched = 0; threadFetched < numFetchingThreads;
threadFetched++) {
// Fetch each of the actively fetching threads.
fetch(status_change);
}
// Record number of instructions fetched this cycle for distribution.
fetchNisnDist.sample(numInst);
if (status_change) {
// Change the fetch stage status if there was a status change.
_status = updateFetchStatus();
}
// Issue the next I-cache request if possible.
for (ThreadID i = 0; i < numThreads; ++i) {
if (issuePipelinedIfetch[i]) {
pipelineIcacheAccesses(i);
}
}
// Send instructions enqueued into the fetch queue to decode.
// Limit rate by fetchWidth. Stall if decode is stalled.
unsigned insts_to_decode = 0;
unsigned available_insts = 0;
for (auto tid : *activeThreads) {
if (!stalls[tid].decode) {
available_insts += fetchQueue[tid].size();
}
}
// Pick a random thread to start trying to grab instructions from
auto tid_itr = activeThreads->begin();
std::advance(tid_itr, random_mt.random<uint8_t>(0, activeThreads->size() - 1));
while (available_insts != 0 && insts_to_decode < decodeWidth) {
ThreadID tid = *tid_itr;
if (!stalls[tid].decode && !fetchQueue[tid].empty()) {
auto inst = fetchQueue[tid].front();
toDecode->insts[toDecode->size++] = inst;
DPRINTF(Fetch, "[tid:%i][sn:%i]: Sending instruction to decode from "
"fetch queue. Fetch queue size: %i.\n",
tid, inst->seqNum, fetchQueue[tid].size());
wroteToTimeBuffer = true;
fetchQueue[tid].pop_front();
insts_to_decode++;
available_insts--;
}
tid_itr++;
// Wrap around if at end of active threads list
if (tid_itr == activeThreads->end())
tid_itr = activeThreads->begin();
}
// If there was activity this cycle, inform the CPU of it.
if (wroteToTimeBuffer) {
DPRINTF(Activity, "Activity this cycle.\n");
cpu->activityThisCycle();
}
// Reset the number of the instruction we've fetched.
numInst = 0;
}
template <class Impl>
bool
DefaultFetch<Impl>::checkSignalsAndUpdate(ThreadID tid)
{
// Update the per thread stall statuses.
if (fromDecode->decodeBlock[tid]) {
stalls[tid].decode = true;
}
if (fromDecode->decodeUnblock[tid]) {
assert(stalls[tid].decode);
assert(!fromDecode->decodeBlock[tid]);
stalls[tid].decode = false;
}
// Check squash signals from commit.
if (fromCommit->commitInfo[tid].squash) {
DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
"from commit.\n",tid);
// In any case, squash.
squash(fromCommit->commitInfo[tid].pc,
fromCommit->commitInfo[tid].doneSeqNum,
fromCommit->commitInfo[tid].squashInst, tid);
// If it was a branch mispredict on a control instruction, update the
// branch predictor with that instruction, otherwise just kill the
// invalid state we generated in after sequence number
if (fromCommit->commitInfo[tid].mispredictInst &&
fromCommit->commitInfo[tid].mispredictInst->isControl()) {
branchPred->squash(fromCommit->commitInfo[tid].doneSeqNum,
fromCommit->commitInfo[tid].pc,
fromCommit->commitInfo[tid].branchTaken,
tid);
} else {
branchPred->squash(fromCommit->commitInfo[tid].doneSeqNum,
tid);
}
return true;
} else if (fromCommit->commitInfo[tid].doneSeqNum) {
// Update the branch predictor if it wasn't a squashed instruction
// that was broadcasted.
branchPred->update(fromCommit->commitInfo[tid].doneSeqNum, tid);
}
// Check squash signals from decode.
if (fromDecode->decodeInfo[tid].squash) {
DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
"from decode.\n",tid);
// Update the branch predictor.
if (fromDecode->decodeInfo[tid].branchMispredict) {
branchPred->squash(fromDecode->decodeInfo[tid].doneSeqNum,
fromDecode->decodeInfo[tid].nextPC,
fromDecode->decodeInfo[tid].branchTaken,
tid);
} else {
branchPred->squash(fromDecode->decodeInfo[tid].doneSeqNum,
tid);
}
if (fetchStatus[tid] != Squashing) {
DPRINTF(Fetch, "Squashing from decode with PC = %s\n",
fromDecode->decodeInfo[tid].nextPC);
// Squash unless we're already squashing
squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
fromDecode->decodeInfo[tid].squashInst,
fromDecode->decodeInfo[tid].doneSeqNum,
tid);
return true;
}
}
if (checkStall(tid) &&
fetchStatus[tid] != IcacheWaitResponse &&
fetchStatus[tid] != IcacheWaitRetry &&
fetchStatus[tid] != ItlbWait &&
fetchStatus[tid] != QuiescePending) {
DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
fetchStatus[tid] = Blocked;
return true;
}
if (fetchStatus[tid] == Blocked ||
fetchStatus[tid] == Squashing) {
// Switch status to running if fetch isn't being told to block or
// squash this cycle.
DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
tid);
fetchStatus[tid] = Running;
return true;
}
// If we've reached this point, we have not gotten any signals that
// cause fetch to change its status. Fetch remains the same as before.
return false;
}
template<class Impl>
typename Impl::DynInstPtr
DefaultFetch<Impl>::buildInst(ThreadID tid, StaticInstPtr staticInst,
StaticInstPtr curMacroop, TheISA::PCState thisPC,
TheISA::PCState nextPC, bool trace)
{
// Get a sequence number.
InstSeqNum seq = cpu->getAndIncrementInstSeq();
// Create a new DynInst from the instruction fetched.
DynInstPtr instruction =
new DynInst(staticInst, curMacroop, thisPC, nextPC, seq, cpu);
instruction->setTid(tid);
instruction->setASID(tid);
instruction->setThreadState(cpu->thread[tid]);
DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x (%d) created "
"[sn:%lli].\n", tid, thisPC.instAddr(),
thisPC.microPC(), seq);
DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n", tid,
instruction->staticInst->
disassemble(thisPC.instAddr()));
#if TRACING_ON
if (trace) {
instruction->traceData =
cpu->getTracer()->getInstRecord(curTick(), cpu->tcBase(tid),
instruction->staticInst, thisPC, curMacroop);
}
#else
instruction->traceData = NULL;
#endif
// Add instruction to the CPU's list of instructions.
instruction->setInstListIt(cpu->addInst(instruction));
// Write the instruction to the first slot in the queue
// that heads to decode.
assert(numInst < fetchWidth);
fetchQueue[tid].push_back(instruction);
assert(fetchQueue[tid].size() <= fetchQueueSize);
DPRINTF(Fetch, "[tid:%i]: Fetch queue entry created (%i/%i).\n",
tid, fetchQueue[tid].size(), fetchQueueSize);
//toDecode->insts[toDecode->size++] = instruction;
// Keep track of if we can take an interrupt at this boundary
delayedCommit[tid] = instruction->isDelayedCommit();
return instruction;
}
template<class Impl>
void
DefaultFetch<Impl>::fetch(bool &status_change)
{
//////////////////////////////////////////
// Start actual fetch
//////////////////////////////////////////
ThreadID tid = getFetchingThread(fetchPolicy);
assert(!cpu->switchedOut());
if (tid == InvalidThreadID) {
// Breaks looping condition in tick()
threadFetched = numFetchingThreads;
if (numThreads == 1) { // @todo Per-thread stats
profileStall(0);
}
return;
}
DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
// The current PC.
TheISA::PCState thisPC = pc[tid];
Addr pcOffset = fetchOffset[tid];
Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
bool inRom = isRomMicroPC(thisPC.microPC());
// If returning from the delay of a cache miss, then update the status
// to running, otherwise do the cache access. Possibly move this up
// to tick() function.
if (fetchStatus[tid] == IcacheAccessComplete) {
DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n", tid);
fetchStatus[tid] = Running;
status_change = true;
} else if (fetchStatus[tid] == Running) {
// Align the fetch PC so its at the start of a fetch buffer segment.
Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr);
// If buffer is no longer valid or fetchAddr has moved to point
// to the next cache block, AND we have no remaining ucode
// from a macro-op, then start fetch from icache.
if (!(fetchBufferValid[tid] && fetchBufferBlockPC == fetchBufferPC[tid])
&& !inRom && !macroop[tid]) {
DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
"instruction, starting at PC %s.\n", tid, thisPC);
fetchCacheLine(fetchAddr, tid, thisPC.instAddr());
if (fetchStatus[tid] == IcacheWaitResponse)
++icacheStallCycles;
else if (fetchStatus[tid] == ItlbWait)
++fetchTlbCycles;
else
++fetchMiscStallCycles;
return;
} else if ((checkInterrupt(thisPC.instAddr()) && !delayedCommit[tid])) {
// Stall CPU if an interrupt is posted and we're not issuing
// an delayed commit micro-op currently (delayed commit instructions
// are not interruptable by interrupts, only faults)
++fetchMiscStallCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is stalled!\n", tid);
return;
}
} else {
if (fetchStatus[tid] == Idle) {
++fetchIdleCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid);
}
// Status is Idle, so fetch should do nothing.
return;
}
++fetchCycles;
TheISA::PCState nextPC = thisPC;
StaticInstPtr staticInst = NULL;
StaticInstPtr curMacroop = macroop[tid];
// If the read of the first instruction was successful, then grab the
// instructions from the rest of the cache line and put them into the
// queue heading to decode.
DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
"decode.\n", tid);
// Need to keep track of whether or not a predicted branch
// ended this fetch block.
bool predictedBranch = false;
// Need to halt fetch if quiesce instruction detected
bool quiesce = false;
TheISA::MachInst *cacheInsts =
reinterpret_cast<TheISA::MachInst *>(fetchBuffer[tid]);
const unsigned numInsts = fetchBufferSize / instSize;
unsigned blkOffset = (fetchAddr - fetchBufferPC[tid]) / instSize;
// Loop through instruction memory from the cache.
// Keep issuing while fetchWidth is available and branch is not
// predicted taken
while (numInst < fetchWidth && fetchQueue[tid].size() < fetchQueueSize
&& !predictedBranch && !quiesce) {
// We need to process more memory if we aren't going to get a
// StaticInst from the rom, the current macroop, or what's already
// in the decoder.
bool needMem = !inRom && !curMacroop &&
!decoder[tid]->instReady();
fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr);
if (needMem) {
// If buffer is no longer valid or fetchAddr has moved to point
// to the next cache block then start fetch from icache.
if (!fetchBufferValid[tid] ||
fetchBufferBlockPC != fetchBufferPC[tid])
break;
if (blkOffset >= numInsts) {
// We need to process more memory, but we've run out of the
// current block.
break;
}
if (ISA_HAS_DELAY_SLOT && pcOffset == 0) {
// Walk past any annulled delay slot instructions.
Addr pcAddr = thisPC.instAddr() & BaseCPU::PCMask;
while (fetchAddr != pcAddr && blkOffset < numInsts) {
blkOffset++;
fetchAddr += instSize;
}
if (blkOffset >= numInsts)
break;
}
MachInst inst = TheISA::gtoh(cacheInsts[blkOffset]);
decoder[tid]->moreBytes(thisPC, fetchAddr, inst);
if (decoder[tid]->needMoreBytes()) {
blkOffset++;
fetchAddr += instSize;
pcOffset += instSize;
}
}
// Extract as many instructions and/or microops as we can from
// the memory we've processed so far.
do {
if (!(curMacroop || inRom)) {
if (decoder[tid]->instReady()) {
staticInst = decoder[tid]->decode(thisPC);
// Increment stat of fetched instructions.
++fetchedInsts;
if (staticInst->isMacroop()) {
curMacroop = staticInst;
} else {
pcOffset = 0;
}
} else {
// We need more bytes for this instruction so blkOffset and
// pcOffset will be updated
break;
}
}
// Whether we're moving to a new macroop because we're at the
// end of the current one, or the branch predictor incorrectly
// thinks we are...
bool newMacro = false;
if (curMacroop || inRom) {
if (inRom) {
staticInst = cpu->microcodeRom.fetchMicroop(
thisPC.microPC(), curMacroop);
} else {
staticInst = curMacroop->fetchMicroop(thisPC.microPC());
}
newMacro |= staticInst->isLastMicroop();
}
DynInstPtr instruction =
buildInst(tid, staticInst, curMacroop,
thisPC, nextPC, true);
ppFetch->notify(instruction);
numInst++;
#if TRACING_ON
if (DTRACE(O3PipeView)) {
instruction->fetchTick = curTick();
}
#endif
nextPC = thisPC;
// If we're branching after this instruction, quit fetching
// from the same block.
predictedBranch |= thisPC.branching();
predictedBranch |=
lookupAndUpdateNextPC(instruction, nextPC);
if (predictedBranch) {
DPRINTF(Fetch, "Branch detected with PC = %s\n", thisPC);
}
newMacro |= thisPC.instAddr() != nextPC.instAddr();
// Move to the next instruction, unless we have a branch.
thisPC = nextPC;
inRom = isRomMicroPC(thisPC.microPC());
if (newMacro) {
fetchAddr = thisPC.instAddr() & BaseCPU::PCMask;
blkOffset = (fetchAddr - fetchBufferPC[tid]) / instSize;
pcOffset = 0;
curMacroop = NULL;
}
if (instruction->isQuiesce()) {
DPRINTF(Fetch,
"Quiesce instruction encountered, halting fetch!\n");
fetchStatus[tid] = QuiescePending;
status_change = true;
quiesce = true;
break;
}
} while ((curMacroop || decoder[tid]->instReady()) &&
numInst < fetchWidth &&
fetchQueue[tid].size() < fetchQueueSize);
// Re-evaluate whether the next instruction to fetch is in micro-op ROM
// or not.
inRom = isRomMicroPC(thisPC.microPC());
}
if (predictedBranch) {
DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
"instruction encountered.\n", tid);
} else if (numInst >= fetchWidth) {
DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
"for this cycle.\n", tid);
} else if (blkOffset >= fetchBufferSize) {
DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of the"
"fetch buffer.\n", tid);
}
macroop[tid] = curMacroop;
fetchOffset[tid] = pcOffset;
if (numInst > 0) {
wroteToTimeBuffer = true;
}
pc[tid] = thisPC;
// pipeline a fetch if we're crossing a fetch buffer boundary and not in
// a state that would preclude fetching
fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr);
issuePipelinedIfetch[tid] = fetchBufferBlockPC != fetchBufferPC[tid] &&
fetchStatus[tid] != IcacheWaitResponse &&
fetchStatus[tid] != ItlbWait &&
fetchStatus[tid] != IcacheWaitRetry &&
fetchStatus[tid] != QuiescePending &&
!curMacroop;
}
template<class Impl>
void
DefaultFetch<Impl>::recvReqRetry()
{
if (retryPkt != NULL) {
assert(cacheBlocked);
assert(retryTid != InvalidThreadID);
assert(fetchStatus[retryTid] == IcacheWaitRetry);
if (cpu->getInstPort().sendTimingReq(retryPkt)) {
fetchStatus[retryTid] = IcacheWaitResponse;
// Notify Fetch Request probe when a retryPkt is successfully sent.
// Note that notify must be called before retryPkt is set to NULL.
ppFetchRequestSent->notify(retryPkt->req);
retryPkt = NULL;
retryTid = InvalidThreadID;
cacheBlocked = false;
}
} else {
assert(retryTid == InvalidThreadID);
// Access has been squashed since it was sent out. Just clear
// the cache being blocked.
cacheBlocked = false;
}
}
///////////////////////////////////////
// //
// SMT FETCH POLICY MAINTAINED HERE //
// //
///////////////////////////////////////
template<class Impl>
ThreadID
DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
{
if (numThreads > 1) {
switch (fetch_priority) {
case SingleThread:
return 0;
case RoundRobin:
return roundRobin();
case IQ:
return iqCount();
case LSQ:
return lsqCount();
case Branch:
return branchCount();
default:
return InvalidThreadID;
}
} else {
list<ThreadID>::iterator thread = activeThreads->begin();
if (thread == activeThreads->end()) {
return InvalidThreadID;
}
ThreadID tid = *thread;
if (fetchStatus[tid] == Running ||
fetchStatus[tid] == IcacheAccessComplete ||
fetchStatus[tid] == Idle) {
return tid;
} else {
return InvalidThreadID;
}
}
}
template<class Impl>
ThreadID
DefaultFetch<Impl>::roundRobin()
{
list<ThreadID>::iterator pri_iter = priorityList.begin();
list<ThreadID>::iterator end = priorityList.end();
ThreadID high_pri;
while (pri_iter != end) {
high_pri = *pri_iter;
assert(high_pri <= numThreads);
if (fetchStatus[high_pri] == Running ||
fetchStatus[high_pri] == IcacheAccessComplete ||
fetchStatus[high_pri] == Idle) {
priorityList.erase(pri_iter);
priorityList.push_back(high_pri);
return high_pri;
}
pri_iter++;
}
return InvalidThreadID;
}
template<class Impl>
ThreadID
DefaultFetch<Impl>::iqCount()
{
//sorted from lowest->highest
std::priority_queue<unsigned,vector<unsigned>,
std::greater<unsigned> > PQ;
std::map<unsigned, ThreadID> threadMap;
list<ThreadID>::iterator threads = activeThreads->begin();
list<ThreadID>::iterator end = activeThreads->end();
while (threads != end) {
ThreadID tid = *threads++;
unsigned iqCount = fromIEW->iewInfo[tid].iqCount;
//we can potentially get tid collisions if two threads
//have the same iqCount, but this should be rare.
PQ.push(iqCount);
threadMap[iqCount] = tid;
}
while (!PQ.empty()) {
ThreadID high_pri = threadMap[PQ.top()];
if (fetchStatus[high_pri] == Running ||
fetchStatus[high_pri] == IcacheAccessComplete ||
fetchStatus[high_pri] == Idle)
return high_pri;
else
PQ.pop();
}
return InvalidThreadID;
}
template<class Impl>
ThreadID
DefaultFetch<Impl>::lsqCount()
{
//sorted from lowest->highest
std::priority_queue<unsigned,vector<unsigned>,
std::greater<unsigned> > PQ;
std::map<unsigned, ThreadID> threadMap;
list<ThreadID>::iterator threads = activeThreads->begin();
list<ThreadID>::iterator end = activeThreads->end();
while (threads != end) {
ThreadID tid = *threads++;
unsigned ldstqCount = fromIEW->iewInfo[tid].ldstqCount;
//we can potentially get tid collisions if two threads
//have the same iqCount, but this should be rare.
PQ.push(ldstqCount);
threadMap[ldstqCount] = tid;
}
while (!PQ.empty()) {
ThreadID high_pri = threadMap[PQ.top()];
if (fetchStatus[high_pri] == Running ||
fetchStatus[high_pri] == IcacheAccessComplete ||
fetchStatus[high_pri] == Idle)
return high_pri;
else
PQ.pop();
}
return InvalidThreadID;
}
template<class Impl>
ThreadID
DefaultFetch<Impl>::branchCount()
{
#if 0
list<ThreadID>::iterator thread = activeThreads->begin();
assert(thread != activeThreads->end());
ThreadID tid = *thread;
#endif
panic("Branch Count Fetch policy unimplemented\n");
return InvalidThreadID;
}
template<class Impl>
void
DefaultFetch<Impl>::pipelineIcacheAccesses(ThreadID tid)
{
if (!issuePipelinedIfetch[tid]) {
return;
}
// The next PC to access.
TheISA::PCState thisPC = pc[tid];
if (isRomMicroPC(thisPC.microPC())) {
return;
}
Addr pcOffset = fetchOffset[tid];
Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
// Align the fetch PC so its at the start of a fetch buffer segment.
Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr);
// Unless buffer already got the block, fetch it from icache.
if (!(fetchBufferValid[tid] && fetchBufferBlockPC == fetchBufferPC[tid])) {
DPRINTF(Fetch, "[tid:%i]: Issuing a pipelined I-cache access, "
"starting at PC %s.\n", tid, thisPC);
fetchCacheLine(fetchAddr, tid, thisPC.instAddr());
}
}
template<class Impl>
void
DefaultFetch<Impl>::profileStall(ThreadID tid) {
DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
// @todo Per-thread stats
if (stalls[tid].drain) {
++fetchPendingDrainCycles;
DPRINTF(Fetch, "Fetch is waiting for a drain!\n");
} else if (activeThreads->empty()) {
++fetchNoActiveThreadStallCycles;
DPRINTF(Fetch, "Fetch has no active thread!\n");
} else if (fetchStatus[tid] == Blocked) {
++fetchBlockedCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
} else if (fetchStatus[tid] == Squashing) {
++fetchSquashCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
} else if (fetchStatus[tid] == IcacheWaitResponse) {
++icacheStallCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n",
tid);
} else if (fetchStatus[tid] == ItlbWait) {
++fetchTlbCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is waiting ITLB walk to "
"finish!\n", tid);
} else if (fetchStatus[tid] == TrapPending) {
++fetchPendingTrapStallCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending trap!\n",
tid);
} else if (fetchStatus[tid] == QuiescePending) {
++fetchPendingQuiesceStallCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending quiesce "
"instruction!\n", tid);
} else if (fetchStatus[tid] == IcacheWaitRetry) {
++fetchIcacheWaitRetryStallCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for an I-cache retry!\n",
tid);
} else if (fetchStatus[tid] == NoGoodAddr) {
DPRINTF(Fetch, "[tid:%i]: Fetch predicted non-executable address\n",
tid);
} else {
DPRINTF(Fetch, "[tid:%i]: Unexpected fetch stall reason (Status: %i).\n",
tid, fetchStatus[tid]);
}
}
#endif//__CPU_O3_FETCH_IMPL_HH__
| BellScurry/gem5-fault-injection | src/cpu/o3/fetch_impl.hh | C++ | bsd-3-clause | 54,320 |
/*
* Copyright (c) 2001-2005 The Regents of The University of Michigan
* Copyright (c) 2010 Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
* Nathan Binkert
*/
#include <cassert>
#include "base/callback.hh"
#include "base/inifile.hh"
#include "base/match.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "base/types.hh"
#include "debug/Checkpoint.hh"
#include "sim/probe/probe.hh"
#include "sim/sim_object.hh"
#include "sim/stats.hh"
using namespace std;
////////////////////////////////////////////////////////////////////////
//
// SimObject member definitions
//
////////////////////////////////////////////////////////////////////////
//
// static list of all SimObjects, used for initialization etc.
//
SimObject::SimObjectList SimObject::simObjectList;
//
// SimObject constructor: used to maintain static simObjectList
//
SimObject::SimObject(const Params *p)
: EventManager(getEventQueue(p->eventq_index)), _params(p)
{
#ifdef DEBUG
doDebugBreak = false;
#endif
simObjectList.push_back(this);
probeManager = new ProbeManager(this);
}
void
SimObject::init()
{
}
void
SimObject::loadState(Checkpoint *cp)
{
if (cp->sectionExists(name())) {
DPRINTF(Checkpoint, "unserializing\n");
unserialize(cp, name());
} else {
DPRINTF(Checkpoint, "no checkpoint section found\n");
}
}
void
SimObject::initState()
{
}
void
SimObject::startup()
{
}
//
// no default statistics, so nothing to do in base implementation
//
void
SimObject::regStats()
{
}
void
SimObject::resetStats()
{
}
/**
* No probe points by default, so do nothing in base.
*/
void
SimObject::regProbePoints()
{
}
/**
* No probe listeners by default, so do nothing in base.
*/
void
SimObject::regProbeListeners()
{
}
ProbeManager *
SimObject::getProbeManager()
{
return probeManager;
}
//
// static function: serialize all SimObjects.
//
void
SimObject::serializeAll(std::ostream &os)
{
SimObjectList::reverse_iterator ri = simObjectList.rbegin();
SimObjectList::reverse_iterator rend = simObjectList.rend();
for (; ri != rend; ++ri) {
SimObject *obj = *ri;
obj->nameOut(os);
obj->serialize(os);
}
}
#ifdef DEBUG
//
// static function: flag which objects should have the debugger break
//
void
SimObject::debugObjectBreak(const string &objs)
{
SimObjectList::const_iterator i = simObjectList.begin();
SimObjectList::const_iterator end = simObjectList.end();
ObjectMatch match(objs);
for (; i != end; ++i) {
SimObject *obj = *i;
obj->doDebugBreak = match.match(obj->name());
}
}
void
debugObjectBreak(const char *objs)
{
SimObject::debugObjectBreak(string(objs));
}
#endif
unsigned int
SimObject::drain(DrainManager *drain_manager)
{
setDrainState(Drained);
return 0;
}
SimObject *
SimObject::find(const char *name)
{
SimObjectList::const_iterator i = simObjectList.begin();
SimObjectList::const_iterator end = simObjectList.end();
for (; i != end; ++i) {
SimObject *obj = *i;
if (obj->name() == name)
return obj;
}
return NULL;
}
| bxshi/gem5 | src/sim/sim_object.cc | C++ | bsd-3-clause | 4,656 |
<?php
/**
* @package yii2-grid
* @author Kartik Visweswaran <kartikv2@gmail.com>
* @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
* @version 3.0.8
*/
namespace kartik\grid;
use kartik\base\AssetBundle;
/**
* Asset bundle for GridView Widget (for exporting content)
*
* @author Kartik Visweswaran <kartikv2@gmail.com>
* @since 1.0
*/
class GridExportAsset extends AssetBundle
{
/**
* @inheritdoc
*/
public function init()
{
$this->setSourcePath(__DIR__ . '/assets');
$this->setupAssets('js', ['js/kv-grid-export']);
parent::init();
}
}
| hucongyang/yii | vendor/kartik-v/yii2-grid/GridExportAsset.php | PHP | bsd-3-clause | 631 |
#include <walle/sys/wallesys.h>
using namespace std;
/// Web Application Library namaspace
namespace walle {
namespace sys {
bool Filesystem::fileExist( const string &file ) {
if ( ::access(file.c_str(),F_OK) == 0 )
return true;
else
return false;
}
bool Filesystem::isLink( const string &file ) {
struct stat statbuf;
if( ::lstat(file.c_str(),&statbuf) == 0 ) {
if ( S_ISLNK(statbuf.st_mode) != 0 )
return true;
}
return false;
}
bool Filesystem::isDir( const string &file ) {
struct stat statbuf;
if( ::stat(file.c_str(),&statbuf) == 0 ) {
if ( S_ISDIR(statbuf.st_mode) != 0 )
return true;
}
return false;
}
bool Filesystem::mkLink( const string &srcfile, const string &destfile ) {
if ( ::symlink(srcfile.c_str(),destfile.c_str()) == 0 )
return true;
else
return false;
}
bool Filesystem::link(const string &srcfile, const string &destfile)
{
if ( ::link(srcfile.c_str(),destfile.c_str()) == 0 )
return true;
else
return false;
}
size_t Filesystem::fileSize( const string &file ) {
struct stat statbuf;
if( stat(file.c_str(),&statbuf)==0 )
return statbuf.st_size;
else
return -1;
}
time_t Filesystem::fileTime( const string &file ) {
struct stat statbuf;
if( stat(file.c_str(),&statbuf)==0 )
return statbuf.st_mtime;
else
return -1;
}
string Filesystem::filePath( const string &file ) {
size_t p;
if ( (p=file.rfind("/")) != file.npos )
return file.substr( 0, p );
return string( "" );
}
string Filesystem::fileName( const string &file ) {
size_t p;
if ( (p=file.rfind("/")) != file.npos )
return file.substr( p+1 );
return file;
}
bool Filesystem::renameFile( const string &oldname, const string &newname ) {
if ( ::rename(oldname.c_str(),newname.c_str()) != -1 )
return true;
else
return false;
}
bool Filesystem::copyFile( const string &srcfile, const string &destfile ) {
FILE *src=NULL, *dest=NULL;
if ( (src=fopen(srcfile.c_str(),"rb")) == NULL ) {
return false;
}
if ( (dest=fopen(destfile.c_str(),"wb+")) == NULL ) {
fclose( src );
return false;
}
const int bufsize = 8192;
char buf[bufsize];
size_t n;
while ( (n=fread(buf,1,bufsize,src)) >= 1 ) {
if ( fwrite(buf,1,n,dest) != n ) {
fclose( src );
fclose( dest );
return false;
}
}
fclose( src );
fclose( dest );
//chmod to 0666
mode_t mask = umask( 0 );
chmod( destfile.c_str(), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH );
umask( mask );
return true;
}
bool Filesystem::deleteFile( const string &file ) {
if ( ::remove(file.c_str()) == 0 )
return true;
else
return false;
}
bool Filesystem::moveFile( const string &srcfile, const string &destfile ) {
if ( renameFile(srcfile,destfile) )
return true;
// rename fail, copy and delete file
if ( copyFile(srcfile,destfile) ) {
if ( deleteFile(srcfile) )
return true;
}
return false;
}
vector<string> Filesystem::dirFiles( const string &dir ) {
vector<string> files;
string file;
DIR *pdir = NULL;
dirent *pdirent = NULL;
if ( (pdir = ::opendir(dir.c_str())) != NULL ) {
while ( (pdirent=readdir(pdir)) != NULL ) {
file = pdirent->d_name;
if ( file!="." && file!=".." ) {
if ( isDir(dir+"/"+file) )
file = "/"+file;
files.push_back( file );
}
}
::closedir( pdir );
}
return files;
}
bool Filesystem::makeDir( const string &dir, const mode_t mode ) {
// check
size_t len = dir.length();
if ( len <= 0 ) return false;
string tomake;
char curchr;
for( size_t i=0; i<len; ++i ) {
// append
curchr = dir[i];
tomake += curchr;
if ( curchr=='/' || i==(len-1) ) {
// need to mkdir
if ( !fileExist(tomake) && !isDir(tomake) ) {
// able to mkdir
mode_t mask = umask( 0 );
if ( mkdir(tomake.c_str(),mode) == -1 ) {
umask( mask );
return false;
}
umask( mask );
}
}
}
return true;
}
bool Filesystem::copyDir( const string &srcdir, const string &destdir ) {
vector<string> files = dirFiles( srcdir );
string from;
string to;
if ( !fileExist(destdir) )
makeDir( destdir );
for ( size_t i=0; i<files.size(); ++i ) {
from = srcdir + "/" + files[i];
to = destdir + "/" + files[i];
if ( files[i][0] == '/' ) {
if ( !copyDir(from,to) )
return false;
}
else if ( !copyFile(from,to) )
return false;
}
return true;
}
bool Filesystem::deleteDir( const string &dir ) {
vector<string> files = dirFiles( dir );
string todel;
// ɾ³ýÎļþ
for ( size_t i=0; i<files.size(); ++i ) {
todel = dir + "/" + files[i];
// ×ÓĿ¼,µÝ¹éµ÷ÓÃ
if ( files[i][0] == '/' ) {
if ( !deleteDir(todel) )
return false;
}
// Îļþ
else if ( !deleteFile(todel) )
return false;
}
// ɾ³ýĿ¼
if ( rmdir(dir.c_str()) == 0 )
return true;
return false;
}
bool Filesystem::moveDir( const string &srcdir, const string &destdir ) {
if ( renameFile(srcdir,destdir) )
return true;
// rename fail, copy and delete dir
if ( copyDir(srcdir,destdir) ) {
if (deleteDir(srcdir) )
return true;
}
return false;
}
}
} // namespace
| lilothar/walle-c11 | walle/sys/Filesystem.cpp | C++ | bsd-3-clause | 5,052 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/test/integration/bookmarks_helper.h"
#include "chrome/browser/sync/test/integration/sync_integration_test_util.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "sync/test/fake_server/bookmark_entity_builder.h"
#include "sync/test/fake_server/entity_builder_factory.h"
#include "sync/test/fake_server/fake_server_verifier.h"
#include "ui/base/layout.h"
using bookmarks::BookmarkModel;
using bookmarks::BookmarkNode;
using bookmarks_helper::AddFolder;
using bookmarks_helper::AddURL;
using bookmarks_helper::CountBookmarksWithTitlesMatching;
using bookmarks_helper::Create1xFaviconFromPNGFile;
using bookmarks_helper::GetBookmarkBarNode;
using bookmarks_helper::GetBookmarkModel;
using bookmarks_helper::GetOtherNode;
using bookmarks_helper::ModelMatchesVerifier;
using bookmarks_helper::Move;
using bookmarks_helper::Remove;
using bookmarks_helper::RemoveAll;
using bookmarks_helper::SetFavicon;
using bookmarks_helper::SetTitle;
using sync_integration_test_util::AwaitCommitActivityCompletion;
class SingleClientBookmarksSyncTest : public SyncTest {
public:
SingleClientBookmarksSyncTest() : SyncTest(SINGLE_CLIENT) {}
~SingleClientBookmarksSyncTest() override {}
// Verify that the local bookmark model (for the Profile corresponding to
// |index|) matches the data on the FakeServer. It is assumed that FakeServer
// is being used and each bookmark has a unique title. Folders are not
// verified.
void VerifyBookmarkModelMatchesFakeServer(int index);
private:
DISALLOW_COPY_AND_ASSIGN(SingleClientBookmarksSyncTest);
};
void SingleClientBookmarksSyncTest::VerifyBookmarkModelMatchesFakeServer(
int index) {
fake_server::FakeServerVerifier fake_server_verifier(GetFakeServer());
std::vector<BookmarkModel::URLAndTitle> local_bookmarks;
GetBookmarkModel(index)->GetBookmarks(&local_bookmarks);
// Verify that the number of local bookmarks matches the number in the
// server.
ASSERT_TRUE(fake_server_verifier.VerifyEntityCountByType(
local_bookmarks.size(),
syncer::BOOKMARKS));
// Verify that all local bookmark titles exist once on the server.
std::vector<BookmarkModel::URLAndTitle>::const_iterator it;
for (it = local_bookmarks.begin(); it != local_bookmarks.end(); ++it) {
ASSERT_TRUE(fake_server_verifier.VerifyEntityCountByTypeAndName(
1,
syncer::BOOKMARKS,
base::UTF16ToUTF8(it->title)));
}
}
IN_PROC_BROWSER_TEST_F(SingleClientBookmarksSyncTest, Sanity) {
ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";
// Starting state:
// other_node
// -> top
// -> tier1_a
// -> http://mail.google.com "tier1_a_url0"
// -> http://www.pandora.com "tier1_a_url1"
// -> http://www.facebook.com "tier1_a_url2"
// -> tier1_b
// -> http://www.nhl.com "tier1_b_url0"
const BookmarkNode* top = AddFolder(0, GetOtherNode(0), 0, "top");
const BookmarkNode* tier1_a = AddFolder(0, top, 0, "tier1_a");
const BookmarkNode* tier1_b = AddFolder(0, top, 1, "tier1_b");
const BookmarkNode* tier1_a_url0 = AddURL(
0, tier1_a, 0, "tier1_a_url0", GURL("http://mail.google.com"));
const BookmarkNode* tier1_a_url1 = AddURL(
0, tier1_a, 1, "tier1_a_url1", GURL("http://www.pandora.com"));
const BookmarkNode* tier1_a_url2 = AddURL(
0, tier1_a, 2, "tier1_a_url2", GURL("http://www.facebook.com"));
const BookmarkNode* tier1_b_url0 = AddURL(
0, tier1_b, 0, "tier1_b_url0", GURL("http://www.nhl.com"));
// Setup sync, wait for its completion, and make sure changes were synced.
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
// Ultimately we want to end up with the following model; but this test is
// more about the journey than the destination.
//
// bookmark_bar
// -> CNN (www.cnn.com)
// -> tier1_a
// -> tier1_a_url2 (www.facebook.com)
// -> tier1_a_url1 (www.pandora.com)
// -> Porsche (www.porsche.com)
// -> Bank of America (www.bankofamerica.com)
// -> Seattle Bubble
// other_node
// -> top
// -> tier1_b
// -> Wired News (www.wired.com)
// -> tier2_b
// -> tier1_b_url0
// -> tier3_b
// -> Toronto Maple Leafs (mapleleafs.nhl.com)
// -> Wynn (www.wynnlasvegas.com)
// -> tier1_a_url0
const BookmarkNode* bar = GetBookmarkBarNode(0);
const BookmarkNode* cnn = AddURL(0, bar, 0, "CNN",
GURL("http://www.cnn.com"));
ASSERT_TRUE(cnn != NULL);
Move(0, tier1_a, bar, 1);
// Wait for the bookmark position change to sync.
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
const BookmarkNode* porsche = AddURL(0, bar, 2, "Porsche",
GURL("http://www.porsche.com"));
// Rearrange stuff in tier1_a.
ASSERT_EQ(tier1_a, tier1_a_url2->parent());
ASSERT_EQ(tier1_a, tier1_a_url1->parent());
Move(0, tier1_a_url2, tier1_a, 0);
Move(0, tier1_a_url1, tier1_a, 2);
// Wait for the rearranged hierarchy to sync.
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
ASSERT_EQ(1, tier1_a_url0->parent()->GetIndexOf(tier1_a_url0));
Move(0, tier1_a_url0, bar, bar->child_count());
const BookmarkNode* boa = AddURL(0, bar, bar->child_count(),
"Bank of America", GURL("https://www.bankofamerica.com"));
ASSERT_TRUE(boa != NULL);
Move(0, tier1_a_url0, top, top->child_count());
const BookmarkNode* bubble = AddURL(
0, bar, bar->child_count(), "Seattle Bubble",
GURL("http://seattlebubble.com"));
ASSERT_TRUE(bubble != NULL);
const BookmarkNode* wired = AddURL(0, bar, 2, "Wired News",
GURL("http://www.wired.com"));
const BookmarkNode* tier2_b = AddFolder(
0, tier1_b, 0, "tier2_b");
Move(0, tier1_b_url0, tier2_b, 0);
Move(0, porsche, bar, 0);
SetTitle(0, wired, "News Wired");
SetTitle(0, porsche, "ICanHazPorsche?");
// Wait for the title change to sync.
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
ASSERT_EQ(tier1_a_url0->id(), top->GetChild(top->child_count() - 1)->id());
Remove(0, top, top->child_count() - 1);
Move(0, wired, tier1_b, 0);
Move(0, porsche, bar, 3);
const BookmarkNode* tier3_b = AddFolder(0, tier2_b, 1, "tier3_b");
const BookmarkNode* leafs = AddURL(
0, tier1_a, 0, "Toronto Maple Leafs", GURL("http://mapleleafs.nhl.com"));
const BookmarkNode* wynn = AddURL(0, bar, 1, "Wynn",
GURL("http://www.wynnlasvegas.com"));
Move(0, wynn, tier3_b, 0);
Move(0, leafs, tier3_b, 0);
// Wait for newly added bookmarks to sync.
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
// Only verify FakeServer data if FakeServer is being used.
// TODO(pvalenzuela): Use this style of verification in more tests once it is
// proven stable.
if (GetFakeServer())
VerifyBookmarkModelMatchesFakeServer(0);
}
IN_PROC_BROWSER_TEST_F(SingleClientBookmarksSyncTest, InjectedBookmark) {
std::string title = "Montreal Canadiens";
fake_server::EntityBuilderFactory entity_builder_factory;
scoped_ptr<fake_server::FakeServerEntity> entity =
entity_builder_factory.NewBookmarkEntityBuilder(
title, GURL("http://canadiens.nhl.com")).Build();
fake_server_->InjectEntity(entity.Pass());
DisableVerifier();
ASSERT_TRUE(SetupClients());
ASSERT_TRUE(SetupSync());
ASSERT_EQ(1, CountBookmarksWithTitlesMatching(0, title));
}
// Test that a client doesn't mutate the favicon data in the process
// of storing the favicon data from sync to the database or in the process
// of requesting data from the database for sync.
IN_PROC_BROWSER_TEST_F(SingleClientBookmarksSyncTest,
SetFaviconHiDPIDifferentCodec) {
// Set the supported scale factors to 1x and 2x such that
// BookmarkModel::GetFavicon() requests both 1x and 2x.
// 1x -> for sync, 2x -> for the UI.
std::vector<ui::ScaleFactor> supported_scale_factors;
supported_scale_factors.push_back(ui::SCALE_FACTOR_100P);
supported_scale_factors.push_back(ui::SCALE_FACTOR_200P);
ui::SetSupportedScaleFactors(supported_scale_factors);
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
ASSERT_TRUE(ModelMatchesVerifier(0));
const GURL page_url("http://www.google.com");
const GURL icon_url("http://www.google.com/favicon.ico");
const BookmarkNode* bookmark = AddURL(0, "title", page_url);
// Simulate receiving a favicon from sync encoded by a different PNG encoder
// than the one native to the OS. This tests the PNG data is not decoded to
// SkBitmap (or any other image format) then encoded back to PNG on the path
// between sync and the database.
gfx::Image original_favicon = Create1xFaviconFromPNGFile(
"favicon_cocoa_png_codec.png");
ASSERT_FALSE(original_favicon.IsEmpty());
SetFavicon(0, bookmark, icon_url, original_favicon,
bookmarks_helper::FROM_SYNC);
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
scoped_refptr<base::RefCountedMemory> original_favicon_bytes =
original_favicon.As1xPNGBytes();
gfx::Image final_favicon = GetBookmarkModel(0)->GetFavicon(bookmark);
scoped_refptr<base::RefCountedMemory> final_favicon_bytes =
final_favicon.As1xPNGBytes();
// Check that the data was not mutated from the original.
EXPECT_TRUE(original_favicon_bytes.get());
EXPECT_TRUE(original_favicon_bytes->Equals(final_favicon_bytes));
}
IN_PROC_BROWSER_TEST_F(SingleClientBookmarksSyncTest,
BookmarkAllNodesRemovedEvent) {
ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";
// Starting state:
// other_node
// -> folder0
// -> tier1_a
// -> http://mail.google.com
// -> http://www.google.com
// -> http://news.google.com
// -> http://yahoo.com
// -> http://www.cnn.com
// bookmark_bar
// -> empty_folder
// -> folder1
// -> http://yahoo.com
// -> http://gmail.com
const BookmarkNode* folder0 = AddFolder(0, GetOtherNode(0), 0, "folder0");
const BookmarkNode* tier1_a = AddFolder(0, folder0, 0, "tier1_a");
ASSERT_TRUE(AddURL(0, folder0, 1, "News", GURL("http://news.google.com")));
ASSERT_TRUE(AddURL(0, folder0, 2, "Yahoo", GURL("http://www.yahoo.com")));
ASSERT_TRUE(AddURL(0, tier1_a, 0, "Gmai", GURL("http://mail.google.com")));
ASSERT_TRUE(AddURL(0, tier1_a, 1, "Google", GURL("http://www.google.com")));
ASSERT_TRUE(
AddURL(0, GetOtherNode(0), 1, "CNN", GURL("http://www.cnn.com")));
ASSERT_TRUE(AddFolder(0, GetBookmarkBarNode(0), 0, "empty_folder"));
const BookmarkNode* folder1 =
AddFolder(0, GetBookmarkBarNode(0), 1, "folder1");
ASSERT_TRUE(AddURL(0, folder1, 0, "Yahoo", GURL("http://www.yahoo.com")));
ASSERT_TRUE(
AddURL(0, GetBookmarkBarNode(0), 2, "Gmai", GURL("http://gmail.com")));
// Set up sync, wait for its completion and verify that changes propagated.
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
// Remove all bookmarks and wait for sync completion.
RemoveAll(0);
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
// Verify other node has no children now.
EXPECT_EQ(0, GetOtherNode(0)->child_count());
EXPECT_EQ(0, GetBookmarkBarNode(0)->child_count());
// Verify model matches verifier.
ASSERT_TRUE(ModelMatchesVerifier(0));
}
| sgraham/nope | chrome/browser/sync/test/integration/single_client_bookmarks_sync_test.cc | C++ | bsd-3-clause | 12,107 |
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utilities to process compresssed files."""
import contextlib
import logging
import os
import pathlib
import re
import shutil
import struct
import tempfile
import zipfile
class _ApkFileManager:
def __init__(self, temp_dir):
self._temp_dir = pathlib.Path(temp_dir)
self._subdir_by_apks_path = {}
self._infolist_by_path = {}
def _MapPath(self, path):
# Use numbered subdirectories for uniqueness.
# Suffix with basename(path) for readability.
default = '-'.join(
[str(len(self._subdir_by_apks_path)),
os.path.basename(path)])
return self._temp_dir / self._subdir_by_apks_path.setdefault(path, default)
def InfoList(self, path):
"""Returns zipfile.ZipFile(path).infolist()."""
ret = self._infolist_by_path.get(path)
if ret is None:
with zipfile.ZipFile(path) as z:
ret = z.infolist()
self._infolist_by_path[path] = ret
return ret
def SplitPath(self, minimal_apks_path, split_name):
"""Returns the path to the apk split extracted by ExtractSplits.
Args:
minimal_apks_path: The .apks file that was passed to ExtractSplits().
split_name: Then name of the split.
Returns:
Path to the extracted .apk file.
"""
subdir = self._subdir_by_apks_path[minimal_apks_path]
return self._temp_dir / subdir / 'splits' / f'{split_name}-master.apk'
def ExtractSplits(self, minimal_apks_path):
"""Extracts the master splits in the given .apks file.
Returns:
List of split names, with "base" always appearing first.
"""
dest = self._MapPath(minimal_apks_path)
split_names = []
logging.debug('Extracting %s', minimal_apks_path)
with zipfile.ZipFile(minimal_apks_path) as z:
for filename in z.namelist():
# E.g.:
# splits/base-master.apk
# splits/base-en.apk
# splits/vr-master.apk
# splits/vr-en.apk
m = re.match(r'splits/(.*)-master\.apk', filename)
if m:
split_names.append(m.group(1))
z.extract(filename, dest)
logging.debug('Extracting %s (done)', minimal_apks_path)
# Make "base" comes first since that's the main chunk of work.
# Also so that --abi-filter detection looks at it first.
return sorted(split_names, key=lambda x: (x != 'base', x))
@contextlib.contextmanager
def ApkFileManager():
"""Context manager that extracts apk splits to a temp dir."""
# Cannot use tempfile.TemporaryDirectory() here because our use of
# multiprocessing results in __del__ methods being called in forked processes.
temp_dir = tempfile.mkdtemp(suffix='-supersize')
zip_files = _ApkFileManager(temp_dir)
yield zip_files
shutil.rmtree(temp_dir)
@contextlib.contextmanager
def UnzipToTemp(zip_path, inner_path):
"""Extract a |inner_path| from a |zip_path| file to an auto-deleted temp file.
Args:
zip_path: Path to the zip file.
inner_path: Path to the file within |zip_path| to extract.
Yields:
The path of the temp created (and auto-deleted when context exits).
"""
try:
logging.debug('Extracting %s', inner_path)
_, suffix = os.path.splitext(inner_path)
# Can't use NamedTemporaryFile() because it deletes via __del__, which will
# trigger in both this and the fork()'ed processes.
fd, temp_file = tempfile.mkstemp(suffix=suffix)
with zipfile.ZipFile(zip_path) as z:
os.write(fd, z.read(inner_path))
os.close(fd)
logging.debug('Extracting %s (done)', inner_path)
yield temp_file
finally:
os.unlink(temp_file)
def ReadZipInfoExtraFieldLength(zip_file, zip_info):
"""Reads the value of |extraLength| from |zip_info|'s local file header.
|zip_info| has an |extra| field, but it's read from the central directory.
Android's zipalign tool sets the extra field only in local file headers.
"""
# Refer to https://en.wikipedia.org/wiki/Zip_(file_format)#File_headers
zip_file.fp.seek(zip_info.header_offset + 28)
return struct.unpack('<H', zip_file.fp.read(2))[0]
def MeasureApkSignatureBlock(zip_file):
"""Measures the size of the v2 / v3 signing block.
Refer to: https://source.android.com/security/apksigning/v2
"""
# Seek to "end of central directory" struct.
eocd_offset_from_end = -22 - len(zip_file.comment)
zip_file.fp.seek(eocd_offset_from_end, os.SEEK_END)
assert zip_file.fp.read(4) == b'PK\005\006', (
'failed to find end-of-central-directory')
# Read out the "start of central directory" offset.
zip_file.fp.seek(eocd_offset_from_end + 16, os.SEEK_END)
start_of_central_directory = struct.unpack('<I', zip_file.fp.read(4))[0]
# Compute the offset after the last zip entry.
last_info = max(zip_file.infolist(), key=lambda i: i.header_offset)
last_header_size = (30 + len(last_info.filename) +
ReadZipInfoExtraFieldLength(zip_file, last_info))
end_of_last_file = (last_info.header_offset + last_header_size +
last_info.compress_size)
return start_of_central_directory - end_of_last_file
| chromium/chromium | tools/binary_size/libsupersize/zip_util.py | Python | bsd-3-clause | 5,188 |
package cucumber.runtime.xstream;
import cucumber.deps.com.thoughtworks.xstream.converters.SingleValueConverter;
import java.util.ArrayList;
import java.util.List;
class ListConverter implements SingleValueConverter {
private final String delimiter;
private final SingleValueConverter delegate;
public ListConverter(String delimiter, SingleValueConverter delegate) {
this.delimiter = delimiter;
this.delegate = delegate;
}
@Override
public String toString(Object obj) {
boolean first = true;
if (obj instanceof List) {
StringBuilder sb = new StringBuilder();
for (Object elem : (List) obj) {
if (!first) {
sb.append(delimiter);
}
sb.append(delegate.toString(elem));
first = false;
}
return sb.toString();
} else {
return delegate.toString(obj);
}
}
@Override
public Object fromString(String s) {
final String[] strings = s.split(delimiter);
List<Object> list = new ArrayList<Object>(strings.length);
for (String elem : strings) {
list.add(delegate.fromString(elem));
}
return list;
}
@Override
public boolean canConvert(Class type) {
return List.class.isAssignableFrom(type);
}
}
| VivaceVivo/cucumber-mod-DI | core/src/main/java/cucumber/runtime/xstream/ListConverter.java | Java | mit | 1,391 |
package com.external.activeandroid.serializer;
/*
* Copyright (C) 2010 Michael Pardo
*
* 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 java.util.Date;
public final class UtilDateSerializer extends TypeSerializer {
public Class<?> getDeserializedType() {
return Date.class;
}
public Class<?> getSerializedType() {
return long.class;
}
public Long serialize(Object data) {
if (data == null) {
return null;
}
return ((Date) data).getTime();
}
public Date deserialize(Object data) {
if (data == null) {
return null;
}
return new Date((Long) data);
}
} | darlk/BeeFramework_Android | src/com/external/activeandroid/serializer/UtilDateSerializer.java | Java | mit | 1,106 |
<?php
namespace Oro\Bundle\TranslationBundle\Tests\Unit\Command;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Oro\Bundle\TranslationBundle\Tests\Unit\Command\Stubs\TestKernel;
use Oro\Bundle\TranslationBundle\Command\OroTranslationPackCommand;
class OroTranslationPackCommandTest extends \PHPUnit_Framework_TestCase
{
public function testConfigure()
{
$kernel = new TestKernel();
$kernel->boot();
$app = new Application($kernel);
$app->add($this->getCommandMock());
$command = $app->find('oro:translation:pack');
$this->assertNotEmpty($command->getDescription());
$this->assertNotEmpty($command->getDefinition());
$this->assertNotEmpty($command->getHelp());
}
/**
* Test command execute
*
* @dataProvider executeInputProvider
*
* @param array $input
* @param array $expectedCalls
* @param bool|string $exception
*/
public function testExecute($input, $expectedCalls = array(), $exception = false)
{
$kernel = new TestKernel();
$kernel->boot();
$app = new Application($kernel);
$commandMock = $this->getCommandMock(array_keys($expectedCalls));
$app->add($commandMock);
$command = $app->find('oro:translation:pack');
$command->setApplication($app);
if ($exception) {
$this->setExpectedException($exception);
}
$transServiceMock = $this->getMockBuilder(
'Oro\Bundle\TranslationBundle\Provider\TranslationServiceProvider'
)
->disableOriginalConstructor()
->getMock();
foreach ($expectedCalls as $method => $count) {
if ($method == 'getTranslationService') {
$commandMock->expects($this->exactly($count))
->method($method)
->will($this->returnValue($transServiceMock));
}
$commandMock->expects($this->exactly($count))->method($method);
}
$tester = new CommandTester($command);
$input += array('command' => $command->getName());
$tester->execute($input);
}
/**
* @return array
*/
public function executeInputProvider()
{
return array(
'error if action not specified' => array(
array('project' => 'SomeProject'),
array(
'dump' => 0,
'upload' => 0
)
),
'error if project not specified' => array(
array('--dump' => true),
array(
'dump' => 0,
'upload' => 0
),
'\RuntimeException'
),
'dump action should perform' => array(
array('--dump' => true, 'project' => 'SomeProject'),
array(
'dump' => 1,
'upload' => 0
),
),
'upload action should perform' => array(
array('--upload' => true, 'project' => 'SomeProject'),
array(
'dump' => 0,
'upload' => 1,
'getTranslationService' => 1,
'getLangPackDir' => 1,
),
),
'dump and upload action should perform' => array(
array('--upload' => true, '--dump' => true, 'project' => 'SomeProject'),
array(
'dump' => 1,
'upload' => 1,
'getTranslationService' => 1,
),
)
);
}
public function testUpload()
{
$this->runUploadDownloadTest('upload');
}
public function testUpdate()
{
$this->runUploadDownloadTest('upload', array('-m' => 'update'));
}
public function testDownload()
{
$this->runUploadDownloadTest('download');
}
public function runUploadDownloadTest($commandName, $args = [])
{
$kernel = new TestKernel();
$kernel->boot();
$projectId = 'someproject';
$adapterMock = $this->getNewMock('Oro\Bundle\TranslationBundle\Provider\CrowdinAdapter');
$adapterMock->expects($this->any())
->method('setProjectId')
->with($projectId);
$uploaderMock = $this->getNewMock('Oro\Bundle\TranslationBundle\Provider\TranslationServiceProvider');
$uploaderMock->expects($this->any())
->method('setAdapter')
->with($adapterMock)
->will($this->returnSelf());
$uploaderMock->expects($this->once())
->method('setLogger')
->with($this->isInstanceOf('Psr\Log\LoggerInterface'))
->will($this->returnSelf());
if (isset($args['-m']) && $args['-m'] == 'update') {
$uploaderMock->expects($this->once())
->method('update');
} else {
$uploaderMock->expects($this->once())
->method($commandName);
}
$kernel->getContainer()->set('oro_translation.uploader.crowdin_adapter', $adapterMock);
$kernel->getContainer()->set('oro_translation.service_provider', $uploaderMock);
$app = new Application($kernel);
$commandMock = $this->getCommandMock();
$app->add($commandMock);
$command = $app->find('oro:translation:pack');
$command->setApplication($app);
$tester = new CommandTester($command);
$input = array('command' => $command->getName(), '--' . $commandName => true, 'project' => $projectId);
if (!empty($args)) {
$input = array_merge($input, $args);
}
$tester->execute($input);
}
public function testExecuteWithoutMode()
{
$kernel = new TestKernel();
$kernel->boot();
$app = new Application($kernel);
$commandMock = $this->getCommandMock();
$app->add($commandMock);
$command = $app->find('oro:translation:pack');
$command->setApplication($app);
$tester = new CommandTester($command);
$input = array('command' => $command->getName(), 'project' => 'test123');
$return = $tester->execute($input);
$this->assertEquals(1, $return);
}
/**
* @return array
*/
public function formatProvider()
{
return array(
'format do not specified, yml default' => array('yml', false),
'format specified xml expected ' => array('xml', 'xml')
);
}
/**
* Prepares command mock
* asText mocked by default in case when we don't need to mock anything
*
* @param array $methods
*
* @return \PHPUnit_Framework_MockObject_MockObject|OroTranslationPackCommand
*/
protected function getCommandMock($methods = array('asText'))
{
$commandMock = $this->getMockBuilder('Oro\Bundle\TranslationBundle\Command\OroTranslationPackCommand')
->setMethods($methods);
return $commandMock->getMock();
}
/**
* @param $class
*
* @return \PHPUnit_Framework_MockObject_MockObject
*/
protected function getNewMock($class)
{
return $this->getMock($class, [], [], '', false);
}
}
| northdakota/platform | src/Oro/Bundle/TranslationBundle/Tests/Unit/Command/OroTranslationPackCommandTest.php | PHP | mit | 7,533 |
class AddSomeIndices < ActiveRecord::Migration
def change
add_index :updates, :created_at
add_index :observations, :created_at
add_index :observations, :observed_on
add_index :identifications, :created_at
end
end
| lucas-ez/inaturalist | db/migrate/20150319205049_add_some_indices.rb | Ruby | mit | 233 |
require File.expand_path('../../test_helper.rb', __FILE__)
require File.expand_path('../freeradius_stats.rb', __FILE__)
class FreeradiusStatsTest < Test::Unit::TestCase
def setup
@options = parse_defaults("freeradius_stats")
end
def teardown
end
def test_clean_run
# Stub the plugin instance where necessary and run
# @plugin=PluginName.new(last_run, memory, options)
# date hash hash
@plugin=FreeradiusStats.new(nil,{},@options)
@plugin.returns(FIXTURES[:stats]).once
res = @plugin.run()
# assertions
assert res[:alerts].empty?
assert res[:errors].empty?
end
def test_alert
@plugin=FreeradiusStats.new(nil,{},@options)
@plugin.returns(FIXTURES[:stats_alert]).once
res = @plugin.run()
# assertions
assert_equal 1, res[:alerts].size
assert res[:errors].empty?
end
FIXTURES=YAML.load(<<-EOS)
:stats: |
Received response ID 230, code 2, length = 140
FreeRADIUS-Total-Access-Requests = 21287
FreeRADIUS-Total-Access-Accepts = 20677
FreeRADIUS-Total-Access-Rejects = 677
FreeRADIUS-Total-Access-Challenges = 0
FreeRADIUS-Total-Auth-Responses = 21354
FreeRADIUS-Total-Auth-Duplicate-Requests = 0
FreeRADIUS-Total-Auth-Malformed-Requests = 0
FreeRADIUS-Total-Auth-Invalid-Requests = 0
FreeRADIUS-Total-Auth-Dropped-Requests = 0
FreeRADIUS-Total-Auth-Unknown-Types = 0
:stats_alert: |
radclient: no response from server for ID 15 socket 3
EOS
end | pingdomserver/scout-plugins | freeradius_stats/test.rb | Ruby | mit | 1,566 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
using Microsoft.DotNet.XUnitExtensions;
namespace System.IO.Ports.Tests
{
public class Read_char_int_int_Generic : PortsTest
{
//Set bounds fore random timeout values.
//If the min is to low read will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
//If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
//If the percentage difference between the expected timeout and the actual timeout
//found through Stopwatch is greater then 10% then the timeout value was not correctly
//to the read method and the testcase fails.
private const double maxPercentageDifference = .15;
//The number of random bytes to receive for parity testing
private const int numRndBytesPairty = 8;
//The number of characters to read at a time for parity testing
private const int numBytesReadPairty = 2;
//The number of random bytes to receive for BytesToRead testing
private const int numRndBytesToRead = 16;
//When we test Read and do not care about actually reading anything we must still
//create an byte array to pass into the method the following is the size of the
//byte array used in this situation
private const int defaultCharArraySize = 1;
private const int NUM_TRYS = 5;
#region Test Cases
[Fact]
public void ReadWithoutOpen()
{
using (SerialPort com = new SerialPort())
{
Debug.WriteLine("Verifying read method throws exception without a call to Open()");
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterFailedOpen()
{
using (SerialPort com = new SerialPort("BAD_PORT_NAME"))
{
Debug.WriteLine("Verifying read method throws exception with a failed call to Open()");
//Since the PortName is set to a bad port name Open will thrown an exception
//however we don't care what it is since we are verifying a read method
Assert.ThrowsAny<Exception>(() => com.Open());
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying read method throws exception after a call to Cloes()");
com.Open();
com.Close();
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort))]
public void Timeout()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout);
com.Open();
VerifyTimeout(com);
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort))]
public void SuccessiveReadTimeoutNoData()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
// com.Encoding = new System.Text.UTF7Encoding();
com.Encoding = Encoding.Unicode;
Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout);
com.Open();
Assert.Throws<TimeoutException>(() => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize));
VerifyTimeout(com);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void SuccessiveReadTimeoutSomeData()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
var t = new Task(WriteToCom1);
com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Encoding = new UTF8Encoding();
Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout);
com1.Open();
//Call WriteToCom1 asynchronously this will write to com1 some time before the following call
//to a read method times out
t.Start();
try
{
com1.Read(new char[defaultCharArraySize], 0, defaultCharArraySize);
}
catch (TimeoutException)
{
}
TCSupport.WaitForTaskCompletion(t);
//Make sure there is no bytes in the buffer so the next call to read will timeout
com1.DiscardInBuffer();
VerifyTimeout(com1);
}
}
private void WriteToCom1()
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] xmitBuffer = new byte[1];
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
//Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.Write(xmitBuffer, 0, xmitBuffer.Length);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DefaultParityReplaceByte()
{
VerifyParityReplaceByte(-1, numRndBytesPairty - 2);
}
[ConditionalFact(nameof(HasNullModem))]
public void NoParityReplaceByte()
{
Random rndGen = new Random(-55);
VerifyParityReplaceByte('\0', rndGen.Next(0, numRndBytesPairty - 1));
}
[ConditionalFact(nameof(HasNullModem))]
public void RNDParityReplaceByte()
{
Random rndGen = new Random(-55);
VerifyParityReplaceByte(rndGen.Next(0, 128), 0);
}
[ConditionalFact(nameof(HasNullModem))]
public void ParityErrorOnLastByte()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(15);
byte[] bytesToWrite = new byte[numRndBytesPairty];
char[] expectedChars = new char[numRndBytesPairty];
char[] actualChars = new char[numRndBytesPairty + 1];
/* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream
We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */
Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte");
//Genrate random characters without an parity error
for (int i = 0; i < bytesToWrite.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 128);
bytesToWrite[i] = randByte;
expectedChars[i] = (char)randByte;
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80);
//Create a parity error on the last byte
expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace;
// Set the last expected char to be the ParityReplace Byte
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.ReadTimeout = 250;
com1.Open();
com2.Open();
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + 1);
com1.Read(actualChars, 0, actualChars.Length);
//Compare the chars that were written with the ones we expected to read
for (int i = 0; i < expectedChars.Length; i++)
{
if (expectedChars[i] != actualChars[i])
{
Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)actualChars[i]);
}
}
if (1 < com1.BytesToRead)
{
Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]);
Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead);
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F);
//Clear the parity error on the last byte
expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1];
VerifyRead(com1, com2, bytesToWrite, expectedChars, expectedChars.Length / 2);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_RND_Buffer_Size()
{
Random rndGen = new Random(-55);
VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead));
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_1_Buffer_Size()
{
VerifyBytesToRead(1);
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_Equal_Buffer_Size()
{
Random rndGen = new Random(-55);
VerifyBytesToRead(numRndBytesToRead);
}
#endregion
#region Verification for Test Cases
private void VerifyTimeout(SerialPort com)
{
Stopwatch timer = new Stopwatch();
int expectedTime = com.ReadTimeout;
int actualTime = 0;
double percentageDifference;
//Warm up read method
Assert.Throws<TimeoutException>(() => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize));
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (int i = 0; i < NUM_TRYS; i++)
{
timer.Start();
Assert.Throws<TimeoutException>(() => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize));
timer.Stop();
actualTime += (int)timer.ElapsedMilliseconds;
timer.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime);
//Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference
if (maxPercentageDifference < percentageDifference)
{
Fail("ERROR!!!: The read method timed-out in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference);
}
}
private void VerifyReadException(SerialPort com, Type expectedException)
{
Assert.Throws(expectedException, () => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize));
}
private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] bytesToWrite = new byte[numRndBytesPairty];
char[] expectedChars = new char[numRndBytesPairty];
byte expectedByte;
//Genrate random characters without an parity error
for (int i = 0; i < bytesToWrite.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 128);
bytesToWrite[i] = randByte;
expectedChars[i] = (char)randByte;
}
if (-1 == parityReplace)
{
//If parityReplace is -1 and we should just use the default value
expectedByte = com1.ParityReplace;
}
else if ('\0' == parityReplace)
{
//If parityReplace is the null charachater and parity replacement should not occur
com1.ParityReplace = (byte)parityReplace;
expectedByte = bytesToWrite[parityErrorIndex];
}
else
{
//Else parityReplace was set to a value and we should expect this value to be returned on a parity error
com1.ParityReplace = (byte)parityReplace;
expectedByte = (byte)parityReplace;
}
//Create an parity error by setting the highest order bit to true
bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80);
expectedChars[parityErrorIndex] = (char)expectedByte;
Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace,
parityErrorIndex);
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.Open();
com2.Open();
VerifyRead(com1, com2, bytesToWrite, expectedChars, numBytesReadPairty);
}
}
private void VerifyBytesToRead(int numBytesRead)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] bytesToWrite = new byte[numRndBytesToRead];
char[] expectedChars;
ASCIIEncoding encoding = new ASCIIEncoding();
//Genrate random characters
for (int i = 0; i < bytesToWrite.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 256);
bytesToWrite[i] = randByte;
}
expectedChars = encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead);
com1.Open();
com2.Open();
VerifyRead(com1, com2, bytesToWrite, expectedChars, numBytesRead);
}
}
private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars, int rcvBufferSize)
{
char[] rcvBuffer = new char[rcvBufferSize];
char[] buffer = new char[expectedChars.Length];
int totalBytesRead;
int totalCharsRead;
int bytesToRead;
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 250;
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length);
totalBytesRead = 0;
totalCharsRead = 0;
bytesToRead = com1.BytesToRead;
while (true)
{
int charsRead;
try
{
charsRead = com1.Read(rcvBuffer, 0, rcvBufferSize);
}
catch (TimeoutException)
{
break;
}
//While their are more characters to be read
int bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead);
if ((bytesToRead > bytesRead && rcvBufferSize != bytesRead) ||
(bytesToRead <= bytesRead && bytesRead != bytesToRead))
{
//If we have not read all of the characters that we should have
Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer");
}
if (expectedChars.Length < totalCharsRead + charsRead)
{
//If we have read in more characters then we expect
Fail("ERROR!!!: We have received more characters then were sent");
}
Array.Copy(rcvBuffer, 0, buffer, totalCharsRead, charsRead);
totalBytesRead += bytesRead;
totalCharsRead += charsRead;
if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead,
com1.BytesToRead);
}
bytesToRead = com1.BytesToRead;
}
//Compare the chars that were written with the ones we expected to read
for (int i = 0; i < expectedChars.Length; i++)
{
if (expectedChars[i] != buffer[i])
{
Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)buffer[i]);
}
}
}
#endregion
}
}
| Jiayili1/corefx | src/System.IO.Ports/tests/SerialPort/Read_char_int_int_Generic.cs | C# | mit | 18,965 |
<?php
namespace Kunstmaan\CacheBundle\Form\Varnish;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Class BanType.
*/
class BanType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('path', TextType::class, [
'label' => 'kunstmaan_cache.varnish.ban.path',
]);
$builder->add('allDomains', CheckboxType::class, [
'label' => 'kunstmaan_cache.varnish.ban.all_domains',
]);
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'kunstmaan_cache_varnish_ban';
}
}
| mwoynarski/KunstmaanBundlesCMS | src/Kunstmaan/CacheBundle/Form/Varnish/BanType.php | PHP | mit | 844 |
package org.robolectric.shadows;
import android.widget.ArrayAdapter;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.util.ReflectionHelpers;
@SuppressWarnings("UnusedDeclaration")
@Implements(ArrayAdapter.class)
public class ShadowArrayAdapter<T> extends ShadowBaseAdapter {
@RealObject private ArrayAdapter<T> realArrayAdapter;
public int getTextViewResourceId() {
return ReflectionHelpers.getField(realArrayAdapter, "mFieldId");
}
public int getResourceId() {
return ReflectionHelpers.getField(realArrayAdapter, "mResource");
}
} | spotify/robolectric | shadows/framework/src/main/java/org/robolectric/shadows/ShadowArrayAdapter.java | Java | mit | 620 |
require File.dirname(__FILE__) + '/../spec_helper'
describe CodeFormatter do
def format(text)
CodeFormatter.new(text).to_html
end
it "determines language based on file path" do
formatter = CodeFormatter.new("")
formatter.language("unknown").should eq("unknown")
formatter.language("hello.rb").should eq("ruby")
formatter.language("hello.js").should eq("java_script")
formatter.language("hello.css").should eq("css")
formatter.language("hello.html.erb").should eq("rhtml")
formatter.language("hello.yml").should eq("yaml")
formatter.language("Gemfile").should eq("ruby")
formatter.language("app.rake").should eq("ruby")
formatter.language("foo.gemspec").should eq("ruby")
formatter.language("rails console").should eq("ruby")
formatter.language("hello.js.rjs").should eq("rjs")
formatter.language("hello.scss").should eq("css")
formatter.language("rails").should eq("ruby")
formatter.language("foo.bar ").should eq("bar")
formatter.language("foo ").should eq("foo")
formatter.language("").should eq("text")
formatter.language(nil).should eq("text")
formatter.language("0```").should eq("text")
end
it "converts to markdown" do
format("hello **world**").strip.should eq("<p>hello <strong>world</strong></p>")
end
it "hard wraps return statements" do
format("hello\nworld").strip.should eq("<p>hello<br>\nworld</p>")
end
it "autolinks a url" do
format("http://www.example.com/").strip.should eq('<p><a href="http://www.example.com/">http://www.example.com/</a></p>')
end
it "formats code block" do
# This could use some more extensive tests
format("```\nfoo\n```").strip.should include("<div class=\"code_block\">")
end
it "handle back-slashes in code block" do
# This could use some more extensive tests
format("```\nf\\'oo\n```").strip.should include("f\\'oo")
end
it "does not allow html" do
format("<img>").strip.should eq("")
end
end
| nischay13144/railscasts | spec/lib/code_formatter_spec.rb | Ruby | mit | 1,988 |
require "libxml"
require "active_support/core_ext/object/blank"
require "stringio"
module ActiveSupport
module XmlMini_LibXMLSAX #:nodoc:
extend self
# Class that will build the hash while the XML document
# is being parsed using SAX events.
class HashBuilder
include LibXML::XML::SaxParser::Callbacks
CONTENT_KEY = "__content__".freeze
HASH_SIZE_KEY = "__hash_size__".freeze
attr_reader :hash
def current_hash
@hash_stack.last
end
def on_start_document
@hash = { CONTENT_KEY => "" }
@hash_stack = [@hash]
end
def on_end_document
@hash = @hash_stack.pop
@hash.delete(CONTENT_KEY)
end
def on_start_element(name, attrs = {})
new_hash = { CONTENT_KEY => "" }.merge!(attrs)
new_hash[HASH_SIZE_KEY] = new_hash.size + 1
case current_hash[name]
when Array then current_hash[name] << new_hash
when Hash then current_hash[name] = [current_hash[name], new_hash]
when nil then current_hash[name] = new_hash
end
@hash_stack.push(new_hash)
end
def on_end_element(name)
if current_hash.length > current_hash.delete(HASH_SIZE_KEY) && current_hash[CONTENT_KEY].blank? || current_hash[CONTENT_KEY] == ""
current_hash.delete(CONTENT_KEY)
end
@hash_stack.pop
end
def on_characters(string)
current_hash[CONTENT_KEY] << string
end
alias_method :on_cdata_block, :on_characters
end
attr_accessor :document_class
self.document_class = HashBuilder
def parse(data)
if !data.respond_to?(:read)
data = StringIO.new(data || "")
end
char = data.getc
if char.nil?
{}
else
data.ungetc(char)
LibXML::XML::Error.set_handler(&LibXML::XML::Error::QUIET_HANDLER)
parser = LibXML::XML::SaxParser.io(data)
document = self.document_class.new
parser.callbacks = document
parser.parse
document.hash
end
end
end
end
| arjes/rails | activesupport/lib/active_support/xml_mini/libxmlsax.rb | Ruby | mit | 2,092 |
"""Individual test"""
import datetime
from django.test import TransactionTestCase
from django.contrib.auth.models import User
from apps.managers.player_mgr.models import Profile
from apps.utils import test_utils
from apps.managers.challenge_mgr.models import RoundSetting
class OverallPrizeTest(TransactionTestCase):
"""
Tests awarding a prize to the individual overall points winner.
"""
def setUp(self):
"""
Sets up a test individual prize for the rest of the tests.
This prize is not saved, as the round field is not yet set.
"""
self.prize = test_utils.setup_prize(award_to="individual_overall",
competition_type="points")
self.current_round = "Round 1"
test_utils.set_competition_round()
# Create test users.
self.users = [User.objects.create_user("test%d" % i, "test@test.com") for i in range(0, 3)]
def testNumAwarded(self):
"""
Simple test to check that the number of prizes to be awarded is one.
"""
self.prize.round = RoundSetting.objects.get(name="Round 1")
self.prize.save()
self.assertEqual(self.prize.num_awarded(), 1,
"This prize should not be awarded to more than one user.")
def testRoundLeader(self):
"""
Tests that we can retrieve the overall individual points leader for a round prize.
"""
self.prize.round = RoundSetting.objects.get(name="Round 1")
self.prize.save()
# Test one user
profile = self.users[0].get_profile()
top_points = Profile.objects.all()[0].points()
profile.add_points(top_points + 1,
datetime.datetime.today() - datetime.timedelta(minutes=1),
"test")
profile.save()
self.assertEqual(self.prize.leader(), profile,
"Current prize leader is not the leading user.")
# Have another user move ahead in points
profile2 = self.users[1].get_profile()
profile2.add_points(profile.points() + 1, datetime.datetime.today(), "test")
profile2.save()
self.assertEqual(self.prize.leader(), profile2, "User 2 should be the leading profile.")
# Have this user get the same amount of points, but an earlier award date.
profile3 = self.users[2].get_profile()
profile3.add_points(profile2.points(),
datetime.datetime.today() - datetime.timedelta(minutes=1), "test")
profile3.save()
self.assertEqual(self.prize.leader(), profile2,
"User 2 should still be the leading profile.")
def tearDown(self):
"""
Deletes the created image file in prizes.
"""
self.prize.image.delete()
self.prize.delete()
class TeamPrizeTest(TransactionTestCase):
"""
Tests awarding a prize to the individual on each team with the most points.
"""
def setUp(self):
"""
Sets up a test individual prize for the rest of the tests.
This prize is not saved, as the round field is not yet set.
"""
self.prize = test_utils.setup_prize(award_to="individual_team", competition_type="points")
self.current_round = "Round 1"
test_utils.set_competition_round()
test_utils.create_teams(self)
def testNumAwarded(self):
"""
Tests that the number of prizes awarded corresponds to the number of teams.
"""
self.prize.round = RoundSetting.objects.get(name="Round 1")
self.prize.save()
self.assertEqual(self.prize.num_awarded(), len(self.teams),
"This should correspond to the number of teams.")
def testRoundLeader(self):
"""
Tests that we can retrieve the overall individual points leader for a round prize.
"""
self.prize.round = RoundSetting.objects.get(name="Round 1")
self.prize.save()
# Test one user
profile = self.users[0].get_profile()
profile.add_points(10, datetime.datetime.today(), "test")
profile.save()
self.assertEqual(self.prize.leader(team=profile.team), profile,
"Current prize leader is not the leading user.")
# Have a user on the same team move ahead in points.
profile3 = self.users[2].get_profile()
profile3.add_points(11, datetime.datetime.today(), "test")
profile3.save()
self.assertEqual(self.prize.leader(team=profile.team), profile3,
"User 3 should be the the leader.")
# Try a user on a different team.
profile2 = self.users[1].get_profile()
profile2.add_points(20, datetime.datetime.today(), "test")
profile2.save()
self.assertEqual(self.prize.leader(team=profile.team), profile3,
"User 3 should be the leading profile on user 1's team.")
self.assertEqual(self.prize.leader(team=profile2.team), profile2,
"User 2 should be the leading profile on user 2's team.")
def tearDown(self):
"""
Deletes the created image file in prizes.
"""
self.prize.image.delete()
self.prize.delete()
| vijayanandau/KnowledgeShare | makahiki/apps/widgets/prizes/tests/individual_prize_tests.py | Python | mit | 5,225 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: Operator x ^ y returns ToNumber(x) ^ ToNumber(y)
es5id: 11.10.2_A3_T2.3
description: >
Type(x) is different from Type(y) and both types vary between
Number (primitive or object) and Null
---*/
//CHECK#1
if ((1 ^ null) !== 1) {
$ERROR('#1: (1 ^ null) === 1. Actual: ' + ((1 ^ null)));
}
//CHECK#2
if ((null ^ 1) !== 1) {
$ERROR('#2: (null ^ 1) === 1. Actual: ' + ((null ^ 1)));
}
//CHECK#3
if ((new Number(1) ^ null) !== 1) {
$ERROR('#3: (new Number(1) ^ null) === 1. Actual: ' + ((new Number(1) ^ null)));
}
//CHECK#4
if ((null ^ new Number(1)) !== 1) {
$ERROR('#4: (null ^ new Number(1)) === 1. Actual: ' + ((null ^ new Number(1))));
}
| PiotrDabkowski/Js2Py | tests/test_cases/language/expressions/bitwise-xor/S11.10.2_A3_T2.3.js | JavaScript | mit | 802 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {runServer} from '../../src/protractor/utils';
describe('Bazel protractor utils', () => {
it('should be able to start devserver', async() => {
// Test will automatically time out if the server couldn't be launched as expected.
await runServer('angular', 'packages/bazel/test/protractor-utils/fake-devserver', '--port', []);
});
});
| petebacondarwin/angular | packages/bazel/test/protractor-utils/index_test.ts | TypeScript | mit | 557 |
require 'mws/feeds/client'
| jack0331/peddler | lib/mws/feeds.rb | Ruby | mit | 27 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Remote.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.Next.UnitTests.Services
{
public class PerformanceTrackerServiceTests
{
[Fact]
public void TestTooFewSamples()
{
// minimum sample is 100
var badAnalyzers = GetBadAnalyzers(@"TestFiles\analyzer_input.csv", to: 80);
Assert.Empty(badAnalyzers);
}
[Fact]
public void TestTracking()
{
var badAnalyzers = GetBadAnalyzers(@"TestFiles\analyzer_input.csv", to: 200);
VerifyBadAnalyzer(badAnalyzers[0], "CSharpRemoveUnnecessaryCastDiagnosticAnalyzer", 101.244432561581, 54.48, 21.8163001442628);
VerifyBadAnalyzer(badAnalyzers[1], "CSharpInlineDeclarationDiagnosticAnalyzer", 49.9389715502954, 26.6686092715232, 9.2987133054884);
VerifyBadAnalyzer(badAnalyzers[2], "VisualBasicRemoveUnnecessaryCastDiagnosticAnalyzer", 42.0967360557792, 23.277619047619, 7.25464266261805);
}
[Fact]
public void TestTrackingMaxSample()
{
var badAnalyzers = GetBadAnalyzers(@"TestFiles\analyzer_input.csv", to: 300);
VerifyBadAnalyzer(badAnalyzers[0], "CSharpRemoveUnnecessaryCastDiagnosticAnalyzer", 85.6039521236341, 58.4542358078603, 18.4245217226717);
VerifyBadAnalyzer(badAnalyzers[1], "VisualBasic.UseAutoProperty.UseAutoPropertyAnalyzer", 45.0918385052674, 29.0622535211268, 9.13728667060397);
VerifyBadAnalyzer(badAnalyzers[2], "CSharpInlineDeclarationDiagnosticAnalyzer", 42.2014208750466, 28.7935371179039, 7.99261581900397);
}
[Fact]
public void TestTrackingRolling()
{
// data starting to rolling at 300 data points
var badAnalyzers = GetBadAnalyzers(@"TestFiles\analyzer_input.csv", to: 400);
VerifyBadAnalyzer(badAnalyzers[0], "CSharpRemoveUnnecessaryCastDiagnosticAnalyzer", 76.2748443491852, 51.1698695652174, 17.3819563479479);
VerifyBadAnalyzer(badAnalyzers[1], "VisualBasic.UseAutoProperty.UseAutoPropertyAnalyzer", 43.5700167914005, 29.2597857142857, 9.21213873850298);
VerifyBadAnalyzer(badAnalyzers[2], "InlineDeclaration.CSharpInlineDeclarationDiagnosticAnalyzer", 36.4336594793033, 23.9764782608696, 7.43956680199015);
}
[Fact]
public void TestBadAnalyzerInfoPII()
{
var badAnalyzer1 = new ExpensiveAnalyzerInfo(true, "test", 0.1, 0.1, 0.1);
Assert.True(badAnalyzer1.PIISafeAnalyzerId == badAnalyzer1.AnalyzerId);
Assert.True(badAnalyzer1.PIISafeAnalyzerId == "test");
var badAnalyzer2 = new ExpensiveAnalyzerInfo(false, "test", 0.1, 0.1, 0.1);
Assert.True(badAnalyzer2.PIISafeAnalyzerId == badAnalyzer2.AnalyzerIdHash);
Assert.True(badAnalyzer2.PIISafeAnalyzerId == "test".GetHashCode().ToString());
}
private void VerifyBadAnalyzer(ExpensiveAnalyzerInfo analyzer, string analyzerId, double lof, double mean, double stddev)
{
Assert.True(analyzer.PIISafeAnalyzerId.IndexOf(analyzerId, StringComparison.OrdinalIgnoreCase) >= 0);
Assert.Equal(lof, analyzer.LocalOutlierFactor, precision: 4);
Assert.Equal(mean, analyzer.Average, precision: 4);
Assert.Equal(stddev, analyzer.AdjustedStandardDeviation, precision: 4);
}
private List<ExpensiveAnalyzerInfo> GetBadAnalyzers(string testFileName, int to)
{
var testFile = ReadTestFile(testFileName);
var (matrix, dataCount) = CreateMatrix(testFile);
to = Math.Min(to, dataCount);
var service = new PerformanceTrackerService(minLOFValue: 0, averageThreshold: 0, stddevThreshold: 0);
for (var i = 0; i < to; i++)
{
service.AddSnapshot(CreateSnapshots(matrix, i), unitCount: 100);
}
var badAnalyzerInfo = new List<ExpensiveAnalyzerInfo>();
service.GenerateReport(badAnalyzerInfo);
return badAnalyzerInfo;
}
private IEnumerable<AnalyzerPerformanceInfo> CreateSnapshots(Dictionary<string, double[]> matrix, int index)
{
foreach (var kv in matrix)
{
var timeSpan = kv.Value[index];
if (double.IsNaN(timeSpan))
{
continue;
}
yield return new AnalyzerPerformanceInfo(kv.Key, true, TimeSpan.FromMilliseconds(timeSpan));
}
}
private (Dictionary<string, double[]> matrix, int dataCount) CreateMatrix(string testFile)
{
var matrix = new Dictionary<string, double[]>();
var lines = testFile.Split('\n');
var expectedDataCount = GetExpectedDataCount(lines[0]);
for (var i = 1; i < lines.Length; i++)
{
if (lines[i].Trim().Length == 0)
{
continue;
}
var data = SkipAnalyzerId(lines[i]).Split(',');
Assert.Equal(data.Length, expectedDataCount);
var analyzerId = GetAnalyzerId(lines[i]);
var timeSpans = new double[expectedDataCount];
for (var j = 0; j < data.Length; j++)
{
double result;
if (!double.TryParse(data[j], NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out result))
{
// no data for this analyzer for this particular run
result = double.NaN;
}
timeSpans[j] = result;
}
matrix[analyzerId] = timeSpans;
}
return (matrix, expectedDataCount);
}
private string GetAnalyzerId(string line)
{
return line.Substring(1, line.LastIndexOf('"') - 1);
}
private int GetExpectedDataCount(string header)
{
var data = header.Split(',');
return data.Length - 1;
}
private string SkipAnalyzerId(string line)
{
return line.Substring(line.LastIndexOf('"') + 2);
}
private string ReadTestFile(string name)
{
var assembly = typeof(PerformanceTrackerServiceTests).Assembly;
var resourceName = GetResourceName(assembly, name);
using (var stream = assembly.GetManifestResourceStream(resourceName))
{
if (stream == null)
{
throw new InvalidOperationException($"Resource '{resourceName}' not found in {assembly.FullName}.");
}
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
private static string GetResourceName(Assembly assembly, string name)
{
var convert = name.Replace(@"\", ".");
return assembly.GetManifestResourceNames().Where(n => n.EndsWith(convert, StringComparison.OrdinalIgnoreCase)).First();
}
}
}
| genlu/roslyn | src/VisualStudio/Core/Test.Next/Services/PerformanceTrackerServiceTests.cs | C# | mit | 7,698 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Gdata
* @subpackage YouTube
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Gdata_Extension
*/
require_once 'Zend/Gdata/Extension.php';
/**
* Represents the yt:releaseDate element
*
* @category Zend
* @package Zend_Gdata
* @subpackage YouTube
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_YouTube_Extension_ReleaseDate extends Zend_Gdata_Extension
{
protected $_rootElement = 'releaseDate';
protected $_rootNamespace = 'yt';
public function __construct($text = null)
{
$this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
parent::__construct();
$this->_text = $text;
}
}
| ramonornela/Zebra | library/Zend/Gdata/YouTube/Extension/ReleaseDate.php | PHP | mit | 1,444 |
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {state, style, trigger} from '@angular/animations';
import {Component, ContentChildren, Directive, EventEmitter, HostBinding, HostListener, Input, OnChanges, Output, QueryList, ViewChildren} from '@angular/core';
import {getDirectiveDef} from '@angular/core/src/render3/definition';
import {TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
describe('inheritance', () => {
it('should throw when trying to inherit a component from a directive', () => {
@Component({
selector: 'my-comp',
template: '<div></div>',
})
class MyComponent {
}
@Directive({
selector: '[my-dir]',
})
class MyDirective extends MyComponent {
}
@Component({
template: `<div my-dir></div>`,
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, MyDirective],
});
expect(() => {
TestBed.createComponent(App);
}).toThrowError('NG0903: Directives cannot inherit Components');
});
describe('multiple children', () => {
it('should ensure that multiple child classes don\'t cause multiple parent execution', () => {
// Assume this inheritance:
// Base
// |
// Super
// / \
// Sub1 Sub2
//
// In the above case:
// 1. Sub1 as will walk the inheritance Sub1, Super, Base
// 2. Sub2 as will walk the inheritance Sub2, Super, Base
//
// Notice that Super, Base will get walked twice. Because inheritance works by wrapping parent
// hostBindings function in a delegate which calls the hostBindings of the directive as well
// as super, we need to ensure that we don't double wrap the hostBindings function. Doing so
// would result in calling the hostBindings multiple times (unnecessarily). This would be
// especially an issue if we have a lot of sub-classes (as is common in component libraries)
const log: string[] = [];
@Directive({selector: '[superDir]'})
class BaseDirective {
@HostBinding('style.background-color')
get backgroundColor() {
log.push('Base.backgroundColor');
return 'white';
}
}
@Directive({selector: '[superDir]'})
class SuperDirective extends BaseDirective {
@HostBinding('style.color')
get color() {
log.push('Super.color');
return 'blue';
}
}
@Directive({selector: '[subDir1]'})
class Sub1Directive extends SuperDirective {
@HostBinding('style.height')
get height() {
log.push('Sub1.height');
return '200px';
}
}
@Directive({selector: '[subDir2]'})
class Sub2Directive extends SuperDirective {
@HostBinding('style.width')
get width() {
log.push('Sub2.width');
return '100px';
}
}
@Component({template: `<div subDir1 subDir2></div>`})
class App {
}
TestBed.configureTestingModule({
declarations: [App, Sub1Directive, Sub2Directive, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges(false); // Don't check for no changes (so that assertion does not need
// to worry about it.)
expect(log).toEqual([
'Base.backgroundColor', 'Super.color', 'Sub1.height', //
'Base.backgroundColor', 'Super.color', 'Sub2.width', //
]);
expect(getDirectiveDef(BaseDirective)!.hostVars).toEqual(2);
expect(getDirectiveDef(SuperDirective)!.hostVars).toEqual(4);
expect(getDirectiveDef(Sub1Directive)!.hostVars).toEqual(6);
expect(getDirectiveDef(Sub2Directive)!.hostVars).toEqual(6);
});
});
describe('ngOnChanges', () => {
it('should be inherited when super is a directive', () => {
const log: string[] = [];
@Directive({selector: '[superDir]'})
class SuperDirective implements OnChanges {
@Input() someInput = '';
ngOnChanges() {
log.push('on changes!');
}
}
@Directive({selector: '[subDir]'})
class SubDirective extends SuperDirective {
}
@Component({template: `<div subDir [someInput]="1"></div>`})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited when super is a simple class', () => {
const log: string[] = [];
class SuperClass {
ngOnChanges() {
log.push('on changes!');
}
}
@Directive({selector: '[subDir]'})
class SubDirective extends SuperClass {
@Input() someInput = '';
}
@Component({template: `<div subDir [someInput]="1"></div>`})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited when super is a directive and grand-super is a directive', () => {
const log: string[] = [];
@Directive({selector: '[grandSuperDir]'})
class GrandSuperDirective implements OnChanges {
@Input() someInput = '';
ngOnChanges() {
log.push('on changes!');
}
}
@Directive({selector: '[superDir]'})
class SuperDirective extends GrandSuperDirective {
}
@Directive({selector: '[subDir]'})
class SubDirective extends SuperDirective {
}
@Component({template: `<div subDir [someInput]="1"></div>`})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective, GrandSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited when super is a directive and grand-super is a simple class', () => {
const log: string[] = [];
class GrandSuperClass {
ngOnChanges() {
log.push('on changes!');
}
}
@Directive({selector: '[superDir]'})
class SuperDirective extends GrandSuperClass {
@Input() someInput = '';
}
@Directive({selector: '[subDir]'})
class SubDirective extends SuperDirective {
}
@Component({template: `<div subDir [someInput]="1"></div>`})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited when super is a simple class and grand-super is a directive', () => {
const log: string[] = [];
@Directive({selector: '[grandSuperDir]'})
class GrandSuperDirective implements OnChanges {
@Input() someInput = '';
ngOnChanges() {
log.push('on changes!');
}
}
class SuperClass extends GrandSuperDirective {}
@Directive({selector: '[subDir]'})
class SubDirective extends SuperClass {
}
@Component({template: `<div subDir [someInput]="1"></div>`})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, GrandSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited when super is a simple class and grand-super is a simple class', () => {
const log: string[] = [];
class GrandSuperClass {
ngOnChanges() {
log.push('on changes!');
}
}
class SuperClass extends GrandSuperClass {}
@Directive({selector: '[subDir]'})
class SubDirective extends SuperClass {
@Input() someInput = '';
}
@Component({template: `<div subDir [someInput]="1"></div>`})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited from undecorated super class which inherits from decorated one', () => {
let changes = 0;
abstract class Base {
// Add an Input so that we have at least one Angular decorator on a class field.
@Input() inputBase: any;
abstract input: any;
}
abstract class UndecoratedBase extends Base {
abstract override input: any;
ngOnChanges() {
changes++;
}
}
@Component({selector: 'my-comp', template: ''})
class MyComp extends UndecoratedBase {
@Input() override input: any;
}
@Component({template: '<my-comp [input]="value"></my-comp>'})
class App {
value = 'hello';
}
TestBed.configureTestingModule({declarations: [MyComp, App]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(changes).toBe(1);
});
});
describe('of bare super class by a directive', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
class SuperDirective {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
beforeEach(() => fired.length = 0);
it('ngOnInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngDoCheck', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentChecked', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewChecked', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngOnDestroy', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'sub destroy',
]);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
class SuperDirective {
@Input() foo = '';
@Input() bar = '';
@Input() baz = '';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
@Input() override baz = '';
@Input() qux = '';
}
@Component({template: `<p sub-dir [foo]="a" [bar]="b" [baz]="c" [qux]="d"></p>`})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir =
fixture.debugElement.query(By.directive(SubDirective)).injector.get(SubDirective);
expect(subDir.foo).toBe('a');
expect(subDir.bar).toBe('b');
expect(subDir.baz).toBe('c');
expect(subDir.qux).toBe('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
class SuperDirective {
@Output() foo = new EventEmitter<string>();
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<div sub-dir (foo)="handleFoo($event)"></div>
`
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
class SuperDirective {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
}
@Component({
template: `
<p sub-dir>test</p>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(SubDirective));
expect(queryResult.nativeElement.tagName).toBe('P');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
class SuperDirective {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
}
@Component({
template: `
<p sub-dir superTitle="test">test</p>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(SubDirective));
expect(queryResult.nativeElement.title).toBe('test!!!');
});
});
describe('ContentChildren', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
class SuperDirective {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<ul sub-dir>
<li child-dir>one</li>
<li child-dir>two</li>
</ul>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, ChildDir],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
});
xdescribe(
'what happens when...',
() => {
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
});
describe('of a directive by another directive', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
beforeEach(() => fired.length = 0);
it('ngOnInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngDoCheck', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentChecked', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewChecked', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngOnDestroy', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'sub destroy',
]);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Directive({selector: '[super-dir]'})
class SuperDirective {
@Input() foo = '';
@Input() bar = '';
@Input() baz = '';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
@Input() override baz = '';
@Input() qux = '';
}
@Component({template: `<p sub-dir [foo]="a" [bar]="b" [baz]="c" [qux]="d"></p>`})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir =
fixture.debugElement.query(By.directive(SubDirective)).injector.get(SubDirective);
expect(subDir.foo).toBe('a');
expect(subDir.bar).toBe('b');
expect(subDir.baz).toBe('c');
expect(subDir.qux).toBe('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@Output() foo = new EventEmitter<string>();
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<div sub-dir (foo)="handleFoo($event)"></div>
`
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
}
@Component({
template: `
<p sub-dir>test</p>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(SubDirective));
expect(queryResult.nativeElement.tagName).toBe('P');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
}
@Component({
template: `
<p sub-dir superTitle="test">test</p>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(SubDirective));
expect(queryResult.nativeElement.title).toBe('test!!!');
});
});
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<ul sub-dir>
<li child-dir>one</li>
<li child-dir>two</li>
</ul>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, ChildDir, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
xdescribe(
'what happens when...',
() => {
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
});
describe('of a directive by a bare class then by another directive', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Directive({
selector: '[super-dir]',
})
class SuperSuperDirective {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
class SuperDirective extends SuperSuperDirective {}
beforeEach(() => fired.length = 0);
it('ngOnInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngDoCheck', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentChecked', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewChecked', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngOnDestroy', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'sub destroy',
]);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Directive({selector: '[super-dir]'})
class SuperSuperDirective {
@Input() foo = '';
@Input() baz = '';
}
class SuperDirective extends SuperSuperDirective {
@Input() bar = '';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
@Input() override baz = '';
@Input() qux = '';
}
@Component({
selector: 'my-app',
template: `<p sub-dir [foo]="a" [bar]="b" [baz]="c" [qux]="d"></p>`,
})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir =
fixture.debugElement.query(By.directive(SubDirective)).injector.get(SubDirective);
expect(subDir.foo).toBe('a');
expect(subDir.bar).toBe('b');
expect(subDir.baz).toBe('c');
expect(subDir.qux).toBe('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Directive({
selector: '[super-dir]',
})
class SuperSuperDirective {
@Output() foo = new EventEmitter<string>();
}
class SuperDirective extends SuperSuperDirective {
@Output() bar = new EventEmitter<string>();
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
ngOnInit() {
this.foo.emit('test1');
this.bar.emit('test2');
}
}
@Component({
template: `
<div sub-dir (foo)="handleFoo($event)" (bar)="handleBar($event)"></div>
`
})
class App {
foo = '';
bar = '';
handleFoo(event: string) {
this.foo = event;
}
handleBar(event: string) {
this.bar = event;
}
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test1');
expect(app.bar).toBe('test2');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Directive({
selector: '[super-dir]',
})
class SuperSuperDirective {
@HostBinding('style.color') color = 'red';
}
class SuperDirective extends SuperSuperDirective {
@HostBinding('style.backgroundColor') bg = 'black';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
}
@Component({
template: `
<p sub-dir>test</p>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(SubDirective));
expect(queryResult.nativeElement.tagName).toBe('P');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Directive({
selector: '[super-dir]',
})
class SuperSuperDirective {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
class SuperDirective extends SuperSuperDirective {
@HostBinding('accessKey')
get boundAltKey() {
return this.superAccessKey + '???';
}
@Input() superAccessKey = '';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
}
@Component({
template: `
<p sub-dir superTitle="test1" superAccessKey="test2">test</p>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const p: HTMLParagraphElement =
fixture.debugElement.query(By.directive(SubDirective)).nativeElement;
expect(p.title).toBe('test1!!!');
expect(p.accessKey).toBe('test2???');
});
});
it('should inherit ContentChildren queries', () => {
let foundChildDir1s: QueryList<ChildDir1>;
let foundChildDir2s: QueryList<ChildDir2>;
@Directive({selector: '[child-dir-one]'})
class ChildDir1 {
}
@Directive({selector: '[child-dir-two]'})
class ChildDir2 {
}
@Directive({
selector: '[super-dir]',
})
class SuperSuperDirective {
@ContentChildren(ChildDir1) childDir1s!: QueryList<ChildDir1>;
}
class SuperDirective extends SuperSuperDirective {
@ContentChildren(ChildDir1) childDir2s!: QueryList<ChildDir2>;
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
ngAfterViewInit() {
foundChildDir1s = this.childDir1s;
foundChildDir2s = this.childDir2s;
}
}
@Component({
template: `
<ul sub-dir>
<li child-dir-one child-dir-two>one</li>
<li child-dir-one>two</li>
<li child-dir-two>three</li>
</ul>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, ChildDir1, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundChildDir1s!.length).toBe(2);
expect(foundChildDir2s!.length).toBe(2);
});
xdescribe(
'what happens when...',
() => {
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
});
describe('of bare super class by a component', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
class SuperComponent {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
beforeEach(() => fired.length = 0);
it('ngOnInit', () => {
@Component({selector: 'my-comp', template: `<p>test</p>`})
class MyComponent extends SuperComponent {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngDoCheck', () => {
@Directive({
selector: 'my-comp',
})
class MyComponent extends SuperComponent {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngOnDestroy', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'sub destroy',
]);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
class SuperComponent {
@Input() foo = '';
@Input() bar = '';
@Input() baz = '';
}
@Component({selector: 'my-comp', template: `<p>test</p>`})
class MyComponent extends SuperComponent {
@Input() override baz = '';
@Input() qux = '';
}
@Component({template: `<my-comp [foo]="a" [bar]="b" [baz]="c" [qux]="d"></my-comp>`})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir: MyComponent =
fixture.debugElement.query(By.directive(MyComponent)).componentInstance;
expect(subDir.foo).toEqual('a');
expect(subDir.bar).toEqual('b');
expect(subDir.baz).toEqual('c');
expect(subDir.qux).toEqual('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
class SuperComponent {
@Output() foo = new EventEmitter<string>();
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<my-comp (foo)="handleFoo($event)"></my-comp>
`
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
class SuperComponent {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
}
@Component({
template: `
<my-comp>test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
class SuperComponent {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
}
@Component({
template: `
<my-comp superTitle="test">test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.title).toBe('test!!!');
});
});
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
class SuperComponent {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({selector: 'my-comp', template: `<ul><ng-content></ng-content></ul>`})
class MyComponent extends SuperComponent {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp>
<li child-dir>one</li>
<li child-dir>two</li>
</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
xdescribe(
'what happens when...',
() => {
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
});
describe('of a directive inherited by a component', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
beforeEach(() => fired.length = 0);
it('ngOnInit', () => {
@Component({selector: 'my-comp', template: `<p>test</p>`})
class MyComponent extends SuperDirective {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngDoCheck', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngOnDestroy', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'sub destroy',
]);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@Input() foo = '';
@Input() bar = '';
@Input() baz = '';
}
@Component({selector: 'my-comp', template: `<p>test</p>`})
class MyComponent extends SuperDirective {
@Input() override baz = '';
@Input() qux = '';
}
@Component({template: `<my-comp [foo]="a" [bar]="b" [baz]="c" [qux]="d"></my-comp>`})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir: MyComponent =
fixture.debugElement.query(By.directive(MyComponent)).componentInstance;
expect(subDir.foo).toEqual('a');
expect(subDir.bar).toEqual('b');
expect(subDir.baz).toEqual('c');
expect(subDir.qux).toEqual('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@Output() foo = new EventEmitter<string>();
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<my-comp (foo)="handleFoo($event)"></my-comp>
`
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
}
@Component({
template: `
<my-comp>test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
}
@Component({
template: `
<my-comp superTitle="test">test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.title).toBe('test!!!');
});
});
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({selector: 'my-comp', template: `<ul><ng-content></ng-content></ul>`})
class MyComponent extends SuperDirective {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp>
<li child-dir>one</li>
<li child-dir>two</li>
</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperDirective, ChildDir],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
it('should inherit ViewChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@ViewChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `
<ul>
<li child-dir *ngFor="let item of items">{{item}}</li>
</ul>
`,
})
class MyComponent extends SuperDirective {
items = [1, 2, 3, 4, 5];
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp></my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(5);
});
xdescribe(
'what happens when...',
() => {
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
});
describe('of a directive inherited by a bare class and then by a component', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
class BareClass extends SuperDirective {}
beforeEach(() => fired.length = 0);
it('ngOnInit', () => {
@Component({selector: 'my-comp', template: `<p>test</p>`})
class MyComponent extends BareClass {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngDoCheck', () => {
@Directive({
selector: 'my-comp',
})
class MyComponent extends BareClass {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends BareClass {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends BareClass {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends BareClass {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends BareClass {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngOnDestroy', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends BareClass {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'sub destroy',
]);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@Input() foo = '';
@Input() baz = '';
}
class BareClass extends SuperDirective {
@Input() bar = '';
}
@Component({selector: 'my-comp', template: `<p>test</p>`})
class MyComponent extends BareClass {
@Input() override baz = '';
@Input() qux = '';
}
@Component({template: `<my-comp [foo]="a" [bar]="b" [baz]="c" [qux]="d"></my-comp>`})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, BareClass, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir: MyComponent =
fixture.debugElement.query(By.directive(MyComponent)).componentInstance;
expect(subDir.foo).toEqual('a');
expect(subDir.bar).toEqual('b');
expect(subDir.baz).toEqual('c');
expect(subDir.qux).toEqual('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@Output() foo = new EventEmitter<string>();
}
class BareClass extends SuperDirective {}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends BareClass {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<my-comp (foo)="handleFoo($event)"></my-comp>
`
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
class BareClass extends SuperDirective {}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends BareClass {
}
@Component({
template: `
<my-comp>test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
class BareClass extends SuperDirective {
@HostBinding('accessKey')
get boundAccessKey() {
return this.superAccessKey + '???';
}
@Input() superAccessKey = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends BareClass {
}
@Component({
template: `
<my-comp superTitle="test1" superAccessKey="test2">test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SuperDirective, BareClass, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.title).toBe('test1!!!');
expect(queryResult.nativeElement.accessKey).toBe('test2???');
});
});
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
class BareClass extends SuperDirective {}
@Component({
selector: 'my-comp',
template: `<ul><ng-content></ng-content></ul>`,
})
class MyComponent extends BareClass {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp>
<li child-dir>one</li>
<li child-dir>two</li>
</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
it('should inherit ViewChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@ViewChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
class BareClass extends SuperDirective {}
@Component({
selector: 'my-comp',
template: `
<ul>
<li child-dir *ngFor="let item of items">{{item}}</li>
</ul>
`,
})
class MyComponent extends BareClass {
items = [1, 2, 3, 4, 5];
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp></my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(5);
});
xdescribe(
'what happens when...',
() => {
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
});
describe('of a component inherited by a component', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
beforeEach(() => fired.length = 0);
it('ngOnInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngDoCheck', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngOnDestroy', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'sub destroy',
]);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
@Input() foo = '';
@Input() bar = '';
@Input() baz = '';
}
@Component({selector: 'my-comp', template: `<p>test</p>`})
class MyComponent extends SuperComponent {
@Input() override baz = '';
@Input() qux = '';
}
@Component({template: `<my-comp [foo]="a" [bar]="b" [baz]="c" [qux]="d"></my-comp>`})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir: MyComponent =
fixture.debugElement.query(By.directive(MyComponent)).componentInstance;
expect(subDir.foo).toEqual('a');
expect(subDir.bar).toEqual('b');
expect(subDir.baz).toEqual('c');
expect(subDir.qux).toEqual('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
@Output() foo = new EventEmitter<string>();
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<my-comp (foo)="handleFoo($event)"></my-comp>
`
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('animations', () => {
it('should work with inherited host bindings and animations', () => {
@Component({
selector: 'super-comp',
template: '<div>super-comp</div>',
host: {
'[@animation]': 'colorExp',
},
animations: [
trigger('animation', [state('color', style({color: 'red'}))]),
],
})
class SuperComponent {
colorExp = 'color';
}
@Component({
selector: 'my-comp',
template: `<div>my-comp</div>`,
})
class MyComponent extends SuperComponent {
}
@Component({
template: '<my-comp>app</my-comp>',
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent],
imports: [NoopAnimationsModule],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.css('my-comp'));
expect(queryResult.nativeElement.style.color).toBe('red');
});
it('should compose animations (from super class)', () => {
@Component({
selector: 'super-comp',
template: '...',
animations: [
trigger('animation1', [state('color', style({color: 'red'}))]),
trigger('animation2', [state('opacity', style({opacity: '0.5'}))]),
],
})
class SuperComponent {
}
@Component({
selector: 'my-comp',
template: '<div>my-comp</div>',
host: {
'[@animation1]': 'colorExp',
'[@animation2]': 'opacityExp',
'[@animation3]': 'bgExp',
},
animations: [
trigger('animation1', [state('color', style({color: 'blue'}))]),
trigger('animation3', [state('bg', style({backgroundColor: 'green'}))]),
],
})
class MyComponent extends SuperComponent {
colorExp = 'color';
opacityExp = 'opacity';
bgExp = 'bg';
}
@Component({
template: '<my-comp>app</my-comp>',
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent],
imports: [NoopAnimationsModule],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.css('my-comp'));
expect(queryResult.nativeElement.style.color).toBe('blue');
expect(queryResult.nativeElement.style.opacity).toBe('0.5');
expect(queryResult.nativeElement.style.backgroundColor).toBe('green');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
}
@Component({
template: `
<my-comp>test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
}
@Component({
template: `
<my-comp superTitle="test">test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.title).toBe('test!!!');
});
});
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `<ul><ng-content></ng-content></ul>`,
})
class MyComponent extends SuperComponent {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp>
<li child-dir>one</li>
<li child-dir>two</li>
</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent, ChildDir],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
it('should inherit ViewChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
@ViewChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `
<ul>
<li child-dir *ngFor="let item of items">{{item}}</li>
</ul>
`,
})
class MyComponent extends SuperComponent {
items = [1, 2, 3, 4, 5];
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp></my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(5);
});
it('should inherit host listeners from base class once', () => {
const events: string[] = [];
@Component({
selector: 'app-base',
template: 'base',
})
class BaseComponent {
@HostListener('click')
clicked() {
events.push('BaseComponent.clicked');
}
}
@Component({
selector: 'app-child',
template: 'child',
})
class ChildComponent extends BaseComponent {
// additional host listeners are defined here to have `hostBindings` function generated on
// component def, which would trigger `hostBindings` functions merge operation in
// InheritDefinitionFeature logic (merging Child and Base host binding functions)
@HostListener('focus')
focused() {
}
override clicked() {
events.push('ChildComponent.clicked');
}
}
@Component({
selector: 'app-grand-child',
template: 'grand-child',
})
class GrandChildComponent extends ChildComponent {
// additional host listeners are defined here to have `hostBindings` function generated on
// component def, which would trigger `hostBindings` functions merge operation in
// InheritDefinitionFeature logic (merging GrandChild and Child host binding functions)
@HostListener('blur')
blurred() {
}
override clicked() {
events.push('GrandChildComponent.clicked');
}
}
@Component({
selector: 'root-app',
template: `
<app-base></app-base>
<app-child></app-child>
<app-grand-child></app-grand-child>
`,
})
class RootApp {
}
const components = [BaseComponent, ChildComponent, GrandChildComponent];
TestBed.configureTestingModule({
declarations: [RootApp, ...components],
});
const fixture = TestBed.createComponent(RootApp);
fixture.detectChanges();
components.forEach(component => {
fixture.debugElement.query(By.directive(component)).nativeElement.click();
});
expect(events).toEqual(
['BaseComponent.clicked', 'ChildComponent.clicked', 'GrandChildComponent.clicked']);
});
xdescribe(
'what happens when...',
() => {
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
});
describe('of a component inherited by a bare class then by a component', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperSuperComponent {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
class SuperComponent extends SuperSuperComponent {}
beforeEach(() => fired.length = 0);
it('ngOnInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngDoCheck', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngOnDestroy', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'sub destroy',
]);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperSuperComponent {
@Input() foo = '';
@Input() baz = '';
}
class BareClass extends SuperSuperComponent {
@Input() bar = '';
}
@Component({selector: 'my-comp', template: `<p>test</p>`})
class MyComponent extends BareClass {
@Input() override baz = '';
@Input() qux = '';
}
@Component({template: `<my-comp [foo]="a" [bar]="b" [baz]="c" [qux]="d"></my-comp>`})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperSuperComponent, BareClass],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const myComp: MyComponent =
fixture.debugElement.query(By.directive(MyComponent)).componentInstance;
expect(myComp.foo).toEqual('a');
expect(myComp.bar).toEqual('b');
expect(myComp.baz).toEqual('c');
expect(myComp.qux).toEqual('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperSuperComponent {
@Output() foo = new EventEmitter<string>();
}
class SuperComponent extends SuperSuperComponent {
@Output() bar = new EventEmitter<string>();
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
ngOnInit() {
this.foo.emit('test1');
this.bar.emit('test2');
}
}
@Component({
template: `
<my-comp (foo)="handleFoo($event)" (bar)="handleBar($event)"></my-comp>
`
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
bar = '';
handleBar(event: string) {
this.bar = event;
}
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent, SuperSuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test1');
expect(app.bar).toBe('test2');
});
});
describe('animations', () => {
it('should compose animations across multiple inheritance levels', () => {
@Component({
selector: 'super-comp',
template: '...',
host: {
'[@animation1]': 'colorExp',
'[@animation2]': 'opacityExp',
},
animations: [
trigger('animation1', [state('color', style({color: 'red'}))]),
trigger('animation2', [state('opacity', style({opacity: '0.5'}))]),
],
})
class SuperComponent {
colorExp = 'color';
opacityExp = 'opacity';
}
@Component({
selector: 'intermediate-comp',
template: '...',
})
class IntermediateComponent extends SuperComponent {
}
@Component({
selector: 'my-comp',
template: '<div>my-comp</div>',
host: {
'[@animation1]': 'colorExp',
'[@animation3]': 'bgExp',
},
animations: [
trigger('animation1', [state('color', style({color: 'blue'}))]),
trigger('animation3', [state('bg', style({backgroundColor: 'green'}))]),
],
})
class MyComponent extends IntermediateComponent {
override colorExp = 'color';
override opacityExp = 'opacity';
bgExp = 'bg';
}
@Component({
template: '<my-comp>app</my-comp>',
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, IntermediateComponent, SuperComponent],
imports: [NoopAnimationsModule],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.css('my-comp'));
expect(queryResult.nativeElement.style.color).toBe('blue');
expect(queryResult.nativeElement.style.opacity).toBe('0.5');
expect(queryResult.nativeElement.style.backgroundColor).toBe('green');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperSuperComponent {
@HostBinding('style.color') color = 'red';
}
class SuperComponent extends SuperSuperComponent {
@HostBinding('style.backgroundColor') bg = 'black';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
}
@Component({
template: `
<my-comp>test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent, SuperSuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperSuperComponent {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
class SuperComponent extends SuperSuperComponent {
@HostBinding('accessKey')
get boundAccessKey() {
return this.superAccessKey + '???';
}
@Input() superAccessKey = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
}
@Component({
template: `
<my-comp superTitle="test1" superAccessKey="test2">test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent, SuperSuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.title).toBe('test1!!!');
expect(queryResult.nativeElement.accessKey).toBe('test2???');
});
});
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `<ul><ng-content></ng-content></ul>`,
})
class MyComponent extends SuperComponent {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp>
<li child-dir>one</li>
<li child-dir>two</li>
</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent, ChildDir],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
it('should inherit ViewChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
@ViewChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `
<ul>
<li child-dir *ngFor="let item of items">{{item}}</li>
</ul>
`,
})
class MyComponent extends SuperComponent {
items = [1, 2, 3, 4, 5];
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp></my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(5);
});
xdescribe(
'what happens when...',
() => {
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
});
});
| ocombe/angular | packages/core/test/acceptance/inherit_definition_feature_spec.ts | TypeScript | mit | 155,194 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
tslib_1.__exportStar(require("./2.9/type"), exports);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHlwZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInR5cGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7O0FBQUEscURBQTJCIn0= | AxelSparkster/axelsparkster.github.io | node_modules/tsutils/typeguard/type.js | JavaScript | mit | 357 |
import requests
from django.utils.translation import ugettext as _
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
from ..base import ProviderException
from .provider import DoubanProvider
class DoubanOAuth2Adapter(OAuth2Adapter):
provider_id = DoubanProvider.id
access_token_url = 'https://www.douban.com/service/auth2/token'
authorize_url = 'https://www.douban.com/service/auth2/auth'
profile_url = 'https://api.douban.com/v2/user/~me'
def complete_login(self, request, app, token, **kwargs):
headers = {'Authorization': 'Bearer %s' % token.token}
resp = requests.get(self.profile_url, headers=headers)
extra_data = resp.json()
"""
Douban may return data like this:
{
'code': 128,
'request': 'GET /v2/user/~me',
'msg': 'user_is_locked:53358092'
}
"""
if 'id' not in extra_data:
msg = extra_data.get('msg', _('Invalid profile data'))
raise ProviderException(msg)
return self.get_provider().sociallogin_from_response(
request, extra_data)
oauth2_login = OAuth2LoginView.adapter_view(DoubanOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(DoubanOAuth2Adapter)
| okwow123/djangol2 | example/env/lib/python2.7/site-packages/allauth/socialaccount/providers/douban/views.py | Python | mit | 1,354 |
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
before_validation :camelize_title
validates_uniqueness_of :title
def camelize_title(role_title = self.title)
self.title = role_title.to_s.camelize
end
def self.[](title)
find_or_create_by_title(title.to_s.camelize)
end
end
| clanplaid/wow.clanplaid.net | vendor/plugins/authentication/app/models/role.rb | Ruby | mit | 313 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class MetadataReferencePropertiesTests
{
[Fact]
public void Constructor()
{
var m = new MetadataReferenceProperties();
Assert.True(m.Aliases.IsEmpty);
Assert.False(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Assembly, m.Kind);
m = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases: ImmutableArray.Create("\\/[.'\":_)??\t\n*#$@^%*&)", "goo"), embedInteropTypes: true);
AssertEx.Equal(new[] { "\\/[.'\":_)??\t\n*#$@^%*&)", "goo" }, m.Aliases);
Assert.True(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Assembly, m.Kind);
m = new MetadataReferenceProperties(MetadataImageKind.Module);
Assert.True(m.Aliases.IsEmpty);
Assert.False(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Module, m.Kind);
Assert.Equal(MetadataReferenceProperties.Module, new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray<string>.Empty, false));
Assert.Equal(MetadataReferenceProperties.Assembly, new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, false));
}
[Fact]
public void Constructor_Errors()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new MetadataReferenceProperties((MetadataImageKind)byte.MaxValue));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("blah")));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, embedInteropTypes: true));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("")));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("x\0x")));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithAliases(ImmutableArray.Create("blah")));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithAliases(new[] { "blah" }));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithEmbedInteropTypes(true));
}
[Fact]
public void WithXxx()
{
var a = new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: true);
Assert.Equal(a.WithAliases(null), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, embedInteropTypes: true));
Assert.Equal(a.WithAliases(default(ImmutableArray<string>)), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, embedInteropTypes: true));
Assert.Equal(a.WithAliases(ImmutableArray<string>.Empty), new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray<string>), embedInteropTypes: true));
Assert.Equal(a.WithAliases(new string[0]), new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray<string>), embedInteropTypes: true));
Assert.Equal(a.WithAliases(new[] { "goo", "aaa" }), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("goo", "aaa"), embedInteropTypes: true));
Assert.Equal(a.WithEmbedInteropTypes(false), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: false));
Assert.Equal(a.WithRecursiveAliases(true), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: true, hasRecursiveAliases: true));
var m = new MetadataReferenceProperties(MetadataImageKind.Module);
Assert.Equal(m.WithAliases(default(ImmutableArray<string>)), new MetadataReferenceProperties(MetadataImageKind.Module, default(ImmutableArray<string>), embedInteropTypes: false));
Assert.Equal(m.WithEmbedInteropTypes(false), new MetadataReferenceProperties(MetadataImageKind.Module, default(ImmutableArray<string>), embedInteropTypes: false));
}
}
}
| abock/roslyn | src/Compilers/Core/CodeAnalysisTest/MetadataReferences/MetadataReferencePropertiesTests.cs | C# | mit | 4,674 |
package com.frostwire.jlibtorrent;
import com.frostwire.jlibtorrent.swig.dht_lookup_vector;
import com.frostwire.jlibtorrent.swig.dht_routing_bucket_vector;
import com.frostwire.jlibtorrent.swig.session_status;
import java.util.ArrayList;
import java.util.List;
/**
* Contains session wide state and counters.
*
* @author gubatron
* @author aldenml
*/
public final class SessionStatus {
private final session_status s;
public SessionStatus(session_status s) {
this.s = s;
}
public session_status getSwig() {
return s;
}
/**
* false as long as no incoming connections have been
* established on the listening socket. Every time you change the listen port, this will
* be reset to false.
*
* @return
*/
public boolean hasIncomingConnections() {
return s.getHas_incoming_connections();
}
/**
* the total download and upload rates accumulated
* from all torrents. This includes bittorrent protocol, DHT and an estimated TCP/IP
* protocol overhead.
*
* @return
*/
public int getUploadRate() {
return s.getUpload_rate();
}
/**
* the total download and upload rates accumulated
* from all torrents. This includes bittorrent protocol, DHT and an estimated TCP/IP
* protocol overhead.
*
* @return
*/
public int getDownloadRate() {
return s.getDownload_rate();
}
/**
* the total number of bytes downloaded and
* uploaded to and from all torrents. This also includes all the protocol overhead.
*
* @return
*/
public long getTotalDownload() {
return s.getTotal_download();
}
/**
* the total number of bytes downloaded and
* uploaded to and from all torrents. This also includes all the protocol overhead.
*
* @return
*/
public long getTotalUpload() {
return s.getTotal_upload();
}
/**
* the rate of the payload
* down- and upload only.
*
* @return
*/
public int getPayloadUploadRate() {
return s.getPayload_upload_rate();
}
/**
* the rate of the payload down- and upload only.
*
* @return
*/
public int getPayloadDownloadRate() {
return s.getPayload_download_rate();
}
/**
* the total transfers of payload
* only. The payload does not include the bittorrent protocol overhead, but only parts of the
* actual files to be downloaded.
*
* @return
*/
public long getTotalPayloadDownload() {
return s.getTotal_payload_download();
}
/**
* the total transfers of payload
* only. The payload does not include the bittorrent protocol overhead, but only parts of the
* actual files to be downloaded.
*
* @return
*/
public long getTotalPayloadUpload() {
return s.getTotal_payload_upload();
}
/**
* The estimated TCP/IP overhead.
*
* @return
*/
public int getIPOverheadUploadRate() {
return s.getIp_overhead_upload_rate();
}
/**
* The estimated TCP/IP overhead.
*
* @return
*/
public int getIPOverheadDownloadRate() {
return s.getIp_overhead_download_rate();
}
/**
* The estimated TCP/IP overhead.
*
* @return
*/
public long getTotalIPOverheadDownload() {
return s.getTotal_ip_overhead_download();
}
/**
* The estimated TCP/IP overhead.
*
* @return
*/
public long getTotalIPOverheadUpload() {
return s.getTotal_ip_overhead_upload();
}
/**
* The upload rate used by DHT traffic.
*
* @return
*/
public int getDHTUploadRate() {
return s.getDht_upload_rate();
}
/**
* The download rate used by DHT traffic.
*
* @return
*/
public int getDHTDownloadRate() {
return s.getDht_download_rate();
}
/**
* The total number of bytes received from the DHT.
*
* @return
*/
public long getTotalDHTDownload() {
return s.getTotal_dht_download();
}
/**
* The total number of bytes sent to the DHT.
*
* @return
*/
public long getTotalDHTUpload() {
return s.getTotal_dht_upload();
}
/*
// the upload and download rate used by tracker traffic. Also the total number
// of bytes sent and received to and from trackers.
int tracker_upload_rate;
int tracker_download_rate;
size_type total_tracker_download;
size_type total_tracker_upload;
// the number of bytes that has been received more than once.
// This can happen if a request from a peer times out and is requested from a different
// peer, and then received again from the first one. To make this lower, increase the
// ``request_timeout`` and the ``piece_timeout`` in the session settings.
size_type total_redundant_bytes;
// the number of bytes that was downloaded which later failed
// the hash-check.
size_type total_failed_bytes;
// the total number of peer connections this session has. This includes
// incoming connections that still hasn't sent their handshake or outgoing connections
// that still hasn't completed the TCP connection. This number may be slightly higher
// than the sum of all peers of all torrents because the incoming connections may not
// be assigned a torrent yet.
int num_peers;
// the current number of unchoked peers.
int num_unchoked;
// the current allowed number of unchoked peers.
int allowed_upload_slots;
// the number of peers that are
// waiting for more bandwidth quota from the torrent rate limiter.
int up_bandwidth_queue;
int down_bandwidth_queue;
// count the number of
// bytes the connections are waiting for to be able to send and receive.
int up_bandwidth_bytes_queue;
int down_bandwidth_bytes_queue;
// tells the number of
// seconds until the next optimistic unchoke change and the start of the next
// unchoke interval. These numbers may be reset prematurely if a peer that is
// unchoked disconnects or becomes notinterested.
int optimistic_unchoke_counter;
int unchoke_counter;
// the number of peers currently
// waiting on a disk write or disk read to complete before it receives or sends
// any more data on the socket. It'a a metric of how disk bound you are.
int disk_write_queue;
int disk_read_queue;
*/
/**
* Only available when built with DHT support. It is set to 0 if the DHT isn't running.
* <p/>
* When the DHT is running, ``dht_nodes`` is set to the number of nodes in the routing
* table. This number only includes *active* nodes, not cache nodes.
* <p/>
* These nodes are used to replace the regular nodes in the routing table in case any of them
* becomes unresponsive.
*
* @return
*/
public int getDHTNodes() {
return s.getDht_nodes();
}
/**
* Only available when built with DHT support. It is set to 0 if the DHT isn't running.
* <p/>
* When the DHT is running, ``dht_node_cache`` is set to the number of nodes in the node cache.
* <p/>
* These nodes are used to replace the regular nodes in the routing table in case any of them
* becomes unresponsive.
*
* @return
*/
public int getDHTNodeCache() {
return s.getDht_node_cache();
}
/**
* the number of torrents tracked by the DHT at the moment.
*
* @return
*/
public int getDHTTorrents() {
return s.getDht_torrents();
}
/**
* An estimation of the total number of nodes in the DHT network.
*
* @return
*/
public long getDHTGlobalNodes() {
return s.getDht_global_nodes();
}
/**
* a vector of the currently running DHT lookups.
*
* @return
*/
public List<DHTLookup> getActiveRequests() {
dht_lookup_vector v = s.getActive_requests();
int size = (int) v.size();
List<DHTLookup> l = new ArrayList<DHTLookup>(size);
for (int i = 0; i < size; i++) {
l.add(new DHTLookup(v.get(i)));
}
return l;
}
/**
* contains information about every bucket in the DHT routing table.
*
* @return
*/
public List<DHTRoutingBucket> getDHTRoutingTable() {
dht_routing_bucket_vector v = s.getDht_routing_table();
int size = (int) v.size();
List<DHTRoutingBucket> l = new ArrayList<DHTRoutingBucket>(size);
for (int i = 0; i < size; i++) {
l.add(new DHTRoutingBucket(v.get(i)));
}
return l;
}
/**
* the number of nodes allocated dynamically for a
* particular DHT lookup. This represents roughly the amount of memory used
* by the DHT.
*
* @return
*/
public int getDHTTotalAllocations() {
return s.getDht_total_allocations();
}
/**
* statistics on the uTP sockets.
*
* @return
*/
public UTPStatus getUTPStats() {
return new UTPStatus(s.getUtp_stats());
}
/**
* the number of known peers across all torrents. These are not necessarily
* connected peers, just peers we know of.
*
* @return
*/
public int getPeerlistSize() {
return s.getPeerlist_size();
}
}
| tchoulihan/frostwire-jlibtorrent | src/com/frostwire/jlibtorrent/SessionStatus.java | Java | mit | 9,844 |
var assert = require('assert');
var jsv = require('jsverify');
var R = require('..');
var eq = require('./shared/eq');
describe('compose', function() {
it('is a variadic function', function() {
eq(typeof R.compose, 'function');
eq(R.compose.length, 0);
});
it('performs right-to-left function composition', function() {
// f :: (String, Number?) -> ([Number] -> [Number])
var f = R.compose(R.map, R.multiply, parseInt);
eq(f.length, 2);
eq(f('10')([1, 2, 3]), [10, 20, 30]);
eq(f('10', 2)([1, 2, 3]), [2, 4, 6]);
});
it('passes context to functions', function() {
function x(val) {
return this.x * val;
}
function y(val) {
return this.y * val;
}
function z(val) {
return this.z * val;
}
var context = {
a: R.compose(x, y, z),
x: 4,
y: 2,
z: 1
};
eq(context.a(5), 40);
});
it('throws if given no arguments', function() {
assert.throws(
function() { R.compose(); },
function(err) {
return err.constructor === Error &&
err.message === 'compose requires at least one argument';
}
);
});
it('can be applied to one argument', function() {
var f = function(a, b, c) { return [a, b, c]; };
var g = R.compose(f);
eq(g.length, 3);
eq(g(1, 2, 3), [1, 2, 3]);
});
});
describe('compose properties', function() {
jsv.property('composes two functions', jsv.fn(), jsv.fn(), jsv.nat, function(f, g, x) {
return R.equals(R.compose(f, g)(x), f(g(x)));
});
jsv.property('associative', jsv.fn(), jsv.fn(), jsv.fn(), jsv.nat, function(f, g, h, x) {
var result = f(g(h(x)));
return R.all(R.equals(result), [
R.compose(f, g, h)(x),
R.compose(f, R.compose(g, h))(x),
R.compose(R.compose(f, g), h)(x)
]);
});
});
| angeloocana/ramda | test/compose.js | JavaScript | mit | 1,837 |
/*
* The MIT License
*
* Copyright (c) 2011, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.cli;
import hudson.remoting.ClassFilter;
import hudson.remoting.ObjectInputStreamEx;
import hudson.remoting.SocketChannelStream;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.security.AlgorithmParameterGenerator;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import org.jenkinsci.remoting.util.AnonymousClassWarnings;
/**
* @deprecated No longer used.
*/
@Deprecated
public class Connection {
public final InputStream in;
public final OutputStream out;
public final DataInputStream din;
public final DataOutputStream dout;
public Connection(Socket socket) throws IOException {
this(SocketChannelStream.in(socket),SocketChannelStream.out(socket));
}
public Connection(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
this.din = new DataInputStream(in);
this.dout = new DataOutputStream(out);
}
//
//
// Convenience methods
//
//
public void writeUTF(String msg) throws IOException {
dout.writeUTF(msg);
}
public String readUTF() throws IOException {
return din.readUTF();
}
public void writeBoolean(boolean b) throws IOException {
dout.writeBoolean(b);
}
public boolean readBoolean() throws IOException {
return din.readBoolean();
}
/**
* Sends a serializable object.
*/
public void writeObject(Object o) throws IOException {
ObjectOutputStream oos = AnonymousClassWarnings.checkingObjectOutputStream(out);
oos.writeObject(o);
// don't close oss, which will close the underlying stream
// no need to flush either, given the way oos is implemented
}
/**
* Receives an object sent by {@link #writeObject(Object)}
*/
public <T> T readObject() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStreamEx(in,
getClass().getClassLoader(), ClassFilter.DEFAULT);
return (T)ois.readObject();
}
public void writeKey(Key key) throws IOException {
writeUTF(new String(Base64.encodeBase64(key.getEncoded())));
}
public X509EncodedKeySpec readKey() throws IOException {
byte[] otherHalf = Base64.decodeBase64(readUTF()); // for historical reasons, we don't use readByteArray()
return new X509EncodedKeySpec(otherHalf);
}
public void writeByteArray(byte[] data) throws IOException {
dout.writeInt(data.length);
dout.write(data);
}
public byte[] readByteArray() throws IOException {
int bufSize = din.readInt();
if (bufSize < 0) {
throw new IOException("DataInputStream unexpectedly returned negative integer");
}
byte[] buf = new byte[bufSize];
din.readFully(buf);
return buf;
}
/**
* Performs a Diffie-Hellman key exchange and produce a common secret between two ends of the connection.
*
* <p>
* DH is also useful as a coin-toss algorithm. Two parties get the same random number without trusting
* each other.
*/
public KeyAgreement diffieHellman(boolean side) throws IOException, GeneralSecurityException {
return diffieHellman(side,512);
}
public KeyAgreement diffieHellman(boolean side, int keySize) throws IOException, GeneralSecurityException {
KeyPair keyPair;
PublicKey otherHalf;
if (side) {
AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
paramGen.init(keySize);
KeyPairGenerator dh = KeyPairGenerator.getInstance("DH");
dh.initialize(paramGen.generateParameters().getParameterSpec(DHParameterSpec.class));
keyPair = dh.generateKeyPair();
// send a half and get a half
writeKey(keyPair.getPublic());
otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey());
} else {
otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey());
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH");
keyPairGen.initialize(((DHPublicKey) otherHalf).getParams());
keyPair = keyPairGen.generateKeyPair();
// send a half and get a half
writeKey(keyPair.getPublic());
}
KeyAgreement ka = KeyAgreement.getInstance("DH");
ka.init(keyPair.getPrivate());
ka.doPhase(otherHalf, true);
return ka;
}
/**
* Upgrades a connection with transport encryption by the specified symmetric cipher.
*
* @return
* A new {@link Connection} object that includes the transport encryption.
*/
public Connection encryptConnection(SecretKey sessionKey, String algorithm) throws IOException, GeneralSecurityException {
Cipher cout = Cipher.getInstance(algorithm);
cout.init(Cipher.ENCRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded()));
CipherOutputStream o = new CipherOutputStream(out, cout);
Cipher cin = Cipher.getInstance(algorithm);
cin.init(Cipher.DECRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded()));
CipherInputStream i = new CipherInputStream(in, cin);
return new Connection(i,o);
}
/**
* Given a byte array that contains arbitrary number of bytes, digests or expands those bits into the specified
* number of bytes without loss of entropy.
*
* Cryptographic utility code.
*/
public static byte[] fold(byte[] bytes, int size) {
byte[] r = new byte[size];
for (int i=Math.max(bytes.length,size)-1; i>=0; i-- ) {
r[i%r.length] ^= bytes[i%bytes.length];
}
return r;
}
private String detectKeyAlgorithm(KeyPair kp) {
return detectKeyAlgorithm(kp.getPublic());
}
private String detectKeyAlgorithm(PublicKey kp) {
if (kp instanceof RSAPublicKey) return "RSA";
if (kp instanceof DSAPublicKey) return "DSA";
throw new IllegalArgumentException("Unknown public key type: "+kp);
}
/**
* Used in conjunction with {@link #verifyIdentity(byte[])} to prove
* that we actually own the private key of the given key pair.
*/
public void proveIdentity(byte[] sharedSecret, KeyPair key) throws IOException, GeneralSecurityException {
String algorithm = detectKeyAlgorithm(key);
writeUTF(algorithm);
writeKey(key.getPublic());
Signature sig = Signature.getInstance("SHA1with"+algorithm);
sig.initSign(key.getPrivate());
sig.update(key.getPublic().getEncoded());
sig.update(sharedSecret);
writeObject(sig.sign());
}
/**
* Verifies that we are talking to a peer that actually owns the private key corresponding to the public key we get.
*/
public PublicKey verifyIdentity(byte[] sharedSecret) throws IOException, GeneralSecurityException {
try {
String serverKeyAlgorithm = readUTF();
PublicKey spk = KeyFactory.getInstance(serverKeyAlgorithm).generatePublic(readKey());
// verify the identity of the server
Signature sig = Signature.getInstance("SHA1with"+serverKeyAlgorithm);
sig.initVerify(spk);
sig.update(spk.getEncoded());
sig.update(sharedSecret);
sig.verify((byte[]) readObject());
return spk;
} catch (ClassNotFoundException e) {
throw new Error(e); // impossible
}
}
public void close() throws IOException {
in.close();
out.close();
}
}
| Vlatombe/jenkins | core/src/main/java/hudson/cli/Connection.java | Java | mit | 9,707 |
#include <utilities.h>
#include <fstream>
namespace Utilities
{
namespace Math
{
double degreesToRadians(double angle)
{
return (angle * PI) / 180;
}
double radiansToDegrees(double angle)
{
return angle * (180/PI);
}
}
namespace File
{
bool getFileContents(std::vector<uint8_t> &fileBuffer, const std::string &filePath)
{
std::ifstream inFileStream(filePath, std::ios::binary);
if (!inFileStream) {
return false;
}
inFileStream.seekg(0, std::ios::end);
auto fileLength = inFileStream.tellg();
inFileStream.seekg(0, std::ios::beg);
fileBuffer.resize(fileLength);
inFileStream.read(reinterpret_cast<char *>(fileBuffer.data()), fileLength);
return true;
}
}
}
| velocic/opengl-tutorial-solutions | 22-loading-3d-models/src/utilities.cpp | C++ | mit | 909 |
var Emitter = require("events").EventEmitter;
var shared;
function Bank(options) {
this.address = options.address;
this.io = options.io;
this.io.i2cConfig();
}
Bank.prototype.read = function(register, numBytes, callback) {
if (register) {
this.io.i2cRead(this.address, register, numBytes, callback);
} else {
this.io.i2cRead(this.address, numBytes, callback);
}
};
Bank.prototype.write = function(register, bytes) {
if (!Array.isArray(bytes)) {
bytes = [bytes];
}
this.io.i2cWrite(this.address, register, bytes);
};
// http://www.nr.edu/csc200/labs-ev3/ev3-user-guide-EN.pdf
function EVS(options) {
if (shared) {
return shared;
}
this.bank = {
a: new Bank({
address: EVS.BANK_A,
io: options.io,
}),
b: new Bank({
address: EVS.BANK_B,
io: options.io,
})
};
shared = this;
}
EVS.shieldPort = function(pin) {
var port = EVS[pin];
if (port === undefined) {
throw new Error("Invalid EVShield pin name");
}
var address, analog, bank, motor, mode, offset, sensor;
var endsWithS1 = false;
if (pin.startsWith("BA")) {
address = EVS.BANK_A;
bank = "a";
} else {
address = EVS.BANK_B;
bank = "b";
}
if (pin.includes("M")) {
motor = pin.endsWith("M1") ? EVS.S1 : EVS.S2;
}
if (pin.includes("S")) {
endsWithS1 = pin.endsWith("S1");
// Used for reading 2 byte integer values from raw sensors
analog = endsWithS1 ? EVS.S1_ANALOG : EVS.S2_ANALOG;
// Sensor Mode (1 or 2?)
mode = endsWithS1 ? EVS.S1_MODE : EVS.S2_MODE;
// Used for read registers
offset = endsWithS1 ? EVS.S1_OFFSET : EVS.S2_OFFSET;
// Used to address "sensor type"
sensor = endsWithS1 ? EVS.S1 : EVS.S2;
}
return {
address: address,
analog: analog,
bank: bank,
mode: mode,
motor: motor,
offset: offset,
port: port,
sensor: sensor,
};
};
EVS.isRawSensor = function(port) {
return port.analog === EVS.S1_ANALOG || port.analog === EVS.S2_ANALOG;
};
EVS.prototype = Object.create(Emitter.prototype, {
constructor: {
value: EVS
}
});
EVS.prototype.setup = function(port, type) {
this.bank[port.bank].write(port.mode, [type]);
};
EVS.prototype.read = function(port, register, numBytes, callback) {
if (port.sensor && port.offset && !EVS.isRawSensor(port)) {
register += port.offset;
}
this.bank[port.bank].read(register, numBytes, callback);
};
EVS.prototype.write = function(port, register, data) {
this.bank[port.bank].write(register, data);
};
/*
* Shield Registers
*/
EVS.BAS1 = 0x01;
EVS.BAS2 = 0x02;
EVS.BBS1 = 0x03;
EVS.BBS2 = 0x04;
EVS.BAM1 = 0x05;
EVS.BAM2 = 0x06;
EVS.BBM1 = 0x07;
EVS.BBM2 = 0x08;
EVS.BANK_A = 0x1A;
EVS.BANK_B = 0x1B;
EVS.S1 = 0x01;
EVS.S2 = 0x02;
EVS.M1 = 0x01;
EVS.M2 = 0x02;
EVS.MM = 0x03;
EVS.Type_NONE = 0x00;
EVS.Type_SWITCH = 0x01;
EVS.Type_ANALOG = 0x02;
EVS.Type_I2C = 0x09;
/*
* Sensor Mode NXT
*/
EVS.Type_NXT_LIGHT_REFLECTED = 0x03;
EVS.Type_NXT_LIGHT = 0x04;
EVS.Type_NXT_COLOR = 0x0D;
EVS.Type_NXT_COLOR_RGBRAW = 0x04;
EVS.Type_NXT_COLORRED = 0x0E;
EVS.Type_NXT_COLORGREEN = 0x0F;
EVS.Type_NXT_COLORBLUE = 0x10;
EVS.Type_NXT_COLORNONE = 0x11;
EVS.Type_DATABIT0_HIGH = 0x40;
/*
* Sensor Port Controls
*/
EVS.S1_MODE = 0x6F;
// EVS.S1_EV3_MODE = 0x6F;
EVS.S1_ANALOG = 0x70;
EVS.S1_OFFSET = 0;
EVS.S2_MODE = 0xA3;
// EVS.S2_EV3_MODE = 0x6F;
EVS.S2_ANALOG = 0xA4;
EVS.S2_OFFSET = 52;
/*
* Sensor Mode EV3
*/
EVS.Type_EV3_LIGHT_REFLECTED = 0x00;
EVS.Type_EV3_LIGHT = 0x01;
EVS.Type_EV3_COLOR = 0x02;
EVS.Type_EV3_COLOR_REFRAW = 0x03;
EVS.Type_EV3_COLOR_RGBRAW = 0x04;
EVS.Type_EV3_TOUCH = 0x12;
EVS.Type_EV3 = 0x13;
/*
* Sensor Read Registers
*/
EVS.Light = 0x83;
EVS.Bump = 0x84;
EVS.ColorMeasure = 0x83;
EVS.Proximity = 0x83;
EVS.Touch = 0x83;
EVS.Ultrasonic = 0x81;
EVS.Mode = 0x81;
/*
* Sensor Read Byte Counts
*/
EVS.Light_Bytes = 2;
EVS.Analog_Bytes = 2;
EVS.Bump_Bytes = 1;
EVS.ColorMeasure_Bytes = 2;
EVS.Proximity_Bytes = 2;
EVS.Touch_Bytes = 1;
/*
* Motor selection
*/
EVS.Motor_1 = 0x01;
EVS.Motor_2 = 0x02;
EVS.Motor_Both = 0x03;
/*
* Motor next action
*/
// stop and let the motor coast.
EVS.Motor_Next_Action_Float = 0x00;
// apply brakes, and resist change to tachometer, but if tach position is forcibly changed, do not restore position
EVS.Motor_Next_Action_Brake = 0x01;
// apply brakes, and restore externally forced change to tachometer
EVS.Motor_Next_Action_BrakeHold = 0x02;
EVS.Motor_Stop = 0x60;
EVS.Motor_Reset = 0x52;
/*
* Motor direction
*/
EVS.Motor_Reverse = 0x00;
EVS.Motor_Forward = 0x01;
/*
* Motor Tachometer movement
*/
// Move the tach to absolute value provided
EVS.Motor_Move_Absolute = 0x00;
// Move the tach relative to previous position
EVS.Motor_Move_Relative = 0x01;
/*
* Motor completion
*/
EVS.Motor_Completion_Dont_Wait = 0x00;
EVS.Motor_Completion_Wait_For = 0x01;
/*
* 0-100
*/
EVS.Speed_Full = 90;
EVS.Speed_Medium = 60;
EVS.Speed_Slow = 25;
/*
* Motor Port Controls
*/
EVS.CONTROL_SPEED = 0x01;
EVS.CONTROL_RAMP = 0x02;
EVS.CONTROL_RELATIVE = 0x04;
EVS.CONTROL_TACHO = 0x08;
EVS.CONTROL_BRK = 0x10;
EVS.CONTROL_ON = 0x20;
EVS.CONTROL_TIME = 0x40;
EVS.CONTROL_GO = 0x80;
EVS.STATUS_SPEED = 0x01;
EVS.STATUS_RAMP = 0x02;
EVS.STATUS_MOVING = 0x04;
EVS.STATUS_TACHO = 0x08;
EVS.STATUS_BREAK = 0x10;
EVS.STATUS_OVERLOAD = 0x20;
EVS.STATUS_TIME = 0x40;
EVS.STATUS_STALL = 0x80;
EVS.COMMAND = 0x41;
EVS.VOLTAGE = 0x6E;
EVS.SETPT_M1 = 0x42;
EVS.SPEED_M1 = 0x46;
EVS.TIME_M1 = 0x47;
EVS.CMD_B_M1 = 0x48;
EVS.CMD_A_M1 = 0x49;
EVS.SETPT_M2 = 0x4A;
EVS.SPEED_M2 = 0x4E;
EVS.TIME_M2 = 0x4F;
EVS.CMD_B_M2 = 0x50;
EVS.CMD_A_M2 = 0x51;
/*
* Motor Read registers.
*/
EVS.POSITION_M1 = 0x52;
EVS.POSITION_M2 = 0x56;
EVS.STATUS_M1 = 0x5A;
EVS.STATUS_M2 = 0x5B;
EVS.TASKS_M1 = 0x5C;
EVS.TASKS_M2 = 0x5D;
EVS.ENCODER_PID = 0x5E;
EVS.SPEED_PID = 0x64;
EVS.PASS_COUNT = 0x6A;
EVS.TOLERANCE = 0x6B;
/*
* Built-in components
*/
EVS.BTN_PRESS = 0xDA;
EVS.RGB_LED = 0xD7;
EVS.CENTER_RGB_LED = 0xDE;
module.exports = EVS;
| manorius/printing_with_node | node_modules/johnny-five/lib/evshield.js | JavaScript | mit | 6,044 |
/*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.api.editor.gutter;
public final class Gutters {
private Gutters() {
}
/** Logical identifer for the breakpoints gutter. */
public static final String BREAKPOINTS_GUTTER = "breakpoints";
/** Logical identifer for the line number gutter. */
public static final String LINE_NUMBERS_GUTTER = "lineNumbers";
/** Logical identifer for the annotations gutter. */
public static final String ANNOTATION_GUTTER = "annotation";
}
| gazarenkov/che-sketch | ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/gutter/Gutters.java | Java | epl-1.0 | 1,006 |
/*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.ssh.shared;
/**
* Constants for ssh API
*
* @author Sergii Leschenko
*/
public final class Constants {
public static final String LINK_REL_GENERATE_PAIR = "create pair";
public static final String LINK_REL_CREATE_PAIR = "create pair";
public static final String LINK_REL_GET_PAIRS = "get pairs";
public static final String LINK_REL_GET_PAIR = "get pair";
public static final String LINK_REL_REMOVE_PAIR = "remove pair";
private Constants() {}
}
| gazarenkov/che-sketch | wsmaster/che-core-api-ssh-shared/src/main/java/org/eclipse/che/api/ssh/shared/Constants.java | Java | epl-1.0 | 1,038 |
<?php
$HOME = realpath(dirname(__FILE__)) . "/../../../..";
require_once($HOME . "/tests/class/Common_TestCase.php");
/*
* This file is part of EC-CUBE
*
* Copyright(c) 2000-2012 LOCKON CO.,LTD. All Rights Reserved.
*
* http://www.lockon.co.jp/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/**
* SC_Utils::getRealURL()のテストクラス.
*
*
* @author Hiroko Tamagawa
* @version $Id: SC_Utils_getRealURLTest.php 22144 2012-12-17 05:25:58Z h_yoshimoto $
*/
class SC_Utils_getRealURLTest extends Common_TestCase {
protected function setUp() {
parent::setUp();
}
protected function tearDown() {
parent::tearDown();
}
/////////////////////////////////////////
// TODO ポート番号のためのコロンが必ず入ってしまうのはOK?
public function testGetRealURL_親ディレクトリへの参照を含む場合_正しくパースできる() {
$input = 'http://www.example.jp/aaa/../index.php';
$this->expected = 'http://www.example.jp:/index.php';
$this->actual = SC_Utils::getRealURL($input);
$this->verify();
}
public function testGetRealURL_親ディレクトリへの参照を複数回含む場合_正しくパースできる() {
$input = 'http://www.example.jp/aaa/bbb/../../ccc/ddd/../index.php';
$this->expected = 'http://www.example.jp:/ccc/index.php';
$this->actual = SC_Utils::getRealURL($input);
$this->verify();
}
public function testGetRealURL_カレントディレクトリへの参照を含む場合_正しくパースできる() {
$input = 'http://www.example.jp/aaa/./index.php';
$this->expected = 'http://www.example.jp:/aaa/index.php';
$this->actual = SC_Utils::getRealURL($input);
$this->verify();
}
public function testGetRealURL_httpsの場合_正しくパースできる() {
$input = 'https://www.example.jp/aaa/./index.php';
$this->expected = 'https://www.example.jp:/aaa/index.php';
$this->actual = SC_Utils::getRealURL($input);
$this->verify();
}
//////////////////////////////////////////
}
| mnmn111/ec-cube-global | tests/class/util/SC_Utils/SC_Utils_getRealURLTest.php | PHP | gpl-2.0 | 2,732 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Validate_Barcode_AdapterAbstract
*/
#require_once 'Zend/Validate/Barcode/AdapterAbstract.php';
/**
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Validate_Barcode_Gtin14 extends Zend_Validate_Barcode_AdapterAbstract
{
/**
* Allowed barcode lengths
* @var integer
*/
protected $_length = 14;
/**
* Allowed barcode characters
* @var string
*/
protected $_characters = '0123456789';
/**
* Checksum function
* @var string
*/
protected $_checksum = '_gtin';
}
| T0MM0R/magento | web/lib/Zend/Validate/Barcode/Gtin14.php | PHP | gpl-2.0 | 1,429 |
<?php
/**
* @file
* Contains \Drupal\devel_generate\Plugin\DevelGenerate\ContentDevelGenerate.
*/
namespace Drupal\devel_generate\Plugin\DevelGenerate;
use Drupal\comment\CommentManagerInterface;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\devel_generate\DevelGenerateBase;
use Drupal\field\Entity\FieldConfig;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a ContentDevelGenerate plugin.
*
* @DevelGenerate(
* id = "content",
* label = @Translation("content"),
* description = @Translation("Generate a given number of content. Optionally delete current content."),
* url = "content",
* permission = "administer devel_generate",
* settings = {
* "num" = 50,
* "kill" = FALSE,
* "max_comments" = 0,
* "title_length" = 4
* }
* )
*/
class ContentDevelGenerate extends DevelGenerateBase implements ContainerFactoryPluginInterface {
/**
* The node storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $nodeStorage;
/**
* The node type storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $nodeTypeStorage;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The comment manager service.
*
* @var \Drupal\comment\CommentManagerInterface
*/
protected $commentManager;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* The url generator service.
*
* @var \Drupal\Core\Routing\UrlGeneratorInterface
*/
protected $urlGenerator;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin ID for the plugin instance.
* @param array $plugin_definition
* @param \Drupal\Core\Entity\EntityStorageInterface $node_storage
* The node storage.
* @param \Drupal\Core\Entity\EntityStorageInterface $node_type_storage
* The node type storage.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\comment\CommentManagerInterface $comment_manager
* The comment manager service.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
* The url generator service.
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The date formatter service.
*/
public function __construct(array $configuration, $plugin_id, array $plugin_definition, EntityStorageInterface $node_storage, EntityStorageInterface $node_type_storage, ModuleHandlerInterface $module_handler, CommentManagerInterface $comment_manager = NULL, LanguageManagerInterface $language_manager, UrlGeneratorInterface $url_generator, DateFormatterInterface $date_formatter) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->moduleHandler = $module_handler;
$this->nodeStorage = $node_storage;
$this->nodeTypeStorage = $node_type_storage;
$this->commentManager = $comment_manager;
$this->languageManager = $language_manager;
$this->urlGenerator = $url_generator;
$this->dateFormatter = $date_formatter;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$entity_manager = $container->get('entity.manager');
return new static(
$configuration, $plugin_id, $plugin_definition,
$entity_manager->getStorage('node'),
$entity_manager->getStorage('node_type'),
$container->get('module_handler'),
$container->has('comment.manager') ? $container->get('comment.manager') : NULL,
$container->get('language_manager'),
$container->get('url_generator'),
$container->get('date.formatter')
);
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$types = $this->nodeTypeStorage->loadMultiple();
if (empty($types)) {
$create_url = $this->urlGenerator->generateFromRoute('node.type_add');
$this->setMessage($this->t('You do not have any content types that can be generated. <a href="@create-type">Go create a new content type</a>', array('@create-type' => $create_url)), 'error', FALSE);
return;
}
$options = array();
foreach ($types as $type) {
$options[$type->id()] = array(
'type' => array('#markup' => $type->label()),
);
if ($this->commentManager) {
$comment_fields = $this->commentManager->getFields('node');
$map = array($this->t('Hidden'), $this->t('Closed'), $this->t('Open'));
$fields = array();
foreach ($comment_fields as $field_name => $info) {
// Find all comment fields for the bundle.
if (in_array($type->id(), $info['bundles'])) {
$instance = FieldConfig::loadByName('node', $type->id(), $field_name);
$default_value = $instance->getDefaultValueLiteral();
$default_mode = reset($default_value);
$fields[] = SafeMarkup::format('@field: !state', array(
'@field' => $instance->label(),
'!state' => $map[$default_mode['status']],
));
}
}
// @todo Refactor display of comment fields.
if (!empty($fields)) {
$options[$type->id()]['comments'] = array(
'data' => array(
'#theme' => 'item_list',
'#items' => $fields,
),
);
}
else {
$options[$type->id()]['comments'] = $this->t('No comment fields');
}
}
}
$header = array(
'type' => $this->t('Content type'),
);
if ($this->commentManager) {
$header['comments'] = array(
'data' => $this->t('Comments'),
'class' => array(RESPONSIVE_PRIORITY_MEDIUM),
);
}
$form['node_types'] = array(
'#type' => 'tableselect',
'#header' => $header,
'#options' => $options,
);
$form['kill'] = array(
'#type' => 'checkbox',
'#title' => $this->t('<strong>Delete all content</strong> in these content types before generating new content.'),
'#default_value' => $this->getSetting('kill'),
);
$form['num'] = array(
'#type' => 'number',
'#title' => $this->t('How many nodes would you like to generate?'),
'#default_value' => $this->getSetting('num'),
'#required' => TRUE,
'#min' => 0,
);
$options = array(1 => $this->t('Now'));
foreach (array(3600, 86400, 604800, 2592000, 31536000) as $interval) {
$options[$interval] = $this->dateFormatter->formatInterval($interval, 1) . ' ' . $this->t('ago');
}
$form['time_range'] = array(
'#type' => 'select',
'#title' => $this->t('How far back in time should the nodes be dated?'),
'#description' => $this->t('Node creation dates will be distributed randomly from the current time, back to the selected time.'),
'#options' => $options,
'#default_value' => 604800,
);
$form['max_comments'] = array(
'#type' => $this->moduleHandler->moduleExists('comment') ? 'number' : 'value',
'#title' => $this->t('Maximum number of comments per node.'),
'#description' => $this->t('You must also enable comments for the content types you are generating. Note that some nodes will randomly receive zero comments. Some will receive the max.'),
'#default_value' => $this->getSetting('max_comments'),
'#min' => 0,
'#access' => $this->moduleHandler->moduleExists('comment'),
);
$form['title_length'] = array(
'#type' => 'number',
'#title' => $this->t('Maximum number of words in titles'),
'#default_value' => $this->getSetting('title_length'),
'#required' => TRUE,
'#min' => 1,
'#max' => 255,
);
$form['add_alias'] = array(
'#type' => 'checkbox',
'#disabled' => !$this->moduleHandler->moduleExists('path'),
'#description' => $this->t('Requires path.module'),
'#title' => $this->t('Add an url alias for each node.'),
'#default_value' => FALSE,
);
$form['add_statistics'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Add statistics for each node (node_counter table).'),
'#default_value' => TRUE,
'#access' => $this->moduleHandler->moduleExists('statistics'),
);
$options = array();
// We always need a language.
$languages = $this->languageManager->getLanguages(LanguageInterface::STATE_ALL);
foreach ($languages as $langcode => $language) {
$options[$langcode] = $language->getName();
}
$form['add_language'] = array(
'#type' => 'select',
'#title' => $this->t('Set language on nodes'),
'#multiple' => TRUE,
'#description' => $this->t('Requires locale.module'),
'#options' => $options,
'#default_value' => array(
$this->languageManager->getDefaultLanguage()->getId(),
),
);
$form['#redirect'] = FALSE;
return $form;
}
/**
* {@inheritdoc}
*/
protected function generateElements(array $values) {
if ($values['num'] <= 50 && $values['max_comments'] <= 10) {
$this->generateContent($values);
}
else {
$this->generateBatchContent($values);
}
}
/**
* Method responsible for creating content when
* the number of elements is less than 50.
*/
private function generateContent($values) {
$values['node_types'] = array_filter($values['node_types']);
if (!empty($values['kill']) && $values['node_types']) {
$this->contentKill($values);
}
if (!empty($values['node_types'])) {
// Generate nodes.
$this->develGenerateContentPreNode($values);
$start = time();
for ($i = 1; $i <= $values['num']; $i++) {
$this->develGenerateContentAddNode($values);
if (function_exists('drush_log') && $i % drush_get_option('feedback', 1000) == 0) {
$now = time();
drush_log(dt('Completed !feedback nodes (!rate nodes/min)', array('!feedback' => drush_get_option('feedback', 1000), '!rate' => (drush_get_option('feedback', 1000) * 60) / ($now - $start))), 'ok');
$start = $now;
}
}
}
$this->setMessage($this->formatPlural($values['num'], '1 node created.', 'Finished creating @count nodes'));
}
/**
* Method responsible for creating content when
* the number of elements is greater than 50.
*/
private function generateBatchContent($values) {
// Setup the batch operations and save the variables.
$operations[] = array('devel_generate_operation', array($this, 'batchContentPreNode', $values));
// Add the kill operation.
if ($values['kill']) {
$operations[] = array('devel_generate_operation', array($this, 'batchContentKill', $values));
}
// Add the operations to create the nodes.
for ($num = 0; $num < $values['num']; $num ++) {
$operations[] = array('devel_generate_operation', array($this, 'batchContentAddNode', $values));
}
// Start the batch.
$batch = array(
'title' => $this->t('Generating Content'),
'operations' => $operations,
'finished' => 'devel_generate_batch_finished',
'file' => drupal_get_path('module', 'devel_generate') . '/devel_generate.batch.inc',
);
batch_set($batch);
}
public function batchContentPreNode($vars, &$context) {
$context['results'] = $vars;
$context['results']['num'] = 0;
$this->develGenerateContentPreNode($context['results']);
}
public function batchContentAddNode($vars, &$context) {
$this->develGenerateContentAddNode($context['results']);
$context['results']['num']++;
}
public function batchContentKill($vars, &$context) {
$this->contentKill($context['results']);
}
/**
* {@inheritdoc}
*/
public function validateDrushParams($args) {
$add_language = drush_get_option('languages');
if (!empty($add_language)) {
$add_language = explode(',', str_replace(' ', '', $add_language));
// Intersect with the enabled languages to make sure the language args
// passed are actually enabled.
$values['values']['add_language'] = array_intersect($add_language, array_keys($this->languageManager->getLanguages(LanguageInterface::STATE_ALL)));
}
$values['kill'] = drush_get_option('kill');
$values['title_length'] = 6;
$values['num'] = array_shift($args);
$values['max_comments'] = array_shift($args);
$all_types = array_keys(node_type_get_names());
$default_types = array_intersect(array('page', 'article'), $all_types);
$selected_types = _convert_csv_to_array(drush_get_option('types', $default_types));
if (empty($selected_types)) {
return drush_set_error('DEVEL_GENERATE_NO_CONTENT_TYPES', dt('No content types available'));
}
$values['node_types'] = array_combine($selected_types, $selected_types);
$node_types = array_filter($values['node_types']);
if (!empty($values['kill']) && empty($node_types)) {
return drush_set_error('DEVEL_GENERATE_INVALID_INPUT', dt('Please provide content type (--types) in which you want to delete the content.'));
}
return $values;
}
/**
* Deletes all nodes of given node types.
*
* @param array $values
* The input values from the settings form.
*/
protected function contentKill($values) {
$nids = $this->nodeStorage->getQuery()
->condition('type', $values['node_types'], 'IN')
->execute();
if (!empty($nids)) {
$nodes = $this->nodeStorage->loadMultiple($nids);
$this->nodeStorage->delete($nodes);
$this->setMessage($this->t('Deleted %count nodes.', array('%count' => count($nids))));
}
}
/**
* Return the same array passed as parameter
* but with an array of uids for the key 'users'.
*/
protected function develGenerateContentPreNode(&$results) {
// Get user id.
$users = $this->getUsers();
$users = array_merge($users, array('0'));
$results['users'] = $users;
}
/**
* Create one node. Used by both batch and non-batch code branches.
*/
protected function develGenerateContentAddNode(&$results) {
if (!isset($results['time_range'])) {
$results['time_range'] = 0;
}
$users = $results['users'];
$node_type = array_rand(array_filter($results['node_types']));
$uid = $users[array_rand($users)];
$node = $this->nodeStorage->create(array(
'nid' => NULL,
'type' => $node_type,
'title' => $this->getRandom()->sentences(mt_rand(1, $results['title_length']), TRUE),
'uid' => $uid,
'revision' => mt_rand(0, 1),
'status' => TRUE,
'promote' => mt_rand(0, 1),
'created' => REQUEST_TIME - mt_rand(0, $results['time_range']),
'langcode' => $this->getLangcode($results),
));
// A flag to let hook_node_insert() implementations know that this is a
// generated node.
$node->devel_generate = $results;
// Populate all fields with sample values.
$this->populateFields($node);
// See devel_generate_node_insert() for actions that happen before and after
// this save.
$node->save();
}
/**
* Determine language based on $results.
*/
protected function getLangcode($results) {
if (isset($results['add_language'])) {
$langcodes = $results['add_language'];
$langcode = $langcodes[array_rand($langcodes)];
}
else {
$langcode = $this->languageManager->getDefaultLanguage()->getId();
}
return $langcode;
}
/**
* Retrive 50 uids from the database.
*/
protected function getUsers() {
$users = array();
$result = db_query_range("SELECT uid FROM {users}", 0, 50);
foreach ($result as $record) {
$users[] = $record->uid;
}
return $users;
}
}
| eric-shell/badcamp-d8 | modules/devel/devel_generate/src/Plugin/DevelGenerate/ContentDevelGenerate.php | PHP | gpl-2.0 | 16,625 |
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/** Generated Model - DO NOT CHANGE */
package org.compiere.model;
import java.sql.ResultSet;
import java.util.Properties;
import org.compiere.util.KeyNamePair;
/** Generated Model for AD_ImpFormat
* @author Adempiere (generated)
* @version Release 3.8.0 - $Id$ */
public class X_AD_ImpFormat extends PO implements I_AD_ImpFormat, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20150223L;
/** Standard Constructor */
public X_AD_ImpFormat (Properties ctx, int AD_ImpFormat_ID, String trxName)
{
super (ctx, AD_ImpFormat_ID, trxName);
/** if (AD_ImpFormat_ID == 0)
{
setAD_ImpFormat_ID (0);
setAD_Table_ID (0);
setFormatType (null);
setName (null);
setProcessing (false);
} */
}
/** Load Constructor */
public X_AD_ImpFormat (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 6 - System - Client
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_ImpFormat[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Import Format.
@param AD_ImpFormat_ID Import Format */
public void setAD_ImpFormat_ID (int AD_ImpFormat_ID)
{
if (AD_ImpFormat_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_ImpFormat_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_ImpFormat_ID, Integer.valueOf(AD_ImpFormat_ID));
}
/** Get Import Format.
@return Import Format */
public int getAD_ImpFormat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_ImpFormat_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Table getAD_Table() throws RuntimeException
{
return (org.compiere.model.I_AD_Table)MTable.get(getCtx(), org.compiere.model.I_AD_Table.Table_Name)
.getPO(getAD_Table_ID(), get_TrxName()); }
/** Set Table.
@param AD_Table_ID
Database Table information
*/
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get Table.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** FormatType AD_Reference_ID=209 */
public static final int FORMATTYPE_AD_Reference_ID=209;
/** Fixed Position = F */
public static final String FORMATTYPE_FixedPosition = "F";
/** Comma Separated = C */
public static final String FORMATTYPE_CommaSeparated = "C";
/** Tab Separated = T */
public static final String FORMATTYPE_TabSeparated = "T";
/** XML = X */
public static final String FORMATTYPE_XML = "X";
/** Custom Separator Char = U */
public static final String FORMATTYPE_CustomSeparatorChar = "U";
/** Set Format.
@param FormatType
Format of the data
*/
public void setFormatType (String FormatType)
{
set_Value (COLUMNNAME_FormatType, FormatType);
}
/** Get Format.
@return Format of the data
*/
public String getFormatType ()
{
return (String)get_Value(COLUMNNAME_FormatType);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Separator Character.
@param SeparatorChar Separator Character */
public void setSeparatorChar (String SeparatorChar)
{
set_Value (COLUMNNAME_SeparatorChar, SeparatorChar);
}
/** Get Separator Character.
@return Separator Character */
public String getSeparatorChar ()
{
return (String)get_Value(COLUMNNAME_SeparatorChar);
}
} | TaymourReda/-https-github.com-adempiere-adempiere | base/src/org/compiere/model/X_AD_ImpFormat.java | Java | gpl-2.0 | 6,439 |
/*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2009 Eric Lafortune (eric@graphics.cornell.edu)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.obfuscate;
import proguard.classfile.*;
import proguard.classfile.util.*;
import proguard.classfile.visitor.*;
import java.io.PrintStream;
/**
* This ClassVisitor prints out the renamed classes and class members with
* their old names and new names.
*
* @see ClassRenamer
*
* @author Eric Lafortune
*/
public class MappingPrinter
extends SimplifiedVisitor
implements ClassVisitor,
MemberVisitor
{
private final PrintStream ps;
/**
* Creates a new MappingPrinter that prints to <code>System.out</code>.
*/
public MappingPrinter()
{
this(System.out);
}
/**
* Creates a new MappingPrinter that prints to the given stream.
* @param printStream the stream to which to print
*/
public MappingPrinter(PrintStream printStream)
{
this.ps = printStream;
}
// Implementations for ClassVisitor.
public void visitProgramClass(ProgramClass programClass)
{
String name = programClass.getName();
String newName = ClassObfuscator.newClassName(programClass);
ps.println(ClassUtil.externalClassName(name) +
" -> " +
ClassUtil.externalClassName(newName) +
":");
// Print out the class members.
programClass.fieldsAccept(this);
programClass.methodsAccept(this);
}
public void visitLibraryClass(LibraryClass libraryClass)
{
}
// Implementations for MemberVisitor.
public void visitProgramField(ProgramClass programClass, ProgramField programField)
{
String newName = MemberObfuscator.newMemberName(programField);
if (newName != null)
{
ps.println(" " +
//lineNumberRange(programClass, programField) +
ClassUtil.externalFullFieldDescription(
0,
programField.getName(programClass),
programField.getDescriptor(programClass)) +
" -> " +
newName);
}
}
public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
{
// Special cases: <clinit> and <init> are always kept unchanged.
// We can ignore them here.
String name = programMethod.getName(programClass);
if (name.equals(ClassConstants.INTERNAL_METHOD_NAME_CLINIT) ||
name.equals(ClassConstants.INTERNAL_METHOD_NAME_INIT))
{
return;
}
String newName = MemberObfuscator.newMemberName(programMethod);
if (newName != null)
{
ps.println(" " +
lineNumberRange(programClass, programMethod) +
ClassUtil.externalFullMethodDescription(
programClass.getName(),
0,
programMethod.getName(programClass),
programMethod.getDescriptor(programClass)) +
" -> " +
newName);
}
}
// Small utility methods.
/**
* Returns the line number range of the given class member, followed by a
* colon, or just an empty String if no range is available.
*/
private static String lineNumberRange(ProgramClass programClass, ProgramMember programMember)
{
String range = programMember.getLineNumberRange(programClass);
return range != null ?
(range + ":") :
"";
}
}
| shakalaca/ASUS_ZenFone_A450CG | external/proguard/src/proguard/obfuscate/MappingPrinter.java | Java | gpl-2.0 | 4,505 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "ags/engine/ac/dynobj/cc_gui.h"
#include "ags/engine/ac/dynobj/script_gui.h"
#include "ags/globals.h"
namespace AGS3 {
// return the type name of the object
const char *CCGUI::GetType() {
return "GUI";
}
// serialize the object into BUFFER (which is BUFSIZE bytes)
// return number of bytes used
int CCGUI::Serialize(const char *address, char *buffer, int bufsize) {
const ScriptGUI *shh = (const ScriptGUI *)address;
StartSerialize(buffer);
SerializeInt(shh->id);
return EndSerialize();
}
void CCGUI::Unserialize(int index, const char *serializedData, int dataSize) {
StartUnserialize(serializedData, dataSize);
int num = UnserializeInt();
ccRegisterUnserializedObject(index, &_G(scrGui)[num], this);
}
} // namespace AGS3
| vanfanel/scummvm | engines/ags/engine/ac/dynobj/cc_gui.cpp | C++ | gpl-2.0 | 1,695 |
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "rel_job".
*
* @property integer $rj_id
* @property string $positiontype
* @property string $rj_name
* @property string $rj_dep
* @property string $work_type
* @property string $max_salary
* @property string $work_city
* @property string $work_year
* @property string $education
* @property string $work_tempt
* @property string $work_desc
* @property string $work_address
* @property integer $company_id
* @property integer $rj_status
* @property integer $addtime
* @property integer $m_id
* @property string $email
* @property integer $is_hot
* @property string $min_salary
* @property integer $is_ok
* @property string $lng
* @property string $lat
*/
class RelJob extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'rel_job';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['rj_name'], 'required'],
[['max_salary'], 'number'],
[['work_desc'], 'string'],
[['company_id', 'rj_status', 'addtime', 'm_id', 'is_hot', 'is_ok'], 'integer'],
[['positiontype', 'rj_dep', 'work_type'], 'string', 'max' => 30],
[['rj_name', 'lng', 'lat'], 'string', 'max' => 20],
[['work_city', 'work_year', 'education'], 'string', 'max' => 10],
[['work_tempt'], 'string', 'max' => 25],
[['work_address'], 'string', 'max' => 255],
[['email'], 'string', 'max' => 50],
[['min_salary'], 'string', 'max' => 220]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'rj_id' => 'Rj ID',
'positiontype' => 'Positiontype',
'rj_name' => 'Rj Name',
'rj_dep' => 'Rj Dep',
'work_type' => 'Work Type',
'max_salary' => 'Max Salary',
'work_city' => 'Work City',
'work_year' => 'Work Year',
'education' => 'Education',
'work_tempt' => 'Work Tempt',
'work_desc' => 'Work Desc',
'work_address' => 'Work Address',
'company_id' => 'Company ID',
'rj_status' => 'Rj Status',
'addtime' => 'Addtime',
'm_id' => 'M ID',
'email' => 'Email',
'is_hot' => 'Is Hot',
'min_salary' => 'Min Salary',
'is_ok' => 'Is Ok',
'lng' => 'Lng',
'lat' => 'Lat',
];
}
}
| zyweb/group5 | models/RelJob.php | PHP | gpl-2.0 | 2,597 |
/*
* Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
/**
* Serializing an object containing a byte stream.
*/
abstract public class AbstractStreamSerializer extends AbstractSerializer
{
/**
* Writes the object to the output stream.
*/
@Override
public void writeObject(Object obj, AbstractHessianOutput out)
throws IOException
{
if (out.addRef(obj)) {
return;
}
int ref = out.writeObjectBegin(getClassName(obj));
if (ref < -1) {
out.writeString("value");
InputStream is = null;
try {
is = getInputStream(obj);
} catch (Exception e) {
log.log(Level.WARNING, e.toString(), e);
}
if (is != null) {
try {
out.writeByteStream(is);
} finally {
is.close();
}
} else {
out.writeNull();
}
out.writeMapEnd();
}
else {
if (ref == -1) {
out.writeClassFieldLength(1);
out.writeString("value");
out.writeObjectBegin(getClassName(obj));
}
InputStream is = null;
try {
is = getInputStream(obj);
} catch (Exception e) {
log.log(Level.WARNING, e.toString(), e);
}
try {
if (is != null)
out.writeByteStream(is);
else
out.writeNull();
} finally {
if (is != null)
is.close();
}
}
}
protected String getClassName(Object obj)
{
return obj.getClass().getName();
}
abstract protected InputStream getInputStream(Object obj)
throws IOException;
}
| mdaniel/svn-caucho-com-resin | modules/hessian/src/com/caucho/hessian/io/AbstractStreamSerializer.java | Java | gpl-2.0 | 3,888 |
<?php defined( 'ABSPATH' ) or exit() ?>
<div class="wrap eventrocket cleanup">
<h2> <?php _e( 'Event Data Cleanup', 'eventrocket' ) ?> </h2>
<?php if ( ! $in_progress ): ?>
<p> <?php
_e( 'There may be occasions where you want to remove all traces of The Events Calendar and associated '
. 'plugins from the database, either because you no longer need it or because you want to start afresh. '
. 'This tool can help with that. <strong> Use with caution! </strong> ', 'eventrocket' );
?> </p>
<?php elseif ( $in_progress && 0 < max( $current_data ) ): ?>
<div class="updated">
<p> <?php _e( '<strong> Still working… </strong> please be patient while the remaining data is '
. 'removed.', 'eventrocket' ); ?>
<img src="<?php echo esc_url( admin_url( 'images/spinner.gif' ) ) ?>" />
</p>
<input type="hidden" name="keep_working" id="keep_working" value="<?php echo esc_attr( $action_url ) ?>" />
</div>
<?php elseif ( $in_progress && 0 === max( $current_data ) ): ?>
<div class="updated"> <p>
<?php _e( '<strong> Cleanup complete! </strong> Now get back to work. ', 'eventrocket' ); ?>
</p> </div>
<?php endif ?>
<?php if ( 0 === max( $current_data ) ): ?>
<p> <strong> <?php _e( 'No event related data found! You’re all set!', 'eventrocket') ?> </strong></p>
<?php else: ?>
<h4> <?php _e( 'Event data found within your database:', 'eventrocket' ) ?> </h4>
<dl>
<dt> <?php _e( 'Event objects', 'eventrocket' ) ?> </dt>
<dd> <?php echo esc_html( $current_data['events'] ) ?> </dd>
<dt> <?php _e( 'Venue objects', 'eventrocket' ) ?> </dt>
<dd> <?php echo esc_html( $current_data['venues'] ) ?> </dd>
<dt> <?php _e( 'Organizer objects', 'eventrocket' ) ?> </dt>
<dd> <?php echo esc_html( $current_data['organizers'] ) ?> </dd>
<dt> <?php _e( 'User capabilities', 'eventrocket' ) ?> </dt>
<dd> <?php echo esc_html( $current_data['capabilities'] ) ?> </dd>
<dt> <?php _e( 'Other settings', 'eventrocket' ) ?> </dt>
<dd> <?php echo esc_html( $current_data['options'] ) ?> </dd>
</dl>
<?php if ( ! $in_progress ): ?>
<h4> <?php _e( 'Run the cleanup tool', 'eventrocket' ) ?> </h4>
<div class="hide-if-no-js">
<p id="cleanup_safety">
<input type="checkbox" name="user_confirms" id="user_confirms" value="1" />
<label for="user_confirms"> <?php _e( 'I understand the risks involved and acknowledge that running '
. 'this cleanup tool without first making a backup may be deemed an act of stupidity.',
'eventrocket' ) ?> </label>
</p>
</div>
<p id="do_cleanup"> <a href="<?php echo esc_attr( $action_url ) ?>" class="button-primary"><?php _e( 'Do cleanup', 'eventrocket' ) ?></a> </p>
<?php endif ?>
<?php endif ?>
</div> | evamichalcak/doartystuff | wp-content/plugins/event-rocket/templates/cleanup-screen.php | PHP | gpl-2.0 | 2,765 |
// license:BSD-3-Clause
// copyright-holders:Curt Coder
/*
TODO:
- tape input/output
- PL-80 plotter
- serial printer
- thermal printer
*/
#include "includes/comx35.h"
#include "formats/imageutl.h"
#include "softlist.h"
/***************************************************************************
PARAMETERS
***************************************************************************/
#define LOG 0
enum
{
COMX_TYPE_BINARY = 1,
COMX_TYPE_BASIC,
COMX_TYPE_BASIC_FM,
COMX_TYPE_RESERVED,
COMX_TYPE_DATA
};
/***************************************************************************
IMPLEMENTATION
***************************************************************************/
/*-------------------------------------------------
image_fread_memory - read image to memory
-------------------------------------------------*/
void comx35_state::image_fread_memory(device_image_interface &image, UINT16 addr, UINT32 count)
{
UINT8 *ram = m_ram->pointer() + (addr - 0x4000);
image.fread(ram, count);
}
/*-------------------------------------------------
QUICKLOAD_LOAD_MEMBER( comx35_state, comx35_comx )
-------------------------------------------------*/
QUICKLOAD_LOAD_MEMBER( comx35_state, comx35_comx )
{
address_space &program = m_maincpu->space(AS_PROGRAM);
UINT8 header[16] = {0};
int size = image.length();
if (size > m_ram->size())
{
return IMAGE_INIT_FAIL;
}
image.fread( header, 5);
if (header[1] != 'C' || header[2] != 'O' || header[3] != 'M' || header[4] != 'X' )
{
return IMAGE_INIT_FAIL;
}
switch (header[0])
{
case COMX_TYPE_BINARY:
/*
Type 1: pure machine code (i.e. no basic)
Byte 0 to 4: 1 - 'COMX'
Byte 5 and 6: Start address (1802 way; see above)
Byte 6 and 7: End address
Byte 9 and 10: Execution address
Byte 11 to Eof, should be stored in ram from start to end; execution address
'xxxx' for the CALL (@xxxx) basic statement to actually run the code.
*/
{
UINT16 start_address, end_address, run_address;
image.fread(header, 6);
start_address = pick_integer_be(header, 0, 2);
end_address = pick_integer_be(header, 2, 2);
run_address = pick_integer_be(header, 4, 2);
image_fread_memory(image, start_address, end_address - start_address);
popmessage("Type CALL (@%04x) to start program", run_address);
}
break;
case COMX_TYPE_BASIC:
/*
Type 2: Regular basic code or machine code followed by basic
Byte 0 to 4: 2 - 'COMX'
Byte 5 and 6: DEFUS value, to be stored on 0x4281 and 0x4282
Byte 7 and 8: EOP value, to be stored on 0x4283 and 0x4284
Byte 9 and 10: End array, start string to be stored on 0x4292 and 0x4293
Byte 11 and 12: start array to be stored on 0x4294 and 0x4295
Byte 13 and 14: EOD and end string to be stored on 0x4299 and 0x429A
Byte 15 to Eof to be stored on 0x4400 and onwards
Byte 0x4281-0x429A (or at least the ones above) should be set otherwise
BASIC won't 'see' the code.
*/
image_fread_memory(image, 0x4281, 4);
image_fread_memory(image, 0x4292, 4);
image_fread_memory(image, 0x4299, 2);
image_fread_memory(image, 0x4400, size);
break;
case COMX_TYPE_BASIC_FM:
/*
Type 3: F&M basic load
Not the most important! But we designed our own basic extension, you can
find it in the F&M basic folder as F&M Basic.comx. When you run this all
basic code should start at address 0x6700 instead of 0x4400 as from
0x4400-0x6700 the F&M basic stuff is loaded. So format is identical to Type
2 except Byte 15 to Eof should be stored on 0x6700 instead. .comx files of
this format can also be found in the same folder as the F&M basic.comx file.
*/
image_fread_memory(image, 0x4281, 4);
image_fread_memory(image, 0x4292, 4);
image_fread_memory(image, 0x4299, 2);
image_fread_memory(image, 0x6700, size);
break;
case COMX_TYPE_RESERVED:
/*
Type 4: Incorrect DATA format, I suggest to forget this one as it won't work
in most cases. Instead I left this one reserved and designed Type 5 instead.
*/
break;
case COMX_TYPE_DATA:
/*
Type 5: Data load
Byte 0 to 4: 5 - 'COMX'
Byte 5 and 6: Array length
Byte 7 to Eof: Basic 'data'
To load this first get the 'start array' from the running COMX, i.e. address
0x4295/0x4296. Calculate the EOD as 'start array' + length of the data (i.e.
file length - 7). Store the EOD back on 0x4299 and ox429A. Calculate the
'Start String' as 'start array' + 'Array length' (Byte 5 and 6). Store the
'Start String' on 0x4292/0x4293. Load byte 7 and onwards starting from the
'start array' value fetched from 0x4295/0x4296.
*/
{
UINT16 start_array, end_array, start_string, array_length;
image.fread(header, 2);
array_length = pick_integer_be(header, 0, 2);
start_array = (program.read_byte(0x4295) << 8) | program.read_byte(0x4296);
end_array = start_array + (size - 7);
program.write_byte(0x4299, end_array >> 8);
program.write_byte(0x429a, end_array & 0xff);
start_string = start_array + array_length;
program.write_byte(0x4292, start_string >> 8);
program.write_byte(0x4293, start_string & 0xff);
image_fread_memory(image, start_array, size);
}
break;
}
return IMAGE_INIT_PASS;
}
//**************************************************************************
// MEMORY ACCESS
//**************************************************************************
//-------------------------------------------------
// mem_r - memory read
//-------------------------------------------------
READ8_MEMBER( comx35_state::mem_r )
{
int extrom = 1;
UINT8 data = m_exp->mrd_r(space, offset, &extrom);
if (offset < 0x4000)
{
if (extrom) data = m_rom->base()[offset & 0x3fff];
}
else if (offset >= 0x4000 && offset < 0xc000)
{
data = m_ram->pointer()[offset - 0x4000];
}
else if (offset >= 0xf400 && offset < 0xf800)
{
data = m_vis->char_ram_r(space, offset & 0x3ff);
}
return data;
}
//-------------------------------------------------
// mem_w - memory write
//-------------------------------------------------
WRITE8_MEMBER( comx35_state::mem_w )
{
m_exp->mwr_w(space, offset, data);
if (offset >= 0x4000 && offset < 0xc000)
{
m_ram->pointer()[offset - 0x4000] = data;
}
else if (offset >= 0xf400 && offset < 0xf800)
{
m_vis->char_ram_w(space, offset & 0x3ff, data);
}
else if (offset >= 0xf800)
{
m_vis->page_ram_w(space, offset & 0x3ff, data);
}
}
//-------------------------------------------------
// io_r - I/O read
//-------------------------------------------------
READ8_MEMBER( comx35_state::io_r )
{
UINT8 data = m_exp->io_r(space, offset);
if (offset == 3)
{
data = m_kbe->read(space, 0);
}
return data;
}
//-------------------------------------------------
// io_w - I/O write
//-------------------------------------------------
WRITE8_MEMBER( comx35_state::io_w )
{
m_exp->io_w(space, offset, data);
if (offset >= 3)
{
cdp1869_w(space, offset, data);
}
}
//**************************************************************************
// ADDRESS MAPS
//**************************************************************************
//-------------------------------------------------
// ADDRESS_MAP( comx35_mem )
//-------------------------------------------------
static ADDRESS_MAP_START( comx35_mem, AS_PROGRAM, 8, comx35_state )
ADDRESS_MAP_UNMAP_HIGH
AM_RANGE(0x0000, 0xffff) AM_READWRITE(mem_r, mem_w)
ADDRESS_MAP_END
//-------------------------------------------------
// ADDRESS_MAP( comx35_io )
//-------------------------------------------------
static ADDRESS_MAP_START( comx35_io, AS_IO, 8, comx35_state )
ADDRESS_MAP_UNMAP_HIGH
AM_RANGE(0x00, 0x07) AM_READWRITE(io_r, io_w)
ADDRESS_MAP_END
//**************************************************************************
// INPUT PORTS
//**************************************************************************
//-------------------------------------------------
// INPUT_CHANGED_MEMBER( comx35_reset )
//-------------------------------------------------
INPUT_CHANGED_MEMBER( comx35_state::trigger_reset )
{
if (newval && BIT(m_d6->read(), 7))
{
machine_reset();
}
}
//-------------------------------------------------
// INPUT_PORTS( comx35 )
//-------------------------------------------------
static INPUT_PORTS_START( comx35 )
PORT_START("D1")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("0 \xE2\x96\xA0") PORT_CODE(KEYCODE_0) PORT_CHAR('0') PORT_CHAR('@')
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_1) PORT_CHAR('1') PORT_CHAR('!')
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_2) PORT_CHAR('2') PORT_CHAR('"')
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_3) PORT_CHAR('3') PORT_CHAR('#')
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_4) PORT_CHAR('4') PORT_CHAR('$')
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_5) PORT_CHAR('5') PORT_CHAR('%')
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_6) PORT_CHAR('6') PORT_CHAR('&')
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_7) PORT_CHAR('7') PORT_CHAR('?')
PORT_START("D2")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_8) PORT_CHAR('8') PORT_CHAR('[')
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_9) PORT_CHAR('9') PORT_CHAR(']')
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_STOP) PORT_CHAR('.') PORT_CHAR(':')
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_COMMA) PORT_CHAR(',') PORT_CHAR(';')
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_MINUS) PORT_CHAR('<') PORT_CHAR('(')
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_OPENBRACE) PORT_CHAR('=') PORT_CHAR('^')
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_EQUALS) PORT_CHAR('>') PORT_CHAR(')')
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_CLOSEBRACE) PORT_CHAR('\\') PORT_CHAR('_')
PORT_START("D3")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_TILDE) PORT_CHAR('?')
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_A) PORT_CHAR('A')
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_B) PORT_CHAR('B')
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_C) PORT_CHAR('C')
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_D) PORT_CHAR('D')
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_E) PORT_CHAR('E')
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F) PORT_CHAR('F')
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_G) PORT_CHAR('G')
PORT_START("D4")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_H) PORT_CHAR('H')
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_I) PORT_CHAR('I')
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_J) PORT_CHAR('J')
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_K) PORT_CHAR('K')
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_L) PORT_CHAR('L')
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_M) PORT_CHAR('M')
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_N) PORT_CHAR('N')
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_O) PORT_CHAR('O')
PORT_START("D5")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_P) PORT_CHAR('P')
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Q) PORT_CHAR('Q')
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_R) PORT_CHAR('R')
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_S) PORT_CHAR('S')
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_T) PORT_CHAR('T')
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_U) PORT_CHAR('U')
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_V) PORT_CHAR('V')
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_W) PORT_CHAR('W')
PORT_START("D6")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_X) PORT_CHAR('X')
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Y) PORT_CHAR('Y')
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Z) PORT_CHAR('Z')
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_COLON) PORT_CHAR('+') PORT_CHAR('{')
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_QUOTE) PORT_CHAR('-') PORT_CHAR('|')
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_BACKSLASH) PORT_CHAR('*') PORT_CHAR('}')
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_SLASH) PORT_CHAR('/') PORT_CHAR('~')
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("SPACE") PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ') PORT_CHAR(8)
PORT_START("D7")
PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("D8")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("CR") PORT_CODE(KEYCODE_ENTER) PORT_CHAR(13)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("ESC") PORT_CODE(KEYCODE_ESC) PORT_CHAR(UCHAR_MAMEKEY(ESC))
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME(UTF8_UP) PORT_CODE(KEYCODE_UP) PORT_CHAR(UCHAR_MAMEKEY(UP))
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME(UTF8_RIGHT) PORT_CODE(KEYCODE_RIGHT) PORT_CHAR(UCHAR_MAMEKEY(RIGHT))
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME(UTF8_LEFT) PORT_CODE(KEYCODE_LEFT) PORT_CHAR(UCHAR_MAMEKEY(LEFT))
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME(UTF8_DOWN) PORT_CODE(KEYCODE_DOWN) PORT_CHAR(UCHAR_MAMEKEY(DOWN))
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("DEL") PORT_CODE(KEYCODE_BACKSPACE) PORT_CHAR(8)
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("D9")
PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("D10")
PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("D11")
PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("MODIFIERS")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("SHIFT") PORT_CODE(KEYCODE_LSHIFT) PORT_CODE(KEYCODE_RSHIFT) PORT_CHAR(UCHAR_SHIFT_1) PORT_WRITE_LINE_DEVICE_MEMBER(CDP1871_TAG, cdp1871_device, shift_w)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("CNTL") PORT_CODE(KEYCODE_LCONTROL) PORT_CODE(KEYCODE_RCONTROL) PORT_CHAR(UCHAR_MAMEKEY(LCONTROL)) PORT_CHAR(UCHAR_MAMEKEY(RCONTROL)) PORT_WRITE_LINE_DEVICE_MEMBER(CDP1871_TAG, cdp1871_device, control_w)
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("RESET")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("RT") PORT_CODE(KEYCODE_F10) PORT_CHAR(UCHAR_MAMEKEY(F10)) PORT_CHANGED_MEMBER(DEVICE_SELF, comx35_state, trigger_reset, 0)
INPUT_PORTS_END
//**************************************************************************
// DEVICE CONFIGURATION
//**************************************************************************
//-------------------------------------------------
// COSMAC_INTERFACE( cosmac_intf )
//-------------------------------------------------
void comx35_state::check_interrupt()
{
m_maincpu->set_input_line(COSMAC_INPUT_LINE_INT, m_cr1 || m_int);
}
READ_LINE_MEMBER( comx35_state::clear_r )
{
return m_clear;
}
READ_LINE_MEMBER( comx35_state::ef2_r )
{
if (m_iden)
{
// interrupts disabled: PAL/NTSC
return m_vis->pal_ntsc_r();
}
else
{
// interrupts enabled: keyboard repeat
return m_kbe->rpt_r();
}
}
READ_LINE_MEMBER( comx35_state::ef4_r )
{
return m_exp->ef4_r(); // | (m_cassette->input() > 0.0f);
}
WRITE_LINE_MEMBER( comx35_state::q_w )
{
m_q = state;
if (m_iden && state)
{
// enable interrupts
m_iden = 0;
}
// cassette output
m_cassette->output(state ? +1.0 : -1.0);
// expansion bus
m_exp->q_w(state);
}
WRITE8_MEMBER( comx35_state::sc_w )
{
switch (data)
{
case COSMAC_STATE_CODE_S0_FETCH:
// not connected
break;
case COSMAC_STATE_CODE_S1_EXECUTE:
// every other S1 triggers a DMAOUT request
if (m_dma)
{
m_dma = 0;
if (!m_iden)
{
m_maincpu->set_input_line(COSMAC_INPUT_LINE_DMAOUT, ASSERT_LINE);
}
}
else
{
m_dma = 1;
}
break;
case COSMAC_STATE_CODE_S2_DMA:
// DMA acknowledge clears the DMAOUT request
m_maincpu->set_input_line(COSMAC_INPUT_LINE_DMAOUT, CLEAR_LINE);
break;
case COSMAC_STATE_CODE_S3_INTERRUPT:
// interrupt acknowledge clears the INT request
m_maincpu->set_input_line(COSMAC_INPUT_LINE_INT, CLEAR_LINE);
break;
}
}
//-------------------------------------------------
// COMX_EXPANSION_INTERFACE( expansion_intf )
//-------------------------------------------------
WRITE_LINE_MEMBER( comx35_state::irq_w )
{
m_int = state;
check_interrupt();
}
//**************************************************************************
// MACHINE INITIALIZATION
//**************************************************************************
//-------------------------------------------------
// device_timer - handler timer events
//-------------------------------------------------
void comx35_state::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr)
{
switch (id)
{
case TIMER_ID_RESET:
m_clear = 1;
break;
}
}
//-------------------------------------------------
// MACHINE_START( comx35 )
//-------------------------------------------------
void comx35_state::machine_start()
{
// clear the RAM since DOS card will go crazy if RAM is not all zeroes
UINT8 *ram = m_ram->pointer();
memset(ram, 0, m_ram->size());
// register for state saving
save_item(NAME(m_clear));
save_item(NAME(m_q));
save_item(NAME(m_iden));
save_item(NAME(m_dma));
save_item(NAME(m_int));
save_item(NAME(m_prd));
save_item(NAME(m_cr1));
}
void comx35_state::machine_reset()
{
m_exp->reset();
int t = RES_K(27) * CAP_U(1) * 1000; // t = R1 * C1
m_clear = 0;
m_iden = 1;
m_cr1 = 1;
m_int = CLEAR_LINE;
m_prd = CLEAR_LINE;
timer_set(attotime::from_msec(t), TIMER_ID_RESET);
}
//**************************************************************************
// MACHINE DRIVERS
//**************************************************************************
//-------------------------------------------------
// MACHINE_CONFIG( pal )
//-------------------------------------------------
static MACHINE_CONFIG_START( pal, comx35_state )
// basic system hardware
MCFG_CPU_ADD(CDP1802_TAG, CDP1802, CDP1869_CPU_CLK_PAL)
MCFG_CPU_PROGRAM_MAP(comx35_mem)
MCFG_CPU_IO_MAP(comx35_io)
MCFG_COSMAC_WAIT_CALLBACK(VCC)
MCFG_COSMAC_CLEAR_CALLBACK(READLINE(comx35_state, clear_r))
MCFG_COSMAC_EF2_CALLBACK(READLINE(comx35_state, ef2_r))
MCFG_COSMAC_EF4_CALLBACK(READLINE(comx35_state, ef4_r))
MCFG_COSMAC_Q_CALLBACK(WRITELINE(comx35_state, q_w))
MCFG_COSMAC_SC_CALLBACK(WRITE8(comx35_state, sc_w))
// sound and video hardware
MCFG_FRAGMENT_ADD(comx35_pal_video)
// peripheral hardware
MCFG_DEVICE_ADD(CDP1871_TAG, CDP1871, CDP1869_CPU_CLK_PAL/8)
MCFG_CDP1871_D1_CALLBACK(IOPORT("D1"))
MCFG_CDP1871_D2_CALLBACK(IOPORT("D2"))
MCFG_CDP1871_D3_CALLBACK(IOPORT("D3"))
MCFG_CDP1871_D4_CALLBACK(IOPORT("D4"))
MCFG_CDP1871_D5_CALLBACK(IOPORT("D5"))
MCFG_CDP1871_D6_CALLBACK(IOPORT("D6"))
MCFG_CDP1871_D7_CALLBACK(IOPORT("D7"))
MCFG_CDP1871_D8_CALLBACK(IOPORT("D8"))
MCFG_CDP1871_D9_CALLBACK(IOPORT("D9"))
MCFG_CDP1871_D10_CALLBACK(IOPORT("D10"))
MCFG_CDP1871_D11_CALLBACK(IOPORT("D11"))
MCFG_CDP1871_DA_CALLBACK(INPUTLINE(CDP1802_TAG, COSMAC_INPUT_LINE_EF3))
MCFG_QUICKLOAD_ADD("quickload", comx35_state, comx35_comx, "comx", 0)
MCFG_CASSETTE_ADD("cassette")
MCFG_CASSETTE_DEFAULT_STATE(CASSETTE_STOPPED | CASSETTE_MOTOR_ENABLED | CASSETTE_SPEAKER_ENABLED)
// expansion bus
MCFG_COMX_EXPANSION_SLOT_ADD(EXPANSION_TAG, comx_expansion_cards, "eb")
MCFG_COMX_EXPANSION_SLOT_IRQ_CALLBACK(WRITELINE(comx35_state, irq_w))
// internal ram
MCFG_RAM_ADD(RAM_TAG)
MCFG_RAM_DEFAULT_SIZE("32K")
// software lists
MCFG_SOFTWARE_LIST_ADD("flop_list", "comx35_flop")
MACHINE_CONFIG_END
//-------------------------------------------------
// MACHINE_CONFIG( ntsc )
//-------------------------------------------------
static MACHINE_CONFIG_START( ntsc, comx35_state )
// basic system hardware
MCFG_CPU_ADD(CDP1802_TAG, CDP1802, CDP1869_CPU_CLK_NTSC)
MCFG_CPU_PROGRAM_MAP(comx35_mem)
MCFG_CPU_IO_MAP(comx35_io)
MCFG_COSMAC_WAIT_CALLBACK(VCC)
MCFG_COSMAC_CLEAR_CALLBACK(READLINE(comx35_state, clear_r))
MCFG_COSMAC_EF2_CALLBACK(READLINE(comx35_state, ef2_r))
MCFG_COSMAC_EF4_CALLBACK(READLINE(comx35_state, ef4_r))
MCFG_COSMAC_Q_CALLBACK(WRITELINE(comx35_state, q_w))
MCFG_COSMAC_SC_CALLBACK(WRITE8(comx35_state, sc_w))
// sound and video hardware
MCFG_FRAGMENT_ADD(comx35_ntsc_video)
// peripheral hardware
MCFG_DEVICE_ADD(CDP1871_TAG, CDP1871, CDP1869_CPU_CLK_PAL/8)
MCFG_CDP1871_D1_CALLBACK(IOPORT("D1"))
MCFG_CDP1871_D2_CALLBACK(IOPORT("D2"))
MCFG_CDP1871_D3_CALLBACK(IOPORT("D3"))
MCFG_CDP1871_D4_CALLBACK(IOPORT("D4"))
MCFG_CDP1871_D5_CALLBACK(IOPORT("D5"))
MCFG_CDP1871_D6_CALLBACK(IOPORT("D6"))
MCFG_CDP1871_D7_CALLBACK(IOPORT("D7"))
MCFG_CDP1871_D8_CALLBACK(IOPORT("D8"))
MCFG_CDP1871_D9_CALLBACK(IOPORT("D9"))
MCFG_CDP1871_D10_CALLBACK(IOPORT("D10"))
MCFG_CDP1871_D11_CALLBACK(IOPORT("D11"))
MCFG_CDP1871_DA_CALLBACK(INPUTLINE(CDP1802_TAG, COSMAC_INPUT_LINE_EF3))
MCFG_QUICKLOAD_ADD("quickload", comx35_state, comx35_comx, "comx", 0)
MCFG_CASSETTE_ADD("cassette")
MCFG_CASSETTE_DEFAULT_STATE(CASSETTE_STOPPED | CASSETTE_MOTOR_ENABLED | CASSETTE_SPEAKER_ENABLED)
// expansion bus
MCFG_COMX_EXPANSION_SLOT_ADD(EXPANSION_TAG, comx_expansion_cards, "eb")
MCFG_COMX_EXPANSION_SLOT_IRQ_CALLBACK(WRITELINE(comx35_state, irq_w))
// internal ram
MCFG_RAM_ADD(RAM_TAG)
MCFG_RAM_DEFAULT_SIZE("32K")
// software lists
MCFG_SOFTWARE_LIST_ADD("flop_list", "comx35_flop")
MACHINE_CONFIG_END
//**************************************************************************
// ROMS
//**************************************************************************
//-------------------------------------------------
// ROM( comx35p )
//-------------------------------------------------
ROM_START( comx35p )
ROM_REGION( 0x4000, CDP1802_TAG, 0 )
ROM_DEFAULT_BIOS( "basic100" )
ROM_SYSTEM_BIOS( 0, "basic100", "COMX BASIC V1.00" )
ROMX_LOAD( "comx_10.u21", 0x0000, 0x4000, CRC(68d0db2d) SHA1(062328361629019ceed9375afac18e2b7849ce47), ROM_BIOS(1) )
ROM_SYSTEM_BIOS( 1, "basic101", "COMX BASIC V1.01" )
ROMX_LOAD( "comx_11.u21", 0x0000, 0x4000, CRC(609d89cd) SHA1(799646810510d8236fbfafaff7a73d5170990f16), ROM_BIOS(2) )
ROM_END
//-------------------------------------------------
// ROM( comx35n )
//-------------------------------------------------
#define rom_comx35n rom_comx35p
//**************************************************************************
// SYSTEM DRIVERS
//**************************************************************************
// YEAR NAME PARENT COMPAT MACHINE INPUT INIT COMPANY FULLNAME FLAGS
COMP( 1983, comx35p, 0, 0, pal, comx35, driver_device, 0, "Comx World Operations Ltd", "COMX 35 (PAL)", MACHINE_IMPERFECT_SOUND )
COMP( 1983, comx35n, comx35p,0, ntsc, comx35, driver_device, 0, "Comx World Operations Ltd", "COMX 35 (NTSC)", MACHINE_IMPERFECT_SOUND )
| h0tw1r3/mame | src/mame/drivers/comx35.cpp | C++ | gpl-2.0 | 23,542 |
var app = angular.module('site', ['ui.bootstrap', 'ngAria']);
app.factory('Backend', ['$http',
function($http) {
var get = function(url) {
return function() {
return $http.get(url).then(function(resp) {
return resp.data;
});
}
};
return {
featured: get('data/featured.json'),
orgs: get('data/organization.json')
}
}
])
.controller('MainCtrl', ['Backend', '$scope', 'filterFilter',
function(Backend, $scope, filterFilter) {
var self = this;
Backend.orgs().then(function(data) {
self.orgs = data;
});
Backend.featured().then(function(data) {
self.featured = data;
$.ajax({
url: 'https://popularrepostg.blob.core.windows.net/popularrepos/projects.json',
dataType: 'jsonp',
jsonpCallback: 'JSON_CALLBACK',
success: function(data) {
var projects = data[0].AllProjects;
$scope.currentPage = 1; //current page
$scope.maxSize = 5; //pagination max size
$scope.entryLimit = 36; //max rows for data table
/* init pagination with $scope.list */
$scope.noOfRepos = projects.length;
$scope.noOfPages = Math.ceil($scope.noOfRepos / $scope.entryLimit);
$scope.resultsSectionTitle = 'All Repos';
$scope.$watch('searchText', function(term) {
// Create $scope.filtered and then calculate $scope.noOfPages, no racing!
$scope.filtered = filterFilter(projects, term);
$scope.noOfRepos = $scope.filtered.length;
$scope.noOfPages = Math.ceil($scope.noOfRepos / $scope.entryLimit);
$scope.resultsSectionTitle = (!term) ? 'All Repos' : (($scope.noOfRepos == 0) ? 'Search results' : ($scope.noOfRepos + ' repositories found'));
});
var featuredProjects = new Array();
self.featured.forEach(function (name) {
for (var i = 0; i < projects.length; i++) {
var project = projects[i];
if (project.Name == name) {
featuredProjects.push(project);
return;
}
}
});
self.projects = projects;
self.featuredProjects = featuredProjects;
$scope.$apply();
}
});
$.ajax({
url: 'https://popularrepostg.blob.core.windows.net/popularrepos/projectssummary.json',
dataType: 'jsonp',
jsonpCallback: 'JSON_CALLBACK',
success: function (stats) {
if (stats != null) {
$scope.overAllStats = stats[0];
}
}
})
});
}
])
.filter('startFrom', function() {
return function(input, start) {
if (input) {
start = +start; //parse to int
return input.slice(start);
}
return [];
}
});
| Gelvazio/ORGANIZACOES | microsoft.github.io/microsoft.github.io-master/js/main.js | JavaScript | gpl-2.0 | 3,518 |
# Copyright (c) 2016--2017 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#
import sys
import cStringIO
import json
import zipfile
import os
from M2Crypto import X509
from spacewalk.satellite_tools.syncLib import log2
from spacewalk.server.rhnServer.satellite_cert import SatelliteCert
import constants
class Manifest(object):
"""Class containing relevant data from RHSM manifest."""
SIGNATURE_NAME = "signature"
INNER_ZIP_NAME = "consumer_export.zip"
ENTITLEMENTS_PATH = "export/entitlements"
CERTIFICATE_PATH = "export/extensions"
PRODUCTS_PATH = "export/products"
CONSUMER_INFO = "export/consumer.json"
META_INFO = "export/meta.json"
UPSTREAM_CONSUMER_PATH = "export/upstream_consumer"
def __init__(self, zip_path):
self.all_entitlements = []
self.manifest_repos = {}
self.sat5_certificate = None
self.satellite_version = None
self.consumer_credentials = None
self.uuid = None
self.name = None
self.ownerid = None
self.api_url = None
self.web_url = None
self.created = None
# Signature and signed data
self.signature = None
self.data = None
# Open manifest from path
top_zip = None
inner_zip = None
inner_file = None
# normalize path
zip_path = os.path.abspath(os.path.expanduser(zip_path))
try:
top_zip = zipfile.ZipFile(zip_path, 'r')
# Fetch inner zip file into memory
try:
# inner_file = top_zip.open(zip_path.split('.zip')[0] + '/' + self.INNER_ZIP_NAME)
inner_file = top_zip.open(self.INNER_ZIP_NAME)
self.data = inner_file.read()
inner_file_data = cStringIO.StringIO(self.data)
signature_file = top_zip.open(self.SIGNATURE_NAME)
self.signature = signature_file.read()
# Open the inner zip file
try:
inner_zip = zipfile.ZipFile(inner_file_data)
self._extract_consumer_info(inner_zip)
self._load_entitlements(inner_zip)
self._extract_certificate(inner_zip)
self._extract_meta_info(inner_zip)
self._extract_consumer_credentials(inner_zip)
finally:
if inner_zip is not None:
inner_zip.close()
finally:
if inner_file is not None:
inner_file.close()
finally:
if top_zip is not None:
top_zip.close()
def _extract_certificate(self, zip_file):
files = zip_file.namelist()
certificates_names = []
for f in files:
if f.startswith(self.CERTIFICATE_PATH) and f.endswith(".xml"):
certificates_names.append(f)
if len(certificates_names) >= 1:
# take only first file
cert_file = zip_file.open(certificates_names[0]) # take only first file
self.sat5_certificate = cert_file.read().strip()
cert_file.close()
# Save version too
sat5_cert = SatelliteCert()
sat5_cert.load(self.sat5_certificate)
self.satellite_version = getattr(sat5_cert, 'satellite-version')
else:
raise MissingSatelliteCertificateError("Satellite Certificate was not found in manifest.")
def _fill_product_repositories(self, zip_file, product):
product_file = zip_file.open(self.PRODUCTS_PATH + '/' + str(product.get_id()) + '.json')
product_data = json.load(product_file)
product_file.close()
try:
for content in product_data['productContent']:
content = content['content']
product.add_repository(content['label'], content['contentUrl'])
except KeyError:
log2(0, 0, "ERROR: Cannot access required field in product '%s'" % product.get_id(), stream=sys.stderr)
raise
def _load_entitlements(self, zip_file):
files = zip_file.namelist()
entitlements_files = []
for f in files:
if f.startswith(self.ENTITLEMENTS_PATH) and f.endswith(".json"):
entitlements_files.append(f)
if len(entitlements_files) >= 1:
self.all_entitlements = []
for entitlement_file in entitlements_files:
entitlements = zip_file.open(entitlement_file)
# try block in try block - this is hack for python 2.4 compatibility
# to support finally
try:
try:
data = json.load(entitlements)
# Extract credentials
certs = data['certificates']
if len(certs) != 1:
raise IncorrectEntitlementsFileFormatError(
"Single certificate in entitlements file '%s' is expected, found: %d"
% (entitlement_file, len(certs)))
cert = certs[0]
credentials = Credentials(data['id'], cert['cert'], cert['key'])
# Extract product IDs
products = []
provided_products = data['pool']['providedProducts'] or []
derived_provided_products = data['pool']['derivedProvidedProducts'] or []
product_ids = [provided_product['productId'] for provided_product
in provided_products + derived_provided_products]
for product_id in set(product_ids):
product = Product(product_id)
self._fill_product_repositories(zip_file, product)
products.append(product)
# Skip entitlements not providing any products
if products:
entitlement = Entitlement(products, credentials)
self.all_entitlements.append(entitlement)
except KeyError:
log2(0, 0, "ERROR: Cannot access required field in file '%s'" % entitlement_file,
stream=sys.stderr)
raise
finally:
entitlements.close()
else:
refer_url = "%s%s" % (self.web_url, self.uuid)
if not refer_url.startswith("http"):
refer_url = "https://" + refer_url
raise IncorrectEntitlementsFileFormatError(
"No subscriptions were found in manifest.\n\nPlease refer to %s for setting up subscriptions."
% refer_url)
def _extract_consumer_info(self, zip_file):
files = zip_file.namelist()
found = False
for f in files:
if f == self.CONSUMER_INFO:
found = True
break
if found:
consumer_info = zip_file.open(self.CONSUMER_INFO)
try:
try:
data = json.load(consumer_info)
self.uuid = data['uuid']
self.name = data['name']
self.ownerid = data['owner']['key']
self.api_url = data['urlApi']
self.web_url = data['urlWeb']
except KeyError:
log2(0, 0, "ERROR: Cannot access required field in file '%s'" % self.CONSUMER_INFO,
stream=sys.stderr)
raise
finally:
consumer_info.close()
else:
raise MissingConsumerInfoError()
def _extract_meta_info(self, zip_file):
files = zip_file.namelist()
found = False
for f in files:
if f == self.META_INFO:
found = True
break
if found:
meta_info = zip_file.open(self.META_INFO)
try:
try:
data = json.load(meta_info)
self.created = data['created']
except KeyError:
log2(0, 0, "ERROR: Cannot access required field in file '%s'" % self.META_INFO, stream=sys.stderr)
raise
finally:
meta_info.close()
else:
raise MissingMetaInfoError()
def _extract_consumer_credentials(self, zip_file):
files = zip_file.namelist()
consumer_credentials = []
for f in files:
if f.startswith(self.UPSTREAM_CONSUMER_PATH) and f.endswith(".json"):
consumer_credentials.append(f)
if len(consumer_credentials) == 1:
upstream_consumer = zip_file.open(consumer_credentials[0])
try:
try:
data = json.load(upstream_consumer)
self.consumer_credentials = Credentials(data['id'], data['cert'], data['key'])
except KeyError:
log2(0, 0, "ERROR: Cannot access required field in file '%s'" % consumer_credentials[0],
stream=sys.stderr)
raise
finally:
upstream_consumer.close()
else:
raise IncorrectCredentialsError(
"ERROR: Single upstream consumer certificate expected, found %d." % len(consumer_credentials))
def get_all_entitlements(self):
return self.all_entitlements
def get_satellite_certificate(self):
return self.sat5_certificate
def get_satellite_version(self):
return self.satellite_version
def get_consumer_credentials(self):
return self.consumer_credentials
def get_name(self):
return self.name
def get_uuid(self):
return self.uuid
def get_ownerid(self):
return self.ownerid
def get_api_url(self):
return self.api_url
def get_created(self):
return self.created
def check_signature(self):
if self.signature and self.data:
certs = os.listdir(constants.CANDLEPIN_CA_CERT_DIR)
# At least one certificate has to match
for cert_name in certs:
cert_file = None
try:
try:
cert_file = open(constants.CANDLEPIN_CA_CERT_DIR + '/' + cert_name, 'r')
cert = X509.load_cert_string(cert_file.read())
except (IOError, X509.X509Error):
continue
finally:
if cert_file is not None:
cert_file.close()
pubkey = cert.get_pubkey()
pubkey.reset_context(md='sha256')
pubkey.verify_init()
pubkey.verify_update(self.data)
if pubkey.verify_final(self.signature):
return True
return False
class Entitlement(object):
def __init__(self, products, credentials):
if products and credentials:
self.products = products
self.credentials = credentials
else:
raise IncorrectEntitlementError()
def get_products(self):
return self.products
def get_credentials(self):
return self.credentials
class Credentials(object):
def __init__(self, identifier, cert, key):
if identifier:
self.id = identifier
else:
raise IncorrectCredentialsError(
"ERROR: ID of credentials has to be defined"
)
if cert and key:
self.cert = cert
self.key = key
else:
raise IncorrectCredentialsError(
"ERROR: Trying to create object with cert = %s and key = %s"
% (cert, key)
)
def get_id(self):
return self.id
def get_cert(self):
return self.cert
def get_key(self):
return self.key
class Product(object):
def __init__(self, identifier):
try:
self.id = int(identifier)
except ValueError:
raise IncorrectProductError(
"ERROR: Invalid product id: %s" % identifier
)
self.repositories = {}
def get_id(self):
return self.id
def get_repositories(self):
return self.repositories
def add_repository(self, label, url):
self.repositories[label] = url
class IncorrectProductError(Exception):
pass
class IncorrectEntitlementError(Exception):
pass
class IncorrectCredentialsError(Exception):
pass
class IncorrectEntitlementsFileFormatError(Exception):
pass
class MissingSatelliteCertificateError(Exception):
pass
class ManifestValidationError(Exception):
pass
class MissingConsumerInfoError(Exception):
pass
class MissingMetaInfoError(Exception):
pass
| ogajduse/spacewalk | backend/cdn_tools/manifest.py | Python | gpl-2.0 | 13,620 |
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Service\V1;
use Magento\TestFramework\TestCase\WebapiAbstract;
class OrderHoldTest extends WebapiAbstract
{
const SERVICE_VERSION = 'V1';
const SERVICE_NAME = 'salesOrderManagementV1';
/**
* @magentoApiDataFixture Magento/Sales/_files/order.php
*/
public function testOrderHold()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$order = $objectManager->get('Magento\Sales\Model\Order')->loadByIncrementId('100000001');
$serviceInfo = [
'rest' => [
'resourcePath' => '/V1/orders/' . $order->getId() . '/hold',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'hold',
],
];
$requestData = ['id' => $order->getId()];
$result = $this->_webApiCall($serviceInfo, $requestData);
$this->assertTrue($result);
}
}
| FPLD/project0 | vendor/magento/magento2-base/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/OrderHoldTest.php | PHP | gpl-2.0 | 1,240 |
package main
import (
log "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/Sirupsen/logrus"
consulapi "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/hashicorp/consul/api"
)
const LockKey = "consul-alerts/leader"
type LeaderElection struct {
lock *consulapi.Lock
cleanupChannel chan struct{}
stopChannel chan struct{}
leader bool
}
func (l *LeaderElection) start() {
clean := false
for !clean {
select {
case <-l.cleanupChannel:
clean = true
default:
log.Infoln("Running for leader election...")
intChan, _ := l.lock.Lock(l.stopChannel)
if intChan != nil {
log.Infoln("Now acting as leader.")
l.leader = true
<-intChan
l.leader = false
log.Infoln("Lost leadership.")
l.lock.Unlock()
l.lock.Destroy()
}
}
}
}
func (l *LeaderElection) stop() {
log.Infoln("cleaning up")
l.cleanupChannel <- struct{}{}
l.stopChannel <- struct{}{}
l.lock.Unlock()
l.lock.Destroy()
l.leader = false
log.Infoln("cleanup done")
}
func startLeaderElection(addr, dc, acl string) *LeaderElection {
config := consulapi.DefaultConfig()
config.Address = addr
config.Datacenter = dc
config.Token = acl
client, _ := consulapi.NewClient(config)
lock, _ := client.LockKey(LockKey)
leader := &LeaderElection{
lock: lock,
cleanupChannel: make(chan struct{}, 1),
stopChannel: make(chan struct{}, 1),
}
go leader.start()
return leader
}
func hasLeader() bool {
return consulClient.CheckKeyExists(LockKey)
}
| hoist/consul-alerts | leader-election.go | GO | gpl-2.0 | 1,548 |
/*
* Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* Provides user interface objects built according to the Basic look and feel.
* The Basic look and feel provides default behavior used by many look and feel
* packages. It contains components, layout managers, events, event listeners,
* and adapters. You can subclass the classes in this package to create your own
* customized look and feel.
* <p>
* These classes are designed to be used while the corresponding
* {@code LookAndFeel} class has been installed
* (<code>UIManager.setLookAndFeel(new <i>XXX</i>LookAndFeel())</code>).
* Using them while a different {@code LookAndFeel} is installed may produce
* unexpected results, including exceptions. Additionally, changing the
* {@code LookAndFeel} maintained by the {@code UIManager} without updating the
* corresponding {@code ComponentUI} of any {@code JComponent}s may also produce
* unexpected results, such as the wrong colors showing up, and is generally not
* encouraged.
* <p>
* <strong>Note:</strong>
* Most of the Swing API is <em>not</em> thread safe. For details, see
* <a
* href="https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html"
* target="_top">Concurrency in Swing</a>,
* a section in
* <em><a href="https://docs.oracle.com/javase/tutorial/"
* target="_top">The Java Tutorial</a></em>.
*
* @since 1.2
* @serial exclude
*/
package javax.swing.plaf.basic;
| md-5/jdk10 | src/java.desktop/share/classes/javax/swing/plaf/basic/package-info.java | Java | gpl-2.0 | 2,590 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration |
\\ / A nd | For copyright notice see file Copyright
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend 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.
foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
template<class Form, class Type>
inline Foam::Matrix<Form, Type>::Matrix()
:
v_(NULL),
n_(0),
m_(0)
{}
template<class Form, class Type>
inline Foam::autoPtr<Foam::Matrix<Form, Type> >
Foam::Matrix<Form, Type>::clone() const
{
return autoPtr<Matrix<Form, Type> >(new Matrix<Form, Type>(*this));
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class Form, class Type>
inline const Foam::Matrix<Form, Type>& Foam::Matrix<Form, Type>::null()
{
return zero;
}
//- Return the number of rows
template<class Form, class Type>
inline Foam::label Foam::Matrix<Form, Type>::n() const
{
return n_;
}
template<class Form, class Type>
inline Foam::label Foam::Matrix<Form, Type>::m() const
{
return m_;
}
template<class Form, class Type>
inline Foam::label Foam::Matrix<Form, Type>::size() const
{
return n_*m_;
}
template<class Form, class Type>
inline void Foam::Matrix<Form, Type>::checki(const label i) const
{
if (!n_)
{
FatalErrorIn("Matrix<Form, Type>::checki(const label)")
<< "attempt to access element from zero sized row"
<< abort(FatalError);
}
else if (i<0 || i>=n_)
{
FatalErrorIn("Matrix<Form, Type>::checki(const label)")
<< "index " << i << " out of range 0 ... " << n_-1
<< abort(FatalError);
}
}
template<class Form, class Type>
inline void Foam::Matrix<Form, Type>::checkj(const label j) const
{
if (!m_)
{
FatalErrorIn("Matrix<Form, Type>::checkj(const label)")
<< "attempt to access element from zero sized column"
<< abort(FatalError);
}
else if (j<0 || j>=m_)
{
FatalErrorIn("Matrix<Form, Type>::checkj(const label)")
<< "index " << j << " out of range 0 ... " << m_-1
<< abort(FatalError);
}
}
// * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * //
template<class Form, class Type>
inline Type* Foam::Matrix<Form, Type>::operator[](const label i)
{
# ifdef FULLDEBUG
checki(i);
# endif
return v_[i];
}
template<class Form, class Type>
inline const Type* Foam::Matrix<Form, Type>::operator[](const label i) const
{
# ifdef FULLDEBUG
checki(i);
# endif
return v_[i];
}
// ************************************************************************* //
| WensiWu/openfoam-extend-foam-extend-3.1 | src/foam/matrices/Matrix/MatrixI.H | C++ | gpl-3.0 | 3,618 |
using UnityEngine;
/// <summary>
/// Functionality common to both NGUI and 2D sprites brought out into a single common parent.
/// Mostly contains everything related to drawing the sprite.
/// </summary>
public abstract class UIBasicSprite : UIWidget
{
public enum Type
{
Simple,
Sliced,
Tiled,
Filled,
Advanced,
}
public enum FillDirection
{
Horizontal,
Vertical,
Radial90,
Radial180,
Radial360,
}
public enum AdvancedType
{
Invisible,
Sliced,
Tiled,
}
public enum Flip
{
Nothing,
Horizontally,
Vertically,
Both,
}
[HideInInspector][SerializeField] protected Type mType = Type.Simple;
[HideInInspector][SerializeField] protected FillDirection mFillDirection = FillDirection.Radial360;
[Range(0f, 1f)]
[HideInInspector][SerializeField] protected float mFillAmount = 1.0f;
[HideInInspector][SerializeField] protected bool mInvert = false;
[HideInInspector][SerializeField] protected Flip mFlip = Flip.Nothing;
// Cached to avoid allocations
[System.NonSerialized] Rect mInnerUV = new Rect();
[System.NonSerialized] Rect mOuterUV = new Rect();
/// <summary>
/// When the sprite type is advanced, this determines whether the center is tiled or sliced.
/// </summary>
public AdvancedType centerType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the left edge is tiled or sliced.
/// </summary>
public AdvancedType leftType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the right edge is tiled or sliced.
/// </summary>
public AdvancedType rightType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the bottom edge is tiled or sliced.
/// </summary>
public AdvancedType bottomType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the top edge is tiled or sliced.
/// </summary>
public AdvancedType topType = AdvancedType.Sliced;
/// <summary>
/// How the sprite is drawn. It's virtual for legacy reasons (UISlicedSprite, UITiledSprite, UIFilledSprite).
/// </summary>
public virtual Type type
{
get
{
return mType;
}
set
{
if (mType != value)
{
mType = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Sprite flip setting.
/// </summary>
public Flip flip
{
get
{
return mFlip;
}
set
{
if (mFlip != value)
{
mFlip = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Direction of the cut procedure.
/// </summary>
public FillDirection fillDirection
{
get
{
return mFillDirection;
}
set
{
if (mFillDirection != value)
{
mFillDirection = value;
mChanged = true;
}
}
}
/// <summary>
/// Amount of the sprite shown. 0-1 range with 0 being nothing shown, and 1 being the full sprite.
/// </summary>
public float fillAmount
{
get
{
return mFillAmount;
}
set
{
float val = Mathf.Clamp01(value);
if (mFillAmount != val)
{
mFillAmount = val;
mChanged = true;
}
}
}
/// <summary>
/// Minimum allowed width for this widget.
/// </summary>
override public int minWidth
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
Vector4 b = border * pixelSize;
int min = Mathf.RoundToInt(b.x + b.z);
return Mathf.Max(base.minWidth, ((min & 1) == 1) ? min + 1 : min);
}
return base.minWidth;
}
}
/// <summary>
/// Minimum allowed height for this widget.
/// </summary>
override public int minHeight
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
Vector4 b = border * pixelSize;
int min = Mathf.RoundToInt(b.y + b.w);
return Mathf.Max(base.minHeight, ((min & 1) == 1) ? min + 1 : min);
}
return base.minHeight;
}
}
/// <summary>
/// Whether the sprite should be filled in the opposite direction.
/// </summary>
public bool invert
{
get
{
return mInvert;
}
set
{
if (mInvert != value)
{
mInvert = value;
mChanged = true;
}
}
}
/// <summary>
/// Whether the widget has a border for 9-slicing.
/// </summary>
public bool hasBorder
{
get
{
Vector4 br = border;
return (br.x != 0f || br.y != 0f || br.z != 0f || br.w != 0f);
}
}
/// <summary>
/// Whether the sprite's material is using a pre-multiplied alpha shader.
/// </summary>
public virtual bool premultipliedAlpha { get { return false; } }
/// <summary>
/// Size of the pixel. Overwritten in the NGUI sprite to pull a value from the atlas.
/// </summary>
public virtual float pixelSize { get { return 1f; } }
#if UNITY_EDITOR
/// <summary>
/// Keep sane values.
/// </summary>
protected override void OnValidate ()
{
base.OnValidate();
mFillAmount = Mathf.Clamp01(mFillAmount);
}
#endif
#region Fill Functions
// Static variables to reduce garbage collection
static protected Vector2[] mTempPos = new Vector2[4];
static protected Vector2[] mTempUVs = new Vector2[4];
/// <summary>
/// Convenience function that returns the drawn UVs after flipping gets considered.
/// X = left, Y = bottom, Z = right, W = top.
/// </summary>
Vector4 drawingUVs
{
get
{
switch (mFlip)
{
case Flip.Horizontally: return new Vector4(mOuterUV.xMax, mOuterUV.yMin, mOuterUV.xMin, mOuterUV.yMax);
case Flip.Vertically: return new Vector4(mOuterUV.xMin, mOuterUV.yMax, mOuterUV.xMax, mOuterUV.yMin);
case Flip.Both: return new Vector4(mOuterUV.xMax, mOuterUV.yMax, mOuterUV.xMin, mOuterUV.yMin);
default: return new Vector4(mOuterUV.xMin, mOuterUV.yMin, mOuterUV.xMax, mOuterUV.yMax);
}
}
}
/// <summary>
/// Final widget's color passed to the draw buffer.
/// </summary>
Color32 drawingColor
{
get
{
Color colF = color;
colF.a = finalAlpha;
if (premultipliedAlpha) colF = NGUITools.ApplyPMA(colF);
if (QualitySettings.activeColorSpace == ColorSpace.Linear)
{
colF.r = Mathf.GammaToLinearSpace(colF.r);
colF.g = Mathf.GammaToLinearSpace(colF.g);
colF.b = Mathf.GammaToLinearSpace(colF.b);
colF.a = Mathf.GammaToLinearSpace(colF.a);
}
return colF;
}
}
/// <summary>
/// Fill the draw buffers.
/// </summary>
protected void Fill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols, Rect outer, Rect inner)
{
mOuterUV = outer;
mInnerUV = inner;
switch (type)
{
case Type.Simple:
SimpleFill(verts, uvs, cols);
break;
case Type.Sliced:
SlicedFill(verts, uvs, cols);
break;
case Type.Filled:
FilledFill(verts, uvs, cols);
break;
case Type.Tiled:
TiledFill(verts, uvs, cols);
break;
case Type.Advanced:
AdvancedFill(verts, uvs, cols);
break;
}
}
/// <summary>
/// Regular sprite fill function is quite simple.
/// </summary>
void SimpleFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Vector4 v = drawingDimensions;
Vector4 u = drawingUVs;
Color32 c = drawingColor;
verts.Add(new Vector3(v.x, v.y));
verts.Add(new Vector3(v.x, v.w));
verts.Add(new Vector3(v.z, v.w));
verts.Add(new Vector3(v.z, v.y));
uvs.Add(new Vector2(u.x, u.y));
uvs.Add(new Vector2(u.x, u.w));
uvs.Add(new Vector2(u.z, u.w));
uvs.Add(new Vector2(u.z, u.y));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
}
/// <summary>
/// Sliced sprite fill function is more complicated as it generates 9 quads instead of 1.
/// </summary>
void SlicedFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Vector4 br = border * pixelSize;
if (br.x == 0f && br.y == 0f && br.z == 0f && br.w == 0f)
{
SimpleFill(verts, uvs, cols);
return;
}
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
mTempPos[0].x = v.x;
mTempPos[0].y = v.y;
mTempPos[3].x = v.z;
mTempPos[3].y = v.w;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
mTempPos[1].x = mTempPos[0].x + br.z;
mTempPos[2].x = mTempPos[3].x - br.x;
mTempUVs[3].x = mOuterUV.xMin;
mTempUVs[2].x = mInnerUV.xMin;
mTempUVs[1].x = mInnerUV.xMax;
mTempUVs[0].x = mOuterUV.xMax;
}
else
{
mTempPos[1].x = mTempPos[0].x + br.x;
mTempPos[2].x = mTempPos[3].x - br.z;
mTempUVs[0].x = mOuterUV.xMin;
mTempUVs[1].x = mInnerUV.xMin;
mTempUVs[2].x = mInnerUV.xMax;
mTempUVs[3].x = mOuterUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
mTempPos[1].y = mTempPos[0].y + br.w;
mTempPos[2].y = mTempPos[3].y - br.y;
mTempUVs[3].y = mOuterUV.yMin;
mTempUVs[2].y = mInnerUV.yMin;
mTempUVs[1].y = mInnerUV.yMax;
mTempUVs[0].y = mOuterUV.yMax;
}
else
{
mTempPos[1].y = mTempPos[0].y + br.y;
mTempPos[2].y = mTempPos[3].y - br.w;
mTempUVs[0].y = mOuterUV.yMin;
mTempUVs[1].y = mInnerUV.yMin;
mTempUVs[2].y = mInnerUV.yMax;
mTempUVs[3].y = mOuterUV.yMax;
}
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (centerType == AdvancedType.Invisible && x == 1 && y == 1) continue;
int y2 = y + 1;
verts.Add(new Vector3(mTempPos[x].x, mTempPos[y].y));
verts.Add(new Vector3(mTempPos[x].x, mTempPos[y2].y));
verts.Add(new Vector3(mTempPos[x2].x, mTempPos[y2].y));
verts.Add(new Vector3(mTempPos[x2].x, mTempPos[y].y));
uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y].y));
uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y2].y));
uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y2].y));
uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y].y));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
}
}
}
/// <summary>
/// Tiled sprite fill function.
/// </summary>
void TiledFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = mainTexture;
if (tex == null) return;
Vector2 size = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
size *= pixelSize;
if (tex == null || size.x < 2f || size.y < 2f) return;
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
Vector4 u;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
u.x = mInnerUV.xMax;
u.z = mInnerUV.xMin;
}
else
{
u.x = mInnerUV.xMin;
u.z = mInnerUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
u.y = mInnerUV.yMax;
u.w = mInnerUV.yMin;
}
else
{
u.y = mInnerUV.yMin;
u.w = mInnerUV.yMax;
}
float x0 = v.x;
float y0 = v.y;
float u0 = u.x;
float v0 = u.y;
while (y0 < v.w)
{
x0 = v.x;
float y1 = y0 + size.y;
float v1 = u.w;
if (y1 > v.w)
{
v1 = Mathf.Lerp(u.y, u.w, (v.w - y0) / size.y);
y1 = v.w;
}
while (x0 < v.z)
{
float x1 = x0 + size.x;
float u1 = u.z;
if (x1 > v.z)
{
u1 = Mathf.Lerp(u.x, u.z, (v.z - x0) / size.x);
x1 = v.z;
}
verts.Add(new Vector3(x0, y0));
verts.Add(new Vector3(x0, y1));
verts.Add(new Vector3(x1, y1));
verts.Add(new Vector3(x1, y0));
uvs.Add(new Vector2(u0, v0));
uvs.Add(new Vector2(u0, v1));
uvs.Add(new Vector2(u1, v1));
uvs.Add(new Vector2(u1, v0));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
x0 += size.x;
}
y0 += size.y;
}
}
/// <summary>
/// Filled sprite fill function.
/// </summary>
void FilledFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
if (mFillAmount < 0.001f) return;
Vector4 v = drawingDimensions;
Vector4 u = drawingUVs;
Color32 c = drawingColor;
// Horizontal and vertical filled sprites are simple -- just end the sprite prematurely
if (mFillDirection == FillDirection.Horizontal || mFillDirection == FillDirection.Vertical)
{
if (mFillDirection == FillDirection.Horizontal)
{
float fill = (u.z - u.x) * mFillAmount;
if (mInvert)
{
v.x = v.z - (v.z - v.x) * mFillAmount;
u.x = u.z - fill;
}
else
{
v.z = v.x + (v.z - v.x) * mFillAmount;
u.z = u.x + fill;
}
}
else if (mFillDirection == FillDirection.Vertical)
{
float fill = (u.w - u.y) * mFillAmount;
if (mInvert)
{
v.y = v.w - (v.w - v.y) * mFillAmount;
u.y = u.w - fill;
}
else
{
v.w = v.y + (v.w - v.y) * mFillAmount;
u.w = u.y + fill;
}
}
}
mTempPos[0] = new Vector2(v.x, v.y);
mTempPos[1] = new Vector2(v.x, v.w);
mTempPos[2] = new Vector2(v.z, v.w);
mTempPos[3] = new Vector2(v.z, v.y);
mTempUVs[0] = new Vector2(u.x, u.y);
mTempUVs[1] = new Vector2(u.x, u.w);
mTempUVs[2] = new Vector2(u.z, u.w);
mTempUVs[3] = new Vector2(u.z, u.y);
if (mFillAmount < 1f)
{
if (mFillDirection == FillDirection.Radial90)
{
if (RadialCut(mTempPos, mTempUVs, mFillAmount, mInvert, 0))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
return;
}
if (mFillDirection == FillDirection.Radial180)
{
for (int side = 0; side < 2; ++side)
{
float fx0, fx1, fy0, fy1;
fy0 = 0f;
fy1 = 1f;
if (side == 0) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
mTempPos[0].x = Mathf.Lerp(v.x, v.z, fx0);
mTempPos[1].x = mTempPos[0].x;
mTempPos[2].x = Mathf.Lerp(v.x, v.z, fx1);
mTempPos[3].x = mTempPos[2].x;
mTempPos[0].y = Mathf.Lerp(v.y, v.w, fy0);
mTempPos[1].y = Mathf.Lerp(v.y, v.w, fy1);
mTempPos[2].y = mTempPos[1].y;
mTempPos[3].y = mTempPos[0].y;
mTempUVs[0].x = Mathf.Lerp(u.x, u.z, fx0);
mTempUVs[1].x = mTempUVs[0].x;
mTempUVs[2].x = Mathf.Lerp(u.x, u.z, fx1);
mTempUVs[3].x = mTempUVs[2].x;
mTempUVs[0].y = Mathf.Lerp(u.y, u.w, fy0);
mTempUVs[1].y = Mathf.Lerp(u.y, u.w, fy1);
mTempUVs[2].y = mTempUVs[1].y;
mTempUVs[3].y = mTempUVs[0].y;
float val = !mInvert ? fillAmount * 2f - side : mFillAmount * 2f - (1 - side);
if (RadialCut(mTempPos, mTempUVs, Mathf.Clamp01(val), !mInvert, NGUIMath.RepeatIndex(side + 3, 4)))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
}
return;
}
if (mFillDirection == FillDirection.Radial360)
{
for (int corner = 0; corner < 4; ++corner)
{
float fx0, fx1, fy0, fy1;
if (corner < 2) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
if (corner == 0 || corner == 3) { fy0 = 0f; fy1 = 0.5f; }
else { fy0 = 0.5f; fy1 = 1f; }
mTempPos[0].x = Mathf.Lerp(v.x, v.z, fx0);
mTempPos[1].x = mTempPos[0].x;
mTempPos[2].x = Mathf.Lerp(v.x, v.z, fx1);
mTempPos[3].x = mTempPos[2].x;
mTempPos[0].y = Mathf.Lerp(v.y, v.w, fy0);
mTempPos[1].y = Mathf.Lerp(v.y, v.w, fy1);
mTempPos[2].y = mTempPos[1].y;
mTempPos[3].y = mTempPos[0].y;
mTempUVs[0].x = Mathf.Lerp(u.x, u.z, fx0);
mTempUVs[1].x = mTempUVs[0].x;
mTempUVs[2].x = Mathf.Lerp(u.x, u.z, fx1);
mTempUVs[3].x = mTempUVs[2].x;
mTempUVs[0].y = Mathf.Lerp(u.y, u.w, fy0);
mTempUVs[1].y = Mathf.Lerp(u.y, u.w, fy1);
mTempUVs[2].y = mTempUVs[1].y;
mTempUVs[3].y = mTempUVs[0].y;
float val = mInvert ?
mFillAmount * 4f - NGUIMath.RepeatIndex(corner + 2, 4) :
mFillAmount * 4f - (3 - NGUIMath.RepeatIndex(corner + 2, 4));
if (RadialCut(mTempPos, mTempUVs, Mathf.Clamp01(val), mInvert, NGUIMath.RepeatIndex(corner + 2, 4)))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
}
return;
}
}
// Fill the buffer with the quad for the sprite
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
/// <summary>
/// Advanced sprite fill function. Contributed by Nicki Hansen.
/// </summary>
void AdvancedFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = mainTexture;
if (tex == null) return;
Vector4 br = border * pixelSize;
if (br.x == 0f && br.y == 0f && br.z == 0f && br.w == 0f)
{
SimpleFill(verts, uvs, cols);
return;
}
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
Vector2 tileSize = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
tileSize *= pixelSize;
if (tileSize.x < 1f) tileSize.x = 1f;
if (tileSize.y < 1f) tileSize.y = 1f;
mTempPos[0].x = v.x;
mTempPos[0].y = v.y;
mTempPos[3].x = v.z;
mTempPos[3].y = v.w;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
mTempPos[1].x = mTempPos[0].x + br.z;
mTempPos[2].x = mTempPos[3].x - br.x;
mTempUVs[3].x = mOuterUV.xMin;
mTempUVs[2].x = mInnerUV.xMin;
mTempUVs[1].x = mInnerUV.xMax;
mTempUVs[0].x = mOuterUV.xMax;
}
else
{
mTempPos[1].x = mTempPos[0].x + br.x;
mTempPos[2].x = mTempPos[3].x - br.z;
mTempUVs[0].x = mOuterUV.xMin;
mTempUVs[1].x = mInnerUV.xMin;
mTempUVs[2].x = mInnerUV.xMax;
mTempUVs[3].x = mOuterUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
mTempPos[1].y = mTempPos[0].y + br.w;
mTempPos[2].y = mTempPos[3].y - br.y;
mTempUVs[3].y = mOuterUV.yMin;
mTempUVs[2].y = mInnerUV.yMin;
mTempUVs[1].y = mInnerUV.yMax;
mTempUVs[0].y = mOuterUV.yMax;
}
else
{
mTempPos[1].y = mTempPos[0].y + br.y;
mTempPos[2].y = mTempPos[3].y - br.w;
mTempUVs[0].y = mOuterUV.yMin;
mTempUVs[1].y = mInnerUV.yMin;
mTempUVs[2].y = mInnerUV.yMax;
mTempUVs[3].y = mOuterUV.yMax;
}
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (centerType == AdvancedType.Invisible && x == 1 && y == 1) continue;
int y2 = y + 1;
if (x == 1 && y == 1) // Center
{
if (centerType == AdvancedType.Tiled)
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureStartY = mTempUVs[y].y;
float tileStartY = startPositionY;
while (tileStartY < endPositionY)
{
float tileStartX = startPositionX;
float textureEndY = mTempUVs[y2].y;
float tileEndY = tileStartY + tileSize.y;
if (tileEndY > endPositionY)
{
textureEndY = Mathf.Lerp(textureStartY, textureEndY, (endPositionY - tileStartY) / tileSize.y);
tileEndY = endPositionY;
}
while (tileStartX < endPositionX)
{
float tileEndX = tileStartX + tileSize.x;
float textureEndX = mTempUVs[x2].x;
if (tileEndX > endPositionX)
{
textureEndX = Mathf.Lerp(textureStartX, textureEndX, (endPositionX - tileStartX) / tileSize.x);
tileEndX = endPositionX;
}
Fill(verts, uvs, cols,
tileStartX, tileEndX,
tileStartY, tileEndY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartX += tileSize.x;
}
tileStartY += tileSize.y;
}
}
else if (centerType == AdvancedType.Sliced)
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else if (x == 1) // Top or bottom
{
if ((y == 0 && bottomType == AdvancedType.Tiled) || (y == 2 && topType == AdvancedType.Tiled))
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureStartY = mTempUVs[y].y;
float textureEndY = mTempUVs[y2].y;
float tileStartX = startPositionX;
while (tileStartX < endPositionX)
{
float tileEndX = tileStartX + tileSize.x;
float textureEndX = mTempUVs[x2].x;
if (tileEndX > endPositionX)
{
textureEndX = Mathf.Lerp(textureStartX, textureEndX, (endPositionX - tileStartX) / tileSize.x);
tileEndX = endPositionX;
}
Fill(verts, uvs, cols,
tileStartX, tileEndX,
startPositionY, endPositionY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartX += tileSize.x;
}
}
else if ((y == 0 && bottomType != AdvancedType.Invisible) || (y == 2 && topType != AdvancedType.Invisible))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else if (y == 1) // Left or right
{
if ((x == 0 && leftType == AdvancedType.Tiled) || (x == 2 && rightType == AdvancedType.Tiled))
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureEndX = mTempUVs[x2].x;
float textureStartY = mTempUVs[y].y;
float tileStartY = startPositionY;
while (tileStartY < endPositionY)
{
float textureEndY = mTempUVs[y2].y;
float tileEndY = tileStartY + tileSize.y;
if (tileEndY > endPositionY)
{
textureEndY = Mathf.Lerp(textureStartY, textureEndY, (endPositionY - tileStartY) / tileSize.y);
tileEndY = endPositionY;
}
Fill(verts, uvs, cols,
startPositionX, endPositionX,
tileStartY, tileEndY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartY += tileSize.y;
}
}
else if ((x == 0 && leftType != AdvancedType.Invisible) || (x == 2 && rightType != AdvancedType.Invisible))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else // Corner
{
if ((y == 0 && bottomType != AdvancedType.Invisible) || (y == 2 && topType != AdvancedType.Invisible) ||
(x == 0 && leftType != AdvancedType.Invisible) || (x == 2 && rightType != AdvancedType.Invisible))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
}
}
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static bool RadialCut (Vector2[] xy, Vector2[] uv, float fill, bool invert, int corner)
{
// Nothing to fill
if (fill < 0.001f) return false;
// Even corners invert the fill direction
if ((corner & 1) == 1) invert = !invert;
// Nothing to adjust
if (!invert && fill > 0.999f) return true;
// Convert 0-1 value into 0 to 90 degrees angle in radians
float angle = Mathf.Clamp01(fill);
if (invert) angle = 1f - angle;
angle *= 90f * Mathf.Deg2Rad;
// Calculate the effective X and Y factors
float cos = Mathf.Cos(angle);
float sin = Mathf.Sin(angle);
RadialCut(xy, cos, sin, invert, corner);
RadialCut(uv, cos, sin, invert, corner);
return true;
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static void RadialCut (Vector2[] xy, float cos, float sin, bool invert, int corner)
{
int i0 = corner;
int i1 = NGUIMath.RepeatIndex(corner + 1, 4);
int i2 = NGUIMath.RepeatIndex(corner + 2, 4);
int i3 = NGUIMath.RepeatIndex(corner + 3, 4);
if ((corner & 1) == 1)
{
if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i2].x = xy[i1].x;
}
}
else if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i2].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i3].y = xy[i2].y;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (!invert) xy[i3].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
else xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
}
else
{
if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i2].y = xy[i1].y;
}
}
else if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i2].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i3].x = xy[i2].x;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (invert) xy[i3].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
else xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
}
}
/// <summary>
/// Helper function that adds the specified values to the buffers.
/// </summary>
static void Fill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols,
float v0x, float v1x, float v0y, float v1y, float u0x, float u1x, float u0y, float u1y, Color col)
{
verts.Add(new Vector3(v0x, v0y));
verts.Add(new Vector3(v0x, v1y));
verts.Add(new Vector3(v1x, v1y));
verts.Add(new Vector3(v1x, v0y));
uvs.Add(new Vector2(u0x, u0y));
uvs.Add(new Vector2(u0x, u1y));
uvs.Add(new Vector2(u1x, u1y));
uvs.Add(new Vector2(u1x, u0y));
cols.Add(col);
cols.Add(col);
cols.Add(col);
cols.Add(col);
}
#endregion // Fill functions
}
| artandrtom/MyRepository | RacingCars/RacingCars/Assets/NGUI/Scripts/Internal/UIBasicSprite.cs | C# | gpl-3.0 | 25,566 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration |
\\ / A nd | For copyright notice see file Copyright
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend 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.
foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "PointEdgeWave.H"
#include "polyMesh.H"
#include "processorPolyPatch.H"
#include "cyclicPolyPatch.H"
#include "ggiPolyPatch.H"
#include "OPstream.H"
#include "IPstream.H"
#include "PstreamCombineReduceOps.H"
#include "debug.H"
#include "typeInfo.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
template <class Type>
Foam::scalar Foam::PointEdgeWave<Type>::propagationTol_ = 0.01;
// Offset labelList. Used for transferring from one cyclic half to the other.
template <class Type>
void Foam::PointEdgeWave<Type>::offset(const label val, labelList& elems)
{
forAll(elems, i)
{
elems[i] += val;
}
}
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
// Gets point-point correspondence. Is
// - list of halfA points (in cyclic patch points)
// - list of halfB points (can overlap with A!)
// - for every patchPoint its corresponding point
template <class Type>
void Foam::PointEdgeWave<Type>::calcCyclicAddressing()
{
label cycHalf = 0;
forAll(mesh_.boundaryMesh(), patchI)
{
const polyPatch& patch = mesh_.boundaryMesh()[patchI];
if (isA<cyclicPolyPatch>(patch))
{
label halfSize = patch.size()/2;
SubList<face> halfAFaces
(
mesh_.faces(),
halfSize,
patch.start()
);
cycHalves_.set
(
cycHalf++,
new primitivePatch(halfAFaces, mesh_.points())
);
SubList<face> halfBFaces
(
mesh_.faces(),
halfSize,
patch.start() + halfSize
);
cycHalves_.set
(
cycHalf++,
new primitivePatch(halfBFaces, mesh_.points())
);
}
}
}
// Handle leaving domain. Implementation referred to Type
template <class Type>
void Foam::PointEdgeWave<Type>::leaveDomain
(
const polyPatch& meshPatch,
const primitivePatch& patch,
const labelList& patchPointLabels,
List<Type>& pointInfo
) const
{
const labelList& meshPoints = patch.meshPoints();
forAll(patchPointLabels, i)
{
label patchPointI = patchPointLabels[i];
const point& pt = patch.points()[meshPoints[patchPointI]];
pointInfo[i].leaveDomain(meshPatch, patchPointI, pt);
}
}
// Handle entering domain. Implementation referred to Type
template <class Type>
void Foam::PointEdgeWave<Type>::enterDomain
(
const polyPatch& meshPatch,
const primitivePatch& patch,
const labelList& patchPointLabels,
List<Type>& pointInfo
) const
{
const labelList& meshPoints = patch.meshPoints();
forAll(patchPointLabels, i)
{
label patchPointI = patchPointLabels[i];
const point& pt = patch.points()[meshPoints[patchPointI]];
pointInfo[i].enterDomain(meshPatch, patchPointI, pt);
}
}
// Transform. Implementation referred to Type
template <class Type>
void Foam::PointEdgeWave<Type>::transform
(
const tensorField& rotTensor,
List<Type>& pointInfo
) const
{
if (rotTensor.size() == 1)
{
const tensor& T = rotTensor[0];
forAll(pointInfo, i)
{
pointInfo[i].transform(T);
}
}
else
{
FatalErrorIn
(
"PointEdgeWave<Type>::transform(const tensorField&, List<Type>&)"
) << "Parallel cyclics not supported"
<< abort(FatalError);
forAll(pointInfo, i)
{
pointInfo[i].transform(rotTensor[i]);
}
}
}
// Update info for pointI, at position pt, with information from
// neighbouring edge.
// Updates:
// - changedPoint_, changedPoints_, nChangedPoints_,
// - statistics: nEvals_, nUnvisitedPoints_
template <class Type>
bool Foam::PointEdgeWave<Type>::updatePoint
(
const label pointI,
const label neighbourEdgeI,
const Type& neighbourInfo,
const scalar tol,
Type& pointInfo
)
{
nEvals_++;
bool wasValid = pointInfo.valid();
bool propagate =
pointInfo.updatePoint
(
mesh_,
pointI,
neighbourEdgeI,
neighbourInfo,
tol
);
if (propagate)
{
if (!changedPoint_[pointI])
{
changedPoint_[pointI] = true;
changedPoints_[nChangedPoints_++] = pointI;
}
}
if (!wasValid && pointInfo.valid())
{
--nUnvisitedPoints_;
}
return propagate;
}
// Update info for pointI, at position pt, with information from
// same point.
// Updates:
// - changedPoint_, changedPoints_, nChangedPoints_,
// - statistics: nEvals_, nUnvisitedPoints_
template <class Type>
bool Foam::PointEdgeWave<Type>::updatePoint
(
const label pointI,
const Type& neighbourInfo,
const scalar tol,
Type& pointInfo
)
{
nEvals_++;
bool wasValid = pointInfo.valid();
bool propagate =
pointInfo.updatePoint
(
mesh_,
pointI,
neighbourInfo,
tol
);
if (propagate)
{
if (!changedPoint_[pointI])
{
changedPoint_[pointI] = true;
changedPoints_[nChangedPoints_++] = pointI;
}
}
if (!wasValid && pointInfo.valid())
{
--nUnvisitedPoints_;
}
return propagate;
}
// Update info for edgeI, at position pt, with information from
// neighbouring point.
// Updates:
// - changedEdge_, changedEdges_, nChangedEdges_,
// - statistics: nEvals_, nUnvisitedEdge_
template <class Type>
bool Foam::PointEdgeWave<Type>::updateEdge
(
const label edgeI,
const label neighbourPointI,
const Type& neighbourInfo,
const scalar tol,
Type& edgeInfo
)
{
nEvals_++;
bool wasValid = edgeInfo.valid();
bool propagate =
edgeInfo.updateEdge
(
mesh_,
edgeI,
neighbourPointI,
neighbourInfo,
tol
);
if (propagate)
{
if (!changedEdge_[edgeI])
{
changedEdge_[edgeI] = true;
changedEdges_[nChangedEdges_++] = edgeI;
}
}
if (!wasValid && edgeInfo.valid())
{
--nUnvisitedEdges_;
}
return propagate;
}
// Check if patches of given type name are present
template <class Type>
template <class PatchType>
Foam::label Foam::PointEdgeWave<Type>::countPatchType() const
{
label nPatches = 0;
forAll(mesh_.boundaryMesh(), patchI)
{
if (isA<PatchType>(mesh_.boundaryMesh()[patchI]))
{
nPatches++;
}
}
return nPatches;
}
// Collect changed patch points
template <class Type>
void Foam::PointEdgeWave<Type>::getChangedPatchPoints
(
const primitivePatch& patch,
DynamicList<Type>& patchInfo,
DynamicList<label>& patchPoints,
DynamicList<label>& owner,
DynamicList<label>& ownerIndex
) const
{
const labelList& meshPoints = patch.meshPoints();
const faceList& localFaces = patch.localFaces();
const labelListList& pointFaces = patch.pointFaces();
forAll(meshPoints, patchPointI)
{
label meshPointI = meshPoints[patchPointI];
if (changedPoint_[meshPointI])
{
patchInfo.append(allPointInfo_[meshPointI]);
//Pout << "Sending " << meshPointI << " " << mesh_.points()[meshPointI] << " o = " << patchInfo[patchInfo.size()-1].origin() << " " << allPointInfo_[meshPointI] << endl;
patchPoints.append(patchPointI);
label patchFaceI = pointFaces[patchPointI][0];
const face& f = localFaces[patchFaceI];
label index = findIndex(f, patchPointI);
owner.append(patchFaceI);
ownerIndex.append(index);
}
}
patchInfo.shrink();
patchPoints.shrink();
owner.shrink();
ownerIndex.shrink();
}
// Update overall for changed patch points
template <class Type>
void Foam::PointEdgeWave<Type>::updateFromPatchInfo
(
const polyPatch& meshPatch,
const primitivePatch& patch,
const labelList& owner,
const labelList& ownerIndex,
List<Type>& patchInfo
)
{
const faceList& localFaces = patch.localFaces();
const labelList& meshPoints = patch.meshPoints();
// Get patch and mesh points.
labelList changedPatchPoints(patchInfo.size());
labelList changedMeshPoints(patchInfo.size());
forAll(owner, i)
{
label faceI = owner[i];
const face& f = localFaces[faceI];
label index = (f.size() - ownerIndex[i]) % f.size();
changedPatchPoints[i] = f[index];
changedMeshPoints[i] = meshPoints[f[index]];
}
// Adapt for entering domain
enterDomain(meshPatch, patch, changedPatchPoints, patchInfo);
// Merge received info
forAll(patchInfo, i)
{
updatePoint
(
changedMeshPoints[i],
patchInfo[i],
propagationTol_,
allPointInfo_[changedMeshPoints[i]]
);
}
}
// Transfer all the information to/from neighbouring processors
template <class Type>
void Foam::PointEdgeWave<Type>::handleProcPatches()
{
// 1. Send all point info on processor patches. Send as
// face label + offset in face.
forAll(mesh_.boundaryMesh(), patchI)
{
const polyPatch& patch = mesh_.boundaryMesh()[patchI];
if (isA<processorPolyPatch>(patch))
{
// Get all changed points in relative addressing
DynamicList<Type> patchInfo(patch.nPoints());
DynamicList<label> patchPoints(patch.nPoints());
DynamicList<label> owner(patch.nPoints());
DynamicList<label> ownerIndex(patch.nPoints());
getChangedPatchPoints
(
patch,
patchInfo,
patchPoints,
owner,
ownerIndex
);
// Adapt for leaving domain
leaveDomain(patch, patch, patchPoints, patchInfo);
const processorPolyPatch& procPatch =
refCast<const processorPolyPatch>(patch);
if (debug)
{
Pout<< "Processor patch " << patchI << ' ' << patch.name()
<< " communicating with " << procPatch.neighbProcNo()
<< " Sending:" << patchInfo.size() << endl;
}
{
OPstream toNeighbour
(
Pstream::blocking,
procPatch.neighbProcNo()
);
toNeighbour << owner << ownerIndex << patchInfo;
}
}
}
//
// 2. Receive all point info on processor patches.
//
forAll(mesh_.boundaryMesh(), patchI)
{
const polyPatch& patch = mesh_.boundaryMesh()[patchI];
if (isA<processorPolyPatch>(patch))
{
const processorPolyPatch& procPatch =
refCast<const processorPolyPatch>(patch);
List<Type> patchInfo;
labelList owner;
labelList ownerIndex;
{
IPstream fromNeighbour
(
Pstream::blocking,
procPatch.neighbProcNo()
);
fromNeighbour >> owner >> ownerIndex >> patchInfo;
}
if (debug)
{
Pout<< "Processor patch " << patchI << ' ' << patch.name()
<< " communicating with " << procPatch.neighbProcNo()
<< " Received:" << patchInfo.size() << endl;
}
// Apply transform to received data for non-parallel planes
if (!procPatch.parallel())
{
transform(procPatch.forwardT(), patchInfo);
}
updateFromPatchInfo
(
patch,
patch,
owner,
ownerIndex,
patchInfo
);
}
}
//
// 3. Handle all shared points
// (Note:irrespective if changed or not for now)
//
const globalMeshData& pd = mesh_.globalData();
List<Type> sharedData(pd.nGlobalPoints());
forAll(pd.sharedPointLabels(), i)
{
label meshPointI = pd.sharedPointLabels()[i];
// Fill my entries in the shared points
sharedData[pd.sharedPointAddr()[i]] = allPointInfo_[meshPointI];
}
// Combine on master. Reduce operator has to handle a list and call
// Type.updatePoint for all elements
combineReduce(sharedData, listUpdateOp<Type>());
forAll(pd.sharedPointLabels(), i)
{
label meshPointI = pd.sharedPointLabels()[i];
// Retrieve my entries from the shared points
updatePoint
(
meshPointI,
sharedData[pd.sharedPointAddr()[i]],
propagationTol_,
allPointInfo_[meshPointI]
);
}
}
template <class Type>
void Foam::PointEdgeWave<Type>::handleCyclicPatches()
{
// 1. Send all point info on cyclic patches. Send as
// face label + offset in face.
label cycHalf = 0;
forAll(mesh_.boundaryMesh(), patchI)
{
const polyPatch& patch = mesh_.boundaryMesh()[patchI];
if (isA<cyclicPolyPatch>(patch))
{
const primitivePatch& halfA = cycHalves_[cycHalf++];
const primitivePatch& halfB = cycHalves_[cycHalf++];
// HalfA : get all changed points in relative addressing
DynamicList<Type> halfAInfo(halfA.nPoints());
DynamicList<label> halfAPoints(halfA.nPoints());
DynamicList<label> halfAOwner(halfA.nPoints());
DynamicList<label> halfAIndex(halfA.nPoints());
getChangedPatchPoints
(
halfA,
halfAInfo,
halfAPoints,
halfAOwner,
halfAIndex
);
// HalfB : get all changed points in relative addressing
DynamicList<Type> halfBInfo(halfB.nPoints());
DynamicList<label> halfBPoints(halfB.nPoints());
DynamicList<label> halfBOwner(halfB.nPoints());
DynamicList<label> halfBIndex(halfB.nPoints());
getChangedPatchPoints
(
halfB,
halfBInfo,
halfBPoints,
halfBOwner,
halfBIndex
);
// HalfA : adapt for leaving domain
leaveDomain(patch, halfA, halfAPoints, halfAInfo);
// HalfB : adapt for leaving domain
leaveDomain(patch, halfB, halfBPoints, halfBInfo);
// Apply rotation for non-parallel planes
const cyclicPolyPatch& cycPatch =
refCast<const cyclicPolyPatch>(patch);
if (!cycPatch.parallel())
{
// received data from half1
transform(cycPatch.forwardT(), halfAInfo);
// received data from half2
transform(cycPatch.forwardT(), halfBInfo);
}
if (debug)
{
Pout<< "Cyclic patch " << patchI << ' ' << patch.name()
<< " Changed on first half : " << halfAInfo.size()
<< " Changed on second half : " << halfBInfo.size()
<< endl;
}
// Half1: update with data from halfB
updateFromPatchInfo
(
patch,
halfA,
halfBOwner,
halfBIndex,
halfBInfo
);
// Half2: update with data from halfA
updateFromPatchInfo
(
patch,
halfB,
halfAOwner,
halfAIndex,
halfAInfo
);
if (debug)
{
//checkCyclic(patch);
}
}
}
}
// Update overall for changed patch points
template <class Type>
void Foam::PointEdgeWave<Type>::updateFromPatchInfo
(
const ggiPolyPatch& to,
const labelListList& shadowAddr,
const labelList& owner,
const labelList& ownerIndex,
List<Type>& patchInfo
)
{
//const labelList& meshPoints = to.meshPoints();
const pointField& points = to.points();
const List<face>& allFaces = mesh_.allFaces();
forAll(patchInfo, i)
{
label fID = to.shadow().zone()[owner[i]];
label pID = allFaces[fID][ownerIndex[i]];
point p = points[pID];
// Update in sending zone without propagation
if(fID >= mesh_.nFaces())
{
allPointInfo_[pID].updatePoint
(
mesh_,
pID,
patchInfo[i],
propagationTol_
);
}
const labelList& addr = shadowAddr[owner[i]];
if(addr.size() > 0)
{
label nearestPoint = -1;
label nearestFace = -1;
scalar dist = GREAT;
forAll(addr, saI)
{
label fID2 = to.zone()[addr[saI]];
const face& f = allFaces[fID2];
forAll(f, pI)
{
label pID2 = f[pI];
scalar d = magSqr(points[pID2] - p);
if(d < dist)
{
nearestFace = fID2;
nearestPoint = pID2;
dist = d;
}
else if(nearestPoint == pID2 && fID2 < mesh_.nFaces())
{
// Choose face in patch over face in zone
nearestFace = fID2;
}
}
}
patchInfo[i].enterDomain(to, nearestPoint, points[nearestPoint]);
if(nearestFace < mesh_.nFaces())
{
// Update in receiving patch with propagation
updatePoint
(
nearestPoint,
patchInfo[i],
propagationTol_,
allPointInfo_[nearestPoint]
);
}
else
{
// Update in receiving zone without propagation
allPointInfo_[nearestPoint].updatePoint
(
mesh_,
nearestPoint,
patchInfo[i],
propagationTol_
);
}
}
}
}
// Transfer all the information to/from neighbouring processors
template <class Type>
void Foam::PointEdgeWave<Type>::handleGgiPatches()
{
forAll(mesh_.boundaryMesh(), patchI)
{
const polyPatch& patch = mesh_.boundaryMesh()[patchI];
if (isA<ggiPolyPatch>(patch))
{
const ggiPolyPatch& master = refCast<const ggiPolyPatch>(patch);
const ggiPolyPatch& slave = master.shadow();
if(master.master() && (master.localParallel() || master.size()))
{
// 1. Collect all point info on master side
DynamicList<Type> masterInfo(master.nPoints());
DynamicList<label> masterOwner(master.nPoints());
DynamicList<label> masterOwnerIndex(master.nPoints());
{
DynamicList<label> patchPoints(master.nPoints());
// Get all changed points in relative addressing
getChangedPatchPoints
(
master,
masterInfo,
patchPoints,
masterOwner,
masterOwnerIndex
);
forAll(masterOwner, i)
{
masterOwner[i] =
master.zoneAddressing()[masterOwner[i]];
}
// Adapt for leaving domain
leaveDomain(master, master, patchPoints, masterInfo);
if (debug)
{
Pout<< "Ggi patch " << master.index() << ' ' << master.name()
<< " Sending:" << masterInfo.size() << endl;
}
}
// 2. Collect all point info on slave side
DynamicList<Type> slaveInfo(slave.nPoints());
DynamicList<label> slaveOwner(slave.nPoints());
DynamicList<label> slaveOwnerIndex(slave.nPoints());
{
DynamicList<label> patchPoints(slave.nPoints());
// Get all changed points in relative addressing
getChangedPatchPoints
(
slave,
slaveInfo,
patchPoints,
slaveOwner,
slaveOwnerIndex
);
forAll(slaveOwner, i)
{
slaveOwner[i] =
slave.zoneAddressing()[slaveOwner[i]];
}
// Adapt for leaving domain
leaveDomain(slave, slave, patchPoints, slaveInfo);
if (debug)
{
Pout<< "Ggi patch " << slave.index() << ' ' << slave.name()
<< " Sending:" << slaveInfo.size() << endl;
}
}
if(!master.localParallel())
{
combineReduce(masterInfo, listAppendOp<Type>());
combineReduce(slaveInfo, listAppendOp<Type>());
combineReduce(masterOwner, listAppendOp<label>());
combineReduce(slaveOwner, listAppendOp<label>());
combineReduce(masterOwnerIndex, listAppendOp<label>());
combineReduce(slaveOwnerIndex, listAppendOp<label>());
}
// 3. Apply point info on master & slave side
if (debug)
{
Pout<< "Ggi patch " << slave.index() << ' ' << slave.name()
<< " Received:" << masterInfo.size() << endl;
Pout<< "Ggi patch " << master.index() << ' ' << master.name()
<< " Received:" << slaveInfo.size() << endl;
}
// Apply transform to received data for non-parallel planes
if (!master.parallel())
{
transform(master.forwardT(), masterInfo);
transform(slave.forwardT(), slaveInfo);
}
updateFromPatchInfo
(
slave,
master.patchToPatch().masterAddr(),
masterOwner,
masterOwnerIndex,
masterInfo
);
updateFromPatchInfo
(
master,
master.patchToPatch().slaveAddr(),
slaveOwner,
slaveOwnerIndex,
slaveInfo
);
}
}
}
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
// Iterate, propagating changedPointsInfo across mesh, until no change (or
// maxIter reached). Initial point values specified.
template <class Type>
Foam::PointEdgeWave<Type>::PointEdgeWave
(
const polyMesh& mesh,
const labelList& changedPoints,
const List<Type>& changedPointsInfo,
List<Type>& allPointInfo,
List<Type>& allEdgeInfo,
const label maxIter
)
:
mesh_(mesh),
allPointInfo_(allPointInfo),
allEdgeInfo_(allEdgeInfo),
changedPoint_(mesh_.nPoints(), false),
changedPoints_(mesh_.nPoints()),
nChangedPoints_(0),
changedEdge_(mesh_.nEdges(), false),
changedEdges_(mesh_.nEdges()),
nChangedEdges_(0),
nCyclicPatches_(countPatchType<cyclicPolyPatch>()),
nGgiPatches_(countPatchType<ggiPolyPatch>()),
cycHalves_(2*nCyclicPatches_),
nEvals_(0),
nUnvisitedPoints_(mesh_.nPoints()),
nUnvisitedEdges_(mesh_.nEdges())
{
if
(
allPointInfo_.size() != mesh_.nPoints()
&& allPointInfo_.size() != mesh_.allPoints().size()
)
{
FatalErrorIn
(
"PointEdgeWave<Type>::PointEdgeWave"
"(const polyMesh&, const labelList&, const List<Type>,"
" List<Type>&, List<Type>&, const label maxIter)"
) << "size of pointInfo work array is not equal to the number"
<< " of points in the mesh" << endl
<< " pointInfo :" << allPointInfo_.size() << endl
<< " mesh.nPoints:" << mesh_.nPoints()
<< exit(FatalError);
}
if (allEdgeInfo_.size() != mesh_.nEdges())
{
FatalErrorIn
(
"PointEdgeWave<Type>::PointEdgeWave"
"(const polyMesh&, const labelList&, const List<Type>,"
" List<Type>&, List<Type>&, const label maxIter)"
) << "size of edgeInfo work array is not equal to the number"
<< " of edges in the mesh" << endl
<< " edgeInfo :" << allEdgeInfo_.size() << endl
<< " mesh.nEdges:" << mesh_.nEdges()
<< exit(FatalError);
}
// Calculate cyclic halves addressing.
if (nCyclicPatches_ > 0)
{
calcCyclicAddressing();
}
// Set from initial changed points data
setPointInfo(changedPoints, changedPointsInfo);
if (debug)
{
Pout<< "Seed points : " << nChangedPoints_ << endl;
}
// Iterate until nothing changes
label iter = iterate(maxIter);
if ((maxIter > 0) && (iter >= maxIter))
{
FatalErrorIn
(
"PointEdgeWave<Type>::PointEdgeWave"
"(const polyMesh&, const labelList&, const List<Type>,"
" List<Type>&, List<Type>&, const label maxIter)"
) << "Maximum number of iterations reached. Increase maxIter." << nl
<< " maxIter:" << maxIter << endl
<< " nChangedPoints:" << nChangedPoints_ << endl
<< " nChangedEdges:" << nChangedEdges_ << endl
<< exit(FatalError);
}
}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
template <class Type>
Foam::PointEdgeWave<Type>::~PointEdgeWave()
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template <class Type>
Foam::label Foam::PointEdgeWave<Type>::getUnsetPoints() const
{
return nUnvisitedPoints_;
}
template <class Type>
Foam::label Foam::PointEdgeWave<Type>::getUnsetEdges() const
{
return nUnvisitedEdges_;
}
// Copy point information into member data
template <class Type>
void Foam::PointEdgeWave<Type>::setPointInfo
(
const labelList& changedPoints,
const List<Type>& changedPointsInfo
)
{
forAll(changedPoints, changedPointI)
{
label pointI = changedPoints[changedPointI];
bool wasValid = allPointInfo_[pointI].valid();
// Copy info for pointI
allPointInfo_[pointI] = changedPointsInfo[changedPointI];
// Maintain count of unset points
if (!wasValid && allPointInfo_[pointI].valid())
{
--nUnvisitedPoints_;
}
// Mark pointI as changed, both on list and on point itself.
if (!changedPoint_[pointI])
{
changedPoint_[pointI] = true;
changedPoints_[nChangedPoints_++] = pointI;
}
}
}
// Propagate information from edge to point. Return number of points changed.
template <class Type>
Foam::label Foam::PointEdgeWave<Type>::edgeToPoint()
{
for
(
label changedEdgeI = 0;
changedEdgeI < nChangedEdges_;
changedEdgeI++
)
{
label edgeI = changedEdges_[changedEdgeI];
if (!changedEdge_[edgeI])
{
FatalErrorIn("PointEdgeWave<Type>::edgeToPoint()")
<< "edge " << edgeI
<< " not marked as having been changed" << nl
<< "This might be caused by multiple occurences of the same"
<< " seed point." << abort(FatalError);
}
const Type& neighbourWallInfo = allEdgeInfo_[edgeI];
// Evaluate all connected points (= edge endpoints)
const edge& e = mesh_.edges()[edgeI];
forAll(e, eI)
{
Type& currentWallInfo = allPointInfo_[e[eI]];
if (currentWallInfo != neighbourWallInfo)
{
updatePoint
(
e[eI],
edgeI,
neighbourWallInfo,
propagationTol_,
currentWallInfo
);
}
}
// Reset status of edge
changedEdge_[edgeI] = false;
}
// Handled all changed edges by now
nChangedEdges_ = 0;
if (nCyclicPatches_ > 0)
{
// Transfer changed points across cyclic halves
handleCyclicPatches();
}
if (nGgiPatches_ > 0)
{
// Transfer changed points across cyclic halves
handleGgiPatches();
}
if (Pstream::parRun())
{
// Transfer changed points from neighbouring processors.
handleProcPatches();
}
if (debug)
{
Pout<< "Changed points : " << nChangedPoints_ << endl;
}
// Sum nChangedPoints over all procs
label totNChanged = nChangedPoints_;
reduce(totNChanged, sumOp<label>());
return totNChanged;
}
// Propagate information from point to edge. Return number of edges changed.
template <class Type>
Foam::label Foam::PointEdgeWave<Type>::pointToEdge()
{
const labelListList& pointEdges = mesh_.pointEdges();
for
(
label changedPointI = 0;
changedPointI < nChangedPoints_;
changedPointI++
)
{
label pointI = changedPoints_[changedPointI];
if (!changedPoint_[pointI])
{
FatalErrorIn("PointEdgeWave<Type>::pointToEdge()")
<< "Point " << pointI
<< " not marked as having been changed" << nl
<< "This might be caused by multiple occurences of the same"
<< " seed point." << abort(FatalError);
}
const Type& neighbourWallInfo = allPointInfo_[pointI];
// Evaluate all connected edges
const labelList& edgeLabels = pointEdges[pointI];
forAll(edgeLabels, edgeLabelI)
{
label edgeI = edgeLabels[edgeLabelI];
Type& currentWallInfo = allEdgeInfo_[edgeI];
if (currentWallInfo != neighbourWallInfo)
{
updateEdge
(
edgeI,
pointI,
neighbourWallInfo,
propagationTol_,
currentWallInfo
);
}
}
// Reset status of point
changedPoint_[pointI] = false;
}
// Handled all changed points by now
nChangedPoints_ = 0;
if (debug)
{
Pout<< "Changed edges : " << nChangedEdges_ << endl;
}
// Sum nChangedPoints over all procs
label totNChanged = nChangedEdges_;
reduce(totNChanged, sumOp<label>());
return totNChanged;
}
// Iterate
template <class Type>
Foam::label Foam::PointEdgeWave<Type>::iterate(const label maxIter)
{
if (nCyclicPatches_ > 0)
{
// Transfer changed points across cyclic halves
handleCyclicPatches();
}
if (nGgiPatches_ > 0)
{
// Transfer changed points across ggi patches
handleGgiPatches();
}
if (Pstream::parRun())
{
// Transfer changed points from neighbouring processors.
handleProcPatches();
}
nEvals_ = 0;
label iter = 0;
while(iter < maxIter)
{
if (debug)
{
Pout<< "Iteration " << iter << endl;
}
label nEdges = pointToEdge();
if (debug)
{
Pout<< "Total changed edges : " << nEdges << endl;
}
if (nEdges == 0)
{
break;
}
label nPoints = edgeToPoint();
if (debug)
{
Pout<< "Total changed points : " << nPoints << endl;
Pout<< "Total evaluations : " << nEvals_ << endl;
Pout<< "Remaining unvisited points: " << nUnvisitedPoints_ << endl;
Pout<< "Remaining unvisited edges : " << nUnvisitedEdges_ << endl;
Pout<< endl;
}
if (nPoints == 0)
{
break;
}
iter++;
}
return iter;
}
// ************************************************************************* //
| Unofficial-Extend-Project-Mirror/openfoam-extend-foam-extend-3.0 | src/meshTools/PointEdgeWave/PointEdgeWave.C | C++ | gpl-3.0 | 34,391 |
using System;
using System.Linq;
using System.Windows.Forms;
using Rubberduck.Parsing.Grammar;
using Rubberduck.Parsing.Symbols;
using Rubberduck.Refactorings.Rename;
namespace Rubberduck.UI.Refactorings
{
public partial class RenameDialog : Form, IRenameView
{
public RenameDialog()
{
InitializeComponent();
InitializeCaptions();
Shown += RenameDialog_Shown;
NewNameBox.TextChanged += NewNameBox_TextChanged;
}
private void InitializeCaptions()
{
Text = RubberduckUI.RenameDialog_Caption;
OkButton.Text = RubberduckUI.OK;
CancelDialogButton.Text = RubberduckUI.CancelButtonText;
TitleLabel.Text = RubberduckUI.RenameDialog_TitleText;
InstructionsLabel.Text = RubberduckUI.RenameDialog_InstructionsLabelText;
NameLabel.Text = RubberduckUI.NameLabelText;
}
private void NewNameBox_TextChanged(object sender, EventArgs e)
{
NewName = NewNameBox.Text;
}
private void RenameDialog_Shown(object sender, EventArgs e)
{
NewNameBox.SelectAll();
NewNameBox.Focus();
}
private Declaration _target;
public Declaration Target
{
get { return _target; }
set
{
_target = value;
if (_target == null)
{
return;
}
NewName = _target.IdentifierName;
var declarationType =
RubberduckUI.ResourceManager.GetString("DeclarationType_" + _target.DeclarationType, RubberduckUI.Culture);
InstructionsLabel.Text = string.Format(RubberduckUI.RenameDialog_InstructionsLabelText, declarationType,
_target.IdentifierName);
}
}
public string NewName
{
get { return NewNameBox.Text; }
set
{
NewNameBox.Text = value;
ValidateNewName();
}
}
private void ValidateNewName()
{
var tokenValues = typeof(Tokens).GetFields().Select(item => item.GetValueDirect(new TypedReference())).Cast<string>().Select(item => item.ToLower());
OkButton.Enabled = NewName != Target.IdentifierName
&& char.IsLetter(NewName.FirstOrDefault())
&& !tokenValues.Contains(NewName.ToLower())
&& !NewName.Any(c => !char.IsLetterOrDigit(c) && c != '_');
InvalidNameValidationIcon.Visible = !OkButton.Enabled;
}
}
} | ptwales/Rubberduck | RetailCoder.VBE/UI/Refactorings/RenameDialog.cs | C# | gpl-3.0 | 2,733 |
/*******************************************************************************
**
** Photivo
**
** Copyright (C) 2008 Jos De Laender <jos.de_laender@telenet.be>
** Copyright (C) 2012-2013 Michael Munzert <mail@mm-log.com>
**
** This file is part of Photivo.
**
** Photivo is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License version 3
** as published by the Free Software Foundation.
**
** Photivo 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 Photivo. If not, see <http://www.gnu.org/licenses/>.
**
*******************************************************************************/
#include "ptError.h"
#include "ptCalloc.h"
#include "ptImage8.h"
#include "ptImage.h"
#include "ptResizeFilters.h"
#include <cstdio>
#include <cstdlib>
#include <cassert>
//==============================================================================
ptImage8::ptImage8():
m_Width(0),
m_Height(0),
m_Colors(0),
m_ColorSpace(ptSpace_sRGB_D65),
m_SizeBytes(0)
{}
//==============================================================================
ptImage8::ptImage8(uint16_t AWidth,
uint16_t AHeight,
short ANrColors)
{
m_Image.clear();
m_ColorSpace = ptSpace_sRGB_D65;
setSize(AWidth, AHeight, ANrColors);
}
//==============================================================================
void ptImage8::setSize(uint16_t AWidth, uint16_t AHeight, int AColorCount) {
m_Width = AWidth;
m_Height = AHeight;
m_Colors = AColorCount;
m_SizeBytes = m_Width * m_Height * m_Colors;
m_Image.resize(m_Width * m_Height);
}
//==============================================================================
void ptImage8::fillColor(uint8_t ARed, uint8_t AGreen, uint8_t ABlue, uint8_t AAlpha) {
std::array<uint8_t, 4> hTemp = {{ARed, AGreen, ABlue, AAlpha}};
std::fill(std::begin(m_Image), std::end(m_Image), hTemp);
}
//==============================================================================
ptImage8::~ptImage8() {
// nothing to do
}
//==============================================================================
ptImage8* ptImage8::Set(const ptImage *Origin) {
assert(NULL != Origin);
assert(ptSpace_Lab != Origin->m_ColorSpace);
setSize(Origin->m_Width, Origin->m_Height, Origin->m_Colors);
m_ColorSpace = Origin->m_ColorSpace;
for (uint32_t i = 0; i < static_cast<uint32_t>(m_Width)*m_Height; i++) {
for (short c = 0; c < 3; c++) {
// Mind the R<->B swap !
m_Image[i][2-c] = Origin->m_Image[i][c]>>8;
}
m_Image[i][3] = 0xff;
}
return this;
}
//==============================================================================
ptImage8 *ptImage8::Set(const ptImage8 *Origin)
{
assert(NULL != Origin);
setSize(Origin->m_Width,
Origin->m_Height,
Origin->m_Colors);
m_ColorSpace = Origin->m_ColorSpace;
m_Image = Origin->m_Image;
return this;
}
//==============================================================================
void ptImage8::FromQImage(const QImage AImage)
{
setSize(AImage.width(), AImage.height(), 4);
m_ColorSpace = ptSpace_sRGB_D65;
memcpy((uint8_t (*)[4]) m_Image.data(), AImage.bits(), m_SizeBytes);
}
| tectronics/photivo | Sources/ptImage8.cpp | C++ | gpl-3.0 | 3,515 |
PhishingFramework::Application.routes.draw do
devise_for :admins
# image tracking routes.
get '/reports/image/:uid.png' => 'reports#image'
# only allow emails to be send from POST request
post '/email/preview_email/:id' => 'email#preview', as: 'preview_email'
post '/email/test_email/:id' => 'email#test', as: 'test_email'
post '/email/launch_email/:id' => 'email#launch', as: 'launch'
# only allow deletion from POST requests
get '/campaigns/delete_smtp_entry/:id' => 'campaigns#list'
get "reports/list"
get "reports/show"
get "reports/delete"
get "tools/emails" => "tools#emails"
get "tools/show_emails/:id" => "tools#show_emails", as: 'show_emails'
post "tools/enumerate_emails" => "tools#enumerate_emails"
delete "tools/emails/:id" => "tools#destroy_email", as: 'destroy_email'
get "tools/download_emails/:id" => "tools#download_emails", as: "download_emails"
get "tools/import_emails" => "tools#import_emails"
resources :campaigns do
collection do
get 'options'
get 'home'
get 'list'
get 'aboutus'
get 'victims'
get 'activity'
delete 'destroy'
end
member do
post 'clear_victims'
end
end
resources :blasts, only: [:show], shallow: true
resources :templates do
collection do
get 'list'
get 'restore'
get 'edit_email'
get 'update_attachment'
delete 'destroy'
end
end
resources :reports do
collection do
get 'list'
get 'stats'
get 'results'
get 'download_logs'
get 'download_stats'
get 'apache_logs'
get 'smtp'
get 'passwords'
post 'results'
delete 'clear'
end
member do
get 'download_excel'
end
end
resources :admin do
collection do
get 'list'
get 'global_settings'
put 'update_global_settings'
end
member do
get 'logins'
post 'approve'
post 'revoke'
delete 'destroy'
end
end
resources :clones do
member do
get 'download'
get 'preview'
end
end
resources :tools
root :to => 'campaigns#home'
match 'access', :to => 'access#menu', as: 'access', via: :get
require 'sidekiq/web'
authenticate :admin do
mount Sidekiq::Web => '/sidekiq'
end
require 'sidekiq/api'
match "queue-status" => proc { [200, {"Content-Type" => "text/plain"}, [Sidekiq::Queue.new.size < 100 ? "OK" : "UHOH" ]] }, via: :get
mount LetterOpenerWeb::Engine, at: 'letter_opener'
match ':controller(/:action(/:id))(.:format)', via: [:get, :post]
end
| zhuyue1314/phishing-frenzy | config/routes.rb | Ruby | gpl-3.0 | 2,411 |
<?php
/* ----------------------------------------------------------------------
* app/controllers/find/BrowseObjectsController.php
* ----------------------------------------------------------------------
* CollectiveAccess
* Open-source collections management software
* ----------------------------------------------------------------------
*
* Software by Whirl-i-Gig (http://www.whirl-i-gig.com)
* Copyright 2009-2013 Whirl-i-Gig
*
* For more information visit http://www.CollectiveAccess.org
*
* This program is free software; you may redistribute it and/or modify it under
* the terms of the provided license as published by Whirl-i-Gig
*
* CollectiveAccess is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This source code is free and modifiable under the terms of
* GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See
* the "license.txt" file for details, or visit the CollectiveAccess web site at
* http://www.CollectiveAccess.org
*
* ----------------------------------------------------------------------
*/
require_once(__CA_LIB_DIR__."/ca/BaseBrowseController.php");
require_once(__CA_LIB_DIR__."/ca/Browse/ObjectBrowse.php");
require_once(__CA_LIB_DIR__."/core/GeographicMap.php");
class BrowseObjectsController extends BaseBrowseController {
# -------------------------------------------------------
/**
* Name of table for which this browse returns items
*/
protected $ops_tablename = 'ca_objects';
/**
* Number of items per results page
*/
protected $opa_items_per_page = array(8, 16, 24, 32);
/**
* List of result views supported for this browse
* Is associative array: keys are view labels, values are view specifier to be incorporated into view name
*/
protected $opa_views;
/**
* List of available result sorting fields
* Is associative array: values are display names for fields, keys are full fields names (table.field) to be used as sort
*/
protected $opa_sorts;
/**
* Name of "find" used to defined result context for ResultContext object
* Must be unique for the table and have a corresponding entry in find_navigation.conf
*/
protected $ops_find_type = 'basic_browse';
# -------------------------------------------------------
public function __construct(&$po_request, &$po_response, $pa_view_paths=null) {
parent::__construct($po_request, $po_response, $pa_view_paths);
$this->opo_browse = new ObjectBrowse($this->opo_result_context->getSearchExpression(), 'providence');
$this->opa_views = array(
'thumbnail' => _t('thumbnails'),
'full' => _t('full'),
'list' => _t('list'),
'editable' => _t('editable')
);
$this->opa_sorts = array_merge(array(
'ca_object_labels.name' => _t('title'),
'ca_objects.type_id' => _t('type'),
'ca_objects.idno_sort' => _t('idno')
), $this->opa_sorts);
}
# -------------------------------------------------------
public function Index($pa_options=null) {
JavascriptLoadManager::register('imageScroller');
JavascriptLoadManager::register('tabUI');
JavascriptLoadManager::register('panel');
parent::Index($pa_options);
}
# -------------------------------------------------------
/**
* Ajax action that returns info on a mapped location based upon the 'id' request parameter.
* 'id' is a list of object_ids to display information before. Each integer id is separated by a semicolon (";")
* The "ca_objects_results_map_balloon_html" view in Results/ is used to render the content.
*/
public function getMapItemInfo() {
$pa_object_ids = explode(';', $this->request->getParameter('id', pString));
$va_access_values = caGetUserAccessValues($this->request);
$this->view->setVar('ids', $pa_object_ids);
$this->view->setVar('access_values', $va_access_values);
$this->render("Results/ca_objects_results_map_balloon_html.php");
}
# -------------------------------------------------------
/**
* Returns string representing the name of the item the browse will return
*
* If $ps_mode is 'singular' [default] then the singular version of the name is returned, otherwise the plural is returned
*/
public function browseName($ps_mode='singular') {
return ($ps_mode === 'singular') ? _t('object') : _t('objects');
}
# -------------------------------------------------------
/**
* Returns string representing the name of this controller (minus the "Controller" part)
*/
public function controllerName() {
return 'BrowseObjects';
}
# -------------------------------------------------------
}
?> | libis/ca_babtekst | app/controllers/find/BrowseObjectsController.php | PHP | gpl-3.0 | 4,873 |
package org.thoughtcrime.securesms.crypto;
import androidx.annotation.NonNull;
import org.thoughtcrime.securesms.util.Hex;
import java.io.IOException;
public class DatabaseSecret {
private final byte[] key;
private final String encoded;
public DatabaseSecret(@NonNull byte[] key) {
this.key = key;
this.encoded = Hex.toStringCondensed(key);
}
public DatabaseSecret(@NonNull String encoded) throws IOException {
this.key = Hex.fromStringCondensed(encoded);
this.encoded = encoded;
}
public String asString() {
return encoded;
}
public byte[] asBytes() {
return key;
}
}
| jtracey/Signal-Android | src/org/thoughtcrime/securesms/crypto/DatabaseSecret.java | Java | gpl-3.0 | 627 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration |
\\ / A nd | For copyright notice see file Copyright
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend 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.
foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "UpwindFitData.H"
#include "surfaceFields.H"
#include "volFields.H"
#include "SVD.H"
#include "syncTools.H"
#include "extendedUpwindCellToFaceStencil.H"
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
template<class Polynomial>
Foam::UpwindFitData<Polynomial>::UpwindFitData
(
const fvMesh& mesh,
const extendedUpwindCellToFaceStencil& stencil,
const bool linearCorrection,
const scalar linearLimitFactor,
const scalar centralWeight
)
:
FitData
<
UpwindFitData<Polynomial>,
extendedUpwindCellToFaceStencil,
Polynomial
>
(
mesh, stencil, linearCorrection, linearLimitFactor, centralWeight
),
owncoeffs_(mesh.nFaces()),
neicoeffs_(mesh.nFaces())
{
if (debug)
{
Info<< "Contructing UpwindFitData<Polynomial>" << endl;
}
calcFit();
if (debug)
{
Info<< "UpwindFitData<Polynomial>::UpwindFitData() :"
<< "Finished constructing polynomialFit data"
<< endl;
}
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class Polynomial>
void Foam::UpwindFitData<Polynomial>::calcFit()
{
const fvMesh& mesh = this->mesh();
const surfaceScalarField& w = mesh.surfaceInterpolation::weights();
const surfaceScalarField::GeometricBoundaryField& bw = w.boundaryField();
// Owner stencil weights
// ~~~~~~~~~~~~~~~~~~~~~
// Get the cell/face centres in stencil order.
List<List<point> > stencilPoints(mesh.nFaces());
this->stencil().collectData
(
this->stencil().ownMap(),
this->stencil().ownStencil(),
mesh.C(),
stencilPoints
);
// find the fit coefficients for every owner
//Pout<< "-- Owner --" << endl;
for(label facei = 0; facei < mesh.nInternalFaces(); facei++)
{
FitData
<
UpwindFitData<Polynomial>,
extendedUpwindCellToFaceStencil,
Polynomial
>::calcFit(owncoeffs_[facei], stencilPoints[facei], w[facei], facei);
//Pout<< " facei:" << facei
// << " at:" << mesh.faceCentres()[facei] << endl;
//forAll(owncoeffs_[facei], i)
//{
// Pout<< " point:" << stencilPoints[facei][i]
// << "\tweight:" << owncoeffs_[facei][i]
// << endl;
//}
}
forAll(bw, patchi)
{
const fvsPatchScalarField& pw = bw[patchi];
if (pw.coupled())
{
label facei = pw.patch().patch().start();
forAll(pw, i)
{
FitData
<
UpwindFitData<Polynomial>,
extendedUpwindCellToFaceStencil,
Polynomial
>::calcFit
(
owncoeffs_[facei], stencilPoints[facei], pw[i], facei
);
facei++;
}
}
}
// Neighbour stencil weights
// ~~~~~~~~~~~~~~~~~~~~~~~~~
// Note:reuse stencilPoints since is major storage
this->stencil().collectData
(
this->stencil().neiMap(),
this->stencil().neiStencil(),
mesh.C(),
stencilPoints
);
// find the fit coefficients for every neighbour
//Pout<< "-- Neighbour --" << endl;
for(label facei = 0; facei < mesh.nInternalFaces(); facei++)
{
FitData
<
UpwindFitData<Polynomial>,
extendedUpwindCellToFaceStencil,
Polynomial
>::calcFit(neicoeffs_[facei], stencilPoints[facei], w[facei], facei);
//Pout<< " facei:" << facei
// << " at:" << mesh.faceCentres()[facei] << endl;
//forAll(neicoeffs_[facei], i)
//{
// Pout<< " point:" << stencilPoints[facei][i]
// << "\tweight:" << neicoeffs_[facei][i]
// << endl;
//}
}
forAll(bw, patchi)
{
const fvsPatchScalarField& pw = bw[patchi];
if (pw.coupled())
{
label facei = pw.patch().patch().start();
forAll(pw, i)
{
FitData
<
UpwindFitData<Polynomial>,
extendedUpwindCellToFaceStencil,
Polynomial
>::calcFit
(
neicoeffs_[facei], stencilPoints[facei], pw[i], facei
);
facei++;
}
}
}
}
// ************************************************************************* //
| Unofficial-Extend-Project-Mirror/openfoam-extend-foam-extend-3.1 | src/finiteVolume/interpolation/surfaceInterpolation/schemes/UpwindFitScheme/UpwindFitData.C | C++ | gpl-3.0 | 5,777 |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# Filename : long_anisotropically_dense.py
# Author : Stephane Grabli
# Date : 04/08/2005
# Purpose : Selects the lines that are long and have a high anisotropic
# a priori density and uses causal density
# to draw without cluttering. Ideally, half of the
# selected lines are culled using the causal density.
#
# ********************* WARNING *************************************
# ******** The Directional a priori density maps must ******
# ******** have been computed prior to using this style module ******
from freestyle.chainingiterators import ChainSilhouetteIterator
from freestyle.functions import DensityF1D
from freestyle.predicates import (
NotUP1D,
QuantitativeInvisibilityUP1D,
UnaryPredicate1D,
pyHighDensityAnisotropyUP1D,
pyHigherLengthUP1D,
pyLengthBP1D,
)
from freestyle.shaders import (
ConstantColorShader,
ConstantThicknessShader,
SamplingShader,
)
from freestyle.types import IntegrationType, Operators
## custom density predicate
class pyDensityUP1D(UnaryPredicate1D):
def __init__(self, wsize, threshold, integration=IntegrationType.MEAN, sampling=2.0):
UnaryPredicate1D.__init__(self)
self._wsize = wsize
self._threshold = threshold
self._integration = integration
self._func = DensityF1D(self._wsize, self._integration, sampling)
self._func2 = DensityF1D(self._wsize, IntegrationType.MAX, sampling)
def __call__(self, inter):
c = self._func(inter)
m = self._func2(inter)
if c < self._threshold:
return 1
if m > 4*c:
if c < 1.5*self._threshold:
return 1
return 0
Operators.select(QuantitativeInvisibilityUP1D(0))
Operators.bidirectional_chain(ChainSilhouetteIterator(),NotUP1D(QuantitativeInvisibilityUP1D(0)))
Operators.select(pyHigherLengthUP1D(40))
## selects lines having a high anisotropic a priori density
Operators.select(pyHighDensityAnisotropyUP1D(0.3,4))
Operators.sort(pyLengthBP1D())
shaders_list = [
SamplingShader(2.0),
ConstantThicknessShader(2),
ConstantColorShader(0.2,0.2,0.25,1),
]
## uniform culling
Operators.create(pyDensityUP1D(3.0,2.0e-2, IntegrationType.MEAN, 0.1), shaders_list)
| Microvellum/Fluid-Designer | win64-vc/2.78/scripts/freestyle/styles/long_anisotropically_dense.py | Python | gpl-3.0 | 3,125 |
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
DOCUMENTATION = '''
---
module: nxos_install_os
extends_documentation_fragment: nxos
short_description: Set boot options like boot, kickstart image and issu.
description:
- Install an operating system by setting the boot options like boot
image and kickstart image and optionally select to install using
ISSU (In Server Software Upgrade).
notes:
- Tested against the following platforms and images
- N9k 7.0(3)I4(6), 7.0(3)I5(3), 7.0(3)I6(1), 7.0(3)I7(1), 7.0(3)F2(2), 7.0(3)F3(2)
- N3k 6.0(2)A8(6), 6.0(2)A8(8), 7.0(3)I6(1), 7.0(3)I7(1)
- N7k 7.3(0)D1(1), 8.0(1), 8.2(1)
- This module requires both the ANSIBLE_PERSISTENT_CONNECT_TIMEOUT and
ANSIBLE_PERSISTENT_COMMAND_TIMEOUT timers to be set to 600 seconds or higher.
The module will exit if the timers are not set properly.
- Do not include full file paths, just the name of the file(s) stored on
the top level flash directory.
- This module attempts to install the software immediately,
which may trigger a reboot.
- In check mode, the module will indicate if an upgrade is needed and
whether or not the upgrade is disruptive or non-disruptive(ISSU).
author:
- Jason Edelman (@jedelman8)
- Gabriele Gerbibo (@GGabriele)
version_added: 2.2
options:
system_image_file:
description:
- Name of the system (or combined) image file on flash.
required: true
kickstart_image_file:
description:
- Name of the kickstart image file on flash.
(Not required on all Nexus platforms)
issu:
version_added: "2.5"
description:
- Upgrade using In Service Software Upgrade (ISSU).
(Only supported on N9k platforms)
- Selecting 'required' or 'yes' means that upgrades will only
proceed if the switch is capable of ISSU.
- Selecting 'desired' means that upgrades will use ISSU if possible
but will fall back to disruptive upgrade if needed.
- Selecting 'no' means do not use ISSU. Forced disruptive.
choices: ['required','desired', 'yes', 'no']
default: 'no'
'''
EXAMPLES = '''
- name: Install OS on N9k
check_mode: no
nxos_install_os:
system_image_file: nxos.7.0.3.I6.1.bin
issu: desired
- name: Wait for device to come back up with new image
wait_for:
port: 22
state: started
timeout: 500
delay: 60
host: "{{ inventory_hostname }}"
- name: Check installed OS for newly installed version
nxos_command:
commands: ['show version | json']
provider: "{{ connection }}"
register: output
- assert:
that:
- output['stdout'][0]['kickstart_ver_str'] == '7.0(3)I6(1)'
'''
RETURN = '''
install_state:
description: Boot and install information.
returned: always
type: dictionary
sample: {
"install_state": [
"Compatibility check is done:",
"Module bootable Impact Install-type Reason",
"------ -------- -------------- ------------ ------",
" 1 yes non-disruptive reset ",
"Images will be upgraded according to following table:",
"Module Image Running-Version(pri:alt) New-Version Upg-Required",
"------ ---------- ---------------------------------------- -------------------- ------------",
" 1 nxos 7.0(3)I6(1) 7.0(3)I7(1) yes",
" 1 bios v4.4.0(07/12/2017) v4.4.0(07/12/2017) no"
],
}
'''
import re
from time import sleep
from ansible.module_utils.network.nxos.nxos import load_config, run_commands
from ansible.module_utils.network.nxos.nxos import nxos_argument_spec, check_args
from ansible.module_utils.basic import AnsibleModule
# Output options are 'text' or 'json'
def execute_show_command(module, command, output='text'):
cmds = [{
'command': command,
'output': output,
}]
return run_commands(module, cmds)
def get_platform(module):
"""Determine platform type"""
data = execute_show_command(module, 'show inventory', 'json')
pid = data[0]['TABLE_inv']['ROW_inv'][0]['productid']
if re.search(r'N3K', pid):
type = 'N3K'
elif re.search(r'N5K', pid):
type = 'N5K'
elif re.search(r'N6K', pid):
type = 'N6K'
elif re.search(r'N7K', pid):
type = 'N7K'
elif re.search(r'N9K', pid):
type = 'N9K'
else:
type = 'unknown'
return type
def parse_show_install(data):
"""Helper method to parse the output of the 'show install all impact' or
'install all' commands.
Sample Output:
Installer will perform impact only check. Please wait.
Verifying image bootflash:/nxos.7.0.3.F2.2.bin for boot variable "nxos".
[####################] 100% -- SUCCESS
Verifying image type.
[####################] 100% -- SUCCESS
Preparing "bios" version info using image bootflash:/nxos.7.0.3.F2.2.bin.
[####################] 100% -- SUCCESS
Preparing "nxos" version info using image bootflash:/nxos.7.0.3.F2.2.bin.
[####################] 100% -- SUCCESS
Performing module support checks.
[####################] 100% -- SUCCESS
Notifying services about system upgrade.
[####################] 100% -- SUCCESS
Compatibility check is done:
Module bootable Impact Install-type Reason
------ -------- -------------- ------------ ------
8 yes disruptive reset Incompatible image for ISSU
21 yes disruptive reset Incompatible image for ISSU
Images will be upgraded according to following table:
Module Image Running-Version(pri:alt) New-Version Upg-Required
------ ---------- ---------------------------------------- ------------
8 lcn9k 7.0(3)F3(2) 7.0(3)F2(2) yes
8 bios v01.17 v01.17 no
21 lcn9k 7.0(3)F3(2) 7.0(3)F2(2) yes
21 bios v01.70 v01.70 no
"""
if len(data) > 0:
data = massage_install_data(data)
ud = {'raw': data}
ud['processed'] = []
ud['disruptive'] = False
ud['upgrade_needed'] = False
ud['error'] = False
ud['install_in_progress'] = False
ud['server_error'] = False
ud['upgrade_succeeded'] = False
ud['use_impact_data'] = False
# Check for server errors
if isinstance(data, int):
if data == -1:
ud['server_error'] = True
elif data >= 500:
ud['server_error'] = True
elif data == -32603:
ud['server_error'] = True
return ud
else:
ud['list_data'] = data.split('\n')
for x in ud['list_data']:
# Check for errors and exit if found.
if re.search(r'Pre-upgrade check failed', x):
ud['error'] = True
break
if re.search(r'[I|i]nvalid command', x):
ud['error'] = True
break
if re.search(r'No install all data found', x):
ud['error'] = True
break
# Check for potentially transient conditions
if re.search(r'Another install procedure may be in progress', x):
ud['install_in_progress'] = True
break
if re.search(r'Backend processing error', x):
ud['server_error'] = True
break
if re.search(r'^(-1|5\d\d)$', x):
ud['server_error'] = True
break
# Check for messages indicating a successful upgrade.
if re.search(r'Finishing the upgrade', x):
ud['upgrade_succeeded'] = True
break
if re.search(r'Install has been successful', x):
ud['upgrade_succeeded'] = True
break
if re.search(r'Switching over onto standby', x):
ud['upgrade_succeeded'] = True
break
# We get these messages when the upgrade is non-disruptive and
# we loose connection with the switchover but far enough along that
# we can be confident the upgrade succeeded.
if re.search(r'timeout trying to send command: install', x):
ud['upgrade_succeeded'] = True
ud['use_impact_data'] = True
break
if re.search(r'[C|c]onnection failure: timed out', x):
ud['upgrade_succeeded'] = True
ud['use_impact_data'] = True
break
# Begin normal parsing.
if re.search(r'----|Module|Images will|Compatibility', x):
ud['processed'].append(x)
continue
# Check to see if upgrade will be disruptive or non-disruptive and
# build dictionary of individual modules and their status.
# Sample Line:
#
# Module bootable Impact Install-type Reason
# ------ -------- ---------- ------------ ------
# 8 yes disruptive reset Incompatible image
rd = r'(\d+)\s+(\S+)\s+(disruptive|non-disruptive)\s+(\S+)'
mo = re.search(rd, x)
if mo:
ud['processed'].append(x)
key = 'm%s' % mo.group(1)
field = 'disruptive'
if mo.group(3) == 'non-disruptive':
ud[key] = {field: False}
else:
ud[field] = True
ud[key] = {field: True}
field = 'bootable'
if mo.group(2) == 'yes':
ud[key].update({field: True})
else:
ud[key].update({field: False})
continue
# Check to see if switch needs an upgrade and build a dictionary
# of individual modules and their individual upgrade status.
# Sample Line:
#
# Module Image Running-Version(pri:alt) New-Version Upg-Required
# ------ ----- ---------------------------------------- ------------
# 8 lcn9k 7.0(3)F3(2) 7.0(3)F2(2) yes
mo = re.search(r'(\d+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(yes|no)', x)
if mo:
ud['processed'].append(x)
key = 'm%s_%s' % (mo.group(1), mo.group(2))
field = 'upgrade_needed'
if mo.group(5) == 'yes':
ud[field] = True
ud[key] = {field: True}
else:
ud[key] = {field: False}
continue
return ud
def massage_install_data(data):
# Transport cli returns a list containing one result item.
# Transport nxapi returns a list containing two items. The second item
# contains the data we are interested in.
default_error_msg = 'No install all data found'
if len(data) == 1:
result_data = data[0]
elif len(data) == 2:
result_data = data[1]
else:
result_data = default_error_msg
# Further processing may be needed for result_data
if len(data) == 2 and isinstance(data[1], dict):
if 'clierror' in data[1].keys():
result_data = data[1]['clierror']
elif 'code' in data[1].keys() and data[1]['code'] == '500':
# We encountered a backend processing error for nxapi
result_data = data[1]['msg']
else:
result_data = default_error_msg
return result_data
def build_install_cmd_set(issu, image, kick, type):
commands = ['terminal dont-ask']
if re.search(r'required|desired|yes', issu):
issu_cmd = 'non-disruptive'
else:
issu_cmd = ''
if type == 'impact':
rootcmd = 'show install all impact'
else:
rootcmd = 'install all'
if kick is None:
commands.append(
'%s nxos %s %s' % (rootcmd, image, issu_cmd))
else:
commands.append(
'%s system %s kickstart %s' % (rootcmd, image, kick))
return commands
def parse_show_version(data):
version_data = {'raw': data[0].split('\n')}
version_data['version'] = ''
version_data['error'] = False
for x in version_data['raw']:
mo = re.search(r'(kickstart|system|NXOS):\s+version\s+(\S+)', x)
if mo:
version_data['version'] = mo.group(2)
continue
if version_data['version'] == '':
version_data['error'] = True
return version_data
def check_mode_legacy(module, issu, image, kick=None):
"""Some platforms/images/transports don't support the 'install all impact'
command so we need to use a different method."""
current = execute_show_command(module, 'show version', 'json')[0]
# Call parse_show_data on empty string to create the default upgrade
# data stucture dictionary
data = parse_show_install('')
upgrade_msg = 'No upgrade required'
# Process System Image
data['error'] = False
tsver = 'show version image bootflash:%s' % image
target_image = parse_show_version(execute_show_command(module, tsver))
if target_image['error']:
data['error'] = True
data['raw'] = target_image['raw']
if current['kickstart_ver_str'] != target_image['version'] and not data['error']:
data['upgrade_needed'] = True
data['disruptive'] = True
upgrade_msg = 'Switch upgraded: system: %s' % tsver
# Process Kickstart Image
if kick is not None and not data['error']:
tkver = 'show version image bootflash:%s' % kick
target_kick = parse_show_version(execute_show_command(module, tkver))
if target_kick['error']:
data['error'] = True
data['raw'] = target_kick['raw']
if current['kickstart_ver_str'] != target_kick['version'] and not data['error']:
data['upgrade_needed'] = True
data['disruptive'] = True
upgrade_msg = upgrade_msg + ' kickstart: %s' % tkver
data['processed'] = upgrade_msg
return data
def check_mode_nextgen(module, issu, image, kick=None):
"""Use the 'install all impact' command for check_mode"""
opts = {'ignore_timeout': True}
commands = build_install_cmd_set(issu, image, kick, 'impact')
data = parse_show_install(load_config(module, commands, True, opts))
# If an error is encountered when issu is 'desired' then try again
# but set issu to 'no'
if data['error'] and issu == 'desired':
issu = 'no'
commands = build_install_cmd_set(issu, image, kick, 'impact')
# The system may be busy from the previous call to check_mode so loop
# until it's done.
data = check_install_in_progress(module, commands, opts)
if data['server_error']:
data['error'] = True
return data
def check_install_in_progress(module, commands, opts):
for attempt in range(20):
data = parse_show_install(load_config(module, commands, True, opts))
if data['install_in_progress']:
sleep(1)
continue
break
return data
def check_mode(module, issu, image, kick=None):
"""Check switch upgrade impact using 'show install all impact' command"""
data = check_mode_nextgen(module, issu, image, kick)
if data['server_error']:
# We encountered an unrecoverable error in the attempt to get upgrade
# impact data from the 'show install all impact' command.
# Fallback to legacy method.
data = check_mode_legacy(module, issu, image, kick)
return data
def do_install_all(module, issu, image, kick=None):
"""Perform the switch upgrade using the 'install all' command"""
impact_data = check_mode(module, issu, image, kick)
if module.check_mode:
# Check mode set in the playbook so just return the impact data.
msg = '*** SWITCH WAS NOT UPGRADED: IMPACT DATA ONLY ***'
impact_data['processed'].append(msg)
return impact_data
if impact_data['error']:
# Check mode discovered an error so return with this info.
return impact_data
elif not impact_data['upgrade_needed']:
# The switch is already upgraded. Nothing more to do.
return impact_data
else:
# If we get here, check_mode returned no errors and the switch
# needs to be upgraded.
if impact_data['disruptive']:
# Check mode indicated that ISSU is not possible so issue the
# upgrade command without the non-disruptive flag.
issu = 'no'
commands = build_install_cmd_set(issu, image, kick, 'install')
opts = {'ignore_timeout': True}
# The system may be busy from the call to check_mode so loop until
# it's done.
upgrade = check_install_in_progress(module, commands, opts)
# Special case: If we encounter a server error at this stage
# it means the command was sent and the upgrade was started but
# we will need to use the impact data instead of the current install
# data.
if upgrade['server_error']:
upgrade['upgrade_succeeded'] = True
upgrade['use_impact_data'] = True
if upgrade['use_impact_data']:
if upgrade['upgrade_succeeded']:
upgrade = impact_data
upgrade['upgrade_succeeded'] = True
else:
upgrade = impact_data
upgrade['upgrade_succeeded'] = False
if not upgrade['upgrade_succeeded']:
upgrade['error'] = True
return upgrade
def main():
argument_spec = dict(
system_image_file=dict(required=True),
kickstart_image_file=dict(required=False),
issu=dict(choices=['required', 'desired', 'no', 'yes'], default='no'),
)
argument_spec.update(nxos_argument_spec)
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True)
warnings = list()
check_args(module, warnings)
# Get system_image_file(sif), kickstart_image_file(kif) and
# issu settings from module params.
sif = module.params['system_image_file']
kif = module.params['kickstart_image_file']
issu = module.params['issu']
if kif == 'null' or kif == '':
kif = None
install_result = do_install_all(module, issu, sif, kick=kif)
if install_result['error']:
msg = "Failed to upgrade device using image "
if kif:
msg = msg + "files: kickstart: %s, system: %s" % (kif, sif)
else:
msg = msg + "file: system: %s" % sif
module.fail_json(msg=msg, raw_data=install_result['list_data'])
state = install_result['processed']
changed = install_result['upgrade_needed']
module.exit_json(changed=changed, install_state=state, warnings=warnings)
if __name__ == '__main__':
main()
| hryamzik/ansible | lib/ansible/modules/network/nxos/nxos_install_os.py | Python | gpl-3.0 | 19,714 |
<?php
/* Copyright (C) 2004-2014 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2016 Frédéric France <frederic.france@free.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/compta/paiement_charge.php
* \ingroup tax
* \brief Page to add payment of a tax
*/
require '../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/paymentsocialcontribution.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
$langs->load("bills");
$chid=GETPOST("id", 'int');
$action=GETPOST('action', 'alpha');
$amounts = array();
// Security check
$socid=0;
if ($user->societe_id > 0)
{
$socid = $user->societe_id;
}
/*
* Actions
*/
if ($action == 'add_payment' || ($action == 'confirm_paiement' && $confirm=='yes'))
{
$error=0;
if ($_POST["cancel"])
{
$loc = DOL_URL_ROOT.'/compta/sociales/card.php?id='.$chid;
header("Location: ".$loc);
exit;
}
$datepaye = dol_mktime(12, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]);
if (! $_POST["paiementtype"] > 0)
{
setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentities("PaymentMode")), null, 'errors');
$error++;
$action = 'create';
}
if ($datepaye == '')
{
setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentities("Date")), null, 'errors');
$error++;
$action = 'create';
}
if (! empty($conf->banque->enabled) && ! $_POST["accountid"] > 0)
{
setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentities("AccountToCredit")), null, 'errors');
$error++;
$action = 'create';
}
if (! $error)
{
$paymentid = 0;
// Read possible payments
foreach ($_POST as $key => $value)
{
if (substr($key,0,7) == 'amount_')
{
$other_chid = substr($key,7);
$amounts[$other_chid] = price2num($_POST[$key]);
}
}
if (count($amounts) <= 0)
{
$error++;
setEventMessages($langs->trans("ErrorNoPaymentDefined"), null, 'errors');
$action='create';
}
if (! $error)
{
$db->begin();
// Create a line of payments
$paiement = new PaymentSocialContribution($db);
$paiement->chid = $chid;
$paiement->datepaye = $datepaye;
$paiement->amounts = $amounts; // Tableau de montant
$paiement->paiementtype = $_POST["paiementtype"];
$paiement->num_paiement = $_POST["num_paiement"];
$paiement->note = $_POST["note"];
if (! $error)
{
$paymentid = $paiement->create($user, (GETPOST('closepaidcontrib')=='on'?1:0));
if ($paymentid < 0)
{
$error++;
setEventMessages($paiement->error, null, 'errors');
$action='create';
}
}
if (! $error)
{
$result=$paiement->addPaymentToBank($user,'payment_sc','(SocialContributionPayment)', GETPOST('accountid','int'),'','');
if (! ($result > 0))
{
$error++;
setEventMessages($paiement->error, null, 'errors');
$action='create';
}
}
if (! $error)
{
$db->commit();
$loc = DOL_URL_ROOT.'/compta/sociales/card.php?id='.$chid;
header('Location: '.$loc);
exit;
}
else
{
$db->rollback();
}
}
}
}
/*
* View
*/
llxHeader();
$form=new Form($db);
// Formulaire de creation d'un paiement de charge
if ($action == 'create')
{
$charge = new ChargeSociales($db);
$charge->fetch($chid);
$charge->accountid=$charge->fk_account?$charge->fk_account:$charge->accountid;
$charge->paiementtype=$charge->mode_reglement_id?$charge->mode_reglement_id:$charge->paiementtype;
$total = $charge->amount;
if (! empty($conf->use_javascript_ajax))
{
print "\n".'<script type="text/javascript" language="javascript">';
//Add js for AutoFill
print ' $(document).ready(function () {';
print ' $(".AutoFillAmount").on(\'click touchstart\', function(){
var amount = $(this).data("value");
document.getElementById($(this).data(\'rowid\')).value = amount ;
});';
print ' });'."\n";
print ' </script>'."\n";
}
print load_fiche_titre($langs->trans("DoPayment"));
print "<br>\n";
if ($mesg)
{
print "<div class=\"error\">$mesg</div>";
}
print '<form name="add_payment" action="'.$_SERVER['PHP_SELF'].'" method="post">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="id" value="'.$chid.'">';
print '<input type="hidden" name="chid" value="'.$chid.'">';
print '<input type="hidden" name="action" value="add_payment">';
dol_fiche_head('', '');
print '<table class="border" width="100%">';
print '<tr><td class="titlefieldcreate">'.$langs->trans("Ref").'</td><td><a href="'.DOL_URL_ROOT.'/compta/sociales/card.php?id='.$chid.'">'.$chid.'</a></td></tr>';
print '<tr><td>'.$langs->trans("Type")."</td><td>".$charge->type_libelle."</td></tr>\n";
print '<tr><td>'.$langs->trans("Period")."</td><td>".dol_print_date($charge->periode,'day')."</td></tr>\n";
print '<tr><td>'.$langs->trans("Label").'</td><td>'.$charge->lib."</td></tr>\n";
/*print '<tr><td>'.$langs->trans("DateDue")."</td><td>".dol_print_date($charge->date_ech,'day')."</td></tr>\n";
print '<tr><td>'.$langs->trans("Amount")."</td><td>".price($charge->amount,0,$outputlangs,1,-1,-1,$conf->currency).'</td></tr>';*/
$sql = "SELECT sum(p.amount) as total";
$sql.= " FROM ".MAIN_DB_PREFIX."paiementcharge as p";
$sql.= " WHERE p.fk_charge = ".$chid;
$resql = $db->query($sql);
if ($resql)
{
$obj=$db->fetch_object($resql);
$sumpaid = $obj->total;
$db->free();
}
/*print '<tr><td>'.$langs->trans("AlreadyPaid").'</td><td>'.price($sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'</td></tr>';
print '<tr><td class="tdtop">'.$langs->trans("RemainderToPay").'</td><td>'.price($total-$sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'</td></tr>';*/
print '<tr><td class="fieldrequired">'.$langs->trans("Date").'</td><td>';
$datepaye = dol_mktime(12, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]);
$datepayment=empty($conf->global->MAIN_AUTOFILL_DATE)?(empty($_POST["remonth"])?-1:$datepaye):0;
$form->select_date($datepayment,'','','','',"add_payment",1,1);
print "</td>";
print '</tr>';
print '<tr><td class="fieldrequired">'.$langs->trans("PaymentMode").'</td><td>';
$form->select_types_paiements(isset($_POST["paiementtype"])?$_POST["paiementtype"]:$charge->paiementtype, "paiementtype");
print "</td>\n";
print '</tr>';
print '<tr>';
print '<td class="fieldrequired">'.$langs->trans('AccountToDebit').'</td>';
print '<td>';
$form->select_comptes(isset($_POST["accountid"])?$_POST["accountid"]:$charge->accountid, "accountid", 0, '',1); // Show opend bank account list
print '</td></tr>';
// Number
print '<tr><td>'.$langs->trans('Numero');
print ' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>';
print '</td>';
print '<td><input name="num_paiement" type="text" value="'.GETPOST('num_paiement').'"></td></tr>'."\n";
print '<tr>';
print '<td class="tdtop">'.$langs->trans("Comments").'</td>';
print '<td class="tdtop"><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_3.'"></textarea></td>';
print '</tr>';
print '</table>';
dol_fiche_end();
/*
* Autres charges impayees
*/
$num = 1;
$i = 0;
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre">';
//print '<td>'.$langs->trans("SocialContribution").'</td>';
print '<td align="left">'.$langs->trans("DateDue").'</td>';
print '<td align="right">'.$langs->trans("Amount").'</td>';
print '<td align="right">'.$langs->trans("AlreadyPaid").'</td>';
print '<td align="right">'.$langs->trans("RemainderToPay").'</td>';
print '<td align="center">'.$langs->trans("Amount").'</td>';
print "</tr>\n";
$var=true;
$total=0;
$totalrecu=0;
while ($i < $num)
{
$objp = $charge;
print '<tr class="oddeven">';
if ($objp->date_ech > 0)
{
print "<td align=\"left\">".dol_print_date($objp->date_ech,'day')."</td>\n";
}
else
{
print "<td align=\"center\"><b>!!!</b></td>\n";
}
print '<td align="right">'.price($objp->amount)."</td>";
print '<td align="right">'.price($sumpaid)."</td>";
print '<td align="right">'.price($objp->amount - $sumpaid)."</td>";
print '<td align="center">';
if ($sumpaid < $objp->amount)
{
$namef = "amount_".$objp->id;
$nameRemain = "remain_".$objp->id;
if (!empty($conf->use_javascript_ajax))
print img_picto("Auto fill",'rightarrow', "class='AutoFillAmount' data-rowid='".$namef."' data-value='".($objp->amount - $sumpaid)."'");
$remaintopay=$objp->amount - $sumpaid;
print '<input type=hidden class="sum_remain" name="'.$nameRemain.'" value="'.$remaintopay.'">';
print '<input type="text" size="8" name="'.$namef.'" id="'.$namef.'">';
}
else
{
print '-';
}
print "</td>";
print "</tr>\n";
$total+=$objp->total;
$total_ttc+=$objp->total_ttc;
$totalrecu+=$objp->am;
$i++;
}
if ($i > 1)
{
// Print total
print "<tr ".$bc[!$var].">";
print '<td colspan="2" align="left">'.$langs->trans("Total").':</td>';
print "<td align=\"right\"><b>".price($total_ttc)."</b></td>";
print "<td align=\"right\"><b>".price($totalrecu)."</b></td>";
print "<td align=\"right\"><b>".price($total_ttc - $totalrecu)."</b></td>";
print '<td align="center"> </td>';
print "</tr>\n";
}
print "</table>";
// Bouton Save payment
print '<br><div class="center"><input type="checkbox" checked name="closepaidcontrib"> '.$langs->trans("ClosePaidContributionsAutomatically");
print '<br><input type="submit" class="button" name="save" value="'.$langs->trans('ToMakePayment').'">';
print ' ';
print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
print '</div>';
print "</form>\n";
}
llxFooter();
$db->close();
| tomours/dolibarr | htdocs/compta/paiement_charge.php | PHP | gpl-3.0 | 10,955 |
#
# Copyright (C) 1997-2016 JDE Developers Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.
# Authors :
# Aitor Martinez Fernandez <aitor.martinez.fernandez@gmail.com>
#
import traceback
import jderobot
import threading
import Ice
from .threadSensor import ThreadSensor
from jderobotTypes import NavdataData
class NavData:
def __init__(self, jdrc, prefix):
self.lock = threading.Lock()
try:
ic = jdrc.getIc()
proxyStr = jdrc.getConfig().getProperty(prefix+".Proxy")
base = ic.stringToProxy(proxyStr)
self.proxy = jderobot.NavdataPrx.checkedCast(base)
self.navData = NavdataData()
self.update()
if not self.proxy:
print ('Interface ' + prefix + ' not configured')
except Ice.ConnectionRefusedException:
print(prefix + ': connection refused')
except:
traceback.print_exc()
exit(-1)
def update(self):
if self.hasproxy():
localNavdata = self.proxy.getNavdata()
navdataData = NavdataData()
navdataData.vehicle = localNavdata.vehicle
navdataData.state = localNavdata.state
navdataData.batteryPercent = localNavdata.batteryPercent
navdataData.magX = localNavdata.magX
navdataData.magY = localNavdata.magY
navdataData.magZ = localNavdata.magZ
navdataData.pressure = localNavdata.pressure
navdataData.temp = localNavdata.temp
navdataData.windSpeed = localNavdata.windSpeed
navdataData.windAngle = localNavdata.windAngle
navdataData.windCompAngle = localNavdata.windCompAngle
navdataData.rotX = localNavdata.rotX
navdataData.rotY = localNavdata.rotY
navdataData.rotZ = localNavdata.rotZ
navdataData.altd = localNavdata.altd
navdataData.vx = localNavdata.vx
navdataData.vy = localNavdata.vy
navdataData.vz = localNavdata.vz
navdataData.ax = localNavdata.ax
navdataData.ay = localNavdata.ay
navdataData.az = localNavdata.az
navdataData.tagsCount = localNavdata.tagsCount
navdataData.tagsType = localNavdata.tagsType
navdataData.tagsXc = localNavdata.tagsXc
navdataData.tagsYc = localNavdata.tagsYc
navdataData.tagsWidth = localNavdata.tagsWidth
navdataData.tagsHeight = localNavdata.tagsHeight
navdataData.tagsOrientation = localNavdata.tagsOrientation
navdataData.tagsDistance = localNavdata.tagsDistance
navdataData.timeStamp = localNavdata.tm
self.lock.acquire()
self.navData = navdataData
self.lock.release()
def hasproxy (self):
'''
Returns if proxy has ben created or not.
@return if proxy has ben created or not (Boolean)
'''
return hasattr(self,"proxy") and self.proxy
def getNavdata(self):
if self.hasproxy():
self.lock.acquire()
navData = self.navData
self.lock.release()
return navData
return None
class NavdataIceClient:
def __init__(self,ic,prefix, start = False):
self.navdata = NavData(ic,prefix)
self.kill_event = threading.Event()
self.thread = ThreadSensor(self.navdata, self.kill_event)
self.thread.daemon = True
if start:
self.start()
def start(self):
'''
Starts the client. If client is stopped you can not start again, Threading.Thread raised error
'''
self.kill_event.clear()
self.thread.start()
def stop(self):
'''
Stops the client. If client is stopped you can not start again, Threading.Thread raised error
'''
self.kill_event.set()
def getNavData(self):
return self.navdata.getNavdata()
def hasproxy (self):
'''
Returns if proxy has ben created or not.
@return if proxy has ben created or not (Boolean)
'''
return self.navdata.hasproxy() | fqez/JdeRobot | src/libs/comm_py/comm/ice/navdataIceClient.py | Python | gpl-3.0 | 4,847 |