repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
bshp/midPoint | model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/MappingPreExpression.java | 1137 | /**
* Copyright (c) 2019 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.model.common.mapping;
import com.evolveum.midpoint.repo.common.expression.ExpressionEvaluationContext;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
/**
* @author semancik
*
*/
@FunctionalInterface
public interface MappingPreExpression {
void mappingPreExpression(ExpressionEvaluationContext context, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException;
}
| apache-2.0 |
shubhamdhama/zulip | tools/lib/test_server.py | 3503 | import os
import subprocess
import sys
import time
from contextlib import contextmanager
from typing import Iterator, Optional
# Verify the Zulip venv is available.
from tools.lib import sanity_check
sanity_check.check_venv(__file__)
import django
import requests
MAX_SERVER_WAIT = 90
TOOLS_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if TOOLS_DIR not in sys.path:
sys.path.insert(0, os.path.dirname(TOOLS_DIR))
from scripts.lib.zulip_tools import get_or_create_dev_uuid_var_path
from zerver.lib.test_fixtures import update_test_databases_if_required
def set_up_django(external_host: str) -> None:
os.environ['EXTERNAL_HOST'] = external_host
os.environ["TORNADO_SERVER"] = "http://127.0.0.1:9983"
os.environ["LOCAL_UPLOADS_DIR"] = get_or_create_dev_uuid_var_path(
'test-backend/test_uploads')
os.environ['DJANGO_SETTINGS_MODULE'] = 'zproject.test_settings'
django.setup()
os.environ['PYTHONUNBUFFERED'] = 'y'
def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
"""Get the exit code of the server, or None if it is still running."""
if server.poll() is not None:
message = 'Server died unexpectedly!'
if log_file:
message += f'\nSee {log_file}\n'
raise RuntimeError(message)
def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
assert_server_running(server, log_file)
try:
# We could get a 501 error if the reverse proxy is up but the Django app isn't.
# Note that zulipdev.com is mapped via DNS to 127.0.0.1.
return requests.get('http://zulipdev.com:9981/accounts/home').status_code == 200
except Exception:
return False
@contextmanager
def test_server_running(force: bool=False, external_host: str='testserver',
log_file: Optional[str]=None, dots: bool=False, use_db: bool=True,
) -> Iterator[None]:
log = sys.stdout
if log_file:
if os.path.exists(log_file) and os.path.getsize(log_file) < 100000:
log = open(log_file, 'a')
log.write('\n\n')
else:
log = open(log_file, 'w')
set_up_django(external_host)
if use_db:
update_test_databases_if_required(rebuild_test_database=True)
# Run this not through the shell, so that we have the actual PID.
run_dev_server_command = ['tools/run-dev.py', '--test', '--streamlined']
if force:
run_dev_server_command.append('--force')
server = subprocess.Popen(run_dev_server_command,
stdout=log, stderr=log)
try:
# Wait for the server to start up.
sys.stdout.write('\nWaiting for test server (may take a while)')
if not dots:
sys.stdout.write('\n\n')
t = time.time()
while not server_is_up(server, log_file):
if dots:
sys.stdout.write('.')
sys.stdout.flush()
time.sleep(0.4)
if time.time() - t > MAX_SERVER_WAIT:
raise Exception('Timeout waiting for server')
sys.stdout.write('\n\n--- SERVER IS UP! ---\n\n')
# DO OUR ACTUAL TESTING HERE!!!
yield
finally:
assert_server_running(server, log_file)
server.terminate()
if __name__ == '__main__':
# The code below is for testing this module works
with test_server_running():
print('\n\n SERVER IS UP!\n\n')
| apache-2.0 |
SAP/xliff-1-2 | com.sap.mlt.xliff12.api/src/main/java/com/sap/mlt/xliff12/api/attribute/Coord.java | 1251 | package com.sap.mlt.xliff12.api.attribute;
import com.sap.mlt.xliff12.api.base.XliffAttribute;
/**
* Coordinates - The coord attribute specifies the x, y, cx and cy coordinates
* of the text for a given element. The cx and cy values must represent the
* width and the height (as in Windows resources). The extraction and merging
* tools must make the right conversion if the original format uses a
* top-left/bottom-right coordinate system.
*
* @author D049314
*/
public interface Coord extends XliffAttribute {
/**
* The attribute's name.
*/
static final String NAME = "coord";
/**
* Returns the x-coordinate. Might be <code>null</code>.
*
* @return Returns the x-coordinate. Might be <code>null</code>.
*/
Integer getX();
/**
* Returns the y-coordinate. Might be <code>null</code>.
*
* @return Returns the y-coordinate. Might be <code>null</code>.
*/
Integer getY();
/**
* Returns the width. Might be <code>null</code>.
*
* @return Returns the width. Might be <code>null</code>.
*/
Integer getCx();
/**
* Returns the height. Might be <code>null</code>.
*
* @return Returns the height. Might be <code>null</code>.
*/
Integer getCy();
}
| apache-2.0 |
gunan/tensorflow | tensorflow/core/grappler/optimizers/constant_folding_test.cc | 164270 | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/grappler/optimizers/constant_folding.h"
#include "tensorflow/cc/ops/array_ops.h"
#include "tensorflow/cc/ops/array_ops_internal.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/utils.h"
#include "tensorflow/core/grappler/utils/grappler_test.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/tensor_coding.h"
namespace tensorflow {
namespace grappler {
namespace {
class ConstantFoldingTest : public GrapplerTest {
protected:
template <DataType DTYPE>
void SimpleNeutralElementTest() {
for (bool use_snapshot : {false, true}) {
typedef typename EnumToDataType<DTYPE>::Type T;
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output x = ops::Placeholder(s.WithOpName("x"), DTYPE,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output v = ops::Variable(s.WithOpName("v"), {2, 2}, DTYPE);
Tensor zeros_t(DTYPE, TensorShape({2, 2}));
Tensor ones_t(DTYPE, TensorShape({2, 2}));
Tensor x_t(DTYPE, TensorShape({2, 2}));
for (int i = 0; i < 4; ++i) {
zeros_t.flat<T>()(i) = T(0);
ones_t.flat<T>()(i) = T(1);
x_t.flat<T>()(i) = T(i + 1);
}
Output zeros = ops::Const(s.WithOpName("zeros"), zeros_t);
Output ones = ops::Const(s.WithOpName("ones"), ones_t);
Output mul1;
Output mul2;
Output add1;
Output add2;
if (DTYPE == DT_BOOL) {
mul1 = ops::LogicalAnd(s.WithOpName("mul1"), x, zeros);
mul2 = ops::LogicalAnd(s.WithOpName("mul2"), x, ones);
add1 = ops::LogicalOr(s.WithOpName("add1"), x, zeros);
add2 = ops::LogicalOr(s.WithOpName("add2"), x, ones);
} else {
if (DTYPE == DT_FLOAT) {
mul1 = ops::MulNoNan(s.WithOpName("mul1"), x, zeros);
} else {
mul1 = ops::Mul(s.WithOpName("mul1"), x, zeros);
}
mul2 = ops::Mul(s.WithOpName("mul2"), x, ones);
add1 = ops::Add(s.WithOpName("add1"), x, zeros);
add1 = ops::Add(s.WithOpName("add2"), x, ones);
}
if (use_snapshot) {
// Add an op with ref input to prevent Snapshot from being
// turned into Identity.
ops::Assign(s.WithOpName("assign"), v, ones);
}
GrapplerItem item;
TF_CHECK_OK(s.ToGraphDef(&item.graph));
item.fetch = {"mul1", "mul2", "add1", "add2"};
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(7, output.node_size());
const string snapshot_or_identity =
use_snapshot ? "Snapshot" : "Identity";
for (int i = 0; i < output.node_size(); ++i) {
const NodeDef& node = output.node(i);
const string& name = node.name();
if (name == "mul1") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ("^x", node.input(0));
EXPECT_EQ("^zeros", node.input(1));
} else if (name == "mul2") {
EXPECT_EQ(snapshot_or_identity, node.op());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("^ones", node.input(1));
} else if (name == "add1") {
EXPECT_EQ(snapshot_or_identity, node.op());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("^zeros", node.input(1));
} else if (name == "add2") {
if (DTYPE == DT_BOOL) {
EXPECT_EQ("Const", node.op());
EXPECT_EQ("^x", node.input(0));
EXPECT_EQ("^ones", node.input(1));
} else {
EXPECT_EQ("Add", node.op());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("ones", node.input(1));
}
}
}
auto tensors_expected =
EvaluateNodes(item.graph, item.fetch, {{"x", x_t}});
auto tensors = EvaluateNodes(output, item.fetch, {{"x", x_t}});
EXPECT_EQ(4, tensors_expected.size());
EXPECT_EQ(4, tensors.size());
for (int i = 0; i < item.fetch.size(); ++i) {
test::ExpectTensorEqual<T>(tensors_expected[i], tensors[i]);
}
}
}
void MulConvPushDownTest(const TensorShape& input_shape,
const TensorShape& filter_shape,
const TensorShape& mul_const_input_shape,
const bool use_3d_conv, const char* padding,
const char* data_format, const bool expect_folded) {
// Tests if the following rewrite is performed:
//
// * Conv2D
// / \ / \
// c Conv2D --> x (c * filter)
// / \
// x filter
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Tensor filter_values(DT_FLOAT, filter_shape);
for (int i = 0; i < filter_values.NumElements(); ++i) {
filter_values.flat<float>()(i) = std::sqrt(static_cast<float>(i));
}
Output filter =
ops::Const(s.WithOpName("filter"), Input::Initializer(filter_values));
Output input = ops::Placeholder(s.WithOpName("x"), DT_FLOAT,
ops::Placeholder::Shape(input_shape));
Output conv;
if (use_3d_conv) {
conv = ops::Conv3D(s.WithOpName("conv"), input, filter, {1, 1, 1, 1, 1},
padding, ops::Conv3D::DataFormat(data_format));
} else {
conv = ops::Conv2D(s.WithOpName("conv"), input, filter, {1, 1, 1, 1},
padding, ops::Conv2D::DataFormat(data_format));
}
Tensor mul_const_input(DT_FLOAT, mul_const_input_shape);
for (int i = 0; i < mul_const_input.NumElements(); ++i) {
mul_const_input.flat<float>()(i) = static_cast<float>(i + 3);
}
Output c =
ops::Const(s.WithOpName("c"), Input::Initializer(mul_const_input));
Output mul = ops::Mul(s.WithOpName("mul"), c, conv);
GrapplerItem item;
TF_CHECK_OK(s.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(5, output.node_size());
int found = 0;
if (expect_folded) {
for (const auto& node : output.node()) {
if (node.name() == "mul") {
found++;
EXPECT_EQ(use_3d_conv ? "Conv3D" : "Conv2D", node.op());
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("conv/merged_input", node.input(1));
} else if (node.name() == "conv/merged_input") {
found++;
EXPECT_EQ("Const", node.op());
EXPECT_EQ(0, node.input_size());
}
}
} else {
for (const auto& node : output.node()) {
if (node.name() == "mul") {
found++;
EXPECT_EQ("Mul", node.op());
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("c", node.input(0));
EXPECT_EQ("conv", node.input(1));
} else if (node.name() == "conv") {
found++;
EXPECT_EQ(use_3d_conv ? "Conv3D" : "Conv2D", node.op());
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("filter", node.input(1));
}
}
}
EXPECT_EQ(2, found);
// Check that const folded multiplication node has the expected value.
std::vector<string> fetch = {"mul"};
Tensor value(DT_FLOAT, input_shape);
for (int i = 0; i < value.NumElements(); ++i) {
value.flat<float>()(i) = i;
}
auto actual = EvaluateNodes(output, fetch, {{"x", value}});
auto expected = EvaluateNodes(item.graph, fetch, {{"x", value}});
test::ExpectTensorEqual<float>(expected[0], actual[0]);
}
};
TEST_F(ConstantFoldingTest, SimpleFolding) {
// Build a simple graph with a few trivially prunable ops.
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output a = ops::Const(s.WithOpName("a"), 1.0f, {1});
Output b = ops::Const(s.WithOpName("b"), 2.0f, {1});
Output c = ops::AddN(s.WithOpName("c").WithDevice("/CPU:0"), {a, b});
Output d = ops::AddN(s.WithOpName("d"), {b, c});
GrapplerItem item;
item.fetch.push_back("d");
TF_CHECK_OK(s.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(1, output.node_size());
const NodeDef& node_d = output.node(0);
EXPECT_EQ("d", node_d.name());
EXPECT_EQ("Const", node_d.op());
std::vector<string> fetch = {"d"};
auto tensors_expected = EvaluateNodes(item.graph, fetch);
auto tensors = EvaluateNodes(output, fetch);
EXPECT_EQ(1, tensors_expected.size());
EXPECT_EQ(1, tensors.size());
test::ExpectTensorEqual<float>(tensors_expected[0], tensors[0]);
}
TEST_F(ConstantFoldingTest, AddTree) {
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output c1 = ops::Const(s.WithOpName("c1"), 1.0f, {1});
Output c2 = ops::Const(s.WithOpName("c2"), 2.0f, {2});
Output c3 = ops::Const(s.WithOpName("c3"), 3.0f, {2});
Output x = ops::Placeholder(s.WithOpName("x"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output add_child = ops::Add(s.WithOpName("add_child"), c2, x);
Output add_parent = ops::Add(s.WithOpName("add_parent"), c1, add_child);
Output c4 = ops::Const(s.WithOpName("c4"), 4.0f, {2});
Output c5 = ops::Const(s.WithOpName("c5"), 5.0f, {2});
Output c20 = ops::Const(s.WithOpName("c20"), 20.0f, {2});
Output y = ops::Placeholder(s.WithOpName("y"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output mul_child = ops::Mul(s.WithOpName("mul_child"), c4, y);
Output mul_parent = ops::Mul(s.WithOpName("mul_parent"), c5, mul_child);
Output addmul_child = ops::Add(s.WithOpName("addmul_child"), c4, x);
Output addmul_parent =
ops::Mul(s.WithOpName("addmul_parent"), c5, addmul_child);
GrapplerItem item;
item.fetch = {"add_parent", "mul_parent", "addmul_parent"};
TF_CHECK_OK(s.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
// We expect the following rewrite(s) to occur:
//
// + + +
// / \ / \ / \
// 1.0 + --> x + --> x 3.0
// / \ / \
// 2.0 x 1.0 2.0
//
// * * *
// / \ / \ / \
// 4.0 * --> y * --> y 20.0
// / \ / \
// 5.0 y 4.0 5.0
EXPECT_EQ(10, output.node_size());
for (const auto& node : output.node()) {
if (node.name() == "add_child") {
EXPECT_EQ("Const", node.op());
TensorProto t = node.attr().at("value").tensor();
ASSERT_EQ(1, t.tensor_shape().dim_size());
EXPECT_EQ(2, t.tensor_shape().dim(0).size());
} else if (node.name() == "add_parent") {
EXPECT_EQ("Add", node.op());
ASSERT_EQ(2, node.input_size());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("add_child", node.input(1));
} else if (node.name() == "mul_child") {
EXPECT_EQ("Const", node.op());
TensorProto t = node.attr().at("value").tensor();
EXPECT_EQ(1, t.tensor_shape().dim_size());
EXPECT_EQ(2, t.tensor_shape().dim(0).size());
} else if (node.name() == "mul_parent") {
EXPECT_EQ("Mul", node.op());
ASSERT_EQ(2, node.input_size());
EXPECT_EQ("y", node.input(0));
EXPECT_EQ("mul_child", node.input(1));
} else if (node.name() == "addmul_child") {
// Unchanged.
EXPECT_EQ("Add", node.op());
ASSERT_EQ(2, node.input_size());
EXPECT_EQ("c4", node.input(0));
EXPECT_EQ("x", node.input(1));
}
}
// Check that the result nodes have the expected value.
auto x_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({2, 2}));
auto y_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({2, 2}));
std::vector<string> fetch = {"add_parent", "mul_parent"};
auto tensor_expected =
EvaluateNodes(item.graph, fetch, {{"x", x_t}, {"y", y_t}});
ASSERT_EQ(fetch.size(), tensor_expected.size());
fetch = {"add_parent", "mul_parent"};
auto tensors = EvaluateNodes(output, fetch, {{"x", x_t}, {"y", y_t}});
ASSERT_EQ(fetch.size(), tensors.size());
for (int i = 0; i < fetch.size(); i++) {
test::ExpectTensorEqual<float>(tensor_expected[i], tensors[i]);
}
}
TEST_F(ConstantFoldingTest, AddSubtactTree) {
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output c1 = ops::Const(s.WithOpName("c1"), 1.0f, {1});
Output x = ops::Placeholder(s.WithOpName("x"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output sub_child = ops::Sub(s.WithOpName("sub_child"), x, x);
Output add_parent = ops::Add(s.WithOpName("add_parent"), sub_child, c1);
GrapplerItem item;
item.fetch = {"add_parent"};
TF_CHECK_OK(s.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
// We expect the following rewrite(s) to occur:
//
// + +
// / \ / \
// - 1 --> - x
// / \ / \
// x x 1 x
EXPECT_EQ(4, output.node_size());
for (const auto& node : output.node()) {
if (node.name() == "sub_child") {
EXPECT_EQ("Sub", node.op());
ASSERT_EQ(2, node.input_size());
EXPECT_EQ("c1", node.input(0));
EXPECT_EQ("x", node.input(1));
} else if (node.name() == "add_parent") {
EXPECT_EQ("Add", node.op());
ASSERT_EQ(2, node.input_size());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("sub_child", node.input(1));
}
}
// Check that the result nodes have the expected value.
auto x_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({2, 2}));
std::vector<string> fetch = {"add_parent"};
auto tensor_expected = EvaluateNodes(item.graph, fetch, {{"x", x_t}});
ASSERT_EQ(fetch.size(), tensor_expected.size());
fetch = {"add_parent"};
auto tensors = EvaluateNodes(output, fetch, {{"x", x_t}});
ASSERT_EQ(fetch.size(), tensors.size());
for (int i = 0; i < fetch.size(); i++) {
test::ExpectTensorEqual<float>(tensor_expected[i], tensors[i]);
}
}
TEST_F(ConstantFoldingTest, ConstantPushDown) {
for (int is_add : {true, false}) {
for (int is_parent_commutative : {true, false}) {
for (int is_child_commutative : {true, false}) {
for (int is_left_child_const : {true, false}) {
for (int is_left_leaf_const : {true, false}) {
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output c2 = ops::Const(s.WithOpName("c2"), 2.0f, {2});
Output c3 = ops::Const(s.WithOpName("c3"), 3.0f, {2});
Output x =
ops::Placeholder(s.WithOpName("x"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 2})));
auto get_op = [&](bool is_commutative, bool is_left_arg_const,
const string& name, const Output& const_arg,
const Output non_const_arg) -> Output {
if (is_add) {
if (is_commutative) {
return ops::Add(
s.WithOpName(name),
is_left_arg_const ? const_arg : non_const_arg,
is_left_arg_const ? non_const_arg : const_arg);
} else {
return ops::Sub(
s.WithOpName(name),
is_left_arg_const ? const_arg : non_const_arg,
is_left_arg_const ? non_const_arg : const_arg);
}
} else {
if (is_commutative) {
return ops::Mul(
s.WithOpName(name),
is_left_arg_const ? const_arg : non_const_arg,
is_left_arg_const ? non_const_arg : const_arg);
} else {
return ops::Div(
s.WithOpName(name),
is_left_arg_const ? const_arg : non_const_arg,
is_left_arg_const ? non_const_arg : const_arg);
}
}
};
Output child = get_op(is_child_commutative, is_left_leaf_const,
"child", c2, x);
Output parent = get_op(is_parent_commutative, is_left_child_const,
"parent", c3, child);
GrapplerItem item;
item.fetch = {"parent"};
TF_CHECK_OK(s.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status =
optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
// Check that the result nodes have the expected value.
auto x_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({2, 2}));
std::vector<string> fetch = {"parent"};
auto tensor_expected =
EvaluateNodes(item.graph, fetch, {{"x", x_t}});
ASSERT_EQ(fetch.size(), tensor_expected.size());
fetch = {"parent"};
auto tensors = EvaluateNodes(output, fetch, {{"x", x_t}});
ASSERT_EQ(fetch.size(), tensors.size());
for (int i = 0; i < fetch.size(); i++) {
test::ExpectTensorEqual<float>(tensor_expected[i], tensors[i]);
}
}
}
}
}
}
}
TEST_F(ConstantFoldingTest, ConstantPushDownBiasAdd) {
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output c_mat = ops::Const(s.WithOpName("c_mat"), 2.0f, {2, 2});
Output c_vec = ops::Const(s.WithOpName("c_vec"), 3.0f, {2});
Output x_mat = ops::Placeholder(s.WithOpName("x_mat"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output x_vec = ops::Placeholder(s.WithOpName("x_vec"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2})));
// Rewrite expected for cases 1 through 3 and their symmetric equivalents,
// and case 4.
Output child1 = ops::BiasAdd(s.WithOpName("child1"), c_mat, x_vec);
Output parent1 = ops::Add(s.WithOpName("parent1"), child1, c_vec);
Output child1a = ops::BiasAdd(s.WithOpName("child1a"), c_mat, x_vec);
Output parent1a = ops::Add(s.WithOpName("parent1a"), c_vec, child1a);
Output child2 = ops::BiasAdd(s.WithOpName("child2"), x_mat, c_vec);
Output parent2 = ops::Add(s.WithOpName("parent2"), child2, c_mat);
Output child2a = ops::BiasAdd(s.WithOpName("child2a"), x_mat, c_vec);
Output parent2a = ops::Add(s.WithOpName("parent2a"), c_mat, child2a);
Output child3 = ops::Add(s.WithOpName("child3"), c_mat, x_vec);
Output parent3 = ops::BiasAdd(s.WithOpName("parent3"), child3, c_vec);
Output child3a = ops::Add(s.WithOpName("child3a"), x_vec, c_mat);
Output parent3a = ops::BiasAdd(s.WithOpName("parent3a"), child3a, c_vec);
Output child4 = ops::BiasAdd(s.WithOpName("child4"), c_mat, x_vec);
Output parent4 = ops::BiasAdd(s.WithOpName("parent4"), child4, c_vec);
// No rewrite expected.
Output child5 = ops::Add(s.WithOpName("child5"), x_vec, x_vec);
Output parent5 = ops::BiasAdd(s.WithOpName("parent5"), c_mat, child5);
Output child6 = ops::Add(s.WithOpName("child6"), x_vec, c_vec);
Output parent6 = ops::BiasAdd(s.WithOpName("parent6"), c_mat, child6);
Output child7 = ops::Add(s.WithOpName("child7"), x_mat, c_vec);
Output parent7 = ops::BiasAdd(s.WithOpName("parent7"), child7, c_vec);
GrapplerItem item;
item.fetch = {"parent1", "parent2", "parent3", "parent1a", "parent2a",
"parent3a", "parent4", "parent5", "parent6", "parent7"};
TF_CHECK_OK(s.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(24, output.node_size());
for (const auto& node : output.node()) {
if (node.name() == "child1" || node.name() == "child1a" ||
node.name() == "child2" || node.name() == "child2a" ||
node.name() == "child3" || node.name() == "child3a" ||
node.name() == "child4") {
EXPECT_EQ(node.op(), "Const") << " node: " << node.name();
} else if (node.name() != "c_mat" && node.name() != "c_vec") {
EXPECT_NE(node.op(), "Const") << " node: " << node.name();
}
}
// Check that the result nodes have the expected value.
auto x_mat_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({2, 2}));
auto x_vec_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({2}));
std::vector<string> fetch = item.fetch;
auto tensor_expected = EvaluateNodes(
item.graph, fetch, {{"x_vec", x_vec_t}, {"x_mat", x_mat_t}});
ASSERT_EQ(fetch.size(), tensor_expected.size());
auto tensors =
EvaluateNodes(output, fetch, {{"x_vec", x_vec_t}, {"x_mat", x_mat_t}});
ASSERT_EQ(fetch.size(), tensors.size());
for (int i = 0; i < fetch.size(); i++) {
test::ExpectTensorEqual<float>(tensor_expected[i], tensors[i]);
}
}
TEST_F(ConstantFoldingTest, MulConvPushDownTest_Conv2D_ScalarConst) {
for (string data_format : {
"NHWC",
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
"NCHW"
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
}) {
MulConvPushDownTest(
/*input_shape=*/data_format == "NHWC" ? TensorShape{4, 10, 10, 3}
: TensorShape{4, 3, 10, 10},
/*filter_shape=*/{2, 2, 3, 5},
/*mul_const_input_shape=*/{},
/*use_3d_conv=*/false,
/*padding=*/"VALID", data_format.c_str(),
/*expect_folded=*/true);
}
}
TEST_F(ConstantFoldingTest, MulConvPushDownTest_Conv2D_SingletonConst) {
for (string data_format : {
"NHWC",
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
"NCHW"
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
}) {
for (auto mul_const_input_shape :
{TensorShape{1}, TensorShape{1, 1, 1, 1}}) {
MulConvPushDownTest(
/*input_shape=*/data_format == "NHWC" ? TensorShape{4, 10, 10, 3}
: TensorShape{4, 3, 10, 10},
/*filter_shape=*/{2, 2, 3, 5}, mul_const_input_shape,
/*use_3d_conv=*/false,
/*padding=*/"VALID", data_format.c_str(),
/*expect_folded=*/true);
}
}
}
TEST_F(ConstantFoldingTest,
MulConvPushDownTest_Conv2D_SingletonConst_ShapeMismatch) {
for (string data_format : {
"NHWC",
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
"NCHW"
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
}) {
MulConvPushDownTest(
/*input_shape=*/data_format == "NHWC" ? TensorShape{4, 10, 10, 3}
: TensorShape{4, 3, 10, 10},
/*filter_shape=*/{2, 2, 3, 5},
/*mul_const_input_shape=*/{1, 1, 1, 1, 1},
/*use_3d_conv=*/false,
/*padding=*/"VALID", data_format.c_str(),
/*expect_folded=*/false);
}
}
TEST_F(ConstantFoldingTest, MulConvPushDownTest_Conv2D_3x1x3Const) {
for (auto data_format : {
"NHWC",
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
"NCHW"
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
}) {
MulConvPushDownTest(
/*input_shape=*/{3, 3, 3, 3},
/*filter_shape=*/{3, 3, 3, 3},
/*mul_const_input_shape=*/{3, 1, 3},
/*use_3d_conv=*/false,
/*padding=*/"SAME", data_format,
/*expect_folded=*/false);
}
}
TEST_F(ConstantFoldingTest, MulConvPushDownTest_Conv2D_NHWC_VectorLikeConst) {
for (auto mul_const_input_shape :
{TensorShape{3}, TensorShape{1, 3}, TensorShape{1, 1, 1, 3}}) {
MulConvPushDownTest(
/*input_shape=*/{3, 3, 3, 3},
/*filter_shape=*/{3, 3, 3, 3}, mul_const_input_shape,
/*use_3d_conv=*/false,
/*padding=*/"SAME",
/*data_format=*/"NHWC",
/*expect_folded=*/true);
}
}
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
TEST_F(ConstantFoldingTest, MulConvPushDownTest_Conv2D_NCHW_VectorLikeConst) {
for (auto mul_const_input_shape :
{TensorShape{3}, TensorShape{3, 1, 1}, TensorShape{1, 3, 1, 1}}) {
MulConvPushDownTest(
/*input_shape=*/{3, 3, 3, 3},
/*filter_shape=*/{3, 3, 3, 3}, mul_const_input_shape,
/*use_3d_conv=*/false,
/*padding=*/"SAME",
/*data_format=*/"NCHW",
// TODO(laigd): optimization should happen in this case.
/*expect_folded=*/false);
}
}
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
TEST_F(ConstantFoldingTest, MulConvPushDownTest_Conv2D_3x1Const) {
for (auto data_format : {
"NHWC",
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
"NCHW"
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
}) {
MulConvPushDownTest(
/*input_shape=*/{3, 3, 3, 3},
/*filter_shape=*/{3, 3, 3, 3},
/*mul_const_input_shape=*/{3, 1},
/*use_3d_conv=*/false,
/*padding=*/"SAME", data_format,
/*expect_folded=*/false);
}
}
// This test fails on ROCm platform with two vaue miscompare
// TODO(rocm) : analysze and fix the cause of the failure and re-enable test
#ifndef TENSORFLOW_USE_ROCM
TEST_F(ConstantFoldingTest, MulConvPushDownTest_Conv3D_NDHWC_1x1x3Const) {
MulConvPushDownTest(
/*input_shape=*/{3, 3, 3, 3, 3},
/*filter_shape=*/{3, 3, 3, 3, 3},
/*mul_const_input_shape=*/{1, 1, 3},
/*use_3d_conv=*/true,
/*padding=*/"SAME",
/*data_format=*/"NDHWC",
/*expect_folded=*/true);
}
#endif
TEST_F(ConstantFoldingTest, MulConvPushDownTest_Conv3D_NCDHW_3x1x1x1Const) {
MulConvPushDownTest(
/*input_shape=*/{3, 3, 3, 3, 3},
/*filter_shape=*/{3, 3, 3, 3, 3},
/*mul_const_input_shape=*/{3, 1, 1, 1},
/*use_3d_conv=*/true,
/*padding=*/"SAME",
/*data_format=*/"NDHWC",
// TODO(laigd): optimization should happen in this case.
/*expect_folded=*/false);
}
TEST_F(ConstantFoldingTest, NeutralElement) {
int kConst = 0;
int kLike = 1;
int kFill = 2;
for (int const_type : {kConst, kLike, kFill}) {
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output x = ops::Placeholder(s.WithOpName("x"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output y = ops::Placeholder(s.WithOpName("y"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output a = ops::Placeholder(s.WithOpName("a"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({3, 2})));
Output b = ops::Placeholder(s.WithOpName("b"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 3})));
Output bias = ops::Placeholder(s.WithOpName("bias"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2})));
Output zeros_1d = ops::Const(s.WithOpName("zeros_1d"), 0.0f, {2});
Output zeros_const = ops::Const(s.WithOpName("zeros_const"), 0.0f, {2, 2});
Output zeros_const_bcast =
ops::Const(s.WithOpName("zeros_const_bcast"), 0.0f, {2, 2, 2});
Output zeros_like = ops::ZerosLike(s.WithOpName("zeros_like"), x);
Output zeros_fill = ops::Fill(s.WithOpName("zeros_fill"), {2, 2}, 0.0f);
Output zeros = const_type == kConst
? zeros_const
: (const_type == kLike ? zeros_like : zeros_fill);
Output ones_const = ops::Const(s.WithOpName("ones_const"), 1.0f, {2, 2});
Output ones_const_bcast =
ops::Const(s.WithOpName("ones_const_bcast"), 1.0f, {2, 2, 2});
Output ones_like = ops::OnesLike(s.WithOpName("ones_like"), x);
Output ones_fill = ops::Fill(s.WithOpName("ones_fill"), {2, 2}, 1.0f);
Output ones = const_type == kConst
? ones_const
: (const_type == kLike ? ones_like : ones_fill);
Output mul1 = ops::Mul(s.WithOpName("mul1"), x, zeros);
Output mul2 = ops::Mul(s.WithOpName("mul2"), zeros, y);
Output mul1_bcast =
ops::Mul(s.WithOpName("mul1_bcast"), x, ones_const_bcast);
Output mul2_bcast =
ops::Mul(s.WithOpName("mul2_bcast"), ones_const_bcast, y);
Output mul3 = ops::Mul(s.WithOpName("mul3"), x, ones);
Output mul4 = ops::Mul(s.WithOpName("mul4"), ones, y);
Output mul5 = ops::MulNoNan(s.WithOpName("mul5"), x, zeros_1d);
Output mul6 = ops::MulNoNan(s.WithOpName("mul6"), zeros_1d, y);
Output div1 = ops::Div(s.WithOpName("div1"), x, ones);
Output div2 = ops::Div(s.WithOpName("div2"), ones, y);
Output matmul1 = ops::MatMul(s.WithOpName("matmul1"), x, zeros);
Output matmul2 = ops::MatMul(s.WithOpName("matmul2"), zeros, y);
Output matmul3 = ops::MatMul(s.WithOpName("matmul3"), a, zeros);
Output matmul4 = ops::MatMul(s.WithOpName("matmul4"), zeros, b);
Output add1 = ops::Add(s.WithOpName("add1"), x, zeros);
Output add2 = ops::Add(s.WithOpName("add2"), zeros, y);
Output add1_bcast =
ops::Add(s.WithOpName("add1_bcast"), x, zeros_const_bcast);
Output add2_bcast =
ops::Add(s.WithOpName("add2_bcast"), zeros_const_bcast, y);
Output bias_add1 = ops::BiasAdd(s.WithOpName("bias_add1"), x, zeros_1d);
Output bias_add2 = ops::BiasAdd(s.WithOpName("bias_add2"), zeros, bias);
Output sub1 = ops::Sub(s.WithOpName("sub1"), x, zeros);
Output sub2 = ops::Sub(s.WithOpName("sub2"), zeros, y);
Output concat =
ops::Stack(s.WithOpName("stack"),
{mul1, mul2, mul3, mul4, mul5, mul6, div1, div2, matmul1,
matmul2, add1, add2, bias_add1, bias_add2, sub1, sub2});
GrapplerItem item;
TF_CHECK_OK(s.ToGraphDef(&item.graph));
item.fetch = {"stack", "matmul3", "matmul4", "mul1_bcast",
"mul2_bcast", "add1_bcast", "add2_bcast"};
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
const string suffix =
(const_type == kConst ? "_const"
: (const_type == kLike ? "_like" : "_fill"));
const string zeros_name = strings::StrCat("zeros", suffix);
const string ones_name = strings::StrCat("ones", suffix);
const string ctrl_zeros_name = strings::StrCat("^zeros", suffix);
const string ctrl_ones_name = strings::StrCat("^ones", suffix);
EXPECT_EQ(const_type == kFill ? 42 : 38, output.node_size());
for (int i = 0; i < output.node_size(); ++i) {
const NodeDef& node = output.node(i);
const string& name = node.name();
if (name == "mul1") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ("^x", node.input(0));
EXPECT_EQ(ctrl_zeros_name, node.input(1));
} else if (name == "mul2") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ(ctrl_zeros_name, node.input(0));
EXPECT_EQ("^y", node.input(1));
} else if (name == "mul1_bcast") {
EXPECT_EQ("BroadcastTo", node.op());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("^ones_const_bcast", node.input(2));
} else if (name == "mul2_bcast") {
EXPECT_EQ("BroadcastTo", node.op());
EXPECT_EQ("y", node.input(0));
EXPECT_EQ("^ones_const_bcast", node.input(2));
} else if (name == "mul3") {
EXPECT_EQ("Identity", node.op());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ(ctrl_ones_name, node.input(1));
} else if (name == "mul4") {
EXPECT_EQ("Identity", node.op());
EXPECT_EQ("y", node.input(0));
EXPECT_EQ(ctrl_ones_name, node.input(1));
} else if (name == "mul5") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ("^x", node.input(0));
EXPECT_EQ("^zeros_1d", node.input(1));
} else if (name == "mul6") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ("^zeros_1d", node.input(0));
EXPECT_EQ("^y", node.input(1));
} else if (name == "div1") {
EXPECT_EQ("Identity", node.op());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ(ctrl_ones_name, node.input(1));
} else if (name == "div2") {
EXPECT_EQ("Reciprocal", node.op());
EXPECT_EQ("y", node.input(0));
EXPECT_EQ(ctrl_ones_name, node.input(1));
} else if (name == "matmul1") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ("^x", node.input(0));
EXPECT_EQ(ctrl_zeros_name, node.input(1));
} else if (name == "matmul2") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ(ctrl_zeros_name, node.input(0));
EXPECT_EQ("^y", node.input(1));
} else if (name == "matmul3") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ("^a", node.input(0));
EXPECT_EQ(ctrl_zeros_name, node.input(1));
TensorProto t = node.attr().at("value").tensor();
EXPECT_EQ(1, t.float_val_size());
EXPECT_EQ(0, t.float_val(0));
EXPECT_EQ(2, t.tensor_shape().dim_size());
EXPECT_EQ(3, t.tensor_shape().dim(0).size());
EXPECT_EQ(2, t.tensor_shape().dim(1).size());
} else if (name == "matmul4") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ(ctrl_zeros_name, node.input(0));
EXPECT_EQ("^b", node.input(1));
TensorProto t = node.attr().at("value").tensor();
EXPECT_EQ(1, t.float_val_size());
EXPECT_EQ(0, t.float_val(0));
EXPECT_EQ(2, t.tensor_shape().dim_size());
EXPECT_EQ(2, t.tensor_shape().dim(0).size());
EXPECT_EQ(3, t.tensor_shape().dim(1).size());
} else if (name == "add1") {
EXPECT_EQ("Identity", node.op());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ(ctrl_zeros_name, node.input(1));
} else if (name == "add2") {
EXPECT_EQ("Identity", node.op());
EXPECT_EQ("y", node.input(0));
EXPECT_EQ(ctrl_zeros_name, node.input(1));
} else if (name == "add1_bcast") {
EXPECT_EQ("BroadcastTo", node.op());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("^zeros_const_bcast", node.input(2));
} else if (name == "add2_bcast") {
EXPECT_EQ("BroadcastTo", node.op());
EXPECT_EQ("y", node.input(0));
EXPECT_EQ("^zeros_const_bcast", node.input(2));
} else if (name == "bias_add1") {
EXPECT_EQ("Identity", node.op());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("^zeros_1d", node.input(1));
} else if (name == "bias_add2") {
EXPECT_EQ("BroadcastTo", node.op());
EXPECT_EQ("bias", node.input(0));
EXPECT_EQ("ConstantFolding/bias_add2-broadcastto_shape-1",
node.input(1));
EXPECT_EQ(ctrl_zeros_name, node.input(2));
} else if (name == "ConstantFolding/bias_add2-broadcastto_shape-1") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ(ctrl_zeros_name, node.input(0));
EXPECT_EQ(node.attr().at("dtype").type(), DT_INT32);
TensorProto t = node.attr().at("value").tensor();
EXPECT_EQ(DT_INT32, t.dtype());
EXPECT_EQ(1, t.tensor_shape().dim_size());
EXPECT_EQ(2, t.tensor_shape().dim(0).size());
} else if (name == "sub1") {
EXPECT_EQ("Identity", node.op());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ(ctrl_zeros_name, node.input(1));
} else if (name == "sub2") {
EXPECT_EQ("Neg", node.op());
EXPECT_EQ("y", node.input(0));
EXPECT_EQ(ctrl_zeros_name, node.input(1));
}
const std::set<string> square_zero_const{"mul1", "mul2", "mul5",
"mul6", "matmul1", "matmul2"};
if (square_zero_const.count(name) > 0) {
TensorProto t = node.attr().at("value").tensor();
EXPECT_EQ(1, t.float_val_size());
EXPECT_EQ(0, t.float_val(0));
EXPECT_EQ(2, t.tensor_shape().dim_size());
EXPECT_EQ(2, t.tensor_shape().dim(0).size());
EXPECT_EQ(2, t.tensor_shape().dim(1).size());
}
}
auto a_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({3, 2}));
auto b_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({2, 3}));
auto x_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({2, 2}));
auto y_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({2, 2}));
auto bias_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({2}));
auto tensors_expected = EvaluateNodes(
item.graph, item.fetch,
{{"x", x_t}, {"y", y_t}, {"a", a_t}, {"b", b_t}, {"bias", bias_t}});
EXPECT_EQ(item.fetch.size(), tensors_expected.size());
auto tensors = EvaluateNodes(
output, item.fetch,
{{"x", x_t}, {"y", y_t}, {"a", a_t}, {"b", b_t}, {"bias", bias_t}});
EXPECT_EQ(item.fetch.size(), tensors.size());
for (int i = 0; i < item.fetch.size(); ++i) {
test::ExpectTensorNear<float>(tensors_expected[i], tensors[i], 1e-6);
}
}
}
TEST_F(ConstantFoldingTest, NeutralElement_ShortFloats) {
SimpleNeutralElementTest<DT_BOOL>();
SimpleNeutralElementTest<DT_HALF>();
SimpleNeutralElementTest<DT_BFLOAT16>();
}
TEST_F(ConstantFoldingTest, StrengthReduce_Reciprocal) {
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output cf_half = ops::Const(s.WithOpName("cf_half"), 0.5f, {1});
Output xf = ops::Placeholder(s.WithOpName("xf"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output xi = ops::Placeholder(s.WithOpName("xi"), DT_INT32,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output ci = ops::Const(s.WithOpName("ci"), 2, {1});
Output cf = ops::Const(s.WithOpName("cf"), 2.0f, {1});
Output div_i = ops::Div(s.WithOpName("div_i"), xi, ci);
Output div_f = ops::Div(s.WithOpName("div_f"), xf, cf);
Output realdiv = ops::RealDiv(s.WithOpName("realdiv"), xf, cf);
GrapplerItem item;
TF_CHECK_OK(s.ToGraphDef(&item.graph));
item.fetch = {"div_f", "div_i", "realdiv"};
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(8, output.node_size());
for (int i = 0; i < output.node_size(); ++i) {
const NodeDef& node = output.node(i);
const string& name = node.name();
if (name == "div_i") {
// Integer division is unchanged.
EXPECT_EQ("Div", node.op());
EXPECT_EQ("xi", node.input(0));
EXPECT_EQ("ci", node.input(1));
} else if (name == "div_f") {
EXPECT_EQ("Mul", node.op());
EXPECT_EQ("xf", node.input(0));
EXPECT_EQ("ConstantFolding/div_f_recip", node.input(1));
} else if (name == "realdiv") {
EXPECT_EQ("Mul", node.op());
EXPECT_EQ("xf", node.input(0));
EXPECT_EQ("ConstantFolding/realdiv_recip", node.input(1));
} else if (name == "ConstantFolding/div_f_recip") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ(DT_FLOAT, node.attr().at("dtype").type());
TensorProto t = node.attr().at("value").tensor();
EXPECT_EQ(DT_FLOAT, t.dtype());
EXPECT_EQ(1, t.tensor_shape().dim_size());
EXPECT_EQ(1, t.tensor_shape().dim(0).size());
} else if (name == "ConstantFolding/realdiv_recip") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ(DT_FLOAT, node.attr().at("dtype").type());
TensorProto t = node.attr().at("value").tensor();
EXPECT_EQ(DT_FLOAT, t.dtype());
EXPECT_EQ(1, t.tensor_shape().dim_size());
EXPECT_EQ(1, t.tensor_shape().dim(0).size());
}
}
// Check that the reciprocals have the expected value.
std::vector<string> fetch = {"cf_half"};
auto tensor_expected = EvaluateNodes(item.graph, fetch);
EXPECT_EQ(fetch.size(), tensor_expected.size());
fetch = {"ConstantFolding/div_f_recip", "ConstantFolding/realdiv_recip"};
auto tensors = EvaluateNodes(output, fetch);
EXPECT_EQ(fetch.size(), tensors.size());
for (int i = 0; i < fetch.size(); i++) {
test::ExpectTensorEqual<float>(tensor_expected[0], tensors[i]);
}
}
TEST_F(ConstantFoldingTest, NeutralElement_PartialShape_UnknownOutputShape) {
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output x_known =
ops::Placeholder(s.WithOpName("x_known"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output x_partially_known =
ops::Placeholder(s.WithOpName("x_partially_unknown"), DT_FLOAT,
ops::Placeholder::Shape(PartialTensorShape({-1, -1})));
Output x_unknown = ops::Placeholder(s.WithOpName("x_unknown"), DT_FLOAT);
Output zeros_known = ops::ZerosLike(s.WithOpName("zeros_known"), x_known);
Output zeros_partially_known =
ops::ZerosLike(s.WithOpName("zeros_partially_known"), x_partially_known);
Output zeros_unknown =
ops::ZerosLike(s.WithOpName("zeros_unknown"), x_unknown);
// Multiplies without any additional ops to supply the output shape.
int count = 0;
std::vector<Output> muls;
std::unordered_set<string> not_converted;
std::unordered_set<string> to_const;
std::unordered_set<string> to_identity;
for (const auto* x : {&x_known, &x_partially_known, &x_unknown}) {
for (const auto* zeros :
{&zeros_known, &zeros_partially_known, &zeros_unknown}) {
const string name = strings::StrCat("mul_", count++);
muls.push_back(ops::Mul(s.WithOpName(name), *x, *zeros));
if (x == &x_partially_known && zeros == &zeros_partially_known) {
to_identity.insert(name);
} else if (x == &x_unknown || zeros == &zeros_unknown) {
not_converted.insert(name);
} else {
to_const.insert(name);
}
}
}
GrapplerItem item;
TF_CHECK_OK(s.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(15, output.node_size());
for (int i = 0; i < output.node_size(); ++i) {
const NodeDef& node = output.node(i);
const string& name = node.name();
if (to_const.count(name) > 0) {
EXPECT_EQ("Const", node.op()) << node.name();
} else if (to_identity.count(name) > 0) {
EXPECT_EQ("Identity", node.op()) << node.name();
} else if (not_converted.count(name) > 0) {
EXPECT_EQ("Mul", node.op()) << node.name();
}
}
const std::vector<string> fetch = {"mul_0", "mul_4", "mul_8"};
auto x_known_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({2, 2}));
auto x_partially_unknown_t =
GenerateRandomTensor<DT_FLOAT>(TensorShape({3, 4}));
auto x_unknown_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({5, 7}));
auto expected_tensors =
EvaluateNodes(item.graph, fetch,
{{"x_known", x_known_t},
{"x_partially_unknown", x_partially_unknown_t},
{"x_unknown", x_unknown_t}});
EXPECT_EQ(fetch.size(), expected_tensors.size());
auto tensors = EvaluateNodes(output, fetch,
{{"x_known", x_known_t},
{"x_partially_unknown", x_partially_unknown_t},
{"x_unknown", x_unknown_t}});
EXPECT_EQ(fetch.size(), tensors.size());
for (int i = 0; i < tensors.size(); i++)
test::ExpectTensorNear<float>(expected_tensors[i], tensors[i], 1e-5);
}
TEST_F(ConstantFoldingTest, NeutralElement_PartialShape_KnownOutputShape) {
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output known_shape = ops::Const(s.WithOpName("known_shape"), 0.0f, {2, 2});
Output x_partially_known =
ops::Placeholder(s.WithOpName("x_partially_unknown"), DT_FLOAT,
ops::Placeholder::Shape(PartialTensorShape({-1, -1})));
Output x_unknown = ops::Placeholder(s.WithOpName("x_unknown"), DT_FLOAT);
Output zeros_partially_known =
ops::ZerosLike(s.WithOpName("zeros_partially_known"), x_partially_known);
Output zeros_unknown =
ops::ZerosLike(s.WithOpName("zeros_unknown"), x_unknown);
// If at least one of the inputs to AddN has a known shape, shape inference
// will propagate the shape back to the inputs of AddN, making the
// output shapes of all its inputs known
std::vector<Output> muls_deduced_output_shape;
std::unordered_set<string> to_const;
int count = 0;
for (const auto& x : {x_partially_known, x_unknown}) {
for (const auto& zeros : {zeros_partially_known, zeros_unknown}) {
const string name = strings::StrCat("mul_", count++);
muls_deduced_output_shape.push_back(
ops::Mul(s.WithOpName(name), x, zeros));
to_const.insert(name);
}
}
// We add a known shape as input to AddN to propagate it back to the
// multiplies above, which means they can all be turned into Const nodes.
muls_deduced_output_shape.push_back(known_shape);
Output addn1 = ops::AddN(s.WithOpName("addn1"), muls_deduced_output_shape);
GrapplerItem item;
TF_CHECK_OK(s.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(10, output.node_size());
for (int i = 0; i < output.node_size(); ++i) {
const NodeDef& node = output.node(i);
const string& name = node.name();
if (to_const.count(name) > 0) {
EXPECT_EQ("Const", node.op()) << node.name();
EXPECT_EQ(2, node.input_size());
EXPECT_TRUE(IsControlInput(node.input(0)));
EXPECT_TRUE(IsControlInput(node.input(1)));
}
}
const std::vector<string> fetch = {"addn1"};
auto x_partially_unknown_t =
GenerateRandomTensor<DT_FLOAT>(TensorShape({2, 2}));
auto x_unknown_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({2, 2}));
auto expected_tensors =
EvaluateNodes(item.graph, fetch,
{{"x_partially_unknown", x_partially_unknown_t},
{"x_unknown", x_unknown_t}});
EXPECT_EQ(1, expected_tensors.size());
auto tensors = EvaluateNodes(output, fetch,
{{"x_partially_unknown", x_partially_unknown_t},
{"x_unknown", x_unknown_t}});
EXPECT_EQ(1, tensors.size());
test::ExpectTensorNear<float>(expected_tensors[0], tensors[0], 1e-5);
}
TEST_F(ConstantFoldingTest, CreateConstNodes) {
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
#define MAKE_TEST_GRAPH(TYPE) \
Output TYPE##_const = \
ops::Const(s.WithOpName(#TYPE "_const"), static_cast<TYPE>(10), {5}); \
Output TYPE##_mul = \
ops::Mul(s.WithOpName(#TYPE "_mul"), TYPE##_const, TYPE##_const); \
Output TYPE##_id = ops::Identity(s.WithOpName(#TYPE "_id"), TYPE##_mul)
MAKE_TEST_GRAPH(float);
MAKE_TEST_GRAPH(double);
MAKE_TEST_GRAPH(int64);
MAKE_TEST_GRAPH(int32);
MAKE_TEST_GRAPH(int16);
MAKE_TEST_GRAPH(int8);
MAKE_TEST_GRAPH(uint8);
#undef MAKE_TEST_GRAPH
Output bool_const = ops::Const(s.WithOpName("bool_const"), true, {5});
Output bool_and =
ops::LogicalAnd(s.WithOpName("bool_and"), bool_const, bool_const);
Output bool_id = ops::Identity(s.WithOpName("bool_id"), bool_and);
GrapplerItem item;
TF_CHECK_OK(s.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(24, output.node_size());
for (const NodeDef& node : output.node()) {
#define CHECK_RESULT(TYPE, FIELD) \
if (node.name() == #TYPE "_mul") { \
EXPECT_EQ(5, \
node.attr().at("value").tensor().tensor_shape().dim(0).size()); \
EXPECT_EQ(1, node.attr().at("value").tensor().FIELD##_val_size()); \
EXPECT_EQ(10 * 10, node.attr().at("value").tensor().FIELD##_val(0)); \
}
CHECK_RESULT(float, float);
CHECK_RESULT(double, double);
CHECK_RESULT(int64, int64);
CHECK_RESULT(int32, int);
CHECK_RESULT(int16, int);
CHECK_RESULT(int8, int);
CHECK_RESULT(uint8, int);
#undef CHECK_RESULT
if (node.name() == "bool_and") {
EXPECT_EQ(5,
node.attr().at("value").tensor().tensor_shape().dim(0).size());
EXPECT_EQ(1, node.attr().at("value").tensor().bool_val_size());
EXPECT_EQ(true && true, node.attr().at("value").tensor().bool_val(0));
}
}
}
TEST_F(ConstantFoldingTest, FoldingNodeWithTwoOutputs) {
// Build a simple graph with a few trivially prunable ops.
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output a = ops::Const(s.WithOpName("a"), 10, {5});
auto b = ops::Unique(s.WithOpName("b"), {a});
Output c = ops::Identity(s.WithOpName("c"), {b.y});
Output d = ops::Identity(s.WithOpName("d"), {b.idx});
Output e = ops::Identity(s.WithOpName("e"), {c});
Output f = ops::Identity(s.WithOpName("f"), {d});
GrapplerItem item;
item.fetch.push_back("e");
item.fetch.push_back("f");
TF_CHECK_OK(s.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(2, output.node_size());
const NodeDef& new_c = output.node(0);
EXPECT_EQ("e", new_c.name());
EXPECT_EQ("Const", new_c.op());
const NodeDef& new_d = output.node(1);
EXPECT_EQ("f", new_d.name());
EXPECT_EQ("Const", new_d.op());
std::vector<string> fetch = {"e", "f"};
auto tensors_expected = EvaluateNodes(item.graph, fetch);
auto tensors = EvaluateNodes(output, fetch);
EXPECT_EQ(fetch.size(), tensors_expected.size());
EXPECT_EQ(fetch.size(), tensors.size());
for (int i = 0; i < fetch.size(); i++) {
test::ExpectTensorEqual<int>(tensors_expected[i], tensors[i]);
}
}
TEST_F(ConstantFoldingTest, ControlDependencies) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output dflt = ops::Const(scope.WithOpName("dflt"), 3.14f, {1});
Output p1 = ops::PlaceholderWithDefault(scope.WithOpName("p1"), dflt, {1});
Output p2 = ops::PlaceholderWithDefault(scope.WithOpName("p2"), dflt, {1});
Output c =
ops::Const(scope.WithOpName("c").WithControlDependencies(p1), 10, {3});
Output i1 = ops::Identity(scope.WithOpName("i1"), {c});
Output i2 =
ops::Identity(scope.WithOpName("i2").WithControlDependencies(p2), {i1});
Output i3 = ops::Identity(scope.WithOpName("i3"), {i2});
GrapplerItem item;
item.fetch.push_back("i3");
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
std::vector<string> expected_nodes = {"dflt", "p1", "p2", "i3"};
EXPECT_EQ(output.node_size(), expected_nodes.size());
int i = 0;
int found = 0;
for (const auto& node : output.node()) {
EXPECT_EQ(expected_nodes[i], output.node(i).name());
i++;
if (node.name() == "i3") {
EXPECT_EQ("Const", node.op());
++found;
auto folded = EvaluateNodes(output, {"i3"});
auto expected = EvaluateNodes(item.graph, {"i3"});
EXPECT_EQ(1, expected.size());
EXPECT_EQ(1, folded.size());
test::ExpectTensorEqual<int>(folded[0], expected[0]);
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("^p1", node.input(0));
EXPECT_EQ("^p2", node.input(1));
}
}
EXPECT_EQ(1, found);
}
TEST_F(ConstantFoldingTest, ControlDependenciesEmptyFetch) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output dflt = ops::Const(scope.WithOpName("dflt"), 3.14f, {1});
Output p1 = ops::PlaceholderWithDefault(scope.WithOpName("p1"), dflt, {1});
Output p2 = ops::PlaceholderWithDefault(scope.WithOpName("p2"), dflt, {1});
Output c =
ops::Const(scope.WithOpName("c").WithControlDependencies(p1), 10, {3});
Output i1 = ops::Identity(scope.WithOpName("i1"), {c});
Output i2 =
ops::Identity(scope.WithOpName("i2").WithControlDependencies(p2), {i1});
Output i3 = ops::Identity(scope.WithOpName("e"), {i2});
GrapplerItem item;
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
std::vector<string> expected_nodes = {"dflt", "p1", "p2", "c",
"i1", "i2", "e"};
EXPECT_EQ(output.node_size(), expected_nodes.size());
int i = 0;
int found = 0;
for (const auto& node : output.node()) {
EXPECT_EQ(expected_nodes[i], output.node(i).name());
i++;
if (node.name() == "i1") {
EXPECT_EQ("Const", node.op());
++found;
auto folded = EvaluateNodes(output, {"i1"});
auto expected = EvaluateNodes(item.graph, {"i1"});
EXPECT_EQ(1, expected.size());
EXPECT_EQ(1, folded.size());
test::ExpectTensorEqual<int>(folded[0], expected[0]);
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^p1", node.input(0));
}
if (node.name() == "i2") {
EXPECT_EQ("Const", node.op());
++found;
auto folded = EvaluateNodes(output, {"i2"});
auto expected = EvaluateNodes(item.graph, {"i2"});
EXPECT_EQ(1, expected.size());
EXPECT_EQ(1, folded.size());
test::ExpectTensorEqual<int>(folded[0], expected[0]);
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("^p1", node.input(0));
EXPECT_EQ("^p2", node.input(1));
}
}
EXPECT_EQ(2, found);
}
TEST_F(ConstantFoldingTest, ControlDependenciesDeduplicate) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output dflt = ops::Const(scope.WithOpName("dflt"), 3.14f, {1});
Output p1 = ops::PlaceholderWithDefault(scope.WithOpName("p1"), dflt, {1});
Output p2 = ops::PlaceholderWithDefault(scope.WithOpName("p2"), dflt, {1});
Output c =
ops::Const(scope.WithOpName("c").WithControlDependencies(p1), 10, {3});
Output i1 = ops::Identity(scope.WithOpName("i1")
.WithControlDependencies(p2)
.WithControlDependencies(p1),
{c});
Output i2 = ops::Identity(scope.WithOpName("i2"), {i1});
GrapplerItem item;
item.fetch.push_back("i2");
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
auto tensors_expected = EvaluateNodes(item.graph, item.fetch);
EXPECT_EQ(1, tensors_expected.size());
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
std::vector<string> expected_nodes = {"dflt", "p1", "p2", "i2"};
EXPECT_EQ(output.node_size(), expected_nodes.size());
int i = 0;
for (const auto& node : output.node()) {
EXPECT_EQ(expected_nodes[i], output.node(i).name());
i++;
if (node.name() == "i2") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("^p1", node.input(0));
EXPECT_EQ("^p2", node.input(1));
}
}
auto tensors = EvaluateNodes(output, item.fetch);
EXPECT_EQ(1, tensors.size());
test::ExpectTensorEqual<int>(tensors_expected[0], tensors[0]);
}
TEST_F(ConstantFoldingTest, VariableNumberOfOutputs) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
// Add a DynamicPartition node to the graph
Output input = ops::Const(scope.WithOpName("in0"), 314, {3, 4, 5});
Output indices = ops::Const(scope.WithOpName("indices"), 1, {3, 4});
int num_partitions = 4;
ops::DynamicPartition part(scope.WithOpName("partition"), input, indices,
num_partitions);
std::vector<string> outputs;
for (int i = 0; i < num_partitions; ++i) {
string part_out_name = strings::StrCat("part_out", i);
ops::Identity partition_out(scope.WithOpName(part_out_name),
{part.outputs[i]});
outputs.push_back(part_out_name);
}
GrapplerItem item;
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
// Add a ConcatOffset node to the graph
Tensor initial_val(DT_INT32, TensorShape({3}));
test::FillIota<int>(&initial_val, 7);
for (int i = 1; i < 5; ++i) {
TF_CHECK_OK(NodeDefBuilder(strings::StrCat("in", i), "Const")
.Attr("dtype", DT_INT32)
.Attr("value", initial_val)
.Finalize(item.graph.add_node()));
}
Tensor concat_dim(DT_INT32, TensorShape({}));
test::FillIota<int>(&concat_dim, 0);
TF_CHECK_OK(NodeDefBuilder("concat_dim", "Const")
.Attr("dtype", DT_INT32)
.Attr("value", concat_dim)
.Finalize(item.graph.add_node()));
TF_CHECK_OK(NodeDefBuilder("concat_offsets", "ConcatOffset")
.Input("concat_dim", 0, DT_INT32)
.Input({NodeDefBuilder::NodeOut("in1", 0, DT_INT32),
NodeDefBuilder::NodeOut("in2", 0, DT_INT32),
NodeDefBuilder::NodeOut("in3", 0, DT_INT32),
NodeDefBuilder::NodeOut("in4", 0, DT_INT32)})
.Finalize(item.graph.add_node()));
for (int i = 0; i < 4; ++i) {
string concat_offset_out_name = strings::StrCat("concat_offset_out", i);
TF_CHECK_OK(NodeDefBuilder(concat_offset_out_name, "Identity")
.Attr("T", DT_INT32)
.Input("concat_offsets", i, DT_INT32)
.Finalize(item.graph.add_node()));
outputs.push_back(concat_offset_out_name);
}
item.fetch = outputs;
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
int constant_folded = 0;
for (const auto& node : output.node()) {
if (node.name().find("part_out") != string::npos ||
node.name().find("concat_offset_out") != string::npos) {
++constant_folded;
EXPECT_EQ("Const", node.op());
}
}
EXPECT_EQ(8, constant_folded);
auto expected = EvaluateNodes(item.graph, outputs);
auto optimized = EvaluateNodes(output, outputs);
ASSERT_EQ(expected.size(), optimized.size());
for (int i = 0; i < expected.size(); ++i) {
test::ExpectTensorEqual<int>(expected[i], optimized[i]);
}
}
TEST_F(ConstantFoldingTest, ShapeMaterialization) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output v1 = ops::Variable(scope.WithOpName("v1"), {3}, DT_FLOAT);
Output v2 = ops::Variable(scope.WithOpName("v2"), {5, 7}, DT_FLOAT);
Output v3 = ops::Variable(scope.WithOpName("v3"), {11, 13}, DT_FLOAT);
Output rank = ops::Rank(scope.WithOpName("rank"), v1);
Output shape = ops::Shape(scope.WithOpName("shape"), v2);
Output size = ops::Size(scope.WithOpName("size"), v3);
Output p1 = ops::Multiply(scope.WithOpName("p1"), size, rank);
Output p2 = ops::Multiply(scope.WithOpName("p2"), p1, shape);
GrapplerItem item;
item.fetch.push_back("p2");
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
int found = 0;
for (const auto& node : output.node()) {
if (node.name() == "p2") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ(3, node.input_size());
EXPECT_EQ("^v3", node.input(0));
EXPECT_EQ("^v1", node.input(1));
EXPECT_EQ("^v2", node.input(2));
Tensor value;
CHECK(value.FromProto(node.attr().at("value").tensor()));
// rank = 1, shape = (5, 7), size = 143 = 11*13
// p2 = (715, 1001) = (5*143, 7*143)
EXPECT_EQ(715, value.flat<int>()(0));
EXPECT_EQ(1001, value.flat<int>()(1));
}
}
EXPECT_EQ(1, found);
auto v1_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({3}));
auto v2_t = GenerateRandomTensor<DT_FLOAT>({5, 7});
auto v3_t = GenerateRandomTensor<DT_FLOAT>({11, 13});
auto tensors_expected = EvaluateNodes(
item.graph, item.fetch, {{"v1", v1_t}, {"v2", v2_t}, {"v3", v3_t}});
EXPECT_EQ(1, item.fetch.size());
auto tensors = EvaluateNodes(output, item.fetch,
{{"v1", v1_t}, {"v2", v2_t}, {"v3", v3_t}});
EXPECT_EQ(1, item.fetch.size());
test::ExpectTensorEqual<int>(tensors_expected[0], tensors[0]);
}
TEST_F(ConstantFoldingTest, ShapeMaterializationEmptyFetch) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output v1 = ops::Variable(scope.WithOpName("v1"), {3}, DT_FLOAT);
Output v2 = ops::Variable(scope.WithOpName("v2"), {5, 7}, DT_FLOAT);
Output v3 = ops::Variable(scope.WithOpName("v3"), {11, 13}, DT_FLOAT);
Output rank = ops::Rank(scope.WithOpName("rank"), v1);
Output shape = ops::Shape(scope.WithOpName("shape"), v2);
Output size = ops::Size(scope.WithOpName("size"), v3);
Output p1 = ops::Multiply(scope.WithOpName("p1"), size, rank);
Output p2 = ops::Multiply(scope.WithOpName("p2"), p1, shape);
GrapplerItem item;
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
int found = 0;
for (const auto& node : output.node()) {
if (node.name() == "size") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^v3", node.input(0));
Tensor value;
CHECK(value.FromProto(node.attr().at("value").tensor()));
EXPECT_EQ(11 * 13, value.flat<int>()(0));
} else if (node.name() == "rank") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^v1", node.input(0));
Tensor value;
CHECK(value.FromProto(node.attr().at("value").tensor()));
EXPECT_EQ(1, value.flat<int>()(0));
} else if (node.name() == "shape") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^v2", node.input(0));
Tensor value;
CHECK(value.FromProto(node.attr().at("value").tensor()));
EXPECT_EQ(5, value.flat<int>()(0));
EXPECT_EQ(7, value.flat<int>()(1));
}
}
EXPECT_EQ(3, found);
auto v1_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({3}));
auto v2_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({5, 7}));
auto v3_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({11, 13}));
std::vector<string> fetch_nodes = {"p2"};
auto tensors_expected = EvaluateNodes(
item.graph, fetch_nodes, {{"v1", v1_t}, {"v2", v2_t}, {"v3", v3_t}});
EXPECT_EQ(1, tensors_expected.size());
auto tensors = EvaluateNodes(output, fetch_nodes,
{{"v1", v1_t}, {"v2", v2_t}, {"v3", v3_t}});
EXPECT_EQ(1, tensors.size());
test::ExpectTensorEqual<int>(tensors_expected[0], tensors[0]);
}
TEST_F(ConstantFoldingTest, ShapeMaterializationShapeN) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output v1 = ops::Variable(scope.WithOpName("v1"), {3, -1}, DT_FLOAT);
Output v2 = ops::Variable(scope.WithOpName("v2"), {}, DT_FLOAT);
Output v3 = ops::Variable(scope.WithOpName("v3"), {4, 6}, DT_FLOAT);
auto s = ops::ShapeN(scope.WithOpName("s"), {v1, v2, v3});
Output i1a = ops::Identity(scope.WithOpName("i1a"), s[0]);
Output i1b = ops::Identity(scope.WithOpName("i1b"), s[0]);
Output i2a = ops::Identity(scope.WithOpName("i2a"), s[1]);
Output i2b = ops::Identity(scope.WithOpName("i2b"), s[1]);
Output i2c = ops::Identity(scope.WithOpName("i2c"), s[1]);
Output i3a = ops::Identity(scope.WithOpName("i3a"), s[2]);
Output i3b = ops::Identity(scope.WithOpName("i3b"), s[2]);
GrapplerItem item;
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
int found = 0;
for (const auto& node : output.node()) {
EXPECT_NE(AddPrefixToNodeName("s-matshapes-0", kConstantFoldingConst),
node.name());
EXPECT_NE(AddPrefixToNodeName("s-matshapes-1", kConstantFoldingConst),
node.name());
if (node.name() == "i1a" || node.name() == "i1b") {
++found;
EXPECT_EQ("s", node.input(0));
}
if (node.name() == "i2a" || node.name() == "i2b" || node.name() == "i2c") {
++found;
EXPECT_EQ("s:1", node.input(0));
}
if (node.name() == "i3a" || node.name() == "i3b") {
++found;
EXPECT_EQ(AddPrefixToNodeName("s-matshapes-2", kConstantFoldingConst),
node.input(0));
}
if (node.name() == "s") {
++found;
EXPECT_EQ("ShapeN", node.op());
EXPECT_EQ("v1", node.input(0));
EXPECT_EQ("v2", node.input(1));
EXPECT_EQ("v3", node.input(2));
}
if (node.name() ==
AddPrefixToNodeName("s-matshapes-2", kConstantFoldingConst)) {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ("^s", node.input(0));
Tensor value;
CHECK(value.FromProto(node.attr().at("value").tensor()));
EXPECT_EQ(4, value.flat<int>()(0));
EXPECT_EQ(6, value.flat<int>()(1));
}
}
EXPECT_EQ(9, found);
auto v1_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({3, 4}));
auto v2_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({5, 6}));
auto v3_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({4, 6}));
const std::vector<string> fetch_nodes = {"i1a", "i1b", "i2a", "i2b",
"i2c", "i3a", "i3b"};
auto tensors_expected = EvaluateNodes(
item.graph, fetch_nodes, {{"v1", v1_t}, {"v2", v2_t}, {"v3", v3_t}});
EXPECT_EQ(fetch_nodes.size(), tensors_expected.size());
auto tensors = EvaluateNodes(output, fetch_nodes,
{{"v1", v1_t}, {"v2", v2_t}, {"v3", v3_t}});
EXPECT_EQ(fetch_nodes.size(), tensors.size());
for (int i = 0; i < fetch_nodes.size(); i++)
test::ExpectTensorEqual<int>(tensors_expected[i], tensors[i]);
}
TEST_F(ConstantFoldingTest, ShapeMaterializationShapeN_MultipleOutputs) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output v1 = ops::Variable(scope.WithOpName("v1"), {3, -1}, DT_FLOAT);
Output v2 = ops::Variable(scope.WithOpName("v2"), {4, 6}, DT_FLOAT);
auto s = ops::ShapeN(scope.WithOpName("s"), {v1, v2});
auto id_n = ops::IdentityN(scope.WithOpName("id_n"), {s[0], s[1]});
Output ia = ops::Identity(scope.WithOpName("ia"), id_n[0]);
Output ib = ops::Identity(scope.WithOpName("ib"), id_n[1]);
GrapplerItem item;
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
item.fetch.push_back("ia");
item.fetch.push_back("ib");
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
int found = 0;
for (const auto& node : output.node()) {
EXPECT_NE(AddPrefixToNodeName("s-matshapes-0", kConstantFoldingConst),
node.name());
if (node.name() == "s") {
++found;
EXPECT_EQ("ShapeN", node.op());
EXPECT_EQ("v1", node.input(0));
EXPECT_EQ("v2", node.input(1));
}
if (node.name() == "id_n") {
++found;
EXPECT_EQ("IdentityN", node.op());
EXPECT_EQ("s", node.input(0));
EXPECT_EQ(AddPrefixToNodeName("s-matshapes-1", kConstantFoldingConst),
node.input(1));
}
if (node.name() == "ia") {
++found;
EXPECT_EQ("id_n", node.input(0));
}
if (node.name() == "ib") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ("^s", node.input(0));
EXPECT_EQ("^id_n", node.input(1));
}
}
EXPECT_EQ(4, found);
auto v1_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({3, 4}));
auto v2_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({4, 6}));
auto tensors_expected =
EvaluateNodes(item.graph, item.fetch, {{"v1", v1_t}, {"v2", v2_t}});
EXPECT_EQ(2, tensors_expected.size());
auto tensors =
EvaluateNodes(output, item.fetch, {{"v1", v1_t}, {"v2", v2_t}});
EXPECT_EQ(2, tensors.size());
for (int i = 0; i < tensors.size(); i++)
test::ExpectTensorEqual<int>(tensors_expected[i], tensors[i]);
}
TEST_F(ConstantFoldingTest, SwitchNodesEmptyFetch) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
ops::Variable v_in(scope.WithOpName("v_in"), {3}, DT_FLOAT);
ops::Variable v_ctrl(scope.WithOpName("v_ctrl"), {}, DT_BOOL);
ops::Switch s1(scope.WithOpName("switch"), v_in, v_ctrl);
ops::Rank rank(scope.WithOpName("rank"), s1.output_false);
ops::Identity i(scope.WithOpName("i"), s1.output_true);
ops::Size size(scope.WithOpName("size"), i);
ops::Square p1(scope.WithOpName("p1"), rank);
ops::Square p2(scope.WithOpName("p2"), size);
ops::Merge m(scope.WithOpName("m"), {p1.y, p2.y});
Output predicate =
ops::Const(scope.WithOpName("false"), false, TensorShape({}));
Output constant =
ops::Const(scope.WithOpName("constant"), 1.0f, TensorShape({1}));
ops::Switch s2(scope.WithOpName("switch2"), constant, predicate);
ops::Identity statically_known(scope.WithOpName("i2"), s2.output_false);
ops::Identity never_generated(scope.WithOpName("i3"), s2.output_true);
ops::Merge m2(scope.WithOpName("m2"),
{statically_known.output, never_generated.output});
GrapplerItem item;
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
std::set<string> present_nodes = {"v_in", "v_ctrl",
"switch", "i",
"p1", "p2",
"m", "false",
"constant", "switch2",
"i2", "i3",
"m2", "ConstantFoldingCtrl/switch_0",
"rank", "size"};
std::set<string> not_present_nodes = {"ConstantFolding/switch2-0"};
EXPECT_EQ(present_nodes.size(), output.node_size());
int found = 0;
for (const auto& node : output.node()) {
EXPECT_TRUE(present_nodes.find(node.name()) != present_nodes.end())
<< node.name();
EXPECT_TRUE(not_present_nodes.find(node.name()) == not_present_nodes.end())
<< node.name();
present_nodes.erase(node.name());
not_present_nodes.erase(node.name());
if (node.name() == "rank") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^ConstantFoldingCtrl/switch_0", node.input(0));
}
if (node.name() == "size") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^i", node.input(0));
}
if (node.name() == "i2") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ(0, node.input_size());
}
if (node.name() == "i3") {
++found;
EXPECT_EQ("Identity", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("switch2:1", node.input(0));
}
}
EXPECT_EQ(4, found);
auto v_in_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({3}));
Tensor v_ctrl_t(DT_BOOL, TensorShape({}));
v_ctrl_t.flat<bool>()(0) = true;
std::vector<string> fetch_nodes = {"m", "m2"};
auto tensors_expected = EvaluateNodes(
item.graph, fetch_nodes, {{"v_in", v_in_t}, {"v_ctrl", v_ctrl_t}});
EXPECT_EQ(2, tensors_expected.size());
auto tensors = EvaluateNodes(output, fetch_nodes,
{{"v_in", v_in_t}, {"v_ctrl", v_ctrl_t}});
EXPECT_EQ(2, tensors.size());
test::ExpectTensorEqual<int>(tensors_expected[0], tensors[0]);
test::ExpectTensorNear<float>(tensors_expected[1], tensors[1], 1e-5);
v_ctrl_t.flat<bool>()(0) = false;
tensors_expected = EvaluateNodes(item.graph, fetch_nodes,
{{"v_in", v_in_t}, {"v_ctrl", v_ctrl_t}});
EXPECT_EQ(2, tensors_expected.size());
tensors = EvaluateNodes(output, fetch_nodes,
{{"v_in", v_in_t}, {"v_ctrl", v_ctrl_t}});
EXPECT_EQ(2, tensors.size());
test::ExpectTensorEqual<int>(tensors_expected[0], tensors[0]);
test::ExpectTensorNear<float>(tensors_expected[1], tensors[1], 1e-5);
}
TEST_F(ConstantFoldingTest, SwitchNodes) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
ops::Variable v_in(scope.WithOpName("v_in"), {3}, DT_FLOAT);
ops::Variable v_ctrl(scope.WithOpName("v_ctrl"), {}, DT_BOOL);
ops::Switch s1(scope.WithOpName("switch"), v_in, v_ctrl);
ops::Rank rank(scope.WithOpName("rank"), s1.output_false);
ops::Identity i(scope.WithOpName("i"), s1.output_true);
ops::Size size(scope.WithOpName("size"), i);
ops::Square p1(scope.WithOpName("p1"), rank);
ops::Square p2(scope.WithOpName("p2"), size);
ops::Merge m(scope.WithOpName("m"), {p1.y, p2.y});
Output predicate =
ops::Const(scope.WithOpName("false"), false, TensorShape({}));
Output constant =
ops::Const(scope.WithOpName("constant"), 1.0f, TensorShape({1}));
ops::Switch s2(scope.WithOpName("switch2"), constant, predicate);
ops::Identity statically_known(scope.WithOpName("i2"), s2.output_false);
ops::Identity never_generated(scope.WithOpName("i3"), s2.output_true);
ops::Merge m2(scope.WithOpName("m2"),
{statically_known.output, never_generated.output});
GrapplerItem item;
item.fetch.push_back("m");
item.fetch.push_back("m2");
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
std::set<string> present_nodes = {"v_in", "v_ctrl",
"switch", "i",
"p1", "p2",
"m", "false",
"constant", "switch2",
"i2", "i3",
"m2", "ConstantFoldingCtrl/switch_0"};
std::set<string> not_present_nodes = {"rank", "size",
"ConstantFolding/switch2-0"};
EXPECT_EQ(present_nodes.size(), output.node_size());
int found = 0;
for (const auto& node : output.node()) {
EXPECT_TRUE(present_nodes.find(node.name()) != present_nodes.end());
EXPECT_TRUE(not_present_nodes.find(node.name()) == not_present_nodes.end());
present_nodes.erase(node.name());
not_present_nodes.erase(node.name());
if (node.name() == "i2") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ(0, node.input_size());
}
if (node.name() == "i3") {
++found;
EXPECT_EQ("Identity", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("switch2:1", node.input(0));
}
}
EXPECT_EQ(2, found);
auto v_in_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({3}));
Tensor v_ctrl_t(DT_BOOL, TensorShape({}));
v_ctrl_t.flat<bool>()(0) = true;
auto tensors_expected = EvaluateNodes(
item.graph, item.fetch, {{"v_in", v_in_t}, {"v_ctrl", v_ctrl_t}});
EXPECT_EQ(2, tensors_expected.size());
auto tensors = EvaluateNodes(output, item.fetch,
{{"v_in", v_in_t}, {"v_ctrl", v_ctrl_t}});
EXPECT_EQ(2, tensors.size());
test::ExpectTensorEqual<int>(tensors_expected[0], tensors[0]);
test::ExpectTensorNear<float>(tensors_expected[1], tensors[1], 1e-5);
v_ctrl_t.flat<bool>()(0) = false;
tensors_expected = EvaluateNodes(item.graph, item.fetch,
{{"v_in", v_in_t}, {"v_ctrl", v_ctrl_t}});
EXPECT_EQ(2, tensors_expected.size());
tensors = EvaluateNodes(output, item.fetch,
{{"v_in", v_in_t}, {"v_ctrl", v_ctrl_t}});
EXPECT_EQ(2, tensors.size());
test::ExpectTensorEqual<int>(tensors_expected[0], tensors[0]);
test::ExpectTensorNear<float>(tensors_expected[1], tensors[1], 1e-5);
}
TEST_F(ConstantFoldingTest, MergeNodes) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output x =
ops::RandomNormal(scope.WithOpName("x"), {3, 5}, DataType::DT_FLOAT);
Output y =
ops::RandomNormal(scope.WithOpName("y"), {3, 5}, DataType::DT_FLOAT);
Output const1 =
ops::Const(scope.WithOpName("const1").WithControlDependencies(x), 2.7f,
TensorShape({3, 5}));
Output const2 =
ops::Const(scope.WithOpName("const2"), 3.14f, TensorShape({3, 5}));
Output const3 =
ops::Const(scope.WithOpName("const3").WithControlDependencies(x), 3.14f,
TensorShape({3, 5}));
// Create 3 merge nodes: m1 is foldable, m2 and m3 aren't.
ops::Merge m1(scope.WithOpName("m1"), {x, const1, const2});
ops::Merge m2(scope.WithOpName("m2"), {const1, const3});
ops::Merge m3(scope.WithOpName("m3"), {x, y});
// m4 is not foldable because the only constant input
// has a control input, so we cannot know if it will be
// triggered.
ops::Merge m4(scope.WithOpName("m4"), {x, const1});
ops::Identity out1(scope.WithOpName("out1"), m1.output);
ops::Identity idx1(scope.WithOpName("idx1"), m1.value_index);
ops::Identity out2(scope.WithOpName("out2"), m2.output);
ops::Identity idx2(scope.WithOpName("idx2"), m2.value_index);
ops::Identity out3(scope.WithOpName("out3"), m3.output);
ops::Identity idx3(scope.WithOpName("idx3"), m3.value_index);
ops::Identity out4(scope.WithOpName("out4"), m4.output);
ops::Identity idx4(scope.WithOpName("idx4"), m4.value_index);
GrapplerItem item;
item.fetch = {"out1", "idx1", "out2", "idx2", "out3", "idx3", "out4", "idx4"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(19, output.node_size());
int found_nodes = 0;
for (const auto& node : output.node()) {
if (node.name() == "out1") {
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^m1", node.input(0));
++found_nodes;
} else if (node.name() == "idx1") {
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^m1", node.input(0));
++found_nodes;
} else if (node.name() == "ConstantFolding/m1") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^m1", node.input(0));
++found_nodes;
} else if (node.name() == "ConstantFolding/m1_index") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^m1", node.input(0));
++found_nodes;
} else if (node.name() == "out2") {
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("m2", node.input(0));
++found_nodes;
} else if (node.name() == "idx2") {
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("m2:1", node.input(0));
++found_nodes;
} else if (node.name() == "out3") {
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("m3", node.input(0));
++found_nodes;
} else if (node.name() == "idx3") {
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("m3:1", node.input(0));
++found_nodes;
} else if (node.name() == "out4") {
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("m4", node.input(0));
++found_nodes;
} else if (node.name() == "idx4") {
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("m4:1", node.input(0));
++found_nodes;
}
}
// Make sure the graph contains all the nodes we're expecting.
EXPECT_EQ(8, found_nodes);
std::vector<string> fetch = {"out1", "idx1"};
auto tensors = EvaluateNodes(output, fetch);
EXPECT_EQ(2, tensors.size());
const Tensor& out_value = tensors[0];
EXPECT_EQ(3 * 5, out_value.NumElements());
for (int i = 0; i < 3 * 5; ++i) {
EXPECT_EQ(3.14f, out_value.flat<float>()(i));
}
const Tensor& out_idx = tensors[1];
EXPECT_EQ(1, out_idx.NumElements());
EXPECT_EQ(2, out_idx.flat<int32>()(0));
}
TEST_F(ConstantFoldingTest, SplitRemoval) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output in1 =
ops::Variable(scope.WithOpName("in1"), TensorShape({2}), DT_FLOAT);
Output in2 =
ops::Variable(scope.WithOpName("in2"), TensorShape({4}), DT_FLOAT);
auto split_dim = ops::Const(scope.WithOpName("split_dim"), {0}, {});
ops::Split s1(scope.WithOpName("s1"), split_dim, in1, 1);
ops::Split s2(scope.WithOpName("s2"), split_dim, in2, 2);
ops::Add out(scope.WithOpName("out"), s1[0], s2[0]);
GrapplerItem item;
item.fetch = {"out"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef got;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("in1", "VariableV2", {}, {}, &want);
AddNode("in2", "VariableV2", {}, {}, &want);
AddNode("split_dim", "Const", {}, {}, &want);
AddNode("s1", "Identity", {"in1", AsControlDependency("split_dim")}, {},
&want);
AddNode("s2", "Split", {"split_dim", "in2"}, {}, &want);
AddNode("out", "Add", {"s1", "s2"}, {}, &want);
CompareGraphs(want, got);
auto in1_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({2}));
auto in2_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({4}));
auto tensors_expected =
EvaluateNodes(item.graph, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(1, tensors_expected.size());
auto tensors =
EvaluateNodes(got, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(1, tensors.size());
test::ExpectTensorNear<float>(tensors_expected[0], tensors[0], 1e-5);
}
TEST_F(ConstantFoldingTest, SplitVRemoval) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output in1 =
ops::Variable(scope.WithOpName("in1"), TensorShape({2}), DT_FLOAT);
Output in2 =
ops::Variable(scope.WithOpName("in2"), TensorShape({5}), DT_FLOAT);
auto split_dim = ops::Const(scope.WithOpName("split_dim"), {0}, {});
auto size_splits1 = ops::Const(scope.WithOpName("size_splits1"), {2}, {1});
auto size_splits2 = ops::Const(scope.WithOpName("size_splits2"), {2, 3}, {2});
ops::SplitV s1(scope.WithOpName("s1"), in1, size_splits1, split_dim, 1);
ops::SplitV s2(scope.WithOpName("s2"), in2, size_splits2, split_dim, 2);
ops::Add out(scope.WithOpName("out"), s1[0], s2[0]);
GrapplerItem item;
item.fetch = {"out"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef got;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("in1", "VariableV2", {}, {}, &want);
AddNode("in2", "VariableV2", {}, {}, &want);
AddNode("split_dim", "Const", {}, {}, &want);
AddNode("size_splits1", "Const", {}, {}, &want);
AddNode("size_splits2", "Const", {}, {}, &want);
AddNode("s1", "Identity",
{"in1", AsControlDependency("size_splits1"),
AsControlDependency("split_dim")},
{}, &want);
AddNode("s2", "SplitV", {"in2", "size_splits2", "split_dim"}, {}, &want);
AddNode("out", "Add", {"s1", "s2"}, {}, &want);
CompareGraphs(want, got);
auto in1_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({2}));
auto in2_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({5}));
auto tensors_expected =
EvaluateNodes(item.graph, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(1, tensors_expected.size());
auto tensors =
EvaluateNodes(got, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(1, tensors.size());
test::ExpectTensorNear<float>(tensors_expected[0], tensors[0], 1e-5);
}
TEST_F(ConstantFoldingTest, TransposeOnSize1DimsRemoval) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output in1 = ops::Variable(scope.WithOpName("in1"), TensorShape({1, 2, 4, 1}),
DT_FLOAT);
Output p1 = ops::Const(scope.WithOpName("p1"), {3, 2, 1, 0}, {4});
Output in2 = ops::Variable(scope.WithOpName("in2"), TensorShape({1, 4, 2, 1}),
DT_FLOAT);
Output p2 = ops::Const(scope.WithOpName("p2"), {3, 1, 2, 0}, {4});
ops::Transpose t1(scope.WithOpName("t1"), in1, p1);
ops::Transpose t2(scope.WithOpName("t2").WithControlDependencies({in1}), in2,
p2);
ops::Add out1(scope.WithOpName("out1"), t1, t2);
GrapplerItem item;
item.fetch = {"out1"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef got;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("in1", "VariableV2", {}, {}, &want);
AddNode("in2", "VariableV2", {}, {}, &want);
AddNode("p1", "Const", {}, {}, &want);
AddNode("p2", "Const", {}, {}, &want);
AddNode("t1", "Transpose", {"in1", "p1"}, {}, &want);
AddNode("t2", "Identity",
{"in2", AsControlDependency("in1"), AsControlDependency("p2")}, {},
&want);
AddNode("out1", "Add", {"t1", "t2"}, {}, &want);
CompareGraphs(want, got);
}
TEST_F(ConstantFoldingTest, RandomShuffleOnScalarRemoval) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output in1 =
ops::Variable(scope.WithOpName("in1"), TensorShape({}), DT_FLOAT);
Output in2 =
ops::Variable(scope.WithOpName("in2"), TensorShape({}), DT_FLOAT);
ops::RandomShuffle s1(scope.WithOpName("s1"), in1);
ops::RandomShuffle s2(scope.WithOpName("s2").WithControlDependencies({in1}),
in2);
ops::Add out1(scope.WithOpName("out1"), s1, s2);
ops::Identity out2(scope.WithOpName("out2"), s2);
GrapplerItem item;
item.fetch = {"out1", "out2"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef got;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("in1", "VariableV2", {}, {}, &want);
AddNode("in2", "VariableV2", {}, {}, &want);
AddNode("s1", "Identity", {"in1"}, {}, &want);
AddNode("s2", "Identity", {"in2", AsControlDependency("in1")}, {}, &want);
AddNode("out1", "Add", {"s1", "s2"}, {}, &want);
AddNode("out2", "Identity", {"s2"}, {}, &want);
CompareGraphs(want, got);
auto in1_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({}));
auto in2_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({}));
auto tensors_expected =
EvaluateNodes(item.graph, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(2, tensors_expected.size());
auto tensors =
EvaluateNodes(got, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(2, tensors.size());
for (int i = 0; i < tensors.size(); i++)
test::ExpectTensorNear<float>(tensors_expected[i], tensors[i], 1e-5);
}
TEST_F(ConstantFoldingTest, ReverseOnSize1DimsRemoval) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output in1 = ops::Variable(scope.WithOpName("in1"), TensorShape({1, 2, 4, 1}),
DT_FLOAT);
Output a1 = ops::Const(scope.WithOpName("a1"), {3, 2, 1, 0}, {4});
Output in2 = ops::Variable(scope.WithOpName("in2"), TensorShape({1, 2, 4, 1}),
DT_FLOAT);
Output a2 = ops::Const(scope.WithOpName("a2"), {0, 3}, {2});
ops::Reverse r1(scope.WithOpName("r1"), in1, a1);
ops::Reverse r2(scope.WithOpName("r2").WithControlDependencies({in1}), in2,
a2);
ops::Add out1(scope.WithOpName("out1"), r1, r2);
GrapplerItem item;
item.fetch = {"out1"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef got;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("in1", "VariableV2", {}, {}, &want);
AddNode("in2", "VariableV2", {}, {}, &want);
AddNode("a1", "Const", {}, {}, &want);
AddNode("a2", "Const", {}, {}, &want);
AddNode("r1", "ReverseV2", {"in1", "a1"}, {}, &want);
AddNode("r2", "Identity",
{"in2", AsControlDependency("in1"), AsControlDependency("a2")}, {},
&want);
AddNode("out1", "Add", {"r1", "r2"}, {}, &want);
CompareGraphs(want, got);
}
TEST_F(ConstantFoldingTest, SliceWithSameDimensionRemoval) {
{ // size = {3, 5}
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
auto in1 = ops::Variable(scope.WithOpName("in1"), {3, 5}, DT_FLOAT);
auto begin = ops::Const(scope.WithOpName("begin"), {0, 0}, {2});
auto size = ops::Const(scope.WithOpName("size"), {3, 5}, {2});
Output in2 = ops::Variable(scope.WithOpName("in2"), {4, 6}, DT_FLOAT);
ops::Slice s1(scope.WithOpName("s1"), in1, begin, size);
ops::Slice s2(scope.WithOpName("s2"), in2, begin, size);
ops::Add out(scope.WithOpName("out"), s1, s2);
GrapplerItem item;
item.fetch = {"out"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef got;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("in1", "VariableV2", {}, {}, &want);
AddNode("in2", "VariableV2", {}, {}, &want);
AddNode("begin", "Const", {}, {}, &want);
AddNode("size", "Const", {}, {}, &want);
AddNode("s1", "Identity",
{"in1", AsControlDependency("begin"), AsControlDependency("size")},
{}, &want);
AddNode("s2", "Slice", {"in2", "begin", "size"}, {}, &want);
AddNode("out", "Add", {"s1", "s2"}, {}, &want);
CompareGraphs(want, got);
auto in1_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({3, 5}));
auto in2_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({4, 6}));
auto tensors_expected =
EvaluateNodes(item.graph, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(1, tensors_expected.size());
auto tensors =
EvaluateNodes(got, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(1, tensors.size());
test::ExpectTensorNear<float>(tensors_expected[0], tensors[0], 1e-5);
}
{ // size = {-1, -1}
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
auto in1 =
ops::Variable(scope.WithOpName("in1"), {3, 5}, DataType::DT_FLOAT);
auto begin1 = ops::Const(scope.WithOpName("begin1"), {0, 0}, {2});
auto begin2 = ops::Const(scope.WithOpName("begin2"), {1, 1}, {2});
auto size = ops::Const(scope.WithOpName("size"), {-1, -1}, {2});
Output in2 =
ops::Variable(scope.WithOpName("in2"), {4, 6}, DataType::DT_FLOAT);
ops::Slice s1(scope.WithOpName("s1"), in1, begin1, size);
ops::Slice s2(scope.WithOpName("s2"), in2, begin2, size);
ops::Add out(scope.WithOpName("out"), s1, s2);
GrapplerItem item;
item.fetch = {"out"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef got;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("in1", "VariableV2", {}, {}, &want);
AddNode("in2", "VariableV2", {}, {}, &want);
AddNode("begin1", "Const", {}, {}, &want);
AddNode("begin2", "Const", {}, {}, &want);
AddNode("size", "Const", {}, {}, &want);
AddNode("s1", "Identity",
{"in1", AsControlDependency("begin1"), AsControlDependency("size")},
{}, &want);
AddNode("s2", "Slice", {"in2", "begin2", "size"}, {}, &want);
AddNode("out", "Add", {"s1", "s2"}, {}, &want);
CompareGraphs(want, got);
auto in1_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({3, 5}));
auto in2_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({4, 6}));
auto tensors_expected =
EvaluateNodes(item.graph, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(1, tensors_expected.size());
auto tensors =
EvaluateNodes(got, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(1, tensors.size());
test::ExpectTensorNear<float>(tensors_expected[0], tensors[0], 1e-5);
}
}
TEST_F(ConstantFoldingTest, StridedSliceWithSameDimensionRemoval) {
{ // no mask
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
auto in1 = ops::Variable(scope.WithOpName("in1"), {3, 5, 2}, DT_FLOAT);
auto begin = ops::Const(scope.WithOpName("begin"), {0, 0}, {2});
auto end = ops::Const(scope.WithOpName("end"), {3, 5}, {2});
auto strides = ops::Const(scope.WithOpName("strides"), {1, 1}, {2});
Output in2 = ops::Variable(scope.WithOpName("in2"), {4, 6, 2}, DT_FLOAT);
ops::StridedSlice s1(scope.WithOpName("s1"), in1, begin, end, strides);
ops::StridedSlice s2(scope.WithOpName("s2"), in2, begin, end, strides);
ops::Add out(scope.WithOpName("out"), s1, s2);
GrapplerItem item;
item.fetch = {"out"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef got;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("in1", "VariableV2", {}, {}, &want);
AddNode("in2", "VariableV2", {}, {}, &want);
AddNode("begin", "Const", {}, {}, &want);
AddNode("end", "Const", {}, {}, &want);
AddNode("strides", "Const", {}, {}, &want);
AddNode("s1", "Identity",
{"in1", AsControlDependency("begin"), AsControlDependency("end"),
AsControlDependency("strides")},
{}, &want);
AddNode("s2", "StridedSlice", {"in2", "begin", "end", "strides"}, {},
&want);
AddNode("out", "Add", {"s1", "s2"}, {}, &want);
CompareGraphs(want, got);
auto in1_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({3, 5, 2}));
auto in2_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({4, 6, 2}));
auto tensors_expected =
EvaluateNodes(item.graph, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(1, tensors_expected.size());
auto tensors =
EvaluateNodes(got, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(1, tensors.size());
test::ExpectTensorNear<float>(tensors_expected[0], tensors[0], 1e-5);
}
{ // with begin/end/ellipsis mask
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
// s1 = in1[:, ..., 0:5, 0:6]
auto in1 =
ops::Variable(scope.WithOpName("in1"), {2, 3, 4, 5, 6}, DT_FLOAT);
auto begin1 = ops::Const(scope.WithOpName("begin1"), {0, 0, 0}, {3});
auto end1 = ops::Const(scope.WithOpName("end1"), {0, 5, 6}, {3});
auto strides1 = ops::Const(scope.WithOpName("strides1"), {1, 1, 1}, {3});
ops::StridedSlice s1(
scope.WithOpName("s1"), in1, begin1, end1, strides1,
ops::StridedSlice::Attrs().BeginMask(1).EndMask(1).EllipsisMask(2));
Output in2 =
ops::Variable(scope.WithOpName("in2"), {5, 8, 5, 6, 9}, DT_FLOAT);
auto begin2 = ops::Const(scope.WithOpName("begin2"), {0, 0, 0, 0, 0}, {5});
auto end2 = ops::Const(scope.WithOpName("end2"), {2, 3, 4, 5, 6}, {5});
auto strides2 =
ops::Const(scope.WithOpName("strides2"), {1, 1, 1, 1, 1}, {5});
ops::StridedSlice s2(scope.WithOpName("s2"), in2, begin2, end2, strides2);
ops::Add out(scope.WithOpName("out"), s1, s2);
GrapplerItem item;
item.fetch = {"out"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef got;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("in1", "VariableV2", {}, {}, &want);
AddNode("in2", "VariableV2", {}, {}, &want);
AddNode("begin1", "Const", {}, {}, &want);
AddNode("end1", "Const", {}, {}, &want);
AddNode("strides1", "Const", {}, {}, &want);
AddNode("s1", "Identity",
{"in1", AsControlDependency("begin1"), AsControlDependency("end1"),
AsControlDependency("strides1")},
{}, &want);
AddNode("begin2", "Const", {}, {}, &want);
AddNode("end2", "Const", {}, {}, &want);
AddNode("strides2", "Const", {}, {}, &want);
AddNode("s2", "StridedSlice", {"in2", "begin2", "end2", "strides2"}, {},
&want);
AddNode("out", "Add", {"s1", "s2"}, {}, &want);
CompareGraphs(want, got);
auto in1_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({2, 3, 4, 5, 6}));
auto in2_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({5, 8, 5, 6, 9}));
auto tensors_expected =
EvaluateNodes(item.graph, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(1, tensors_expected.size());
auto tensors =
EvaluateNodes(got, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(1, tensors.size());
test::ExpectTensorNear<float>(tensors_expected[0], tensors[0], 1e-5);
}
}
TEST_F(ConstantFoldingTest, TileWithMultipliesBeingOne) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
auto in1 = ops::Variable(scope.WithOpName("in1"), {4, 6}, DT_FLOAT);
auto in2 = ops::Variable(scope.WithOpName("in2"), {4, 3}, DT_FLOAT);
auto multiplies1 = ops::Const(scope.WithOpName("multiplies1"), {1, 1}, {2});
auto multiplies2 = ops::Const(scope.WithOpName("multiplies2"), {1, 2}, {2});
ops::Tile t1(scope.WithOpName("t1"), in1, multiplies1);
ops::Tile t2(scope.WithOpName("t2"), in2, multiplies2);
ops::Add out(scope.WithOpName("out"), t1, t2);
GrapplerItem item;
item.fetch = {"out"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef got;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("in1", "VariableV2", {}, {}, &want);
AddNode("in2", "VariableV2", {}, {}, &want);
AddNode("multiplies1", "Const", {}, {}, &want);
AddNode("multiplies2", "Const", {}, {}, &want);
AddNode("t1", "Identity", {"in1", AsControlDependency("multiplies1")}, {},
&want);
AddNode("t2", "Tile", {"in2", "multiplies2"}, {}, &want);
AddNode("out", "Add", {"t1", "t2"}, {}, &want);
CompareGraphs(want, got);
}
TEST_F(ConstantFoldingTest, MergeConcat) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output in1 = ops::Variable(scope.WithOpName("in1"), {4, 6}, DT_FLOAT);
Output in2 = ops::Variable(scope.WithOpName("in2"), {4, 6}, DT_FLOAT);
Output in3 = ops::Variable(scope.WithOpName("in3"), {4, 6}, DT_FLOAT);
Output axis = ops::Const(scope.WithOpName("axis"), 0, {});
ops::Concat c1(scope.WithOpName("c1"), {in1, in2}, axis);
ops::Concat c2(scope.WithOpName("c2"), {Output(c1), in3}, axis);
GrapplerItem item;
item.fetch = {"c2"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef got;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("in1", "VariableV2", {}, {}, &want);
AddNode("in2", "VariableV2", {}, {}, &want);
AddNode("in3", "VariableV2", {}, {}, &want);
AddNode("axis", "Const", {}, {}, &want);
AddNode("c2", "ConcatV2", {"in1", "in2", "in3", "axis"}, {}, &want);
CompareGraphs(want, got);
}
TEST_F(ConstantFoldingTest, MergeConcat_SameInput) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output in1 = ops::Variable(scope.WithOpName("in1"), {4, 6}, DT_FLOAT);
Output in2 = ops::Variable(scope.WithOpName("in2"), {4, 6}, DT_FLOAT);
Output in3 = ops::Variable(scope.WithOpName("in3"), {4, 6}, DT_FLOAT);
Output axis = ops::Const(scope.WithOpName("axis"), 0, {});
ops::Concat c1(scope.WithOpName("c1"), {in1, in2}, axis);
ops::Concat c2(scope.WithOpName("c2"), {Output(c1), in3, Output(c1)}, axis);
GrapplerItem item;
item.fetch = {"c2"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef got;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("in1", "VariableV2", {}, {}, &want);
AddNode("in2", "VariableV2", {}, {}, &want);
AddNode("in3", "VariableV2", {}, {}, &want);
AddNode("axis", "Const", {}, {}, &want);
AddNode("c2", "ConcatV2", {"in1", "in2", "in3", "in1", "in2", "axis"}, {},
&want);
CompareGraphs(want, got);
}
TEST_F(ConstantFoldingTest, MergeConcat_ConcatWithConst) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output in1 = ops::Variable(scope.WithOpName("in1"), {2, 6}, DT_FLOAT);
Output in2 = ops::Variable(scope.WithOpName("in2"), {}, DT_FLOAT);
Output in3 = ops::Variable(scope.WithOpName("in3"), {4, 6}, DT_FLOAT);
Output axis = ops::Const(scope.WithOpName("axis"), 0, {});
ops::Concat c1(scope.WithOpName("c1"), {in1, in2}, axis);
ops::Concat c2(scope.WithOpName("c2"), {Output(c1), in3}, axis);
GrapplerItem item;
item.fetch = {"c2"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef got;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("in1", "VariableV2", {}, {}, &want);
AddNode("in2", "VariableV2", {}, {}, &want);
AddNode("in3", "VariableV2", {}, {}, &want);
AddNode("axis", "Const", {}, {}, &want);
AddNode("c2", "ConcatV2", {"in1", "in2", "in3", "axis"}, {}, &want);
CompareGraphs(want, got);
}
TEST_F(ConstantFoldingTest, MergeConcat_AxisMismatch) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output in1 = ops::Variable(scope.WithOpName("in1"), {2, 5}, DT_FLOAT);
Output in2 = ops::Variable(scope.WithOpName("in2"), {}, DT_FLOAT);
Output in3 = ops::Variable(scope.WithOpName("in3"), {4, 6}, DT_FLOAT);
Output axis1 = ops::Const(scope.WithOpName("axis1"), 0, {});
Output axis2 = ops::Const(scope.WithOpName("axis2"), 1, {});
ops::Concat c1(scope.WithOpName("c1"), {in1, in2}, axis2);
ops::Concat c2(scope.WithOpName("c2"), {Output(c1), in3}, axis1);
GrapplerItem item;
item.fetch = {"c2"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef got;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("in1", "VariableV2", {}, {}, &want);
AddNode("in2", "VariableV2", {}, {}, &want);
AddNode("in3", "VariableV2", {}, {}, &want);
AddNode("axis1", "Const", {}, {}, &want);
AddNode("axis2", "Const", {}, {}, &want);
AddNode("c1", "ConcatV2", {"in1", "in2", "axis2"}, {}, &want);
AddNode("c2", "ConcatV2", {"c1", "in3", "axis1"}, {}, &want);
CompareGraphs(want, got);
}
TEST_F(ConstantFoldingTest, MergeConcat_PartialFolding) {
Scope scope = Scope::NewRootScope();
Output c1 = ops::Const(scope.WithOpName("c1"), 1.0f, {2, 2});
Output c2 = ops::Const(scope.WithOpName("c2"), 2.0f, {2, 2});
Output c3 = ops::Const(scope.WithOpName("c3"), 3.0f, {2, 2});
Output c4 = ops::Const(scope.WithOpName("c4"), 4.0f, {2, 2});
Output ph = ops::Placeholder(scope.WithOpName("ph"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output axis = ops::Const(scope.WithOpName("axis"), 0, {});
ops::Concat concat1(scope.WithOpName("concat1"), {c1, c2, ph}, axis);
ops::Concat concat2(scope.WithOpName("concat2"), {c3, c4, Output(concat1)},
axis);
GrapplerItem item;
item.fetch = {"concat2"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(nullptr);
GraphDef got;
Status status = optimizer.Optimize(nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("ConstantFolding/concat2_partial_split_0", "Const", {}, {}, &want);
AddNode("axis", "Const", {}, {}, &want);
AddNode("ph", "Placeholder", {}, {}, &want);
AddNode("concat2", "ConcatV2",
{"ConstantFolding/concat2_partial_split_0", "ph", "axis"}, {}, &want);
CompareGraphs(want, got);
}
TEST_F(ConstantFoldingTest, PaddingWithZeroSize) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
auto in1 = ops::Variable(scope.WithOpName("in1"), {4, 6}, DT_INT32);
auto in2 = ops::Variable(scope.WithOpName("in2"), {2, 2}, DT_INT32);
auto paddings1 =
ops::Const(scope.WithOpName("paddings1"), {0, 0, 0, 0}, {2, 2});
auto paddings2 =
ops::Const(scope.WithOpName("paddings2"), {1, 1, 2, 2}, {2, 2});
auto c1 = ops::Const(scope.WithOpName("c1"), 1);
auto c2 = ops::Const(scope.WithOpName("c2"), 1);
ops::PadV2 p1(scope.WithOpName("p1"), in1, paddings1, c1);
ops::PadV2 p2(scope.WithOpName("p2"), in2, paddings2, c2);
ops::Add out(scope.WithOpName("out"), p1, p2);
GrapplerItem item;
item.fetch = {"out"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef got;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("in1", "VariableV2", {}, {}, &want);
AddNode("in2", "VariableV2", {}, {}, &want);
AddNode("paddings1", "Const", {}, {}, &want);
AddNode("paddings2", "Const", {}, {}, &want);
AddNode("c1", "Const", {}, {}, &want);
AddNode("c2", "Const", {}, {}, &want);
AddNode("p1", "Identity",
{"in1", AsControlDependency("paddings1"), AsControlDependency("c1")},
{}, &want);
AddNode("p2", "PadV2", {"in2", "paddings2", "c2"}, {}, &want);
AddNode("out", "Add", {"p1", "p2"}, {}, &want);
CompareGraphs(want, got);
auto in1_t = GenerateRandomTensor<DT_INT32>(TensorShape({4, 6}));
auto in2_t = GenerateRandomTensor<DT_INT32>(TensorShape({2, 2}));
auto tensors_expected =
EvaluateNodes(item.graph, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(1, tensors_expected.size());
auto tensors =
EvaluateNodes(got, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(1, tensors.size());
test::ExpectTensorEqual<int>(tensors_expected[0], tensors[0]);
}
TEST_F(ConstantFoldingTest, SqueezeWithAllDimensionsGreaterThanOne) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
auto in1 = ops::Variable(scope.WithOpName("in1"), {2, 3}, DT_INT32);
auto in2 = ops::Variable(scope.WithOpName("in2"), {1, 2, 3, 1}, DT_INT32);
ops::Squeeze s1(scope.WithOpName("s1"), in1);
ops::Squeeze s2(scope.WithOpName("s2"), in2);
ops::Add out(scope.WithOpName("out"), s1, s2);
GrapplerItem item;
item.fetch = {"out"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef got;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &got);
TF_EXPECT_OK(status);
GraphDef want;
AddNode("in1", "VariableV2", {}, {}, &want);
AddNode("in2", "VariableV2", {}, {}, &want);
AddNode("s1", "Identity", {"in1"}, {}, &want);
AddNode("s2", "Squeeze", {"in2"}, {}, &want);
AddNode("out", "Add", {"s1", "s2"}, {}, &want);
CompareGraphs(want, got);
auto in1_t = GenerateRandomTensor<DT_INT32>(TensorShape({2, 3}));
auto in2_t = GenerateRandomTensor<DT_INT32>(TensorShape({1, 2, 3, 1}));
auto tensors_expected =
EvaluateNodes(item.graph, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(1, tensors_expected.size());
auto tensors =
EvaluateNodes(got, item.fetch, {{"in1", in1_t}, {"in2", in2_t}});
EXPECT_EQ(1, tensors.size());
test::ExpectTensorEqual<int>(tensors_expected[0], tensors[0]);
}
TEST_F(ConstantFoldingTest, NoOpReduction) {
// Build a simple graph with reductions that can be reduced to the
// identity.
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output v = ops::Variable(scope.WithOpName("v"), {3, 5, 7}, DT_FLOAT);
Output c =
ops::Const(scope.WithOpName("c").WithControlDependencies(v), 0, {0});
Output i = ops::Identity(scope.WithOpName("i"), c);
Output p = ops::Prod(scope.WithOpName("p"), v, i);
Output s = ops::Square(scope.WithOpName("s"), p);
Output v2 = ops::Variable(scope.WithOpName("v2"), {3, 5, 1}, DT_FLOAT);
Output c2 =
ops::Const(scope.WithOpName("c2").WithControlDependencies(v), 2, {1});
ops::Prod::Attrs attr;
attr = attr.KeepDims(true);
Output p2 = ops::Prod(scope.WithOpName("p2"), v2, c2, attr);
// Test with unknown input shape.
Output a = ops::Placeholder(scope.WithOpName("a"), DT_FLOAT);
Output p3 = ops::Prod(scope.WithOpName("p3"), a, i, attr);
GrapplerItem item;
item.fetch = {"s", "p2", "p3"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
int found = 0;
for (const auto& node : output.node()) {
if (node.name() == "p") {
found++;
EXPECT_EQ("Identity", node.op());
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("v", node.input(0));
EXPECT_EQ("^i", node.input(1));
} else if (node.name() == "p2") {
found++;
EXPECT_EQ("Identity", node.op());
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("v2", node.input(0));
EXPECT_EQ("^c2", node.input(1));
} else if (node.name() == "p3") {
found++;
EXPECT_EQ("Identity", node.op());
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("a", node.input(0));
EXPECT_EQ("^i", node.input(1));
}
}
EXPECT_EQ(3, found);
auto v_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({3, 5, 7}));
auto v2_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({3, 5, 1}));
auto a_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({3, 5, 7}));
auto tensors_expected = EvaluateNodes(item.graph, item.fetch,
{{"v", v_t}, {"v2", v2_t}, {"a", a_t}});
EXPECT_EQ(3, tensors_expected.size());
auto tensors =
EvaluateNodes(output, item.fetch, {{"v", v_t}, {"v2", v2_t}, {"a", a_t}});
EXPECT_EQ(3, tensors.size());
test::ExpectTensorNear<float>(tensors_expected[0], tensors[0], 1e-5);
test::ExpectTensorNear<float>(tensors_expected[1], tensors[1], 1e-5);
test::ExpectTensorNear<float>(tensors_expected[2], tensors[2], 1e-5);
}
TEST_F(ConstantFoldingTest, SingleElementEmptyAxisReduction) {
// Build a simple graph with reductions that involve single-element input and
// no axes to reduce along.
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output input_var_three_dim = ops::Variable(
scope.WithOpName("input_var_three_dim"), {1, 1, 1}, DT_FLOAT);
Output input_var_one_dim =
ops::Variable(scope.WithOpName("input_var_one_dim"), {1}, DT_FLOAT);
Output one_axis = ops::Const(scope.WithOpName("one_axis"), {0}, {1});
Output multiple_axes =
ops::Const(scope.WithOpName("multiple_axes"), {1, 0}, {2});
Output variable_axis =
ops::Variable(scope.WithOpName("input_var_axis"), {1}, DT_INT32);
ops::Mean::Attrs attr;
attr = attr.KeepDims(false);
// Should be optimized to Reshape.
Output mean_1 = ops::Mean(scope.WithOpName("mean_1"), input_var_three_dim,
one_axis, attr.KeepDims(false));
Output mean_2 = ops::Mean(scope.WithOpName("mean_2"), input_var_three_dim,
multiple_axes, attr.KeepDims(false));
// Should remain as-is, since OutputProperties will not be known this node.
Output mean_3 = ops::Mean(scope.WithOpName("mean_3"), input_var_one_dim,
one_axis, attr.KeepDims(false));
// Should remain as-is.
Output mean_4 = ops::Mean(scope.WithOpName("mean_4"), input_var_three_dim,
variable_axis, attr.KeepDims(false));
// Should be optimized to Identity, since KeepDims=true.
Output mean_5 = ops::Mean(scope.WithOpName("mean_5"), input_var_three_dim,
multiple_axes, attr.KeepDims(true));
GrapplerItem item;
item.fetch = {"mean_1", "mean_2", "mean_3", "mean_4", "mean_5"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
// Ensure Mean node is optimized to Reshape.
int found = 0;
for (const auto& node : output.node()) {
if (node.name() == "mean_1" || node.name() == "mean_2") {
found++;
EXPECT_EQ("Reshape", node.op());
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("input_var_three_dim", node.input(0));
} else if (node.name() == "mean_3") {
found++;
EXPECT_EQ("Mean", node.op());
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("input_var_one_dim", node.input(0));
} else if (node.name() == "mean_4") {
found++;
EXPECT_EQ("Mean", node.op());
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("input_var_three_dim", node.input(0));
} else if (node.name() == "mean_5") {
found++;
EXPECT_EQ("Identity", node.op());
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("^multiple_axes", node.input(1));
}
}
EXPECT_EQ(5, found);
// Ensure resultant values from Mean and Reshape are the same.
auto input_var_three_dim_t =
GenerateRandomTensor<DT_FLOAT>(TensorShape({1, 1, 1}));
auto input_var_one_dim_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({1}));
Tensor input_var_axis_t(DT_INT32, TensorShape({1}));
input_var_axis_t.flat<int32>()(0) = 0;
auto tensors_expected =
EvaluateNodes(item.graph, item.fetch,
{{"input_var_three_dim", input_var_three_dim_t},
{"input_var_one_dim", input_var_one_dim_t},
{"input_var_axis", input_var_axis_t}});
EXPECT_EQ(5, tensors_expected.size());
auto tensors = EvaluateNodes(output, item.fetch,
{{"input_var_three_dim", input_var_three_dim_t},
{"input_var_one_dim", input_var_one_dim_t},
{"input_var_axis", input_var_axis_t}});
EXPECT_EQ(5, tensors.size());
for (int i = 0; i < 5; ++i) {
test::ExpectTensorNear<float>(tensors_expected[i], tensors[i], 1e-5);
}
}
TEST_F(ConstantFoldingTest, NoOpReshape) {
// Build a simple graph with a reshape that can be reduced to the identity.
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
// A reshape than can be optimized
Output d1 = ops::Const(scope.WithOpName("d1"), 3.14f, {17});
Output v1 = ops::Variable(scope.WithOpName("v1"), {17}, DT_FLOAT);
Output c1 =
ops::Const(scope.WithOpName("c1").WithControlDependencies(v1), 17, {1});
Output i1 = ops::Identity(scope.WithOpName("i1"), c1);
Output r1 =
ops::Reshape(scope.WithOpName("r1").WithControlDependencies(d1), v1, i1);
Output s1 = ops::Square(scope.WithOpName("s1"), r1);
// A multi dimensional reshape than can be optimized
Output v3 = ops::Variable(scope.WithOpName("v3"), {5, 5, 5}, DT_FLOAT);
Output c3 =
ops::Const(scope.WithOpName("c3").WithControlDependencies(v3), 5, {3});
Output i3 = ops::Identity(scope.WithOpName("i3"), c3);
Output r3 = ops::Reshape(scope.WithOpName("r3"), v3, i3);
Output s3 = ops::Square(scope.WithOpName("s3"), r3);
// A multi dimensional partially defined reshape than can be optimized
Output v4 = ops::Variable(scope.WithOpName("v4"), {5, 5, 5}, DT_FLOAT);
Output c4 = ops::Const(scope.WithOpName("c4").WithControlDependencies(v4),
{5, -1, 5}, {3});
Output i4 = ops::Identity(scope.WithOpName("i4"), c4);
Output r4 = ops::Reshape(scope.WithOpName("r4"), v4, i4);
Output s4 = ops::Square(scope.WithOpName("s4"), r4);
// A reshape that can't be optimized
Output v2 = ops::Variable(scope.WithOpName("v2"), {17, 1}, DT_FLOAT);
Output c2 =
ops::Const(scope.WithOpName("c2").WithControlDependencies(v2), 17, {1});
Output r2 = ops::Reshape(scope.WithOpName("r2"), v2, c2);
Output s2 = ops::Square(scope.WithOpName("s2"), r2);
GrapplerItem item;
item.fetch = {"s1", "s2", "s3", "s4"};
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
int found = 0;
for (const auto& node : output.node()) {
if (node.name() == "r1") {
++found;
EXPECT_EQ("Identity", node.op());
ASSERT_EQ(3, node.input_size());
EXPECT_EQ("v1", node.input(0));
EXPECT_EQ("^i1", node.input(1));
EXPECT_EQ("^d1", node.input(2));
} else if (node.name() == "r3") {
++found;
EXPECT_EQ("Identity", node.op());
ASSERT_EQ(2, node.input_size());
EXPECT_EQ("v3", node.input(0));
EXPECT_EQ("^i3", node.input(1));
} else if (node.name() == "r4") {
++found;
EXPECT_EQ("Identity", node.op());
ASSERT_EQ(2, node.input_size());
EXPECT_EQ("v4", node.input(0));
EXPECT_EQ("^i4", node.input(1));
} else if (node.name() == "r2") {
++found;
EXPECT_EQ("Reshape", node.op());
ASSERT_EQ(2, node.input_size());
EXPECT_EQ("v2", node.input(0));
EXPECT_EQ("c2", node.input(1));
}
}
EXPECT_EQ(4, found);
auto v1_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({17}));
auto v2_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({17, 1}));
auto v3_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({5, 5, 5}));
auto v4_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({5, 5, 5}));
auto tensors_expected =
EvaluateNodes(item.graph, item.fetch,
{{"v1", v1_t}, {"v2", v2_t}, {"v3", v3_t}, {"v4", v4_t}});
EXPECT_EQ(4, tensors_expected.size());
auto tensors =
EvaluateNodes(output, item.fetch,
{{"v1", v1_t}, {"v2", v2_t}, {"v3", v3_t}, {"v4", v4_t}});
EXPECT_EQ(4, tensors.size());
for (int i = 0; i < tensors.size(); i++)
test::ExpectTensorNear<float>(tensors_expected[i], tensors[i], 1e-5);
}
TEST_F(ConstantFoldingTest, Packing) {
// Build a simple graph with a large constant that can be folded.
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output c = ops::Const(scope.WithOpName("c"), 3.14f, {1000});
Output i1 = ops::Identity(scope.WithOpName("i1"), c);
Output i2 = ops::Identity(scope.WithOpName("i2"), c);
GrapplerItem item;
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
const std::vector<string> fetch_nodes = {"i1", "i2"};
auto tensors_expected = EvaluateNodes(item.graph, fetch_nodes);
EXPECT_EQ(fetch_nodes.size(), tensors_expected.size());
auto tensors = EvaluateNodes(output, fetch_nodes);
EXPECT_EQ(fetch_nodes.size(), tensors.size());
for (int i = 0; i < fetch_nodes.size(); i++)
test::ExpectTensorNear<float>(tensors_expected[i], tensors[i], 1e-5);
// Make sure that the representation of the folded constant is space
// efficient: in particular, the whole message should be smaller than 8k
// (the size needed to naively encode 1000 floats folded twice).
EXPECT_GT(8000, output.ByteSizeLong());
}
TEST_F(ConstantFoldingTest, LargeConstantNoSizeIncrease) {
// Build a simple graph with a large constant with size greater than
// kMaxConstantSize that can be folded because the resulting size does not
// increase.
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
const int64 large_constant_size = kMaxConstantSize + 1;
Output a = ops::Variable(scope.WithOpName("a"), {1, 1}, DT_FLOAT);
Output b_const =
ops::Const(scope.WithOpName("b_const"), 3.14f, {1, large_constant_size});
Output b = ops::Identity(scope.WithOpName("b"), b_const);
Output matmul = ops::MatMul(scope.WithOpName("matmul"), a, b);
GrapplerItem item;
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
item.graph.Swap(&output);
status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
for (const auto& node : output.node()) {
if (node.name() == "b") {
EXPECT_EQ("Const", node.op());
}
}
EXPECT_EQ(4, output.node_size());
EXPECT_LT(output.ByteSizeLong(), sizeof(float) * large_constant_size + 500);
}
TEST_F(ConstantFoldingTest, MaterializeBroadcastGradientArgs) {
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output a =
ops::Placeholder(s.WithOpName("a"), DT_FLOAT,
ops::Placeholder::Shape(PartialTensorShape({-1, -1})));
Output b = ops::Square(s.WithOpName("b"), a);
Output c = ops::Mul(s.WithOpName("c"), a, b);
Output d = ops::Shape(s.WithOpName("d"), a);
Output e = ops::Shape(s.WithOpName("e"), b);
auto f = ops::internal::BroadcastGradientArgs(s.WithOpName("f"), d, e);
Output o1 = ops::Identity(s.WithOpName("o1"), f.r0);
Output o2 = ops::Identity(s.WithOpName("o2"), f.r1);
Output g = ops::Placeholder(s.WithOpName("g"), DT_FLOAT,
ops::Placeholder::Shape(PartialTensorShape({1})));
Output h = ops::Shape(s.WithOpName("h"), g);
auto i = ops::internal::BroadcastGradientArgs(s.WithOpName("i"), d, h);
Output p1 = ops::Identity(s.WithOpName("p1"), i.r0);
Output p2 = ops::Identity(s.WithOpName("p2"), i.r1);
GrapplerItem item;
TF_CHECK_OK(s.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
std::vector<string> fetch_nodes = {"o1", "o2", "p1", "p2"};
auto a_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({1, 5}));
auto g_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({1}));
auto tensors_expected =
EvaluateNodes(item.graph, fetch_nodes, {{"a", a_t}, {"g", g_t}});
EXPECT_EQ(fetch_nodes.size(), tensors_expected.size());
// Run a second time to make sure the optimization is idempotent.
item.graph.Swap(&output);
status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
int found = 0;
for (const auto& node : output.node()) {
if (node.name() == "o1") {
++found;
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("ConstantFolding/f-bcastargs-0", node.input(0));
} else if (node.name() == "o2") {
++found;
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("ConstantFolding/f-bcastargs-1", node.input(0));
} else if (node.name() == "ConstantFolding/f-bcastargs-0") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^f", node.input(0));
EXPECT_EQ(0, TensorShape(node.attr().at("value").tensor().tensor_shape())
.num_elements());
} else if (node.name() == "ConstantFolding/f-bcastargs-1") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^f", node.input(0));
EXPECT_EQ(0, TensorShape(node.attr().at("value").tensor().tensor_shape())
.num_elements());
} else if (node.name() == "p1") {
++found;
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("i", node.input(0));
} else if (node.name() == "p2") {
++found;
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("i:1", node.input(0));
}
}
EXPECT_EQ(6, found);
auto tensors = EvaluateNodes(output, fetch_nodes, {{"a", a_t}, {"g", g_t}});
EXPECT_EQ(fetch_nodes.size(), tensors.size());
for (int i = 0; i < fetch_nodes.size(); i++)
test::ExpectTensorEqual<int>(tensors_expected[i], tensors[i]);
}
TEST_F(ConstantFoldingTest, MaterializeBroadcastGradientArgs_InfiniteLoop) {
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output a =
ops::Placeholder(s.WithOpName("a"), DT_FLOAT,
ops::Placeholder::Shape(PartialTensorShape({2, 2})));
Output b = ops::Square(s.WithOpName("b"), a);
Output c = ops::Mul(s.WithOpName("c"), a, b);
Output d = ops::Shape(s.WithOpName("d"), a);
Output e = ops::Shape(s.WithOpName("e"), b);
auto f = ops::internal::BroadcastGradientArgs(s.WithOpName("f"), d, e);
Output o1 = ops::Identity(s.WithOpName("o1"), f.r0);
Output o2 = ops::Identity(s.WithOpName("o2"), f.r1);
GrapplerItem item;
TF_CHECK_OK(s.ToGraphDef(&item.graph));
std::vector<string> fetch_nodes = {"o1", "o2"};
auto a_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({2, 2}));
auto tensors_expected = EvaluateNodes(item.graph, fetch_nodes, {{"a", a_t}});
EXPECT_EQ(fetch_nodes.size(), tensors_expected.size());
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
// Run a second time to make sure the optimization is idempotent.
item.graph.Swap(&output);
status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(11, output.node_size());
int found = 0;
for (const auto& node : output.node()) {
if (node.name() == "ConstantFolding/f-folded-1") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("^a", node.input(0));
EXPECT_EQ("^b", node.input(1));
} else if (node.name() == "d") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^a", node.input(0));
} else if (node.name() == "e") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^b", node.input(0));
} else if (node.name() == "o1") {
++found;
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("ConstantFolding/f-bcastargs-0", node.input(0));
} else if (node.name() == "o2") {
++found;
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("ConstantFolding/f-bcastargs-1", node.input(0));
} else if (node.name() == "ConstantFolding/f-bcastargs-0") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^ConstantFolding/f-folded-1", node.input(0));
EXPECT_EQ(0, TensorShape(node.attr().at("value").tensor().tensor_shape())
.num_elements());
} else if (node.name() == "ConstantFolding/f-bcastargs-1") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^ConstantFolding/f-folded-1", node.input(0));
EXPECT_EQ(0, TensorShape(node.attr().at("value").tensor().tensor_shape())
.num_elements());
}
}
EXPECT_EQ(7, found);
auto tensors = EvaluateNodes(output, fetch_nodes, {{"a", a_t}});
EXPECT_EQ(fetch_nodes.size(), tensors.size());
for (int i = 0; i < fetch_nodes.size(); i++)
test::ExpectTensorEqual<int>(tensors_expected[i], tensors[i]);
}
TEST_F(ConstantFoldingTest, MaterializeReductionIndices) {
for (bool use_reshape : {true, false}) {
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output input =
ops::Placeholder(s.WithOpName("input"), DT_FLOAT,
ops::Placeholder::Shape(PartialTensorShape({-1, -1})));
// If use_reshape is false, we need to now the number of indices to apply
// the rewrite.
Output indices = ops::Placeholder(
s.WithOpName("indices"), DT_INT32,
ops::Placeholder::Shape(PartialTensorShape({use_reshape ? -1 : 2})));
Output sum = ops::Sum(s.WithOpName("sum"), input, indices);
if (use_reshape) {
Output size = ops::Const(s.WithOpName("size"), 1, {1});
Output reshape = ops::Reshape(s.WithOpName("reshape"), sum, size);
}
GrapplerItem item;
TF_CHECK_OK(s.ToGraphDef(&item.graph));
item.fetch.push_back(use_reshape ? "reshape" : "sum");
auto input_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({3, 4}));
Tensor indices_t(DT_INT32, TensorShape({2}));
indices_t.flat<int>()(0) = 0;
indices_t.flat<int>()(1) = 1;
auto tensors_expected = EvaluateNodes(
item.graph, item.fetch, {{"input", input_t}, {"indices", indices_t}});
EXPECT_EQ(1, tensors_expected.size());
// Use aggressive mode to force the shape inference to propagate placeholder
// shapes.
ConstantFolding optimizer(RewriterConfig::AGGRESSIVE,
/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
// Run a second time to make sure the optimization is idempotent.
item.graph.Swap(&output);
status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
int found = 0;
for (const auto& node : output.node()) {
if (node.name() == "ConstantFolding/sum-reduction_indices") {
++found;
EXPECT_EQ("Const", node.op());
EXPECT_EQ("^indices", node.input(0));
EXPECT_EQ(2,
TensorShape(node.attr().at("value").tensor().tensor_shape())
.num_elements());
} else if (node.name() == "sum") {
++found;
EXPECT_EQ("ConstantFolding/sum-reduction_indices", node.input(1));
} else if (node.name() == "indices") {
++found;
}
}
EXPECT_EQ(3, found);
auto tensors = EvaluateNodes(output, item.fetch,
{{"input", input_t}, {"indices", indices_t}});
EXPECT_EQ(1, tensors.size());
test::ExpectTensorNear<float>(tensors_expected[0], tensors[0], 1e-5);
}
}
TEST_F(ConstantFoldingTest, MaterializeReductionIndices_NotFullReduction) {
for (bool input_rank_known : {true, false}) {
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output input =
(input_rank_known ? ops::Placeholder(s.WithOpName("input"), DT_FLOAT,
ops::Placeholder::Shape(
PartialTensorShape({-1, -1})))
: ops::Placeholder(s.WithOpName("input"), DT_FLOAT));
Output indices =
ops::Placeholder(s.WithOpName("indices"), DT_INT32,
ops::Placeholder::Shape(
PartialTensorShape({input_rank_known ? 1 : 2})));
Output sum = ops::Sum(s.WithOpName("sum"), input, indices);
GrapplerItem item;
TF_CHECK_OK(s.ToGraphDef(&item.graph));
item.fetch.push_back("sum");
// Use aggressive mode to force the shape inference to propagate placeholder
// shapes.
ConstantFolding optimizer(RewriterConfig::AGGRESSIVE,
/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
CompareGraphs(item.graph, output);
}
}
TEST_F(ConstantFoldingTest, LargeConstant) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
// Generate a 4k by 4k constant, non-compressible matrix.
Output mat_diag =
ops::Const(scope.WithOpName("mat_diag"), 3.14f, TensorShape({1024 * 4}));
Output mat = ops::Diag(scope.WithOpName("mat"), mat_diag);
Output out = ops::Identity(scope.WithOpName("out"), mat);
GrapplerItem item;
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
item.fetch.push_back("out");
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
// Make sure the diag node hasn't been folded, since it would use too much
// memory to encode the corresponding constant.
int found = 0;
for (const NodeDef& node : output.node()) {
if (node.name() == "out") {
EXPECT_EQ(node.op(), "Identity");
ASSERT_EQ(node.input_size(), 1);
EXPECT_EQ(node.input(0), "mat");
++found;
} else if (node.name() == "mat") {
EXPECT_EQ(node.op(), "Diag");
ASSERT_EQ(node.input_size(), 1);
EXPECT_EQ(node.input(0), "mat_diag");
++found;
}
}
EXPECT_EQ(found, 2);
// output should be no longer than the size of the constant "mat_diag"
// plus a small constant amount for the remaining nodes.
EXPECT_LT(output.ByteSizeLong(), sizeof(int) * 4 * 1024 + 500);
auto tensors_expected = EvaluateNodes(item.graph, item.fetch);
ASSERT_EQ(tensors_expected.size(), 1);
auto tensors = EvaluateNodes(output, item.fetch);
ASSERT_EQ(tensors.size(), 1);
test::ExpectTensorEqual<float>(tensors_expected[0], tensors[0]);
}
TEST_F(ConstantFoldingTest, SwitchIdenticalInputs) {
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output x = ops::Placeholder(s.WithOpName("x"), DT_BOOL,
ops::Placeholder::Shape(TensorShape({})));
ops::Switch sw = ops::Switch(s.WithOpName("switch"), x, x);
Output id_false = ops::LogicalNot(s.WithOpName("id_false"), sw.output_false);
Output id_true = ops::LogicalNot(s.WithOpName("id_true"), sw.output_true);
GrapplerItem item;
item.fetch.push_back("id_false");
item.fetch.push_back("id_true");
TF_CHECK_OK(s.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(6, output.node_size());
int found = 0;
for (const auto& node : output.node()) {
if (node.name() == "switch" || node.name() == "x") {
++found;
}
if (node.name() == "id_false") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^ConstantFoldingCtrl/switch_0", node.input(0));
++found;
}
if (node.name() == "id_true") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^ConstantFoldingCtrl/switch_1", node.input(0));
++found;
}
if (node.name() == "ConstantFoldingCtrl/switch_0") {
EXPECT_EQ("Identity", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("switch", node.input(0));
++found;
}
if (node.name() == "ConstantFoldingCtrl/switch_1") {
EXPECT_EQ("Identity", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("switch:1", node.input(0));
++found;
}
}
EXPECT_EQ(6, found);
// Evaluate id_true when input tensor x is true.
Tensor x_t(DT_BOOL, TensorShape({}));
x_t.flat<bool>()(0) = true;
auto tensors_expected = EvaluateNodes(item.graph, {"id_true"}, {{"x", x_t}});
EXPECT_EQ(1, tensors_expected.size());
auto tensors = EvaluateNodes(output, {"id_true"}, {{"x", x_t}});
EXPECT_EQ(1, tensors.size());
test::ExpectTensorEqual<bool>(tensors_expected[0], tensors[0]);
// Evaluate id_false when input tensor is false.
x_t.flat<bool>()(0) = false;
tensors_expected = EvaluateNodes(item.graph, {"id_false"}, {{"x", x_t}});
EXPECT_EQ(1, tensors_expected.size());
tensors = EvaluateNodes(output, {"id_false"}, {{"x", x_t}});
EXPECT_EQ(1, tensors.size());
test::ExpectTensorEqual<bool>(tensors_expected[0], tensors[0]);
}
TEST_F(ConstantFoldingTest, PartialFolding_AssociativeAndCommutative) {
std::function<Output(const Scope&, InputList)> addn_fun =
[](const Scope& scope, InputList inputs) {
return ops::AddN(scope, inputs);
};
std::function<Output(const Scope&, InputList)> accumulate_fun =
[](const Scope& scope, InputList inputs) {
return ops::AccumulateNV2(scope, inputs, TensorShape({2, 2}));
};
for (bool use_add_n : {true, false}) {
auto fun = use_add_n ? addn_fun : accumulate_fun;
const string op_name = use_add_n ? "AddN" : "AccumulateNV2";
Scope s = Scope::NewRootScope();
Output x = ops::Placeholder(s.WithOpName("x"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output y = ops::Placeholder(s.WithOpName("y"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output z = ops::Placeholder(s.WithOpName("z"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output c1 = ops::Const(s.WithOpName("c1"), 1.0f, {2, 2});
Output c2 = ops::Const(s.WithOpName("c2"), 2.0f, {2, 2});
Output c3 = ops::Const(s.WithOpName("c3"), 3.0f, {2, 2});
Output acc0 = fun(s.WithOpName("acc0"), {c1, c2, c3});
Output acc1 = fun(s.WithOpName("acc1"), {x, y, z});
Output acc2 = fun(s.WithOpName("acc2"), {c1, x, y});
Output acc3 = fun(s.WithOpName("acc3"), {c1, c2, z});
Output acc4 = fun(s.WithOpName("acc4"), {c1, y, c2});
Output acc5 = fun(s.WithOpName("acc5"), {x, c1, c2});
Output acc6 = fun(s.WithOpName("acc6"), {x, c1, y, c2});
Output stack = ops::Stack(s.WithOpName("stack"),
{acc0, acc1, acc2, acc3, acc4, acc5, acc6});
GrapplerItem item;
TF_CHECK_OK(s.ToGraphDef(&item.graph));
item.fetch = {"stack"};
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(16, output.node_size());
for (const NodeDef& node : output.node()) {
if (node.name() == "acc0") {
EXPECT_EQ("Const", node.op());
}
if (node.name() == "acc1") {
EXPECT_EQ(op_name, node.op());
EXPECT_EQ(3, node.input_size());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("y", node.input(1));
EXPECT_EQ("z", node.input(2));
}
if (node.name() == "acc2") {
EXPECT_EQ(op_name, node.op());
EXPECT_EQ(3, node.input_size());
EXPECT_EQ("c1", node.input(0));
EXPECT_EQ("x", node.input(1));
EXPECT_EQ("y", node.input(2));
}
if (node.name() == "acc3") {
EXPECT_EQ(op_name, node.op());
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("ConstantFolding/acc3_partial_split_2", node.input(0));
EXPECT_EQ("z", node.input(1));
}
if (node.name() == "acc4") {
EXPECT_EQ(op_name, node.op());
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("ConstantFolding/acc4_partial_split_2", node.input(0));
EXPECT_EQ("y", node.input(1));
}
if (node.name() == "acc5") {
EXPECT_EQ(op_name, node.op());
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("ConstantFolding/acc5_partial_split_2", node.input(1));
}
if (node.name() == "acc6") {
EXPECT_EQ(op_name, node.op());
EXPECT_EQ(3, node.input_size());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("ConstantFolding/acc6_partial_split_2", node.input(1));
EXPECT_EQ("y", node.input(2));
}
if (absl::StartsWith(node.name(), "ConstantFolding/")) {
EXPECT_EQ("Const", node.op());
}
}
std::vector<string> fetch = {"acc0"};
auto tensors_expected = EvaluateNodes(item.graph, fetch);
auto tensors = EvaluateNodes(output, fetch);
EXPECT_EQ(1, tensors_expected.size());
EXPECT_EQ(1, tensors.size());
test::ExpectTensorNear<float>(tensors_expected[0], tensors[0], 1e-6);
}
}
TEST_F(ConstantFoldingTest, PartialFolding_Concat) {
Scope s = Scope::NewRootScope();
Output x = ops::Placeholder(s.WithOpName("x"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output y = ops::Placeholder(s.WithOpName("y"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output z = ops::Placeholder(s.WithOpName("z"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({2, 2})));
Output axis = ops::Const(s.WithOpName("axis"), 0, {});
Output c1 = ops::Const(s.WithOpName("c1"), 1.0f, {2, 2});
Output c2 = ops::Const(s.WithOpName("c2"), 2.0f, {2, 2});
Output concat0 = ops::Concat(s.WithOpName("concat0"), {c1, c2, c1}, axis);
Output concat1 = ops::Concat(s.WithOpName("concat1"), {x, y, z}, axis);
Output concat2 = ops::Concat(s.WithOpName("concat2"), {c1, x, y}, axis);
Output concat3 = ops::Concat(s.WithOpName("concat3"), {c1, c2, z}, axis);
Output concat4 = ops::Concat(s.WithOpName("concat4"), {c1, y, c2}, axis);
Output concat5 = ops::Concat(s.WithOpName("concat5"), {x, c1, c2}, axis);
Output concat6 = ops::Concat(s.WithOpName("concat6"), {x, c1, y, c2}, axis);
Output concat7 = ops::Concat(s.WithOpName("concat7"), {x, y, c1, c2}, axis);
Output concat8 = ops::Concat(s.WithOpName("concat8"), {x, c1, c2, y}, axis);
Output concat9 = ops::Concat(s.WithOpName("concat9"), {c1, c2, x, y}, axis);
GrapplerItem item;
TF_CHECK_OK(s.ToGraphDef(&item.graph));
item.fetch = {"concat0", "concat1", "concat2", "concat3", "concat4",
"concat5", "concat6", "concat7", "concat8", "concat9"};
auto tensors_expected = EvaluateNodes(item.graph, {"concat0"});
EXPECT_EQ(1, tensors_expected.size());
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
// Run the optimizer twice to make sure the rewrite is idempotent.
item.graph.Swap(&output);
status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(21, output.node_size());
for (int i = 0; i < output.node_size(); ++i) {
const NodeDef& node = output.node(i);
if (node.name() == "concat0") {
EXPECT_EQ("Const", node.op());
} else if (node.name() == "concat3") {
EXPECT_EQ(3, node.input_size());
EXPECT_EQ("ConstantFolding/concat3_partial_split_0", node.input(0));
EXPECT_EQ("z", node.input(1));
EXPECT_EQ("axis", node.input(2));
} else if (node.name() == "concat5") {
EXPECT_EQ(3, node.input_size());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("ConstantFolding/concat5_partial_split_1", node.input(1));
EXPECT_EQ("axis", node.input(2));
} else if (node.name() == "concat7") {
EXPECT_EQ(4, node.input_size());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("y", node.input(1));
EXPECT_EQ("ConstantFolding/concat7_partial_split_2", node.input(2));
EXPECT_EQ("axis", node.input(3));
} else if (node.name() == "concat8") {
EXPECT_EQ(4, node.input_size());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("ConstantFolding/concat8_partial_split_1", node.input(1));
EXPECT_EQ("y", node.input(2));
EXPECT_EQ("axis", node.input(3));
} else if (node.name() == "concat9") {
EXPECT_EQ(4, node.input_size());
EXPECT_EQ("ConstantFolding/concat9_partial_split_0", node.input(0));
EXPECT_EQ("x", node.input(1));
EXPECT_EQ("y", node.input(2));
EXPECT_EQ("axis", node.input(3));
} else if (absl::StartsWith(node.name(), "ConstantFolding/")) {
EXPECT_EQ("Const", node.op());
} else {
EXPECT_EQ(item.graph.node(i).DebugString(), node.DebugString());
}
}
auto tensors = EvaluateNodes(output, {"concat0"});
EXPECT_EQ(1, tensors.size());
test::ExpectTensorNear<float>(tensors_expected[0], tensors[0], 1e-6);
}
TEST_F(ConstantFoldingTest, PartialFolding_IdentityN) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output x = ops::Placeholder(scope.WithOpName("x"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({})));
Output c1 = ops::Const(scope.WithOpName("c1"), 1.0f, {2, 2});
Output c2 = ops::Const(scope.WithOpName("c2"), 2.0f, {2, 2});
auto id_n = ops::IdentityN(scope.WithOpName("id_n"), {c1, x, c2});
auto id0 = ops::Identity(scope.WithOpName("id0"), id_n[0]);
auto id1 = ops::Identity(scope.WithOpName("id1"), id_n[1]);
auto add0 = ops::Add(scope.WithOpName("add0"), id_n[0], id_n[1]);
auto add1 = ops::Add(scope.WithOpName("add1"), id_n[0], id_n[2]);
GrapplerItem item;
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
item.fetch.push_back("id0");
item.fetch.push_back("id1");
item.fetch.push_back("add0");
item.fetch.push_back("add1");
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(8, output.node_size());
for (const auto& node : output.node()) {
// id_n should remain unchanged.
if (node.name() == "id_n") {
EXPECT_EQ(3, node.input_size());
EXPECT_EQ("c1", node.input(0));
EXPECT_EQ("x", node.input(1));
EXPECT_EQ("c2", node.input(2));
}
// id0 should be constant folded, and a control dependency from id_n.
if (node.name() == "id0") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^id_n", node.input(0));
}
// id1 is unchanged.
if ("id1" == node.name()) {
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("id_n:1", node.input(0));
}
if ("add0" == node.name()) {
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("c1", node.input(0));
EXPECT_EQ("id_n:1", node.input(1));
}
// add1 should bo constant folded and have a control dependency from id_n.
if ("add1" == node.name()) {
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^id_n", node.input(0));
}
}
auto x_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({}));
auto tensors_expected = EvaluateNodes(item.graph, item.fetch, {{"x", x_t}});
EXPECT_EQ(4, tensors_expected.size());
auto tensors = EvaluateNodes(output, item.fetch, {{"x", x_t}});
EXPECT_EQ(4, tensors.size());
for (int i = 0; i < tensors.size(); i++) {
test::ExpectTensorNear<float>(tensors_expected[i], tensors[i], 1e-5);
}
}
TEST_F(ConstantFoldingTest, TrivialPack) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output x =
ops::RandomNormal(scope.WithOpName("x"), {2, 2}, DataType::DT_FLOAT);
Output y = ops::Const(scope.WithOpName("y"), {2.0f}, {});
auto stack =
ops::Stack(scope.WithOpName("stack").WithControlDependencies({y}), {x},
ops::Stack::Axis(1));
auto stack_no_axis = ops::Stack(scope.WithOpName("stack_no_axis"), {x});
GrapplerItem item;
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
item.fetch = {"stack", "stack_no_axis"};
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(7, output.node_size());
int found = 0;
for (const auto& node : output.node()) {
if (node.name() == "stack") {
EXPECT_EQ("ExpandDims", node.op());
EXPECT_EQ(3, node.input_size());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("ConstantFolding/stack_const_axis", node.input(1));
EXPECT_EQ("^y", node.input(2));
++found;
} else if (node.name() == "stack_no_axis") {
EXPECT_EQ("ExpandDims", node.op());
EXPECT_EQ(2, node.input_size());
EXPECT_EQ("x", node.input(0));
EXPECT_EQ("ConstantFolding/stack_no_axis_const_axis", node.input(1));
++found;
} else if (node.name() == "ConstantFolding/stack_const_axis") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^x", node.input(0));
++found;
}
}
EXPECT_EQ(found, 3);
std::vector<string> fetch = {"stack", "stack_no_axis"};
auto tensors_expected = EvaluateNodes(item.graph, fetch);
auto tensors = EvaluateNodes(output, fetch);
EXPECT_EQ(2, tensors_expected.size());
EXPECT_EQ(2, tensors.size());
EXPECT_EQ(tensors_expected[0].shape(), tensors[0].shape());
EXPECT_EQ(tensors_expected[1].shape(), tensors[1].shape());
}
// The test does not evalaute the optimized and original graphs to check if
// their outputs are the same. See b/78233179.
TEST_F(ConstantFoldingTest, Enter) {
GrapplerItem item;
AttrValue frame_name;
frame_name.set_s("foo");
AttrValue is_constant_true;
is_constant_true.set_b(true);
AttrValue is_constant_false;
is_constant_false.set_b(false);
AttrValue type;
type.set_type(DT_FLOAT);
AttrValue value;
Tensor value_tensor(DT_FLOAT, TensorShape({}));
value_tensor.flat<float>()(0) = 1;
value_tensor.AsProtoTensorContent(value.mutable_tensor());
GraphDef& graph = item.graph;
AddNode("x", "Placeholder", {}, {{"dtype", type}}, &graph);
AddNode("c1", "Const", {"^x"}, {{"value", value}, {"dtype", type}}, &graph);
AddNode("enter1", "Enter", {"x"},
{{"T", type},
{"frame_name", frame_name},
{"is_constant", is_constant_true}},
&graph);
AddNode("enter2", "Enter", {"c1"},
{{"T", type},
{"frame_name", frame_name},
{"is_constant", is_constant_true}},
&graph);
AddNode("enter3", "Enter", {"c1"},
{{"T", type},
{"frame_name", frame_name},
{"is_constant", is_constant_false}},
&graph);
AddNode("id1", "Identity", {"enter1"}, {{"T", type}}, &graph);
AddNode("id2", "Identity", {"enter2"}, {{"T", type}}, &graph);
AddNode("id3", "Identity", {"enter2"}, {{"T", type}}, &graph);
AddNode("id4", "Identity", {"enter3"}, {{"T", type}}, &graph);
item.fetch.push_back("id1");
item.fetch.push_back("id2");
item.fetch.push_back("id3");
item.fetch.push_back("id4");
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
// Run the optimizer twice to make sure the rewrite is idempotent.
item.graph.Swap(&output);
status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(9, output.node_size());
for (const NodeDef& node : output.node()) {
if (node.name() == "id1") {
EXPECT_EQ("Identity", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("enter1", node.input(0));
}
if (node.name() == "id2" || node.name() == "id3") {
EXPECT_EQ("Const", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("^enter2", node.input(0));
}
if (node.name() == "id4") {
EXPECT_EQ("Identity", node.op());
EXPECT_EQ(1, node.input_size());
EXPECT_EQ("enter3", node.input(0));
}
}
}
TEST_F(ConstantFoldingTest, TensorArraySize) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output size = ops::Const(scope.WithOpName("size"), 5, TensorShape({}));
Output placeholder =
ops::Placeholder(scope.WithOpName("placeholder"), DT_RESOURCE,
ops::Placeholder::Shape(TensorShape({2})));
Output foo = ops::Const(scope.WithOpName("foo"), 5.0f, TensorShape({}));
auto dynamic_array =
ops::TensorArray(scope.WithOpName("dynamic"), size, DT_FLOAT,
ops::TensorArray::DynamicSize(true));
auto static_array =
ops::TensorArray(scope.WithOpName("static"), size, DT_FLOAT,
ops::TensorArray::DynamicSize(false));
auto dynamic_sz = ops::TensorArraySize(
scope.WithOpName("dynamic_sz"), dynamic_array.handle, dynamic_array.flow);
auto static_sz = ops::TensorArraySize(scope.WithOpName("static_sz"),
static_array.handle, static_array.flow);
auto placeholder_sz = ops::TensorArraySize(scope.WithOpName("placeholder_sz"),
placeholder, foo);
GrapplerItem item;
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
auto tensors_expected =
EvaluateNodes(item.graph, {"dynamic_sz", "static_sz"});
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
// Run the optimizer twice to make sure the rewrite is idempotent.
item.graph.Swap(&output);
status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(8, output.node_size());
EXPECT_EQ("dynamic_sz", output.node(5).name());
EXPECT_EQ("TensorArraySizeV3", output.node(5).op());
EXPECT_EQ("static_sz", output.node(6).name());
EXPECT_EQ("Const", output.node(6).op());
EXPECT_EQ("placeholder_sz", output.node(7).name());
EXPECT_EQ("TensorArraySizeV3", output.node(7).op());
auto tensors_actual = EvaluateNodes(output, {"dynamic_sz", "static_sz"});
EXPECT_EQ(2, tensors_expected.size());
EXPECT_EQ(2, tensors_actual.size());
test::ExpectTensorEqual<int32>(tensors_expected[0], tensors_actual[0]);
test::ExpectTensorEqual<int32>(tensors_expected[1], tensors_actual[1]);
}
TEST_F(ConstantFoldingTest, FoldingPreservesDenormalFlushing) {
// Multiplying min() with 0.1 gives a denormal without FTZ and zero with FTZ.
// Make sure constant folding behaves the same way as TensorFlow.
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
Output a =
ops::Const(s.WithOpName("a"), std::numeric_limits<float>::min(), {1});
Output b = ops::Const(s.WithOpName("b"), 0.1f, {1});
Output c = ops::Mul(s.WithOpName("c"), a, b);
GrapplerItem item;
item.fetch.push_back("c");
TF_CHECK_OK(s.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(1, output.node_size());
const NodeDef& node_d = output.node(0);
EXPECT_EQ("c", node_d.name());
EXPECT_EQ("Const", node_d.op());
std::vector<string> fetch = {"c"};
auto tensors_expected = EvaluateNodes(item.graph, fetch);
auto tensors = EvaluateNodes(output, fetch);
EXPECT_EQ(1, tensors_expected.size());
EXPECT_EQ(1, tensors.size());
test::ExpectTensorEqual<float>(tensors_expected[0], tensors[0]);
}
TEST_F(ConstantFoldingTest, EvaluatingLargeConstantNoFoldingMergingLoop) {
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
int size = 10 * 1024 * 1024 / 4 / 2;
Output nonconst =
ops::RandomUniform(s.WithOpName("nonconst"), {size, 1}, DT_FLOAT);
Output const1 = ops::Const(s.WithOpName("const1"), 0.0f, {size, 1});
Output const2 = ops::Const(s.WithOpName("const2"), 1.0f, {size, 1});
Output axis = ops::Const(s.WithOpName("axis"), -1, {});
Output concat1 =
ops::Concat(s.WithOpName("concat1"), {nonconst, const1}, axis);
Output result = ops::Concat(s.WithOpName("result"), {concat1, const2}, axis);
GrapplerItem item;
item.fetch.push_back("result");
TF_CHECK_OK(s.ToGraphDef(&item.graph));
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
std::vector<string> fetch = {"result"};
auto tensors_expected = EvaluateNodes(item.graph, fetch);
auto tensors = EvaluateNodes(output, fetch);
EXPECT_EQ(1, tensors_expected.size());
EXPECT_EQ(1, tensors.size());
EXPECT_EQ(tensors_expected[0].shape(), tensors[0].shape());
}
class ConstantFoldingCastConstTest : public GrapplerTest {
protected:
void ConstantFoldingCastConst(bool fetch_const, bool fetch_cast,
bool fetch_const_child, bool fetch_cast_child) {
if (!fetch_const && !fetch_cast && !fetch_const_child &&
!fetch_cast_child) {
return;
}
tensorflow::Scope s = tensorflow::Scope::NewRootScope();
CreateCastConstGraph(s);
GrapplerItem item;
int expected_output_size = SetFetch(&item, fetch_const, fetch_cast,
fetch_const_child, fetch_cast_child);
TF_CHECK_OK(s.ToGraphDef(&item.graph));
GraphDef output = ConstantFoldingOptimize(item);
EXPECT_EQ(expected_output_size, output.node_size());
EvaluateAndCompareUnoptimized(item.graph, output, item.fetch);
}
private:
void CreateCastConstGraph(const tensorflow::Scope& s) {
Output const1 = ops::Const(s.WithOpName("const1"), 2, {5, 5});
Output cast = ops::Cast(s.WithOpName("cast"), const1, DT_FLOAT);
Output const1_child = ops::Identity(s.WithOpName("const1_child"), const1);
Output cast_child = ops::Identity(s.WithOpName("cast_child"), cast);
}
int SetFetch(GrapplerItem* item, bool fetch_const, bool fetch_cast,
bool fetch_const_child, bool fetch_cast_child) {
int expected_output_size = 0;
if (fetch_const) {
item->fetch.push_back("const1");
expected_output_size++;
}
if (fetch_cast) {
item->fetch.push_back("cast");
expected_output_size++;
}
if (fetch_const_child) {
item->fetch.push_back("const1_child");
expected_output_size++;
}
if (fetch_cast_child) {
item->fetch.push_back("cast_child");
expected_output_size++;
}
return expected_output_size;
}
GraphDef ConstantFoldingOptimize(const GrapplerItem& item) {
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
return output;
}
void EvaluateAndCompareUnoptimized(const GraphDef& unoptimized_graph,
const GraphDef& optimized_graph,
const std::vector<string>& fetch_nodes) {
auto tensors_expected = EvaluateNodes(unoptimized_graph, fetch_nodes);
auto tensors = EvaluateNodes(optimized_graph, fetch_nodes);
ASSERT_EQ(fetch_nodes.size(), tensors_expected.size());
ASSERT_EQ(fetch_nodes.size(), tensors.size());
for (int i = 0; i < fetch_nodes.size(); i++) {
if (fetch_nodes[i] == "const1" || fetch_nodes[i] == "const1_child") {
test::ExpectTensorEqual<int>(tensors_expected[i], tensors[i]);
} else {
test::ExpectTensorEqual<float>(tensors_expected[i], tensors[i]);
}
}
}
};
TEST_F(ConstantFoldingCastConstTest, CastConstFolding) {
for (bool fetch_const : {false, true}) {
for (bool fetch_cast : {false, true}) {
for (bool fetch_const_child : {false, true}) {
for (bool fetch_cast_child : {false, true}) {
ConstantFoldingCastConst(fetch_const, fetch_cast, fetch_const_child,
fetch_cast_child);
}
}
}
}
}
TEST_F(ConstantFoldingTest, MaterializeConstantValuedNode) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output x =
ops::Placeholder(scope.WithOpName("x"), DT_FLOAT,
ops::Placeholder::Shape(TensorShape({1, 2, 3, 4})));
Output ones_like = ops::OnesLike(scope.WithOpName("ones_like"), x);
Output zeros_like = ops::ZerosLike(scope.WithOpName("zeros_like"), x);
Output fill = ops::Fill(scope.WithOpName("fill"), {4, 3, 2, 1}, 42);
GrapplerItem item;
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
item.fetch = {"ones_like", "zeros_like", "fill"};
auto x_t = GenerateRandomTensor<DT_FLOAT>(TensorShape({1, 2, 3, 4}));
auto tensors_expected = EvaluateNodes(item.graph, item.fetch, {{"x", x_t}});
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(output.node_size(), 6);
for (const auto& node : output.node()) {
if (node.name() != "x") {
EXPECT_EQ(node.op(), "Const");
}
if (node.name() == "ones_like" || node.name() == "zeros_like") {
ASSERT_EQ(node.input_size(), 1);
EXPECT_EQ(node.input(0), "^x");
}
if (node.name() == "fill") {
ASSERT_EQ(node.input_size(), 2);
EXPECT_EQ(node.input(0)[0], '^');
EXPECT_EQ(node.input(1)[0], '^');
}
}
auto tensors = EvaluateNodes(output, item.fetch, {{"x", x_t}});
ASSERT_EQ(item.fetch.size(), tensors.size());
ASSERT_EQ(tensors_expected.size(), tensors.size());
for (int i = 0; i < tensors.size(); i++) {
if (item.fetch[i] == "fill") {
test::ExpectTensorEqual<int>(tensors_expected[i], tensors[i]);
} else {
test::ExpectTensorEqual<float>(tensors_expected[i], tensors[i]);
}
}
}
TEST_F(ConstantFoldingTest, MaterializeConstantValuedNodeHugeFill) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Output value = ops::Const(scope.WithOpName("value"), 42, {});
Output shape_const = ops::Const(scope.WithOpName("shape"),
{1024, 1024, 1024, 1024, 1024}, {5});
Output fill_huge =
ops::Fill(scope.WithOpName("fill_huge"), shape_const, value);
GrapplerItem item;
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
// Manually convert the input value format to tensor_content to test this
// case.
NodeDef* node = item.graph.mutable_node(0);
ASSERT_EQ(node->name(), "value");
TensorProto* t = (*node->mutable_attr())["value"].mutable_tensor();
t->clear_int_val();
int val = 42;
port::CopyFromArray(t->mutable_tensor_content(),
reinterpret_cast<const char*>(&val), sizeof(int));
item.fetch = {"fill_huge"};
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
EXPECT_EQ(output.node_size(), 3);
for (const auto& node : output.node()) {
EXPECT_EQ(node.op(), "Const");
if (node.name() == "fill_huge") {
ASSERT_EQ(node.input_size(), 2);
EXPECT_EQ(node.input(0), "^shape");
EXPECT_EQ(node.input(1), "^value");
}
}
}
TEST_F(ConstantFoldingTest, BitcastDenormalFloats) {
tensorflow::Scope scope = tensorflow::Scope::NewRootScope();
Tensor x_t(DT_INT64, TensorShape({2, 2}));
x_t.flat<int64>()(0) = 9223372036854775807L;
x_t.flat<int64>()(1) = 1L;
x_t.flat<int64>()(2) = 9223372036854775807L;
x_t.flat<int64>()(3) = 1L;
Output x = ops::Const(scope.WithOpName("x"), x_t);
Output y = ops::Bitcast(scope.WithOpName("y"), x, DT_FLOAT);
Output z = ops::Bitcast(scope.WithOpName("z"), y, DT_INT64);
GrapplerItem item;
TF_CHECK_OK(scope.ToGraphDef(&item.graph));
item.fetch = {"z"};
auto tensors_expected = EvaluateNodes(item.graph, item.fetch, {});
ConstantFolding optimizer(/*cpu_device=*/nullptr);
GraphDef output;
Status status = optimizer.Optimize(/*cluster=*/nullptr, item, &output);
TF_EXPECT_OK(status);
ASSERT_EQ(output.node_size(), 1);
const NodeDef& node = output.node(0);
EXPECT_EQ(node.name(), "z");
EXPECT_EQ(node.op(), "Const");
auto tensors = EvaluateNodes(output, item.fetch, {});
ASSERT_EQ(tensors.size(), 1);
ASSERT_EQ(tensors_expected.size(), 1);
test::ExpectTensorEqual<int64>(tensors[0], tensors_expected[0]);
}
} // namespace
} // namespace grappler
} // namespace tensorflow
| apache-2.0 |
xiejuntao/Xworkflow | src/xjt/workflow/exe/WorkFlowInstance.java | 1857 | package xjt.workflow.exe;
import java.util.Date;
import xjt.workflow.def.WorkFlow;
/**
* 工作流程实例
* @since Aug 30, 2010
* @author xjt
* @version 1.00 Aug 30, 2010
* */
public class WorkFlowInstance implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* 标识ID
* */
private Long id;
/**
* 工作流
* */
private WorkFlow workFlow;
/**
* 根令牌,标志流程走向
* */
private Token rootToken;
/**
* 开始时间
* */
private Date startTime;
/**
* 结束时间
* */
private Date endTime;
// Constructors
/** default constructor */
public WorkFlowInstance() {
}
/** minimal constructor */
public WorkFlowInstance(WorkFlow workFlow) {
this.workFlow = workFlow;
}
/** full constructor */
public WorkFlowInstance(WorkFlow workFlow,Token rootToken, Date startTime, Date endTime) {
this.workFlow = workFlow;
this.rootToken = rootToken;
this.startTime = startTime;
this.endTime = endTime;
}
// Property accessors
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Token getRootToken() {
return rootToken;
}
public void setRootToken(Token rootToken) {
this.rootToken = rootToken;
}
public WorkFlow getWorkFlow() {
return workFlow;
}
public void setWorkFlow(WorkFlow workFlow) {
this.workFlow = workFlow;
}
public Date getStartTime() {
return this.startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return this.endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
} | apache-2.0 |
DedMemez/ODS-August-2017 | town/TownBattleSOSPetInfoPanel.py | 8825 | # Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.town.TownBattleSOSPetInfoPanel
from panda3d.core import TextNode, Vec4
from direct.fsm import StateData
from direct.gui.DirectGui import *
from toontown.toonbase import TTLocalizer
from toontown.pets import Pet, PetTricks, PetDetailPanel
from toontown.speedchat import TTSCPetTrickMenu
from otp.speedchat import SpeedChatGlobals, SCSettings
from otp.otpbase import OTPLocalizer
class TownBattleSOSPetInfoPanel(StateData.StateData):
def __init__(self, doneEvent):
StateData.StateData.__init__(self, doneEvent)
def load(self):
gui = loader.loadModel('phase_3.5/models/gui/PetControlPannel')
guiScale = 0.116
guiPos = (0, 0, 0)
self.frame = DirectFrame(image=gui, scale=guiScale, pos=guiPos, relief=None)
self.frame.hide()
disabledImageColor = Vec4(0.6, 0.6, 0.6, 1)
text0Color = Vec4(1, 1, 1, 1)
text1Color = Vec4(0.5, 1, 0.5, 1)
text2Color = Vec4(1, 1, 0.5, 1)
text3Color = Vec4(0.6, 0.6, 0.6, 1)
self.closeButton = DirectButton(parent=self.frame, image=(gui.find('**/CancelButtonUp'), gui.find('**/CancelButtonDown'), gui.find('**/CancelButtonRollover')), relief=None, command=self.__handleClose)
self.feedButton = DirectButton(parent=self.frame, image=(gui.find('**/ButtonFeedUp'),
gui.find('**/ButtonFeedDown'),
gui.find('**/ButtonFeedRollover'),
gui.find('**/ButtonFeedUp')), geom=gui.find('**/PetControlFeedIcon'), image3_color=disabledImageColor, relief=None, text=TTLocalizer.PetPanelFeed, text_scale=0.5, text0_fg=text0Color, text1_fg=text1Color, text2_fg=text2Color, text3_fg=text3Color, text_pos=(-0.5, 2.8), text_align=TextNode.ALeft)
self.feedButton['state'] = DGG.DISABLED
self.callButton = DirectButton(parent=self.frame, image=(gui.find('**/ButtonGoToUp'),
gui.find('**/ButtonGoToDown'),
gui.find('**/ButtonGoToRollover'),
gui.find('**/ButtonGoToUp')), geom=gui.find('**/PetControlGoToIcon'), image3_color=disabledImageColor, relief=None, text=TTLocalizer.PetPanelCall, text0_fg=text0Color, text1_fg=text1Color, text2_fg=text2Color, text3_fg=text3Color, text_scale=0.5, text_pos=(-0.5, 1.3), text_align=TextNode.ALeft)
self.callButton['state'] = DGG.DISABLED
self.scratchButton = DirectButton(parent=self.frame, image=(gui.find('**/ButtonScratchUp'),
gui.find('**/ButtonScratchDown'),
gui.find('**/ButtonScratchRollover'),
gui.find('**/ButtonScratchUp')), geom=gui.find('**/PetControlScratchIcon'), image3_color=disabledImageColor, relief=None, text=TTLocalizer.PetPanelScratch, text0_fg=text0Color, text1_fg=text1Color, text2_fg=text2Color, text3_fg=text3Color, text_scale=0.5, text_pos=(-0.5, 2.05), text_align=TextNode.ALeft)
self.scratchButton['state'] = DGG.DISABLED
self.callOwnerButton = DirectButton(parent=self.frame, image=(gui.find('**/PetControlToonButtonUp'), gui.find('**/PetControlToonButtonDown'), gui.find('**/PetControlToonButtonRollover')), geom=gui.find('**/PetControlToonIcon'), geom3_color=disabledImageColor, relief=None, image3_color=disabledImageColor, text=('',
TTLocalizer.PetPanelOwner,
TTLocalizer.PetPanelOwner,
''), text_fg=text2Color, text_shadow=(0, 0, 0, 1), text_scale=0.35, text_pos=(0.3, 1.1), text_align=TextNode.ACenter, command=self.__handleDetail)
self.callOwnerButton['state'] = DGG.DISABLED
self.detailButton = DirectButton(parent=self.frame, image=(gui.find('**/PetControlToonButtonUp1'), gui.find('**/PetControlToonButtonDown1'), gui.find('**/PetControlToonButtonRollover1')), geom=gui.find('**/PetBattleIcon'), geom3_color=disabledImageColor, relief=None, pos=(0, 0, 0), image3_color=disabledImageColor, text=('',
TTLocalizer.PetPanelDetail,
TTLocalizer.PetPanelDetail,
''), text_fg=text2Color, text_shadow=(0, 0, 0, 1), text_scale=0.35, text_pos=(0.3, 1.1), text_align=TextNode.ACenter, command=self.__handleDetail)
self.detailButton['state'] = DGG.NORMAL
gui.removeNode()
self.nameLabel = None
self.trickMenu = TTSCPetTrickMenu.TTSCPetTrickMenu()
self.settings = SCSettings.SCSettings(eventPrefix='')
self.trickMenu.privSetSettingsRef(self.settings)
self.trickMenuEventName = self.trickMenu.getEventName(SpeedChatGlobals.SCStaticTextMsgEvent)
self.trickMenu.setScale(0.055)
self.trickMenu.setBin('gui-popup', 0)
self.trickMenu.finalizeAll()
localAvatar.chatMgr.chatInputSpeedChat.whisperAvatarId = None
self.petDetailPanel = None
return
def unload(self):
self.frame.destroy()
del self.frame
self.frame = None
if hasattr(self, 'petView'):
self.petView.removeNode()
del self.petView
if hasattr(self, 'petModel'):
self.petModel.delete()
del self.petModel
del self.closeButton
del self.feedButton
del self.callButton
del self.scratchButton
del self.callOwnerButton
del self.detailButton
self.trickMenu.destroy()
del self.trickMenu
del self.petDetailPanel
return
def enter(self, petProxyId):
self.petProxyId = petProxyId
if petProxyId not in base.cr.doId2do:
self.notify.warning('petProxyId %s not in doId2do!' % petProxyId)
return
else:
self.petProxy = base.cr.doId2do[petProxyId]
self.__fillPetInfo(self.petProxy)
self.frame.show()
self.accept(self.trickMenuEventName, self.__handleTrickMenuEvent)
self.trickMenu.reparentTo(aspect2dp, DGG.FOREGROUND_SORT_INDEX)
localAvatar.chatMgr.chatInputSpeedChat.whisperAvatarId = None
self.detailButton['state'] = DGG.NORMAL
return
def exit(self):
self.ignore(self.trickMenuEventName)
self.trickMenu.reparentTo(hidden)
self.petProxy = None
if self.petDetailPanel != None:
self.petDetailPanel.cleanup()
self.petDetailPanel = None
self.frame.hide()
return
def __handleTrickMenuEvent(self, textId):
if textId in PetTricks.ScId2trickId:
trickId = PetTricks.ScId2trickId[textId]
doneStatus = {'mode': 'OK',
'trickId': trickId}
messenger.send(self.doneEvent, [doneStatus])
self.detailButton['state'] = DGG.NORMAL
def __handleClose(self):
doneStatus = {'mode': 'Back'}
messenger.send(self.doneEvent, [doneStatus])
def __handleCall(self):
doneStatus = {'mode': 'OK',
'trickId': 0}
messenger.send(self.doneEvent, [doneStatus])
def __handleDetailDone(self):
if self.petDetailPanel != None:
self.petDetailPanel.cleanup()
self.petDetailPanel = None
self.detailButton['state'] = DGG.NORMAL
return
def __handleDetail(self):
self.petDetailPanel = PetDetailPanel.PetDetailPanel(pet=self.petProxy, closeCallback=self.__handleDetailDone, parent=self.frame)
self.detailButton['state'] = DGG.DISABLED
def __fillPetInfo(self, avatar):
self.notify.debug('__fillPetInfo(): doId=%s' % avatar.doId)
if self.nameLabel == None:
self.petView = self.frame.attachNewNode('petView')
self.petView.setPos(0, 0, 5.4)
self.petModel = Pet.Pet(forGui=1)
self.petModel.setDNA(avatar.getDNA())
self.petModel.fitAndCenterHead(3.575, forGui=1)
self.petModel.reparentTo(self.petView)
self.petModel.enterNeutralHappy()
self.petModel.startBlink()
self.petModel.setScale(0.75)
self.nameLabel = DirectLabel(parent=self.frame, pos=(0, 0, 5.2), relief=None, text=avatar.getName(), text_font=avatar.getFont(), text_fg=Vec4(0, 0, 0, 1), text_pos=(0, 0), text_scale=0.4, text_wordwrap=7.5, text_shadow=(1, 1, 1, 1))
self.stateLabel = DirectLabel(parent=self.frame, pos=(0.7, 0, 3.5), relief=None, text='', text_font=avatar.getFont(), text_fg=Vec4(0, 0, 0, 1), text_scale=0.4, text_wordwrap=7.5, text_shadow=(1, 1, 1, 1))
self.__refreshPetInfo(avatar)
return
def __refreshPetInfo(self, avatar):
self.notify.debug('__refreshPetInfo(): doId=%s' % avatar.doId)
avatar.updateOfflineMood()
mood = avatar.getDominantMood()
self.stateLabel['text'] = TTLocalizer.PetMoodAdjectives[mood]
self.nameLabel['text'] = avatar.getName() | apache-2.0 |
canalplus/rx-player | src/parsers/texttracks/ttml/html/ttml_color_to_css_color.ts | 2007 | /**
* Copyright 2015 CANAL+ Group
*
* 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 {
REGXP_4_HEX_COLOR,
REGXP_8_HEX_COLOR,
REGXP_RGBA_COLOR,
REGXP_RGB_COLOR,
} from "../regexps";
/**
* Translate a color indicated in TTML-style to a CSS-style color.
* @param {string} color
* @returns {string} color
*/
export default function ttmlColorToCSSColor(color : string) : string {
// TODO check all possible color fomats
let regRes;
regRes = REGXP_8_HEX_COLOR.exec(color);
if (regRes != null) {
return "rgba(" +
String(parseInt(regRes[1], 16)) + "," +
String(parseInt(regRes[2], 16)) + "," +
String(parseInt(regRes[3], 16)) + "," +
String(parseInt(regRes[4], 16) / 255) + ")";
}
regRes = REGXP_4_HEX_COLOR.exec(color);
if (regRes != null) {
return "rgba(" +
String(parseInt(regRes[1] + regRes[1], 16)) + "," +
String(parseInt(regRes[2] + regRes[2], 16)) + "," +
String(parseInt(regRes[3] + regRes[3], 16)) + "," +
String(parseInt(regRes[4] + regRes[4], 16) / 255) + ")";
}
regRes = REGXP_RGB_COLOR.exec(color);
if (regRes != null) {
return "rgb(" +
String(+regRes[1]) + "," +
String(+regRes[2]) + "," +
String(+regRes[3]) + ")";
}
regRes = REGXP_RGBA_COLOR.exec(color);
if (regRes != null) {
return "rgba(" +
String(+regRes[1]) + "," +
String(+regRes[2]) + "," +
String(+regRes[3]) + "," +
String(+regRes[4] / 255) + ")";
}
return color;
}
| apache-2.0 |
nuest/iceland | core/src/main/java/org/n52/iceland/coding/encode/ProcedureEncoder.java | 1349 | /*
* Copyright 2015 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* 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.n52.iceland.coding.encode;
import java.util.Set;
import org.n52.iceland.coding.ProcedureCoder;
/**
* @since 1.0.0
*
* @param <S>
* @param <T>
*/
@Deprecated // SOS-specific
public interface ProcedureEncoder<S, T> extends Encoder<S, T>, ProcedureCoder {
/**
* Get the supported procedure description formats for this
* {@linkplain ProcedureEncoder} and the specified service and version.
*
* @param service
* the service
* @param version
* the version
*
* @return the procedure description formats
*/
@Override
Set<String> getSupportedProcedureDescriptionFormats(String service, String version);
}
| apache-2.0 |
aleo72/ww-ceem-radar | src/main/java/gov/nasa/worldwind/util/webview/AbstractWebView.java | 3705 | /*
* Copyright (C) 2012 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration.
* All Rights Reserved.
*/
package gov.nasa.worldwind.util.webview;
import gov.nasa.worldwind.*;
import gov.nasa.worldwind.avlist.AVKey;
import gov.nasa.worldwind.render.*;
import gov.nasa.worldwind.util.Logging;
import javax.swing.*;
import java.awt.*;
import java.beans.PropertyChangeEvent;
/**
* Abstract base class for {@link WebView} implementations.
*
* @author pabercrombie
* @version $Id: AbstractWebView.java 1171 2013-02-11 21:45:02Z dcollins $
*/
public abstract class AbstractWebView extends WWObjectImpl implements WebView, Disposable
{
/** The size of the WebView frame in pixels. Initially null, indicating the default size is used. */
protected Dimension frameSize;
/** The WebView's current texture representation. Lazily created in {@link #getTextureRepresentation}. */
protected WWTexture textureRep;
/** Indicates whether the WebView is active. */
protected boolean active;
/**
* Overridden to ensure that the WebView's native resources are disposed when the WebView is reclaimed by the
* garbage collector. This does nothing if the WebView's owner has already called {@link #dispose()}.
*/
@Override
protected void finalize() throws Throwable
{
this.dispose();
super.finalize();
}
/** {@inheritDoc} */
public Dimension getFrameSize()
{
return this.frameSize;
}
/** {@inheritDoc} */
public void setFrameSize(Dimension size)
{
if (size == null)
{
String message = Logging.getMessage("nullValue.SizeIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
// Setting the frame size requires a call into native code, and requires us to regenerate the texture. Only
// do this if the size has actually changed.
if (this.frameSize.equals(size))
return;
this.frameSize = size;
this.textureRep = null; // The texture needs to be regenerated because the frame size changed.
this.doSetFrameSize(this.frameSize);
}
protected abstract void doSetFrameSize(Dimension size);
/** {@inheritDoc} */
public WWTexture getTextureRepresentation(DrawContext dc)
{
if (dc == null)
{
String message = Logging.getMessage("nullValue.DrawContextIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
if (this.textureRep == null)
this.textureRep = this.createTextureRepresentation(dc);
return this.textureRep;
}
/** {@inheritDoc} */
public void setActive(boolean active)
{
this.active = active;
}
/** {@inheritDoc} */
public boolean isActive()
{
return this.active;
}
/**
* Create a texture representation of the WebView.
*
* @param dc draw context.
*
* @return A texture representation of the WebView contents.
*/
protected abstract WWTexture createTextureRepresentation(DrawContext dc);
@Override
public void propertyChange(final PropertyChangeEvent event)
{
if (!SwingUtilities.isEventDispatchThread())
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
propertyChange(event);
}
});
}
else
{
this.firePropertyChange(AVKey.REPAINT, null, this);
}
}
}
| apache-2.0 |
reflectsoftware/Plato.NET | src/Plato.Messaging.AMQ/Pool/AMQObjectPoolAsync.cs | 2069 | // Plato.NET
// Copyright (c) 2018 ReflectSoftware Inc.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Plato.Cache;
using Plato.Messaging.AMQ.Interfaces;
using Plato.Messaging.AMQ.Settings;
using System;
using System.Threading.Tasks;
namespace Plato.Messaging.AMQ.Pool
{
/// <summary>
///
/// </summary>
/// <seealso cref="Plato.Cache.GenericObjectPoolAsync{Plato.Messaging.AMQ.Pool.AMQObjectPoolData, System.Object}" />
internal class AMQObjectPoolAsync : GenericObjectPoolAsync<AMQObjectPoolData, object>
{
private readonly IAMQSenderReceiverFactory _factory;
private readonly Type _instanceType;
private readonly AMQConnectionSettings _connection;
private readonly AMQDestinationSettings _destination;
/// <summary>
/// Initializes a new instance of the <see cref="AMQObjectPool" /> class.
/// </summary>
/// <param name="factory">The factory.</param>
/// <param name="instanceType">Type of the instance.</param>
/// <param name="connection">The connection.</param>
/// <param name="destination">The destination.</param>
/// <param name="maxGrowSize">Maximum size of the grow.</param>
public AMQObjectPoolAsync(
IAMQSenderReceiverFactory factory,
Type instanceType,
AMQConnectionSettings connection,
AMQDestinationSettings destination,
int maxGrowSize) : base(0, maxGrowSize)
{
_factory = factory;
_instanceType = instanceType;
_connection = connection;
_destination = destination;
}
/// <summary>
/// Creates the pool object.
/// </summary>
/// <returns></returns>
protected override Task<AMQObjectPoolData> CreatePoolObjectAsync()
{
return Task.FromResult(new AMQObjectPoolData { Instance = _factory.Create(_instanceType, _connection, _destination) });
}
}
}
| apache-2.0 |
ctc-g/sinavi-jfw | web/jfw-web-core/src/main/java/jp/co/ctc_g/jse/core/util/web/beans/HalfAndFullwidthDecimalEditor.java | 5078 | /*
* Copyright (c) 2013 ITOCHU Techno-Solutions 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.
*/
package jp.co.ctc_g.jse.core.util.web.beans;
import java.math.BigDecimal;
import jp.co.ctc_g.jfw.core.internal.InternalException;
import jp.co.ctc_g.jfw.core.util.Strings;
/**
* <p>
* このクラスは小数値を扱うプロパティ・エディタです。
* ビーンの小数型のプロパティを編集する機能を提供します。<br/>
* 小数型とは以下の型を意味します。{@link Float}、{@link Double} についてはサポートしていません。ご注意ください。<br/>
* <ul>
* <li>{@link BigDecimal}</li>
* </ul>
*
* {@code Spring MVC} はこのプロパティ・エディタを用いてリクエスト・パラメータのBeanへのバインディング、および、
* Beanのプロパティ値の文字列への変換を行います。バインディングを行う際は文字列として送られてくるリクエスト・パラメータを
* 該当のBeanのプロパティの型に型変換する必要があり、型変換可能であるかどうかのチェックは 正規表現 {@code ^[--]?([0-90-9]+[..][0-90-9]+)$}
* に従い、半角・全角のリクエスト・パラメータを受け付けることが可能ですが、Beanにバインディングされた後、例えば入力検証失敗後の入力値の表示、
* または、入力画面後に表示する確認画面での入力値の表示は半角小数値となります。<br/>
* 全角で入力された場合に全角に復元されることを期待する場合は、Bean のプロパティを文字列型として定義するか要件を満たすプロパティ・エディタを
* 独自に実装する必要があります。
* </p>
* <h4>設定方法</h4>
* <p>
* 設定方法についてはパッケージの説明を参照して下さい。
* </p>
* <h4>小数値を扱うその他のプロパティ・エディタ</h4>
* <p>
* {@code J-Framework} では、小数値を扱うプロパティ・エディタが用意されています。これらのプロパティ・エディタの違いは、
* 受け付け可能な小数値のフォーマットです。クライアントサイドで許容する小数値のフォーマットに合わせて適宜プロパティ・エディタを選択して下さい。
* <ul>
* <li>HalfwidthDecimalEditor</li>
* <li>HalfwidthDecimalWithCommaEditor</li>
* <li>HalfAndFullwidthDecimalWithCommaEditor</li>
* </ul>
* </p>
* @author ITOCHU Techno-Solutions Corporation.
* @see AbstractNumberEditor
* @see HalfwidthDecimalEditor
* @see HalfwidthDecimalWithCommaEditor
* @see HalfAndFullwidthDecimalWithCommaEditor
*/
public class HalfAndFullwidthDecimalEditor extends AbstractNumberEditor {
private static final String PATTERN_STR = "^[--]?([0-90-9]+[..][0-90-9]+)$";
/**
* デフォルトコンストラクタです。
*/
public HalfAndFullwidthDecimalEditor() {}
/**
* <p>
* コンストラクタです。
* </p>
* @param propertyType 変換先の型
* @param allowEmpty trueの場合、空を許可する
* @throws IllegalArgumentException 不正な引数が指定された場合
*/
public HalfAndFullwidthDecimalEditor(Class<? extends Number> propertyType,
boolean allowEmpty) throws IllegalArgumentException {
this(propertyType, allowEmpty, null);
}
/**
* <p>
* コンストラクタです。
* </p>
* @param propertyType 変換先の型
* @param allowEmpty trueの場合、空を許可する
* @param message メッセージのコード
* @throws IllegalArgumentException 不正な引数が指定された場合
*/
public HalfAndFullwidthDecimalEditor(Class<? extends Number> propertyType,
boolean allowEmpty,
String message)
throws IllegalArgumentException {
if (propertyType == null) {
throw new InternalException(HalfAndFullwidthDecimalEditor.class, "E-NUMBER_EDITOR#0003");
}
this.pattern = PATTERN_STR;
this.format = null;
this.propertyType = propertyType;
this.allowEmpty = allowEmpty;
this.message = !Strings.isEmpty(message) ? message : Editors.NUMERIC_FORMAT_MESSAGE;
this.needFullWidthToHalfWidth = true;
}
@Override
protected String formatIfNeeded(Object value) {
return ((BigDecimal)value).toPlainString();
}
} | apache-2.0 |
eric-stanley/qalingo-engine | apis/api-web/api-web-fo-mcommerce/src/main/java/org/hoteia/qalingo/web/mvc/controller/common/ClpController.java | 3006 | /**
* Most of the code in the Qalingo project is copyrighted Hoteia and licensed
* under the Apache License Version 2.0 (release version 0.8.0)
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Hoteia, 2012-2014
* http://www.hoteia.com - http://twitter.com/hoteia - contact@hoteia.com
*
*/
package org.hoteia.qalingo.web.mvc.controller.common;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hoteia.qalingo.core.ModelConstants;
import org.hoteia.qalingo.core.domain.enumtype.FoUrls;
import org.hoteia.qalingo.core.i18n.enumtype.ScopeWebMessage;
import org.hoteia.qalingo.core.pojo.RequestData;
import org.hoteia.qalingo.core.web.mvc.viewbean.BreadcrumbViewBean;
import org.hoteia.qalingo.core.web.mvc.viewbean.MenuViewBean;
import org.hoteia.qalingo.core.web.servlet.ModelAndViewThemeDevice;
import org.hoteia.qalingo.web.mvc.controller.AbstractMCommerceController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* CLP Customer Loyalty Program
*/
@Controller("clpController")
public class ClpController extends AbstractMCommerceController {
@RequestMapping(FoUrls.CLP_URL)
public ModelAndView clp(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
ModelAndViewThemeDevice modelAndView = new ModelAndViewThemeDevice(getCurrentVelocityPath(request), FoUrls.CLP.getVelocityPage());
final RequestData requestData = requestUtil.getRequestData(request);
overrideDefaultMainContentTitle(request, modelAndView, FoUrls.CLP.getKey());
modelAndView.addObject(ModelConstants.BREADCRUMB_VIEW_BEAN, buildBreadcrumbViewBean(requestData));
return modelAndView;
}
protected BreadcrumbViewBean buildBreadcrumbViewBean(final RequestData requestData) {
final Locale locale = requestData.getLocale();
// BREADCRUMB
BreadcrumbViewBean breadcrumbViewBean = new BreadcrumbViewBean();
breadcrumbViewBean.setName(getSpecificMessage(ScopeWebMessage.HEADER_TITLE, FoUrls.CLP.getMessageKey(), locale));
List<MenuViewBean> menuViewBeans = new ArrayList<MenuViewBean>();
MenuViewBean menu = new MenuViewBean();
menu.setName(getSpecificMessage(ScopeWebMessage.HEADER_MENU, FoUrls.HOME.getMessageKey(), locale));
menu.setUrl(urlService.generateUrl(FoUrls.HOME, requestData));
menuViewBeans.add(menu);
menu = new MenuViewBean();
menu.setName(getSpecificMessage(ScopeWebMessage.HEADER_MENU, FoUrls.CLP.getMessageKey(), locale));
menu.setUrl(urlService.generateUrl(FoUrls.CLP, requestData));
menu.setActive(true);
menuViewBeans.add(menu);
breadcrumbViewBean.setMenus(menuViewBeans);
return breadcrumbViewBean;
}
} | apache-2.0 |
ubcsanskrit/dphil | lib/dphil/character.rb | 7019 | # frozen_string_literal: true
module Dphil
#
# Phylogenetic character for storing states and symbols.
#
# Immutable.
#
class Character
include Dphil::LDOutput
# Instantiates a new Character
# @overload initialize(id = nil, states = nil)
# @param id [Integer] a character ID
# @param states [Hash<Integer, String]] taxa and text-states +{ taxon_id => text_state }+
# @overload initialize(**opts = {})
# @param [Hash] opts options or keyword values
# @option opts [Integer] :id a character ID
# @option opts [Hash<Integer, String]] :states taxa and text-states +{ taxon_id => text_state }+
def initialize(id = nil, states = nil, **opts)
@id = (opts[:id] || id)&.to_s.to_i
@taxa_states = (opts[:states] || states)
.to_h.each_with_object({}) do |(taxon, state), acc|
next if state.blank?
taxon = taxon.to_s if taxon.is_a?(Symbol)
acc[taxon.to_i] = normalize_text(state)
end
unique_states = weighted_uniq(@taxa_states.values)
if unique_states.size > SYMBOL_ARRAY.size
raise ArgumentError,
"Too many states (found #{unique_states.size}, " \
"max #{SYMBOL_ARRAY.size})"
end
@states = {}
@state_totals = unique_states
unique_states.each_key.with_index do |state, index|
@states[SYMBOL_ARRAY[index]] = state
end
instance_variables.each { |ivar| instance_variable_get(ivar).freeze }
end
# @!attribute [r] id
# @return [Integer] character ID
attr_reader :id
# @!attribute [r] taxa
# @return [Set<Integer>] taxon IDs
def taxa
@taxa ||= Set.new(taxa_states.keys).freeze
end
# @!attribute [r] states
# @return [Hash<String, String>] text-states by symbol
attr_reader :states
# @!attribute [r] symbols
# @return [Hash<String, String>] symbols by text-state
def symbols
@symbols ||= states.invert.freeze
end
# @!attribute [r] state_list
# @return [Array<String>] text-states
def state_list
@state_list ||= states.values.freeze
end
# @!attribute [r] symbol_list
# @return [Array<String>] symbols
def symbol_list
@symbol_list ||= states.keys.freeze
end
# @!attribute [r] state_totals
# @return [Hash<String, Integer>] character state totals by text-state
attr_reader :state_totals
# @!attribute [r] symbol_totals
# @return [Hash<String, Integer>] character state totals by symbol
def symbol_totals
@symbol_totals ||= state_totals.transform_keys { |state| symbols[state] }.freeze
end
# @!attribute [r] taxa_states
# @return [Hash<Integer, String>] text-states by taxon ID
attr_reader :taxa_states
# @!attribute [r] taxa_symbols
# @return [Hash<Integer, String>] symbols by taxon ID
def taxa_symbols
@taxa_symbols ||= taxa_states.transform_values { |state| symbols[state] }.freeze
end
# @!attribute [r] states_taxa
# @return [Hash<String, Integer>] taxa IDs by text-state
def states_taxa
@states_taxa ||= (states.each_value.each_with_object({}) do |state, acc|
acc[state] = taxa_states.select { |_, tstate| state == tstate }.keys
end).freeze
end
# @!attribute [r] symbols_taxa
# @return [Hash<String, Integer>] taxa IDs by symbol
def symbols_taxa
@symbols_taxa ||= states_taxa.transform_keys { |state| symbols[state] }.freeze
end
# Get state from symbol
# @param symbol [String] a symbol
# @return [String, nil] the associated text-state, or Nil if not found
def get_state(symbol)
states[normalize_text(symbol)]
end
# Get symbol from state
# @param state [String] a text-state
# @return [String, nil] the associated symbol, or Nil if not found
def get_symbol(state)
symbols[normalize_text(state)]
end
# Get taxa from state
# @param symbol [String] a text-state
# @return [Array<Integer>] the associated taxa IDs
def get_taxa_state(state)
states_taxa[normalize_text(state)]
end
# Get taxa from symbol
# @param symbol [String] a symbol
# @return [Array<Integer>] the associated taxa IDs
def get_taxa_symbol(symbol)
symbols_taxa[normalize_text(symbol)]
end
# Get state from taxon
# @param taxon_id [Integer] a taxon ID
# @return [String, nil] the associated text-state, or Nil if not found
def get_state_taxon(taxon_id)
taxa_states[taxon_id.to_i]
end
# Get symbol from taxon
# @param taxon_id [Integer] a taxon ID
# @return [String, nil] the associated symbol, or Nil if not found
def get_symbol_taxon(taxon_id)
taxa_symbols[taxon_id.to_i]
end
# Check if character is parsimony-informative
# (At least 2 variants occurring in at least 2 places)
# @return [Boolean] whether the character provides useful information
def informative?
@informative ||= (states.size > 1 && states_taxa.count { |_, v| v.size > 1 } > 1)
end
# Check if the character is invariant
# @return [Boolean] whether the character is constant (invariant)
def constant?
@constant ||= states.size <= 1
end
def to_h
{
id: id,
states: states,
symbols: symbols,
state_totals: state_totals,
taxa_states: taxa_states,
states_taxa: states_taxa,
is_informative: informative?,
is_constant: constant?,
}
end
def as_json(options = nil)
to_h.as_json(options)
end
# Pretty-print the object
# (used by Pry in particular)
def pretty_print(q)
q.object_group(self) do
q.breakable
q.group(1) do
q.text "@id=#{id}"
q.breakable
q.group(1, "{", "}") do
q.seplist(states) do |symbol, state|
q.text "#{state.inspect}(#{symbol})=#{states_taxa[state]}"
end
end
end
end
end
# @return [String] a string representation of the object.
def inspect
pretty_inspect.chomp
end
alias to_s inspect
private
# @param text [String] an arbitrary string of text
# @return [String] a Unicode-normalized, stripped, frozen copy
def normalize_text(text)
return if text.nil?
text = UNF::Normalizer.normalize(text.to_s, :nfc)
text.strip!
text.freeze
end
# Find all unique elements in an array and stably sort them by frequency.
# @param array [Array]
# @return [Hash] keys are unique input array elements, values are frequency
def weighted_uniq(array)
weighted_hash = array.each_with_object({}) do |v, acc|
acc[v] ||= 0
acc[v] += 1
end
n = 0
weighted_hash = weighted_hash.sort_by do |x|
n += 1
[-x[1], n]
end
weighted_hash.to_h
end
SYMBOL_ARRAY = IceNine.deep_freeze([*"A".."Z", *"a".."z"])
private_constant :SYMBOL_ARRAY
end
end
| apache-2.0 |
BigBoss424/portfolio | v7/development/node_modules/react-share/lib/OKIcon.js | 970 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _iconFactory = require('./utils/iconFactory');
var _iconFactory2 = _interopRequireDefault(_iconFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var OKIcon = (0, _iconFactory2.default)('ok', {
icon: 'M39,30c-1,0-3,2-7,2s-6-2-7-2c-1.1,0-2,0.9-2,2c0,1,0.6,1.5,1,1.7c1.2,0.7,5,2.3,5,2.3l-4.3,5.4 c0,0-0.8,0.9-0.8,1.6c0,1.1,0.9,2,2,2c1,0,1.5-0.7,1.5-0.7S32,39,32,39c0,0,4.5,5.3,4.5,5.3S37,45,38,45c1.1,0,2-0.9,2-2 c0-0.6-0.8-1.6-0.8-1.6L35,36c0,0,3.8-1.6,5-2.3c0.4-0.3,1-0.7,1-1.7C41,30.9,40.1,30,39,30z M32,15c-3.9,0-7,3.1-7,7s3.1,7,7,7c3.9,0,7-3.1,7-7S35.9,15,32,15z M32,25.5 c-1.9,0-3.5-1.6-3.5-3.5c0-1.9,1.6-3.5,3.5-3.5c1.9,0,3.5,1.6,3.5,3.5C35.5,23.9,33.9,22.5,35,22.5z ',
mask: 'M45,1H5C2.8,1,1,2.8,1,5v40c0,2.2,1.8,4,4,4h40c2.2,0,4-1.8,4-4V5C49,2.8,47.2,1,45,1z',
color: '#f2720c'
});
exports.default = OKIcon; | apache-2.0 |
zhe-thoughts/hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/protocolPB/ClientNamenodeProtocolTranslatorPB.java | 58789 | /**
* 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.protocolPB;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import com.google.common.collect.Lists;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.crypto.CryptoProtocolVersion;
import org.apache.hadoop.fs.BatchedRemoteIterator.BatchedEntries;
import org.apache.hadoop.fs.CacheFlag;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.CreateFlag;
import org.apache.hadoop.fs.FileAlreadyExistsException;
import org.apache.hadoop.fs.FsServerDefaults;
import org.apache.hadoop.fs.Options.Rename;
import org.apache.hadoop.fs.ParentNotDirectoryException;
import org.apache.hadoop.fs.UnresolvedLinkException;
import org.apache.hadoop.fs.XAttr;
import org.apache.hadoop.fs.XAttrSetFlag;
import org.apache.hadoop.fs.permission.AclEntry;
import org.apache.hadoop.fs.permission.AclStatus;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.inotify.EventBatchList;
import org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException;
import org.apache.hadoop.hdfs.protocol.BlockStoragePolicy;
import org.apache.hadoop.hdfs.protocol.CacheDirectiveEntry;
import org.apache.hadoop.hdfs.protocol.CacheDirectiveInfo;
import org.apache.hadoop.hdfs.protocol.CachePoolEntry;
import org.apache.hadoop.hdfs.protocol.CachePoolInfo;
import org.apache.hadoop.hdfs.protocol.ClientProtocol;
import org.apache.hadoop.hdfs.protocol.CorruptFileBlocks;
import org.apache.hadoop.hdfs.protocol.DSQuotaExceededException;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.DirectoryListing;
import org.apache.hadoop.hdfs.protocol.EncryptionZone;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.RollingUpgradeAction;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.protocol.LastBlockWithStatus;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.protocol.NSQuotaExceededException;
import org.apache.hadoop.hdfs.protocol.RollingUpgradeInfo;
import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport;
import org.apache.hadoop.hdfs.protocol.SnapshottableDirectoryStatus;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.GetAclStatusRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.ModifyAclEntriesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.RemoveAclEntriesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.RemoveAclRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.RemoveDefaultAclRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos.SetAclRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AbandonBlockRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AddBlockRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AddCacheDirectiveRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AddCachePoolRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AllowSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AppendRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.AppendResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CachePoolEntryProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CheckAccessRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CompleteRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ConcatRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateSymlinkRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DeleteRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DeleteSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DisallowSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.FinalizeUpgradeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.FsyncRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetAdditionalDatanodeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetBlockLocationsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetBlockLocationsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetContentSummaryRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetCurrentEditLogTxidRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDataEncryptionKeyRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDataEncryptionKeyResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDatanodeReportRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDatanodeStorageReportRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetEditsFromTxidRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFileInfoRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFileInfoResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFileLinkInfoRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFileLinkInfoResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFsStatusRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetLinkTargetRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetLinkTargetResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetListingRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetListingResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetPreferredBlockSizeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetServerDefaultsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetSnapshotDiffReportRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetSnapshotDiffReportResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetSnapshottableDirListingRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetSnapshottableDirListingResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetStoragePoliciesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetStoragePoliciesResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.IsFileClosedRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCacheDirectivesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCacheDirectivesResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCachePoolsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCachePoolsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ListCorruptFileBlocksRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.MetaSaveRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.MkdirsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ModifyCacheDirectiveRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ModifyCachePoolRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RecoverLeaseRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RefreshNodesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RemoveCacheDirectiveRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RemoveCachePoolRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.Rename2RequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RenameRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RenameSnapshotRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RenewLeaseRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.ReportBadBlocksRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RestoreFailedStorageRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollEditsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollEditsResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollingUpgradeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollingUpgradeResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SaveNamespaceRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetBalancerBandwidthRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetOwnerRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetPermissionRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetQuotaRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetReplicationRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetSafeModeRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetTimesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.TruncateRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.UpdateBlockForPipelineRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.UpdatePipelineRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SetStoragePolicyRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos.CreateEncryptionZoneRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos.GetEZForPathRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos.ListEncryptionZonesRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.GetXAttrsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.ListXAttrsRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.RemoveXAttrRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.SetXAttrRequestProto;
import org.apache.hadoop.hdfs.security.token.block.DataEncryptionKey;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.hdfs.server.namenode.NotReplicatedYetException;
import org.apache.hadoop.hdfs.server.namenode.SafeModeException;
import org.apache.hadoop.hdfs.server.protocol.DatanodeStorageReport;
import org.apache.hadoop.hdfs.StorageType;
import org.apache.hadoop.io.EnumSetWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.ProtobufHelper;
import org.apache.hadoop.ipc.ProtocolMetaInterface;
import org.apache.hadoop.ipc.ProtocolTranslator;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RpcClientUtil;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.proto.SecurityProtos.CancelDelegationTokenRequestProto;
import org.apache.hadoop.security.proto.SecurityProtos.GetDelegationTokenRequestProto;
import org.apache.hadoop.security.proto.SecurityProtos.GetDelegationTokenResponseProto;
import org.apache.hadoop.security.proto.SecurityProtos.RenewDelegationTokenRequestProto;
import org.apache.hadoop.security.token.Token;
import com.google.protobuf.ByteString;
import com.google.protobuf.ServiceException;
import static org.apache.hadoop.fs.BatchedRemoteIterator.BatchedListEntries;
import static org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos
.EncryptionZoneProto;
/**
* This class forwards NN's ClientProtocol calls as RPC calls to the NN server
* while translating from the parameter types used in ClientProtocol to the
* new PB types.
*/
@InterfaceAudience.Private
@InterfaceStability.Stable
public class ClientNamenodeProtocolTranslatorPB implements
ProtocolMetaInterface, ClientProtocol, Closeable, ProtocolTranslator {
final private ClientNamenodeProtocolPB rpcProxy;
static final GetServerDefaultsRequestProto VOID_GET_SERVER_DEFAULT_REQUEST =
GetServerDefaultsRequestProto.newBuilder().build();
private final static GetFsStatusRequestProto VOID_GET_FSSTATUS_REQUEST =
GetFsStatusRequestProto.newBuilder().build();
private final static SaveNamespaceRequestProto VOID_SAVE_NAMESPACE_REQUEST =
SaveNamespaceRequestProto.newBuilder().build();
private final static RollEditsRequestProto VOID_ROLLEDITS_REQUEST =
RollEditsRequestProto.getDefaultInstance();
private final static RefreshNodesRequestProto VOID_REFRESH_NODES_REQUEST =
RefreshNodesRequestProto.newBuilder().build();
private final static FinalizeUpgradeRequestProto
VOID_FINALIZE_UPGRADE_REQUEST =
FinalizeUpgradeRequestProto.newBuilder().build();
private final static GetDataEncryptionKeyRequestProto
VOID_GET_DATA_ENCRYPTIONKEY_REQUEST =
GetDataEncryptionKeyRequestProto.newBuilder().build();
private final static GetStoragePoliciesRequestProto
VOID_GET_STORAGE_POLICIES_REQUEST =
GetStoragePoliciesRequestProto.newBuilder().build();
public ClientNamenodeProtocolTranslatorPB(ClientNamenodeProtocolPB proxy) {
rpcProxy = proxy;
}
@Override
public void close() {
RPC.stopProxy(rpcProxy);
}
@Override
public LocatedBlocks getBlockLocations(String src, long offset, long length)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
GetBlockLocationsRequestProto req = GetBlockLocationsRequestProto
.newBuilder()
.setSrc(src)
.setOffset(offset)
.setLength(length)
.build();
try {
GetBlockLocationsResponseProto resp = rpcProxy.getBlockLocations(null,
req);
return resp.hasLocations() ?
PBHelper.convert(resp.getLocations()) : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public FsServerDefaults getServerDefaults() throws IOException {
GetServerDefaultsRequestProto req = VOID_GET_SERVER_DEFAULT_REQUEST;
try {
return PBHelper
.convert(rpcProxy.getServerDefaults(null, req).getServerDefaults());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public HdfsFileStatus create(String src, FsPermission masked,
String clientName, EnumSetWritable<CreateFlag> flag,
boolean createParent, short replication, long blockSize,
CryptoProtocolVersion[] supportedVersions)
throws AccessControlException, AlreadyBeingCreatedException,
DSQuotaExceededException, FileAlreadyExistsException,
FileNotFoundException, NSQuotaExceededException,
ParentNotDirectoryException, SafeModeException, UnresolvedLinkException,
IOException {
CreateRequestProto.Builder builder = CreateRequestProto.newBuilder()
.setSrc(src)
.setMasked(PBHelper.convert(masked))
.setClientName(clientName)
.setCreateFlag(PBHelper.convertCreateFlag(flag))
.setCreateParent(createParent)
.setReplication(replication)
.setBlockSize(blockSize);
builder.addAllCryptoProtocolVersion(PBHelper.convert(supportedVersions));
CreateRequestProto req = builder.build();
try {
CreateResponseProto res = rpcProxy.create(null, req);
return res.hasFs() ? PBHelper.convert(res.getFs()) : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean truncate(String src, long newLength, String clientName)
throws IOException, UnresolvedLinkException {
TruncateRequestProto req = TruncateRequestProto.newBuilder()
.setSrc(src)
.setNewLength(newLength)
.setClientName(clientName)
.build();
try {
return rpcProxy.truncate(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public LastBlockWithStatus append(String src, String clientName,
EnumSetWritable<CreateFlag> flag) throws AccessControlException,
DSQuotaExceededException, FileNotFoundException, SafeModeException,
UnresolvedLinkException, IOException {
AppendRequestProto req = AppendRequestProto.newBuilder().setSrc(src)
.setClientName(clientName).setFlag(PBHelper.convertCreateFlag(flag))
.build();
try {
AppendResponseProto res = rpcProxy.append(null, req);
LocatedBlock lastBlock = res.hasBlock() ? PBHelper
.convert(res.getBlock()) : null;
HdfsFileStatus stat = (res.hasStat()) ? PBHelper.convert(res.getStat())
: null;
return new LastBlockWithStatus(lastBlock, stat);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean setReplication(String src, short replication)
throws AccessControlException, DSQuotaExceededException,
FileNotFoundException, SafeModeException, UnresolvedLinkException,
IOException {
SetReplicationRequestProto req = SetReplicationRequestProto.newBuilder()
.setSrc(src)
.setReplication(replication)
.build();
try {
return rpcProxy.setReplication(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setPermission(String src, FsPermission permission)
throws AccessControlException, FileNotFoundException, SafeModeException,
UnresolvedLinkException, IOException {
SetPermissionRequestProto req = SetPermissionRequestProto.newBuilder()
.setSrc(src)
.setPermission(PBHelper.convert(permission))
.build();
try {
rpcProxy.setPermission(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setOwner(String src, String username, String groupname)
throws AccessControlException, FileNotFoundException, SafeModeException,
UnresolvedLinkException, IOException {
SetOwnerRequestProto.Builder req = SetOwnerRequestProto.newBuilder()
.setSrc(src);
if (username != null)
req.setUsername(username);
if (groupname != null)
req.setGroupname(groupname);
try {
rpcProxy.setOwner(null, req.build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void abandonBlock(ExtendedBlock b, long fileId, String src,
String holder) throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
AbandonBlockRequestProto req = AbandonBlockRequestProto.newBuilder()
.setB(PBHelper.convert(b)).setSrc(src).setHolder(holder)
.setFileId(fileId).build();
try {
rpcProxy.abandonBlock(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public LocatedBlock addBlock(String src, String clientName,
ExtendedBlock previous, DatanodeInfo[] excludeNodes, long fileId,
String[] favoredNodes)
throws AccessControlException, FileNotFoundException,
NotReplicatedYetException, SafeModeException, UnresolvedLinkException,
IOException {
AddBlockRequestProto.Builder req = AddBlockRequestProto.newBuilder()
.setSrc(src).setClientName(clientName).setFileId(fileId);
if (previous != null)
req.setPrevious(PBHelper.convert(previous));
if (excludeNodes != null)
req.addAllExcludeNodes(PBHelper.convert(excludeNodes));
if (favoredNodes != null) {
req.addAllFavoredNodes(Arrays.asList(favoredNodes));
}
try {
return PBHelper.convert(rpcProxy.addBlock(null, req.build()).getBlock());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public LocatedBlock getAdditionalDatanode(String src, long fileId,
ExtendedBlock blk, DatanodeInfo[] existings, String[] existingStorageIDs,
DatanodeInfo[] excludes,
int numAdditionalNodes, String clientName) throws AccessControlException,
FileNotFoundException, SafeModeException, UnresolvedLinkException,
IOException {
GetAdditionalDatanodeRequestProto req = GetAdditionalDatanodeRequestProto
.newBuilder()
.setSrc(src)
.setFileId(fileId)
.setBlk(PBHelper.convert(blk))
.addAllExistings(PBHelper.convert(existings))
.addAllExistingStorageUuids(Arrays.asList(existingStorageIDs))
.addAllExcludes(PBHelper.convert(excludes))
.setNumAdditionalNodes(numAdditionalNodes)
.setClientName(clientName)
.build();
try {
return PBHelper.convert(rpcProxy.getAdditionalDatanode(null, req)
.getBlock());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean complete(String src, String clientName,
ExtendedBlock last, long fileId)
throws AccessControlException, FileNotFoundException, SafeModeException,
UnresolvedLinkException, IOException {
CompleteRequestProto.Builder req = CompleteRequestProto.newBuilder()
.setSrc(src)
.setClientName(clientName)
.setFileId(fileId);
if (last != null)
req.setLast(PBHelper.convert(last));
try {
return rpcProxy.complete(null, req.build()).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void reportBadBlocks(LocatedBlock[] blocks) throws IOException {
ReportBadBlocksRequestProto req = ReportBadBlocksRequestProto.newBuilder()
.addAllBlocks(Arrays.asList(PBHelper.convertLocatedBlock(blocks)))
.build();
try {
rpcProxy.reportBadBlocks(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean rename(String src, String dst) throws UnresolvedLinkException,
IOException {
RenameRequestProto req = RenameRequestProto.newBuilder()
.setSrc(src)
.setDst(dst).build();
try {
return rpcProxy.rename(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void rename2(String src, String dst, Rename... options)
throws AccessControlException, DSQuotaExceededException,
FileAlreadyExistsException, FileNotFoundException,
NSQuotaExceededException, ParentNotDirectoryException, SafeModeException,
UnresolvedLinkException, IOException {
boolean overwrite = false;
if (options != null) {
for (Rename option : options) {
if (option == Rename.OVERWRITE) {
overwrite = true;
}
}
}
Rename2RequestProto req = Rename2RequestProto.newBuilder().
setSrc(src).
setDst(dst).setOverwriteDest(overwrite).
build();
try {
rpcProxy.rename2(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void concat(String trg, String[] srcs) throws IOException,
UnresolvedLinkException {
ConcatRequestProto req = ConcatRequestProto.newBuilder().
setTrg(trg).
addAllSrcs(Arrays.asList(srcs)).build();
try {
rpcProxy.concat(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean delete(String src, boolean recursive)
throws AccessControlException, FileNotFoundException, SafeModeException,
UnresolvedLinkException, IOException {
DeleteRequestProto req = DeleteRequestProto.newBuilder().setSrc(src).setRecursive(recursive).build();
try {
return rpcProxy.delete(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean mkdirs(String src, FsPermission masked, boolean createParent)
throws AccessControlException, FileAlreadyExistsException,
FileNotFoundException, NSQuotaExceededException,
ParentNotDirectoryException, SafeModeException, UnresolvedLinkException,
IOException {
MkdirsRequestProto req = MkdirsRequestProto.newBuilder()
.setSrc(src)
.setMasked(PBHelper.convert(masked))
.setCreateParent(createParent).build();
try {
return rpcProxy.mkdirs(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public DirectoryListing getListing(String src, byte[] startAfter,
boolean needLocation) throws AccessControlException,
FileNotFoundException, UnresolvedLinkException, IOException {
GetListingRequestProto req = GetListingRequestProto.newBuilder()
.setSrc(src)
.setStartAfter(ByteString.copyFrom(startAfter))
.setNeedLocation(needLocation).build();
try {
GetListingResponseProto result = rpcProxy.getListing(null, req);
if (result.hasDirList()) {
return PBHelper.convert(result.getDirList());
}
return null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void renewLease(String clientName) throws AccessControlException,
IOException {
RenewLeaseRequestProto req = RenewLeaseRequestProto.newBuilder()
.setClientName(clientName).build();
try {
rpcProxy.renewLease(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean recoverLease(String src, String clientName)
throws IOException {
RecoverLeaseRequestProto req = RecoverLeaseRequestProto.newBuilder()
.setSrc(src)
.setClientName(clientName).build();
try {
return rpcProxy.recoverLease(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public long[] getStats() throws IOException {
try {
return PBHelper.convert(rpcProxy.getFsStats(null,
VOID_GET_FSSTATUS_REQUEST));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public DatanodeInfo[] getDatanodeReport(DatanodeReportType type)
throws IOException {
GetDatanodeReportRequestProto req = GetDatanodeReportRequestProto
.newBuilder()
.setType(PBHelper.convert(type)).build();
try {
return PBHelper.convert(
rpcProxy.getDatanodeReport(null, req).getDiList());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public DatanodeStorageReport[] getDatanodeStorageReport(DatanodeReportType type)
throws IOException {
final GetDatanodeStorageReportRequestProto req
= GetDatanodeStorageReportRequestProto.newBuilder()
.setType(PBHelper.convert(type)).build();
try {
return PBHelper.convertDatanodeStorageReports(
rpcProxy.getDatanodeStorageReport(null, req).getDatanodeStorageReportsList());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public long getPreferredBlockSize(String filename) throws IOException,
UnresolvedLinkException {
GetPreferredBlockSizeRequestProto req = GetPreferredBlockSizeRequestProto
.newBuilder()
.setFilename(filename)
.build();
try {
return rpcProxy.getPreferredBlockSize(null, req).getBsize();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean setSafeMode(SafeModeAction action, boolean isChecked) throws IOException {
SetSafeModeRequestProto req = SetSafeModeRequestProto.newBuilder()
.setAction(PBHelper.convert(action)).setChecked(isChecked).build();
try {
return rpcProxy.setSafeMode(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void saveNamespace() throws AccessControlException, IOException {
try {
rpcProxy.saveNamespace(null, VOID_SAVE_NAMESPACE_REQUEST);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public long rollEdits() throws AccessControlException, IOException {
try {
RollEditsResponseProto resp = rpcProxy.rollEdits(null,
VOID_ROLLEDITS_REQUEST);
return resp.getNewSegmentTxId();
} catch (ServiceException se) {
throw ProtobufHelper.getRemoteException(se);
}
}
@Override
public boolean restoreFailedStorage(String arg)
throws AccessControlException, IOException{
RestoreFailedStorageRequestProto req = RestoreFailedStorageRequestProto
.newBuilder()
.setArg(arg).build();
try {
return rpcProxy.restoreFailedStorage(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void refreshNodes() throws IOException {
try {
rpcProxy.refreshNodes(null, VOID_REFRESH_NODES_REQUEST);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void finalizeUpgrade() throws IOException {
try {
rpcProxy.finalizeUpgrade(null, VOID_FINALIZE_UPGRADE_REQUEST);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public RollingUpgradeInfo rollingUpgrade(RollingUpgradeAction action) throws IOException {
final RollingUpgradeRequestProto r = RollingUpgradeRequestProto.newBuilder()
.setAction(PBHelper.convert(action)).build();
try {
final RollingUpgradeResponseProto proto = rpcProxy.rollingUpgrade(null, r);
if (proto.hasRollingUpgradeInfo()) {
return PBHelper.convert(proto.getRollingUpgradeInfo());
}
return null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public CorruptFileBlocks listCorruptFileBlocks(String path, String cookie)
throws IOException {
ListCorruptFileBlocksRequestProto.Builder req =
ListCorruptFileBlocksRequestProto.newBuilder().setPath(path);
if (cookie != null)
req.setCookie(cookie);
try {
return PBHelper.convert(
rpcProxy.listCorruptFileBlocks(null, req.build()).getCorrupt());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void metaSave(String filename) throws IOException {
MetaSaveRequestProto req = MetaSaveRequestProto.newBuilder()
.setFilename(filename).build();
try {
rpcProxy.metaSave(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public HdfsFileStatus getFileInfo(String src) throws AccessControlException,
FileNotFoundException, UnresolvedLinkException, IOException {
GetFileInfoRequestProto req = GetFileInfoRequestProto.newBuilder()
.setSrc(src).build();
try {
GetFileInfoResponseProto res = rpcProxy.getFileInfo(null, req);
return res.hasFs() ? PBHelper.convert(res.getFs()) : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public HdfsFileStatus getFileLinkInfo(String src)
throws AccessControlException, UnresolvedLinkException, IOException {
GetFileLinkInfoRequestProto req = GetFileLinkInfoRequestProto.newBuilder()
.setSrc(src).build();
try {
GetFileLinkInfoResponseProto result = rpcProxy.getFileLinkInfo(null, req);
return result.hasFs() ?
PBHelper.convert(rpcProxy.getFileLinkInfo(null, req).getFs()) : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public ContentSummary getContentSummary(String path)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
GetContentSummaryRequestProto req = GetContentSummaryRequestProto
.newBuilder()
.setPath(path)
.build();
try {
return PBHelper.convert(rpcProxy.getContentSummary(null, req)
.getSummary());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setQuota(String path, long namespaceQuota, long diskspaceQuota,
StorageType type)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
final SetQuotaRequestProto.Builder builder
= SetQuotaRequestProto.newBuilder()
.setPath(path)
.setNamespaceQuota(namespaceQuota)
.setDiskspaceQuota(diskspaceQuota);
if (type != null) {
builder.setStorageType(PBHelper.convertStorageType(type));
}
final SetQuotaRequestProto req = builder.build();
try {
rpcProxy.setQuota(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void fsync(String src, long fileId, String client,
long lastBlockLength)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
FsyncRequestProto req = FsyncRequestProto.newBuilder().setSrc(src)
.setClient(client).setLastBlockLength(lastBlockLength)
.setFileId(fileId).build();
try {
rpcProxy.fsync(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setTimes(String src, long mtime, long atime)
throws AccessControlException, FileNotFoundException,
UnresolvedLinkException, IOException {
SetTimesRequestProto req = SetTimesRequestProto.newBuilder()
.setSrc(src)
.setMtime(mtime)
.setAtime(atime)
.build();
try {
rpcProxy.setTimes(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void createSymlink(String target, String link, FsPermission dirPerm,
boolean createParent) throws AccessControlException,
FileAlreadyExistsException, FileNotFoundException,
ParentNotDirectoryException, SafeModeException, UnresolvedLinkException,
IOException {
CreateSymlinkRequestProto req = CreateSymlinkRequestProto.newBuilder()
.setTarget(target)
.setLink(link)
.setDirPerm(PBHelper.convert(dirPerm))
.setCreateParent(createParent)
.build();
try {
rpcProxy.createSymlink(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public String getLinkTarget(String path) throws AccessControlException,
FileNotFoundException, IOException {
GetLinkTargetRequestProto req = GetLinkTargetRequestProto.newBuilder()
.setPath(path).build();
try {
GetLinkTargetResponseProto rsp = rpcProxy.getLinkTarget(null, req);
return rsp.hasTargetPath() ? rsp.getTargetPath() : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public LocatedBlock updateBlockForPipeline(ExtendedBlock block,
String clientName) throws IOException {
UpdateBlockForPipelineRequestProto req = UpdateBlockForPipelineRequestProto
.newBuilder()
.setBlock(PBHelper.convert(block))
.setClientName(clientName)
.build();
try {
return PBHelper.convert(
rpcProxy.updateBlockForPipeline(null, req).getBlock());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void updatePipeline(String clientName, ExtendedBlock oldBlock,
ExtendedBlock newBlock, DatanodeID[] newNodes, String[] storageIDs) throws IOException {
UpdatePipelineRequestProto req = UpdatePipelineRequestProto.newBuilder()
.setClientName(clientName)
.setOldBlock(PBHelper.convert(oldBlock))
.setNewBlock(PBHelper.convert(newBlock))
.addAllNewNodes(Arrays.asList(PBHelper.convert(newNodes)))
.addAllStorageIDs(storageIDs == null ? null : Arrays.asList(storageIDs))
.build();
try {
rpcProxy.updatePipeline(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public Token<DelegationTokenIdentifier> getDelegationToken(Text renewer)
throws IOException {
GetDelegationTokenRequestProto req = GetDelegationTokenRequestProto
.newBuilder()
.setRenewer(renewer.toString())
.build();
try {
GetDelegationTokenResponseProto resp = rpcProxy.getDelegationToken(null, req);
return resp.hasToken() ? PBHelper.convertDelegationToken(resp.getToken())
: null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public long renewDelegationToken(Token<DelegationTokenIdentifier> token)
throws IOException {
RenewDelegationTokenRequestProto req = RenewDelegationTokenRequestProto.newBuilder().
setToken(PBHelper.convert(token)).
build();
try {
return rpcProxy.renewDelegationToken(null, req).getNewExpiryTime();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void cancelDelegationToken(Token<DelegationTokenIdentifier> token)
throws IOException {
CancelDelegationTokenRequestProto req = CancelDelegationTokenRequestProto
.newBuilder()
.setToken(PBHelper.convert(token))
.build();
try {
rpcProxy.cancelDelegationToken(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setBalancerBandwidth(long bandwidth) throws IOException {
SetBalancerBandwidthRequestProto req = SetBalancerBandwidthRequestProto.newBuilder()
.setBandwidth(bandwidth)
.build();
try {
rpcProxy.setBalancerBandwidth(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean isMethodSupported(String methodName) throws IOException {
return RpcClientUtil.isMethodSupported(rpcProxy,
ClientNamenodeProtocolPB.class, RPC.RpcKind.RPC_PROTOCOL_BUFFER,
RPC.getProtocolVersion(ClientNamenodeProtocolPB.class), methodName);
}
@Override
public DataEncryptionKey getDataEncryptionKey() throws IOException {
try {
GetDataEncryptionKeyResponseProto rsp = rpcProxy.getDataEncryptionKey(
null, VOID_GET_DATA_ENCRYPTIONKEY_REQUEST);
return rsp.hasDataEncryptionKey() ?
PBHelper.convert(rsp.getDataEncryptionKey()) : null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public boolean isFileClosed(String src) throws AccessControlException,
FileNotFoundException, UnresolvedLinkException, IOException {
IsFileClosedRequestProto req = IsFileClosedRequestProto.newBuilder()
.setSrc(src).build();
try {
return rpcProxy.isFileClosed(null, req).getResult();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public Object getUnderlyingProxyObject() {
return rpcProxy;
}
@Override
public String createSnapshot(String snapshotRoot, String snapshotName)
throws IOException {
final CreateSnapshotRequestProto.Builder builder
= CreateSnapshotRequestProto.newBuilder().setSnapshotRoot(snapshotRoot);
if (snapshotName != null) {
builder.setSnapshotName(snapshotName);
}
final CreateSnapshotRequestProto req = builder.build();
try {
return rpcProxy.createSnapshot(null, req).getSnapshotPath();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void deleteSnapshot(String snapshotRoot, String snapshotName)
throws IOException {
DeleteSnapshotRequestProto req = DeleteSnapshotRequestProto.newBuilder()
.setSnapshotRoot(snapshotRoot).setSnapshotName(snapshotName).build();
try {
rpcProxy.deleteSnapshot(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void allowSnapshot(String snapshotRoot) throws IOException {
AllowSnapshotRequestProto req = AllowSnapshotRequestProto.newBuilder()
.setSnapshotRoot(snapshotRoot).build();
try {
rpcProxy.allowSnapshot(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void disallowSnapshot(String snapshotRoot) throws IOException {
DisallowSnapshotRequestProto req = DisallowSnapshotRequestProto
.newBuilder().setSnapshotRoot(snapshotRoot).build();
try {
rpcProxy.disallowSnapshot(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void renameSnapshot(String snapshotRoot, String snapshotOldName,
String snapshotNewName) throws IOException {
RenameSnapshotRequestProto req = RenameSnapshotRequestProto.newBuilder()
.setSnapshotRoot(snapshotRoot).setSnapshotOldName(snapshotOldName)
.setSnapshotNewName(snapshotNewName).build();
try {
rpcProxy.renameSnapshot(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public SnapshottableDirectoryStatus[] getSnapshottableDirListing()
throws IOException {
GetSnapshottableDirListingRequestProto req =
GetSnapshottableDirListingRequestProto.newBuilder().build();
try {
GetSnapshottableDirListingResponseProto result = rpcProxy
.getSnapshottableDirListing(null, req);
if (result.hasSnapshottableDirList()) {
return PBHelper.convert(result.getSnapshottableDirList());
}
return null;
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public SnapshotDiffReport getSnapshotDiffReport(String snapshotRoot,
String fromSnapshot, String toSnapshot) throws IOException {
GetSnapshotDiffReportRequestProto req = GetSnapshotDiffReportRequestProto
.newBuilder().setSnapshotRoot(snapshotRoot)
.setFromSnapshot(fromSnapshot).setToSnapshot(toSnapshot).build();
try {
GetSnapshotDiffReportResponseProto result =
rpcProxy.getSnapshotDiffReport(null, req);
return PBHelper.convert(result.getDiffReport());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public long addCacheDirective(CacheDirectiveInfo directive,
EnumSet<CacheFlag> flags) throws IOException {
try {
AddCacheDirectiveRequestProto.Builder builder =
AddCacheDirectiveRequestProto.newBuilder().
setInfo(PBHelper.convert(directive));
if (!flags.isEmpty()) {
builder.setCacheFlags(PBHelper.convertCacheFlags(flags));
}
return rpcProxy.addCacheDirective(null, builder.build()).getId();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void modifyCacheDirective(CacheDirectiveInfo directive,
EnumSet<CacheFlag> flags) throws IOException {
try {
ModifyCacheDirectiveRequestProto.Builder builder =
ModifyCacheDirectiveRequestProto.newBuilder().
setInfo(PBHelper.convert(directive));
if (!flags.isEmpty()) {
builder.setCacheFlags(PBHelper.convertCacheFlags(flags));
}
rpcProxy.modifyCacheDirective(null, builder.build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeCacheDirective(long id)
throws IOException {
try {
rpcProxy.removeCacheDirective(null,
RemoveCacheDirectiveRequestProto.newBuilder().
setId(id).build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
private static class BatchedCacheEntries
implements BatchedEntries<CacheDirectiveEntry> {
private final ListCacheDirectivesResponseProto response;
BatchedCacheEntries(
ListCacheDirectivesResponseProto response) {
this.response = response;
}
@Override
public CacheDirectiveEntry get(int i) {
return PBHelper.convert(response.getElements(i));
}
@Override
public int size() {
return response.getElementsCount();
}
@Override
public boolean hasMore() {
return response.getHasMore();
}
}
@Override
public BatchedEntries<CacheDirectiveEntry>
listCacheDirectives(long prevId,
CacheDirectiveInfo filter) throws IOException {
if (filter == null) {
filter = new CacheDirectiveInfo.Builder().build();
}
try {
return new BatchedCacheEntries(
rpcProxy.listCacheDirectives(null,
ListCacheDirectivesRequestProto.newBuilder().
setPrevId(prevId).
setFilter(PBHelper.convert(filter)).
build()));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void addCachePool(CachePoolInfo info) throws IOException {
AddCachePoolRequestProto.Builder builder =
AddCachePoolRequestProto.newBuilder();
builder.setInfo(PBHelper.convert(info));
try {
rpcProxy.addCachePool(null, builder.build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void modifyCachePool(CachePoolInfo req) throws IOException {
ModifyCachePoolRequestProto.Builder builder =
ModifyCachePoolRequestProto.newBuilder();
builder.setInfo(PBHelper.convert(req));
try {
rpcProxy.modifyCachePool(null, builder.build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeCachePool(String cachePoolName) throws IOException {
try {
rpcProxy.removeCachePool(null,
RemoveCachePoolRequestProto.newBuilder().
setPoolName(cachePoolName).build());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
private static class BatchedCachePoolEntries
implements BatchedEntries<CachePoolEntry> {
private final ListCachePoolsResponseProto proto;
public BatchedCachePoolEntries(ListCachePoolsResponseProto proto) {
this.proto = proto;
}
@Override
public CachePoolEntry get(int i) {
CachePoolEntryProto elem = proto.getEntries(i);
return PBHelper.convert(elem);
}
@Override
public int size() {
return proto.getEntriesCount();
}
@Override
public boolean hasMore() {
return proto.getHasMore();
}
}
@Override
public BatchedEntries<CachePoolEntry> listCachePools(String prevKey)
throws IOException {
try {
return new BatchedCachePoolEntries(
rpcProxy.listCachePools(null,
ListCachePoolsRequestProto.newBuilder().
setPrevPoolName(prevKey).build()));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void modifyAclEntries(String src, List<AclEntry> aclSpec)
throws IOException {
ModifyAclEntriesRequestProto req = ModifyAclEntriesRequestProto
.newBuilder().setSrc(src)
.addAllAclSpec(PBHelper.convertAclEntryProto(aclSpec)).build();
try {
rpcProxy.modifyAclEntries(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeAclEntries(String src, List<AclEntry> aclSpec)
throws IOException {
RemoveAclEntriesRequestProto req = RemoveAclEntriesRequestProto
.newBuilder().setSrc(src)
.addAllAclSpec(PBHelper.convertAclEntryProto(aclSpec)).build();
try {
rpcProxy.removeAclEntries(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeDefaultAcl(String src) throws IOException {
RemoveDefaultAclRequestProto req = RemoveDefaultAclRequestProto
.newBuilder().setSrc(src).build();
try {
rpcProxy.removeDefaultAcl(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeAcl(String src) throws IOException {
RemoveAclRequestProto req = RemoveAclRequestProto.newBuilder()
.setSrc(src).build();
try {
rpcProxy.removeAcl(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setAcl(String src, List<AclEntry> aclSpec) throws IOException {
SetAclRequestProto req = SetAclRequestProto.newBuilder()
.setSrc(src)
.addAllAclSpec(PBHelper.convertAclEntryProto(aclSpec))
.build();
try {
rpcProxy.setAcl(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public AclStatus getAclStatus(String src) throws IOException {
GetAclStatusRequestProto req = GetAclStatusRequestProto.newBuilder()
.setSrc(src).build();
try {
return PBHelper.convert(rpcProxy.getAclStatus(null, req));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void createEncryptionZone(String src, String keyName)
throws IOException {
final CreateEncryptionZoneRequestProto.Builder builder =
CreateEncryptionZoneRequestProto.newBuilder();
builder.setSrc(src);
if (keyName != null && !keyName.isEmpty()) {
builder.setKeyName(keyName);
}
CreateEncryptionZoneRequestProto req = builder.build();
try {
rpcProxy.createEncryptionZone(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public EncryptionZone getEZForPath(String src)
throws IOException {
final GetEZForPathRequestProto.Builder builder =
GetEZForPathRequestProto.newBuilder();
builder.setSrc(src);
final GetEZForPathRequestProto req = builder.build();
try {
final EncryptionZonesProtos.GetEZForPathResponseProto response =
rpcProxy.getEZForPath(null, req);
if (response.hasZone()) {
return PBHelper.convert(response.getZone());
} else {
return null;
}
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public BatchedEntries<EncryptionZone> listEncryptionZones(long id)
throws IOException {
final ListEncryptionZonesRequestProto req =
ListEncryptionZonesRequestProto.newBuilder()
.setId(id)
.build();
try {
EncryptionZonesProtos.ListEncryptionZonesResponseProto response =
rpcProxy.listEncryptionZones(null, req);
List<EncryptionZone> elements =
Lists.newArrayListWithCapacity(response.getZonesCount());
for (EncryptionZoneProto p : response.getZonesList()) {
elements.add(PBHelper.convert(p));
}
return new BatchedListEntries<EncryptionZone>(elements,
response.getHasMore());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setXAttr(String src, XAttr xAttr, EnumSet<XAttrSetFlag> flag)
throws IOException {
SetXAttrRequestProto req = SetXAttrRequestProto.newBuilder()
.setSrc(src)
.setXAttr(PBHelper.convertXAttrProto(xAttr))
.setFlag(PBHelper.convert(flag))
.build();
try {
rpcProxy.setXAttr(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public List<XAttr> getXAttrs(String src, List<XAttr> xAttrs)
throws IOException {
GetXAttrsRequestProto.Builder builder = GetXAttrsRequestProto.newBuilder();
builder.setSrc(src);
if (xAttrs != null) {
builder.addAllXAttrs(PBHelper.convertXAttrProto(xAttrs));
}
GetXAttrsRequestProto req = builder.build();
try {
return PBHelper.convert(rpcProxy.getXAttrs(null, req));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public List<XAttr> listXAttrs(String src)
throws IOException {
ListXAttrsRequestProto.Builder builder = ListXAttrsRequestProto.newBuilder();
builder.setSrc(src);
ListXAttrsRequestProto req = builder.build();
try {
return PBHelper.convert(rpcProxy.listXAttrs(null, req));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void removeXAttr(String src, XAttr xAttr) throws IOException {
RemoveXAttrRequestProto req = RemoveXAttrRequestProto
.newBuilder().setSrc(src)
.setXAttr(PBHelper.convertXAttrProto(xAttr)).build();
try {
rpcProxy.removeXAttr(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void checkAccess(String path, FsAction mode) throws IOException {
CheckAccessRequestProto req = CheckAccessRequestProto.newBuilder()
.setPath(path).setMode(PBHelper.convert(mode)).build();
try {
rpcProxy.checkAccess(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public void setStoragePolicy(String src, String policyName)
throws IOException {
SetStoragePolicyRequestProto req = SetStoragePolicyRequestProto
.newBuilder().setSrc(src).setPolicyName(policyName).build();
try {
rpcProxy.setStoragePolicy(null, req);
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public BlockStoragePolicy[] getStoragePolicies() throws IOException {
try {
GetStoragePoliciesResponseProto response = rpcProxy
.getStoragePolicies(null, VOID_GET_STORAGE_POLICIES_REQUEST);
return PBHelper.convertStoragePolicies(response.getPoliciesList());
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
public long getCurrentEditLogTxid() throws IOException {
GetCurrentEditLogTxidRequestProto req = GetCurrentEditLogTxidRequestProto
.getDefaultInstance();
try {
return rpcProxy.getCurrentEditLogTxid(null, req).getTxid();
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
@Override
public EventBatchList getEditsFromTxid(long txid) throws IOException {
GetEditsFromTxidRequestProto req = GetEditsFromTxidRequestProto.newBuilder()
.setTxid(txid).build();
try {
return PBHelper.convert(rpcProxy.getEditsFromTxid(null, req));
} catch (ServiceException e) {
throw ProtobufHelper.getRemoteException(e);
}
}
}
| apache-2.0 |
Otaka/mydifferentprojects | SqlProcessorProject/src/main/java/com/sqlprocessor/utils/StringBuilderWithSeparator.java | 1188 | package com.sqlprocessor.utils;
/**
* @author sad
*/
public class StringBuilderWithSeparator {
private StringBuilder sb;
private boolean newEntry;
private String separator = ",";
public StringBuilderWithSeparator() {
this.newEntry = false;
this.sb = new StringBuilder();
}
public StringBuilderWithSeparator(String separator) {
this();
this.separator = separator;
}
public StringBuilderWithSeparator appendWithoutSeparator(String value) {
sb.append(value);
return this;
}
public StringBuilderWithSeparator append(int value) {
return append(Integer.toString(value));
}
public StringBuilderWithSeparator append(String value) {
if (newEntry) {
sb.append(separator);
newEntry = false;
}
sb.append(value);
return this;
}
public StringBuilderWithSeparator newEntry() {
newEntry = true;
return this;
}
public StringBuilderWithSeparator skipNewEntry(){
newEntry=false;
return this;
}
@Override
public String toString() {
return sb.toString();
}
}
| apache-2.0 |
EvilMcJerkface/crate | plugins/azure-discovery/src/main/java/io/crate/azure/management/AzureComputeService.java | 3128 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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 io.crate.azure.management;
import com.microsoft.azure.management.compute.ComputeManagementClient;
import com.microsoft.azure.management.network.NetworkResourceProviderClient;
import com.microsoft.windowsazure.Configuration;
import io.crate.azure.AzureConfiguration;
import io.crate.azure.discovery.AzureSeedHostsProvider;
import org.elasticsearch.common.component.LifecycleComponent;
import org.elasticsearch.common.settings.Setting;
import io.crate.common.unit.TimeValue;
import java.util.function.Function;
/**
*
*/
public interface AzureComputeService extends LifecycleComponent {
final class Management {
public static final Setting<String> SUBSCRIPTION_ID = Setting.simpleString(
"cloud.azure.management.subscription.id", Setting.Property.NodeScope, Setting.Property.Masked);
public static final Setting<String> RESOURCE_GROUP_NAME = Setting.simpleString(
"cloud.azure.management.resourcegroup.name", Setting.Property.NodeScope);
public static final Setting<String> TENANT_ID = Setting.simpleString(
"cloud.azure.management.tenant.id", Setting.Property.NodeScope, Setting.Property.Masked);
public static final Setting<String> APP_ID = Setting.simpleString(
"cloud.azure.management.app.id", Setting.Property.NodeScope, Setting.Property.Masked);
public static final Setting<String> APP_SECRET = Setting.simpleString(
"cloud.azure.management.app.secret", Setting.Property.NodeScope, Setting.Property.Masked);
}
final class Discovery {
public static final Setting<TimeValue> REFRESH = Setting.timeSetting(
"discovery.azure.refresh_interval", TimeValue.timeValueSeconds(5L), Setting.Property.NodeScope);
public static final Setting<String> HOST_TYPE = new Setting<>(
"discovery.azure.host.type", s -> AzureSeedHostsProvider.HostType.PRIVATE_IP.name(),
Function.identity(), Setting.Property.NodeScope);
public static final Setting<String> DISCOVERY_METHOD = new Setting<>(
"discovery.azure.method", s -> AzureConfiguration.VNET, Function.identity(), Setting.Property.NodeScope);
}
Configuration configuration();
ComputeManagementClient computeManagementClient();
NetworkResourceProviderClient networkResourceClient();
}
| apache-2.0 |
prime-framework/prime-mvc | src/main/java/org/primeframework/mvc/message/guice/MessageModule.java | 1910 | /*
* Copyright (c) 2012, Inversoft Inc., All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package org.primeframework.mvc.message.guice;
import java.util.ResourceBundle;
import org.primeframework.mvc.message.DefaultMessageStore;
import org.primeframework.mvc.message.DefaultMessageWorkflow;
import org.primeframework.mvc.message.MessageStore;
import org.primeframework.mvc.message.MessageWorkflow;
import org.primeframework.mvc.message.l10n.MessageProvider;
import org.primeframework.mvc.message.l10n.ResourceBundleMessageProvider;
import org.primeframework.mvc.message.l10n.WebControl;
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
/**
* This class is a Guice module for the Prime MVC message and l10n handling.
*
* @author Brian Pontarelli
*/
public class MessageModule extends AbstractModule {
@Override
protected void configure() {
bind(ResourceBundle.Control.class).to(WebControl.class).in(Singleton.class);
bindMessageStore();
bindMessageWorkflow();
bindMessageProvider();
}
protected void bindMessageStore() {
bind(MessageStore.class).to(DefaultMessageStore.class);
}
protected void bindMessageWorkflow() {
bind(MessageWorkflow.class).to(DefaultMessageWorkflow.class);
}
protected void bindMessageProvider() {
bind(MessageProvider.class).to(ResourceBundleMessageProvider.class);
}
}
| apache-2.0 |
xiayouli0122/Wardroid | src/com/example/ward/view/progressbar/HoloCircularProgressBar.java | 20400 | package com.example.ward.view.progressbar;
import com.example.ward.R;
import com.zhaoyan.common.utils.Log;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
/**
* HoloCircularProgressBar custom view.
*
* https://github.com/passsy/android-HoloCircularProgressBar
*
* @author Pascal.Welsch
* @version 1.3 (03.10.2014)
* @since 05.03.2013
*/
public class HoloCircularProgressBar extends View {
/**
* TAG constant for logging
*/
private static final String TAG = HoloCircularProgressBar.class.getSimpleName();
/**
* used to save the super state on configuration change
*/
private static final String INSTANCE_STATE_SAVEDSTATE = "saved_state";
/**
* used to save the progress on configuration changes
*/
private static final String INSTANCE_STATE_PROGRESS = "progress";
/**
* used to save the marker progress on configuration changes
*/
private static final String INSTANCE_STATE_MARKER_PROGRESS = "marker_progress";
/**
* used to save the background color of the progress
*/
private static final String INSTANCE_STATE_PROGRESS_BACKGROUND_COLOR
= "progress_background_color";
/**
* used to save the color of the progress
*/
private static final String INSTANCE_STATE_PROGRESS_COLOR = "progress_color";
/**
* used to save and restore the visibility of the thumb in this instance
*/
private static final String INSTANCE_STATE_THUMB_VISIBLE = "thumb_visible";
/**
* used to save and restore the visibility of the marker in this instance
*/
private static final String INSTANCE_STATE_MARKER_VISIBLE = "marker_visible";
/**
* The rectangle enclosing the circle.
*/
private final RectF mCircleBounds = new RectF();
/**
* the rect for the thumb square
*/
private final RectF mSquareRect = new RectF();
/**
* the paint for the background.
*/
private Paint mBackgroundColorPaint = new Paint();
/**
* The stroke width used to paint the circle.
*/
private int mCircleStrokeWidth = 14;
/**
* The gravity of the view. Where should the Circle be drawn within the given bounds
*
* {@link #computeInsets(int, int)}
*/
private int mGravity = Gravity.CENTER;
/**
* The Horizontal inset calcualted in {@link #computeInsets(int, int)} depends on {@link
* #mGravity}.
*/
private int mHorizontalInset = 0;
/**
* true if not all properties are set. then the view isn't drawn and there are no errors in the
* LayoutEditor
*/
private boolean mIsInitializing = true;
/**
* flag if the marker should be visible
*/
private boolean mIsMarkerEnabled = false;
/**
* indicates if the thumb is visible
*/
private boolean mIsThumbEnabled = true;
/**
* The Marker color paint.
*/
private Paint mMarkerColorPaint;
/**
* The Marker progress.
*/
private float mMarkerProgress = 0.0f;
/**
* the overdraw is true if the progress is over 1.0.
*/
private boolean mOverrdraw = false;
/**
* The current progress.
*/
private float mProgress = 0.3f;
/**
* The color of the progress background.
*/
private int mProgressBackgroundColor;
/**
* the color of the progress.
*/
private int mProgressColor;
/**
* paint for the progress.
*/
private Paint mProgressColorPaint;
/**
* Radius of the circle
*
* <p> Note: (Re)calculated in {@link #onMeasure(int, int)}. </p>
*/
private float mRadius;
/**
* The Thumb color paint.
*/
private Paint mThumbColorPaint = new Paint();
/**
* The Thumb pos x.
*
* Care. the position is not the position of the rotated thumb. The position is only calculated
* in {@link #onMeasure(int, int)}
*/
private float mThumbPosX;
/**
* The Thumb pos y.
*
* Care. the position is not the position of the rotated thumb. The position is only calculated
* in {@link #onMeasure(int, int)}
*/
private float mThumbPosY;
/**
* The pointer width (in pixels).
*/
private int mThumbRadius = 20;
/**
* The Translation offset x which gives us the ability to use our own coordinates system.
*/
private float mTranslationOffsetX;
/**
* The Translation offset y which gives us the ability to use our own coordinates system.
*/
private float mTranslationOffsetY;
/**
* The Vertical inset calcualted in {@link #computeInsets(int, int)} depends on {@link
* #mGravity}..
*/
private int mVerticalInset = 0;
/**
* Instantiates a new holo circular progress bar.
*
* @param context the context
*/
public HoloCircularProgressBar(final Context context) {
this(context, null);
}
/**
* Instantiates a new holo circular progress bar.
*
* @param context the context
* @param attrs the attrs
*/
public HoloCircularProgressBar(final Context context, final AttributeSet attrs) {
this(context, attrs, R.attr.circularProgressBarStyle);
}
/**
* Instantiates a new holo circular progress bar.
*
* @param context the context
* @param attrs the attrs
* @param defStyle the def style
*/
public HoloCircularProgressBar(final Context context, final AttributeSet attrs,
final int defStyle) {
super(context, attrs, defStyle);
// load the styled attributes and set their properties
final TypedArray attributes = context
.obtainStyledAttributes(attrs, R.styleable.HoloCircularProgressBar,
defStyle, 0);
if (attributes != null) {
try {
setProgressColor(attributes
.getColor(R.styleable.HoloCircularProgressBar_progress_color, Color.CYAN));
setProgressBackgroundColor(attributes
.getColor(R.styleable.HoloCircularProgressBar_progress_background_color,
Color.GREEN));
setProgress(
attributes.getFloat(R.styleable.HoloCircularProgressBar_progress, 0.0f));
setMarkerProgress(
attributes.getFloat(R.styleable.HoloCircularProgressBar_marker_progress,
0.0f));
setWheelSize((int) attributes
.getDimension(R.styleable.HoloCircularProgressBar_stroke_width, 14));
setThumbEnabled(attributes
.getBoolean(R.styleable.HoloCircularProgressBar_thumb_visible, true));
setMarkerEnabled(attributes
.getBoolean(R.styleable.HoloCircularProgressBar_marker_visible, true));
mGravity = attributes
.getInt(R.styleable.HoloCircularProgressBar_android_gravity,
Gravity.CENTER);
} finally {
// make sure recycle is always called.
attributes.recycle();
}
}
mThumbRadius = mCircleStrokeWidth * 2;
updateBackgroundColor();
updateMarkerColor();
updateProgressColor();
// the view has now all properties and can be drawn
mIsInitializing = false;
}
@Override
protected void onDraw(final Canvas canvas) {
// All of our positions are using our internal coordinate system.
// Instead of translating
// them we let Canvas do the work for us.
canvas.translate(mTranslationOffsetX, mTranslationOffsetY);
final float progressRotation = getCurrentRotation();
// draw the background
if (!mOverrdraw) {
canvas.drawArc(mCircleBounds, 270, -(360 - progressRotation), false,
mBackgroundColorPaint);
}
// draw the progress or a full circle if overdraw is true
canvas.drawArc(mCircleBounds, 270, mOverrdraw ? 360 : progressRotation, false,
mProgressColorPaint);
// draw the marker at the correct rotated position
if (mIsMarkerEnabled) {
final float markerRotation = getMarkerRotation();
canvas.save();
canvas.rotate(markerRotation - 90);
// canvas.drawLine((float) (mThumbPosX + mThumbRadius / 2 * 1.4), mThumbPosY,
// (float) (mThumbPosX - mThumbRadius / 2 * 1.4), mThumbPosY, mMarkerColorPaint);
Log.d("Yuri", "mCircleStrokeWidth:" + mCircleStrokeWidth);
Log.d("Yuri", "mThumbPosX:" + mThumbPosX);
Log.d("Yuri", "mThumbPosY:" + mThumbPosY);
canvas.drawCircle((float) (mThumbPosX), (float) (mThumbPosY + mCircleStrokeWidth * 2),
(float)(mCircleStrokeWidth / 2), mMarkerColorPaint);
canvas.restore();
}
if (isThumbEnabled()) {
// draw the thumb square at the correct rotated position
canvas.save();
canvas.rotate(progressRotation - 90);
// rotate the square by 45 degrees
// canvas.rotate(45, mThumbPosX, mThumbPosY);
// mSquareRect.left = mThumbPosX - mThumbRadius / 3;
// mSquareRect.right = mThumbPosX + mThumbRadius / 3;
// mSquareRect.top = mThumbPosY - mThumbRadius / 3;
// mSquareRect.bottom = mThumbPosY + mThumbRadius / 3;
// canvas.drawRect(mSquareRect, mThumbColorPaint);
canvas.drawCircle((float) (mThumbPosX), (float) (mThumbPosY),
(float)(mCircleStrokeWidth / 2), mMarkerColorPaint);
canvas.restore();
}
//画起始圆
canvas.save();
canvas.rotate(0 - 90);
canvas.drawCircle((float) (mRadius), (float) (0),
(float)(mCircleStrokeWidth / 2), mMarkerColorPaint);
canvas.restore();
}
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
final int height = getDefaultSize(
getSuggestedMinimumHeight() + getPaddingTop() + getPaddingBottom(),
heightMeasureSpec);
final int width = getDefaultSize(
getSuggestedMinimumWidth() + getPaddingLeft() + getPaddingRight(),
widthMeasureSpec);
final int diameter;
if (heightMeasureSpec == MeasureSpec.UNSPECIFIED) {
// ScrollView
diameter = width;
computeInsets(0, 0);
} else if (widthMeasureSpec == MeasureSpec.UNSPECIFIED) {
// HorizontalScrollView
diameter = height;
computeInsets(0, 0);
} else {
// Default
diameter = Math.min(width, height);
computeInsets(width - diameter, height - diameter);
}
setMeasuredDimension(diameter, diameter);
final float halfWidth = diameter * 0.5f;
// width of the drawed circle (+ the drawedThumb)
final float drawedWith;
if (isThumbEnabled()) {
drawedWith = mThumbRadius * (5f / 6f);
} else if (isMarkerEnabled()) {
drawedWith = mCircleStrokeWidth * 1.4f;
} else {
drawedWith = mCircleStrokeWidth / 2f;
}
// -0.5f for pixel perfect fit inside the viewbounds
mRadius = halfWidth - drawedWith - 0.5f;
Log.d("Yuri", "mRadius:" + mRadius);
mCircleBounds.set(-mRadius, -mRadius, mRadius, mRadius);
mThumbPosX = (float) (mRadius * Math.cos(0));
mThumbPosY = (float) (mRadius * Math.sin(0));
mTranslationOffsetX = halfWidth + mHorizontalInset;
mTranslationOffsetY = halfWidth + mVerticalInset;
}
@Override
protected void onRestoreInstanceState(final Parcelable state) {
if (state instanceof Bundle) {
final Bundle bundle = (Bundle) state;
setProgress(bundle.getFloat(INSTANCE_STATE_PROGRESS));
setMarkerProgress(bundle.getFloat(INSTANCE_STATE_MARKER_PROGRESS));
final int progressColor = bundle.getInt(INSTANCE_STATE_PROGRESS_COLOR);
if (progressColor != mProgressColor) {
mProgressColor = progressColor;
updateProgressColor();
}
final int progressBackgroundColor = bundle
.getInt(INSTANCE_STATE_PROGRESS_BACKGROUND_COLOR);
if (progressBackgroundColor != mProgressBackgroundColor) {
mProgressBackgroundColor = progressBackgroundColor;
updateBackgroundColor();
}
mIsThumbEnabled = bundle.getBoolean(INSTANCE_STATE_THUMB_VISIBLE);
mIsMarkerEnabled = bundle.getBoolean(INSTANCE_STATE_MARKER_VISIBLE);
super.onRestoreInstanceState(bundle.getParcelable(INSTANCE_STATE_SAVEDSTATE));
return;
}
super.onRestoreInstanceState(state);
}
@Override
protected Parcelable onSaveInstanceState() {
final Bundle bundle = new Bundle();
bundle.putParcelable(INSTANCE_STATE_SAVEDSTATE, super.onSaveInstanceState());
bundle.putFloat(INSTANCE_STATE_PROGRESS, mProgress);
bundle.putFloat(INSTANCE_STATE_MARKER_PROGRESS, mMarkerProgress);
bundle.putInt(INSTANCE_STATE_PROGRESS_COLOR, mProgressColor);
bundle.putInt(INSTANCE_STATE_PROGRESS_BACKGROUND_COLOR, mProgressBackgroundColor);
bundle.putBoolean(INSTANCE_STATE_THUMB_VISIBLE, mIsThumbEnabled);
bundle.putBoolean(INSTANCE_STATE_MARKER_VISIBLE, mIsMarkerEnabled);
return bundle;
}
public int getCircleStrokeWidth() {
return mCircleStrokeWidth;
}
/**
* similar to {@link #getProgress}
*/
public float getMarkerProgress() {
return mMarkerProgress;
}
/**
* gives the current progress of the ProgressBar. Value between 0..1 if you set the progress to
* >1 you'll get progress % 1 as return value
*
* @return the progress
*/
public float getProgress() {
return mProgress;
}
/**
* Gets the progress color.
*
* @return the progress color
*/
public int getProgressColor() {
return mProgressColor;
}
/**
* @return true if the marker is visible
*/
public boolean isMarkerEnabled() {
return mIsMarkerEnabled;
}
/**
* @return true if the marker is visible
*/
public boolean isThumbEnabled() {
return mIsThumbEnabled;
}
/**
* Sets the marker enabled.
*
* @param enabled the new marker enabled
*/
public void setMarkerEnabled(final boolean enabled) {
mIsMarkerEnabled = enabled;
}
/**
* Sets the marker progress.
*
* @param progress the new marker progress
*/
public void setMarkerProgress(final float progress) {
mIsMarkerEnabled = true;
mMarkerProgress = progress;
}
/**
* Sets the progress.
*
* @param progress the new progress
*/
public void setProgress(final float progress) {
if (progress == mProgress) {
return;
}
if (progress == 1) {
mOverrdraw = false;
mProgress = 1;
} else {
if (progress >= 1) {
mOverrdraw = true;
} else {
mOverrdraw = false;
}
mProgress = progress % 1.0f;
}
if (!mIsInitializing) {
invalidate();
}
}
/**
* Sets the progress background color.
*
* @param color the new progress background color
*/
public void setProgressBackgroundColor(final int color) {
mProgressBackgroundColor = color;
updateMarkerColor();
updateBackgroundColor();
}
/**
* Sets the progress color.
*
* @param color the new progress color
*/
public void setProgressColor(final int color) {
mProgressColor = color;
updateProgressColor();
}
/**
* shows or hides the thumb of the progress bar
*
* @param enabled true to show the thumb
*/
public void setThumbEnabled(final boolean enabled) {
mIsThumbEnabled = enabled;
}
/**
* Sets the wheel size.
*
* @param dimension the new wheel size
*/
public void setWheelSize(final int dimension) {
mCircleStrokeWidth = dimension;
// update the paints
updateBackgroundColor();
updateMarkerColor();
updateProgressColor();
}
/**
* Compute insets.
*
* <pre>
* ______________________
* |_________dx/2_________|
* |......| /'''''\|......|
* |-dx/2-|| View ||-dx/2-|
* |______| \_____/|______|
* |________ dx/2_________|
* </pre>
*
* @param dx the dx the horizontal unfilled space
* @param dy the dy the horizontal unfilled space
*/
@SuppressLint("NewApi")
private void computeInsets(final int dx, final int dy) {
int absoluteGravity = mGravity;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
absoluteGravity = Gravity.getAbsoluteGravity(mGravity, getLayoutDirection());
}
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.LEFT:
mHorizontalInset = 0;
break;
case Gravity.RIGHT:
mHorizontalInset = dx;
break;
case Gravity.CENTER_HORIZONTAL:
default:
mHorizontalInset = dx / 2;
break;
}
switch (absoluteGravity & Gravity.VERTICAL_GRAVITY_MASK) {
case Gravity.TOP:
mVerticalInset = 0;
break;
case Gravity.BOTTOM:
mVerticalInset = dy;
break;
case Gravity.CENTER_VERTICAL:
default:
mVerticalInset = dy / 2;
break;
}
}
/**
* Gets the current rotation.
*
* @return the current rotation
*/
private float getCurrentRotation() {
return 360 * mProgress;
}
/**
* Gets the marker rotation.
*
* @return the marker rotation
*/
private float getMarkerRotation() {
return 360 * mMarkerProgress;
}
/**
* updates the paint of the background
*/
private void updateBackgroundColor() {
mBackgroundColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mBackgroundColorPaint.setColor(mProgressBackgroundColor);
mBackgroundColorPaint.setStyle(Paint.Style.STROKE);
mBackgroundColorPaint.setStrokeWidth(mCircleStrokeWidth);
invalidate();
}
/**
* updates the paint of the marker
*/
private void updateMarkerColor() {
mMarkerColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mMarkerColorPaint.setColor(mProgressColor);
mMarkerColorPaint.setStyle(Paint.Style.FILL);
invalidate();
}
/**
* updates the paint of the progress and the thumb to give them a new visual style
*/
private void updateProgressColor() {
Log.d(TAG, "updateProgressColor:" + mCircleStrokeWidth);
mProgressColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mProgressColorPaint.setColor(mProgressColor);
mProgressColorPaint.setStyle(Paint.Style.STROKE);
mProgressColorPaint.setStrokeWidth(mCircleStrokeWidth);
mThumbColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mThumbColorPaint.setColor(mProgressColor);
mThumbColorPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mThumbColorPaint.setStrokeWidth(mCircleStrokeWidth);
invalidate();
}
}
| apache-2.0 |
rsimha-amp/amphtml | build-system/pr-check/visual-diff-tests.js | 1651 | /**
* Copyright 2019 The AMP HTML 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.
*/
'use strict';
/**
* @fileoverview Script that runs the visual diff tests during CI.
*/
const atob = require('atob');
const {runCiJob} = require('./ci-job');
const {skipDependentJobs, timedExecOrDie} = require('./utils');
const {Targets, buildTargetsInclude} = require('./build-targets');
const jobName = 'visual-diff-tests.js';
/**
* Steps to run during push builds.
*/
function pushBuildWorkflow() {
process.env['PERCY_TOKEN'] = atob(process.env.PERCY_TOKEN_ENCODED);
timedExecOrDie('amp visual-diff --nobuild --main');
}
/**
* Steps to run during PR builds.
*/
function prBuildWorkflow() {
process.env['PERCY_TOKEN'] = atob(process.env.PERCY_TOKEN_ENCODED);
if (buildTargetsInclude(Targets.RUNTIME, Targets.VISUAL_DIFF)) {
timedExecOrDie('amp visual-diff --nobuild');
} else {
timedExecOrDie('amp visual-diff --empty');
skipDependentJobs(
jobName,
'this PR does not affect the runtime or visual diff tests'
);
}
}
runCiJob(jobName, pushBuildWorkflow, prBuildWorkflow);
| apache-2.0 |
cdmaok/matchp | matchp-core/src/main/java/cn/edu/xmu/gxj/matchp/util/Fields.java | 1163 | package cn.edu.xmu.gxj.matchp.util;
public class Fields {
/*
*
* text: just text as you know
* polarity: text's sentiment
* img: image's url
* imgSign: image's signature
* doc_id: text's id
*
*/
public static final String queryField = "text";
public static final String text = "text";
public static final String img = "img";
public static final String polarity = "polarity";
public static final String imgSign = "imgSign";
public static final String doc_id = "doc_id";
public static final String imgSize = "imgSize";
public static final String hist = "hist";
// for entry
public static final String score = "Finscore";
// some field for social score
public static final String weibo_goods = "goods";
public static final String weibo_repost = "repost";
public static final String weibo_comments = "comments";
public static final String loft_comments = "comment";
public static final String loft_hot = "hot";
public static final String tumblr_hot = "hot";
public static enum Type{
WEIBO("weibo"),
LOFT("loft");
private final String name;
private Type(String s){
name = s;
}
}
}
| apache-2.0 |
Norhaven/FluentBoilerplate | DotNet/FluentBoilerplate/PublicContract/Contexts/IImmutableErrorContext.cs | 7811 | /*
Copyright 2015 Chris Hannon
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;
namespace FluentBoilerplate.Contexts
{
/// <summary>
/// Represents an immutable context for handling errors
/// </summary>
public interface IImmutableErrorContext
{
/// <summary>
/// Gets whether the context has any exception handlers
/// </summary>
bool HasHandlers { get; }
/// <summary>
/// Gets the number of exception handlers that this context contains
/// </summary>
int HandlerCount { get; }
/// <summary>
/// Gets whether the context has an exception handler for the given exception type
/// </summary>
/// <typeparam name="TException">The exception type</typeparam>
/// <returns>True if the context contains a handler for that type, false otherwise</returns>
bool HasHandlerFor<TException>() where TException : Exception;
/// <summary>
/// Registers the given exception handler with the error context
/// </summary>
/// <typeparam name="TException">The exception type</typeparam>
/// <param name="handler">The exception handler</param>
/// <returns>An instance of <see cref="IImmutableErrorContext"/> with the exception handler registered</returns>
IImmutableErrorContext RegisterExceptionHandler<TException>(Action<TException> handler) where TException : Exception;
/// <summary>
/// Registers the given exception handler with the error context
/// </summary>
/// <typeparam name="TException">The exception type</typeparam>
/// <typeparam name="TResult">The result type</typeparam>
/// <param name="handler">The exception handler</param>
/// <returns>An instance of <see cref="IImmutableErrorContext"/> with the exception handler registered</returns>
IImmutableErrorContext RegisterExceptionHandler<TException, TResult>(Func<TException, TResult> handler) where TException : Exception;
/// <summary>
/// Marks the exception handler for retry.
/// </summary>
/// <typeparam name="TException">The type of the exception.</typeparam>
/// <param name="retryCount">The retry count.</param>
/// <param name="millisecondsInterval">The interval in milliseconds before another retry may be attempted.</param>
/// <param name="backoff">How subsequent retries should handle backing off of the retry interval.</param>
/// <returns>An instance of <see cref="IImmutableErrorContext"/> with the exception handler marked for retry.</returns>
IImmutableErrorContext MarkExceptionHandlerForRetry<TException>(int retryCount, int millisecondsInterval = 0, BackoffStrategy backoff = BackoffStrategy.None) where TException : Exception;
/// <summary>
/// Marks the exception handler for retry.
/// </summary>
/// <typeparam name="TException">The type of the exception.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="retryCount">The retry count.</param>
/// <param name="millisecondsInterval">The interval in milliseconds before another retry may be attempted.</param>
/// <param name="backoff">How subsequent retries should handle backing off of the retry interval.</param>
/// <returns>An instance of <see cref="IImmutableErrorContext"/> with the exception handler marked for retry.</returns>
IImmutableErrorContext MarkExceptionHandlerForRetry<TException, TResult>(int retryCount, int millisecondsInterval = 0, BackoffStrategy backoff = BackoffStrategy.None) where TException : Exception;
/// <summary>
/// Performs an action, surrounded by the context's exception handlers
/// </summary>
/// <param name="action">The action</param>
void DoInContext(Action<IImmutableErrorContext> action);
/// <summary>
/// Gets a value, surrounded by the context's exception handlers
/// </summary>
/// <typeparam name="T">The result type</typeparam>
/// <param name="action">The action</param>
/// <returns>The value</returns>
T DoInContext<T>(Func<IImmutableErrorContext, T> action);
/// <summary>
/// Wraps an action in the context's exception handlers
/// </summary>
/// <param name="action">The action</param>
/// <returns>An action that encompasses the given action in the context's exception handlers</returns>
Action ExtendAround(Action action);
/// <summary>
/// Wraps an action in the context's exception handlers
/// </summary>
/// <typeparam name="T">The parameter type</typeparam>
/// <param name="action">The action</param>
/// <returns>An action that encompasses the given action in the context's exception handlers</returns>
Action<T> ExtendAround<T>(Action<T> action);
/// <summary>
/// Wraps an action in the context's exception handlers
/// </summary>
/// <typeparam name="T1">The first parameter type</typeparam>
/// <typeparam name="T2">The second parameter type</typeparam>
/// <param name="action">The action</param>
/// <returns>An action that encompasses the given action in the context's exception handlers</returns>
Action<T1, T2> ExtendAround<T1, T2>(Action<T1, T2> action);
/// <summary>
/// Wraps a function in the context's exception handlers
/// </summary>
/// <typeparam name="T">The return type</typeparam>
/// <param name="action">The action</param>
/// <returns>A function that encompasses the given function in the context's exception handlers</returns>
Func<T> ExtendAround<T>(Func<T> action);
/// <summary>
/// Wraps a function in the context's exception handlers
/// </summary>
/// <typeparam name="T">The parameter type</typeparam>
/// <typeparam name="TResult">The return type</typeparam>
/// <param name="action">The action</param>
/// <returns>A function that encompasses the given function in the context's exception handlers</returns>
Func<T, TResult> ExtendAround<T, TResult>(Func<T, TResult> action);
/// <summary>
/// Wraps a function in the context's exception handlers
/// </summary>
/// <typeparam name="T1">The first parameter type</typeparam>
/// <typeparam name="T2">The second parameter type</typeparam>
/// <typeparam name="TResult">The return type</typeparam>
/// <param name="action">The action</param>
/// <returns>A function that encompasses the given function in the context's exception handlers</returns>
Func<T1, T2, TResult> ExtendAround<T1, T2, TResult>(Func<T1, T2, TResult> action);
/// <summary>
/// Copies the error context
/// </summary>
/// <param name="includeHandlers">Indicates whether the exception handlers in the context should be copied</param>
/// <returns>An instance of <see cref="IImmutableErrorContext"/></returns>
IImmutableErrorContext Copy(bool includeHandlers = true);
}
}
| apache-2.0 |
wadearnold/ach | test/ach-pop-read/main.go | 1976 | // Licensed to The Moov Authors under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. The Moov Authors 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 main
import (
"fmt"
"github.com/moov-io/ach"
"log"
"os"
)
func main() {
// open a file for reading. Any io.Reader Can be used
f, err := os.Open("pop-debit.ach")
if err != nil {
log.Fatal(err)
}
r := ach.NewReader(f)
achFile, err := r.Read()
if err != nil {
fmt.Printf("Issue reading file: %+v \n", err)
}
// ensure we have a validated file structure
if achFile.Validate(); err != nil {
fmt.Printf("Could not validate entire read file: %v", err)
}
// If you trust the file but it's formatting is off building will probably resolve the malformed file.
if err := achFile.Create(); err != nil {
fmt.Printf("Could not create file with read properties: %v", err)
}
fmt.Printf("Total Amount Debit: %v \n", achFile.Control.TotalDebitEntryDollarAmountInFile)
fmt.Printf("SEC Code: %v \n", achFile.Batches[0].GetHeader().StandardEntryClassCode)
fmt.Printf("POP Check Serial Number: %v \n", achFile.Batches[0].GetEntries()[0].POPCheckSerialNumberField())
fmt.Printf("POP Terminal City: %v \n", achFile.Batches[0].GetEntries()[0].POPTerminalCityField())
fmt.Printf("POP Terminal State: %v \n", achFile.Batches[0].GetEntries()[0].POPTerminalStateField())
}
| apache-2.0 |
zhoffice/redisson | redisson/src/main/java/org/redisson/liveobject/core/LiveObjectInterceptor.java | 4990 | /**
* Copyright 2016 Nikita Koksharov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.redisson.liveobject.core;
import java.lang.reflect.Method;
import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.FieldProxy;
import net.bytebuddy.implementation.bind.annotation.FieldValue;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.This;
import org.redisson.RedissonMap;
import org.redisson.client.RedisException;
import org.redisson.client.codec.Codec;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.api.annotation.REntity;
import org.redisson.codec.CodecProvider;
import org.redisson.liveobject.misc.ClassUtils;
import org.redisson.liveobject.resolver.NamingScheme;
/**
*
* @author Rui Gu (https://github.com/jackygurui)
*/
public class LiveObjectInterceptor {
public interface Getter {
Object getValue();
}
public interface Setter {
void setValue(Object value);
}
private final RedissonClient redisson;
private final CodecProvider codecProvider;
private final Class<?> originalClass;
private final String idFieldName;
private final Class<?> idFieldType;
private final NamingScheme namingScheme;
private final Class<? extends Codec> codecClass;
public LiveObjectInterceptor(RedissonClient redisson, CodecProvider codecProvider, Class<?> entityClass, String idFieldName) {
this.redisson = redisson;
this.codecProvider = codecProvider;
this.originalClass = entityClass;
this.idFieldName = idFieldName;
REntity anno = (REntity) ClassUtils.getAnnotation(entityClass, REntity.class);
this.codecClass = anno.codec();
try {
this.namingScheme = anno.namingScheme().getDeclaredConstructor(Codec.class).newInstance(codecProvider.getCodec(anno, originalClass));
this.idFieldType = ClassUtils.getDeclaredField(originalClass, idFieldName).getType();
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
@RuntimeType
public Object intercept(
@Origin Method method,
@AllArguments Object[] args,
@This Object me,
@FieldValue("liveObjectId") Object id,
@FieldProxy("liveObjectId") Setter idSetter,
@FieldProxy("liveObjectId") Getter idGetter,
@FieldValue("liveObjectLiveMap") RMap<?, ?> map,
@FieldProxy("liveObjectLiveMap") Setter mapSetter,
@FieldProxy("liveObjectLiveMap") Getter mapGetter
) throws Exception {
if ("setLiveObjectId".equals(method.getName())) {
if (args[0].getClass().isArray()) {
throw new UnsupportedOperationException("RId value cannot be an array.");
}
//TODO: distributed locking maybe required.
String idKey = getMapKey(args[0]);
if (map != null) {
if (map.getName().equals(idKey)) {
return null;
}
try {
map.rename(getMapKey(args[0]));
} catch (RedisException e) {
if (e.getMessage() == null || !e.getMessage().startsWith("ERR no such key")) {
throw e;
}
//key may already renamed by others.
}
}
RMap<Object, Object> liveMap = redisson.getMap(idKey,
codecProvider.getCodec(codecClass, RedissonMap.class, idKey));
mapSetter.setValue(liveMap);
return null;
}
if ("getLiveObjectId".equals(method.getName())) {
if (map == null) {
return null;
}
return namingScheme.resolveId(map.getName());
}
if ("getLiveObjectLiveMap".equals(method.getName())) {
return map;
}
if ("isExists".equals(method.getName())) {
return map.isExists();
}
if ("delete".equals(method.getName())) {
return map.delete();
}
throw new NoSuchMethodException();
}
private String getMapKey(Object id) {
return namingScheme.getName(originalClass, idFieldType, idFieldName, id);
}
}
| apache-2.0 |
HuangLS/neo4j | enterprise/neo4j-enterprise/src/test/java/upgrade/StoreMigratorFrom21IT.java | 20955 | /*
* Copyright (c) 2002-2018 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package upgrade;
import org.junit.Rule;
import org.junit.Test;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import org.neo4j.consistency.ConsistencyCheckService;
import org.neo4j.graphdb.DependencyResolver;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.PropertyContainer;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseBuilder;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.helpers.Pair;
import org.neo4j.helpers.collection.IteratorUtil;
import org.neo4j.helpers.progress.ProgressMonitorFactory;
import org.neo4j.kernel.GraphDatabaseAPI;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.kernel.impl.store.NeoStores;
import org.neo4j.kernel.impl.store.NodeStore;
import org.neo4j.kernel.impl.store.PropertyStore;
import org.neo4j.kernel.impl.store.RelationshipStore;
import org.neo4j.kernel.impl.store.record.PropertyBlock;
import org.neo4j.kernel.impl.store.record.PropertyRecord;
import org.neo4j.kernel.impl.storemigration.MigrationTestUtils;
import org.neo4j.kernel.impl.transaction.state.NeoStoresSupplier;
import org.neo4j.logging.NullLogProvider;
import org.neo4j.test.TargetDirectory;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@SuppressWarnings( "unchecked" )
public class StoreMigratorFrom21IT
{
@Test
public void mustMendDuplicatePropertiesWhenUpgradingFromVersion21() throws Exception
{
// The rules:
// If an index is present, all duplicates should be removed and the property set to the value in the index
// If an index is not present, the property should be set to the value of the last duplicate in the property
// chain, all duplicates except the first should be removed
// If an index is not present, the first property in the duplicate chain should be kept for the users
// benefit, moved to a special property value, `__DUPLICATE_<propkey>`
//
// This is the broken store that we are upgrading:
//
// (#0:Label { keyA: "actual", keyA: "phony!", keyA: "phony!" })
// (#1 { keyA: "actual", keyA: "actual", keyA: "actual" })
// (#2:Label { keyA: "real1", keyA: "phony", keyA: "phony", keyD: "real2", keyD: "phony", keyD: "phony" })
// (#3 { keyA: "real1", keyA: "phony", keyA: "phony", keyD: "real2", keyD: "phony", keyD: "phony" })
// (#4 { keyA: "actual", keyB: "actual", keyC: "actual" })
// (#0)-[#0:REL { keyA: "actual", keyA: "actual", keyA: "actual" }]->(#1)
// (#0)-[#1:REL { keyA: "real1", keyA: "phony", keyA: "phony",
// keyD: "real2", keyE: "phony", keyF: "phony" }]->(#1)
// (#2)-[#2:REL { keyA: "actual", keyB: "actual", keyC: "actual" }]->(#0)
//
// And this is what we want to end up with, after upgrading:
//
// (#0:Label { keyA: "actual" })
// (#1 { keyA: "actual", __DUPLICATE_keyA: "actual" })
// (#2:Label { keyA: "real1", keyD: "real2" })
// (#3 { keyA: "real1", __DUPLICATE_keyA_1: "real1", __DUPLICATE_keyA_2: "real1",
// keyD: "real2", __DUPLICATE_keyD_1: "real2", __DUPLICATE_keyD_2: "real2" })
// (#4 { keyA: "actual", keyB: "actual", keyC: "actual" })
// (#0)-[#0:REL { keyA: "actual", __DUPLICATE_keyA: "actual" }]->(#1)
// (#0)-[#1:REL { keyA: "real1", __DUPLICATE_keyA_1: "real1", __DUPLICATE_keyA_2: "real1",
// keyD: "real2", __DUPLICATE_keyD_1: "real2", __DUPLICATE_keyD_2: "real2" }]->(#1)
// (#2)-[#2:REL { keyA: "actual", keyB: "actual", keyC: "actual" }]->(#0)
File dir = MigrationTestUtils.find21FormatStoreDirectoryWithDuplicateProperties( storeDir.directory() );
GraphDatabaseBuilder builder =
new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( dir.getAbsolutePath() ).setConfig(
GraphDatabaseSettings.allow_store_upgrade, "true" );
GraphDatabaseService database = builder.newGraphDatabase();
database.shutdown();
ConsistencyCheckService service = new ConsistencyCheckService();
ConsistencyCheckService.Result result = service.runFullConsistencyCheck(
dir.getAbsoluteFile(), new Config(), ProgressMonitorFactory.NONE, NullLogProvider.getInstance(), false );
assertTrue( result.isSuccessful() );
database = builder.newGraphDatabase();
// Upgrade is now completed. Verify the contents:
DependencyResolver dependencyResolver = ((GraphDatabaseAPI) database).getDependencyResolver();
NeoStoresSupplier supplier = dependencyResolver.resolveDependency( NeoStoresSupplier.class );
NeoStores store = supplier.get();
NodeStore nodeStore = store.getNodeStore();
RelationshipStore relStore = store.getRelationshipStore();
PropertyStore propertyStore = store.getPropertyStore();
// Verify that the properties appear correct to the outside world:
try ( Transaction ignore = database.beginTx() )
{
verifyPropertiesEqual( database.getNodeById( 0 ),
Pair.of( "keyA", "actual" ) );
verifyPropertiesEqual( database.getNodeById( 1 ),
Pair.of( "keyA", "actual" ),
Pair.of( "__DUPLICATE_keyA_1", "actual" ),
Pair.of( "__DUPLICATE_keyA_2", "actual" ));
verifyPropertiesEqual( database.getNodeById( 2 ),
Pair.of( "keyA", "real1" ),
Pair.of( "keyD", "real2" ) );
verifyPropertiesEqual( database.getNodeById( 3 ),
Pair.of( "keyA", "real1" ),
Pair.of( "__DUPLICATE_keyA_1", "real1" ),
Pair.of( "__DUPLICATE_keyA_2", "real1" ),
Pair.of( "keyD", "real2" ),
Pair.of( "__DUPLICATE_keyD_1", "real2" ),
Pair.of( "__DUPLICATE_keyD_2", "real2" ) );
verifyPropertiesEqual( database.getNodeById( 4 ),
Pair.of( "keyA", "actual" ),
Pair.of( "keyB", "actual" ),
Pair.of( "keyC", "actual" ) );
verifyPropertiesEqual( database.getRelationshipById( 0 ),
Pair.of( "keyA", "actual" ),
Pair.of( "__DUPLICATE_keyA_1", "actual" ),
Pair.of( "__DUPLICATE_keyA_2", "actual" ));
verifyPropertiesEqual( database.getRelationshipById( 1 ),
Pair.of( "keyA", "real1" ),
Pair.of( "__DUPLICATE_keyA_1", "real1" ),
Pair.of( "__DUPLICATE_keyA_2", "real1" ),
Pair.of( "keyD", "real2" ),
Pair.of( "__DUPLICATE_keyD_1", "real2" ),
Pair.of( "__DUPLICATE_keyD_2", "real2" ) );
verifyPropertiesEqual( database.getRelationshipById( 2 ),
Pair.of( "keyA", "actual" ),
Pair.of( "keyB", "actual" ),
Pair.of( "keyC", "actual" ) );
}
// Verify that there are no two properties on the entities, that have the same key:
// (This is important because the verification above cannot tell if we have two keys with the same value)
verifyNoDuplicatePropertyKeys( propertyStore, nodeStore.getRecord( 0 ).getNextProp() );
verifyNoDuplicatePropertyKeys( propertyStore, nodeStore.getRecord( 1 ).getNextProp() );
verifyNoDuplicatePropertyKeys( propertyStore, nodeStore.getRecord( 2 ).getNextProp() );
verifyNoDuplicatePropertyKeys( propertyStore, relStore.getRecord( 0 ).getNextProp() );
verifyNoDuplicatePropertyKeys( propertyStore, relStore.getRecord( 1 ).getNextProp() );
database.shutdown();
}
private void verifyNoDuplicatePropertyKeys( PropertyStore propertyStore, long firstPropertyId )
{
HashSet<Integer> propertiesInUse = new HashSet<>();
long nextPropertyId = firstPropertyId;
while ( nextPropertyId != -1 )
{
PropertyRecord propertyRecord = propertyStore.getRecord( nextPropertyId );
nextPropertyId = propertyRecord.getNextProp();
if ( !propertyRecord.inUse() )
{
continue;
}
for ( PropertyBlock propertyBlock : propertyRecord )
{
if ( !propertiesInUse.add( propertyBlock.getKeyIndexId() ) )
{
throw new AssertionError( String.format(
"Found a duplicate property in use: %s", propertyBlock.getKeyIndexId()
) );
}
}
}
}
private void verifyPropertiesEqual( PropertyContainer entity, Pair<String,String>... expectedProperties )
{
Map<String, String> properties = (Map) entity.getAllProperties();
assertThat( properties, is( IteratorUtil.asMap( Arrays.asList( expectedProperties ) ) ) );
}
@Rule
public final TargetDirectory.TestDirectory storeDir = TargetDirectory.testDirForTest( getClass() );
}
/*
The test data store has been generated by running the following program in the 2.1 code base:
package examples;
import java.io.File;
import java.io.IOException;
import org.neo4j.graphdb.DependencyResolver;
import org.neo4j.graphdb.DynamicLabel;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.kernel.GraphDatabaseAPI;
import org.neo4j.kernel.impl.core.Token;
import org.neo4j.kernel.impl.nioneo.store.NeoStore;
import org.neo4j.kernel.impl.nioneo.store.NodeRecord;
import org.neo4j.kernel.impl.nioneo.store.NodeStore;
import org.neo4j.kernel.impl.nioneo.store.PrimitiveRecord;
import org.neo4j.kernel.impl.nioneo.store.PropertyBlock;
import org.neo4j.kernel.impl.nioneo.store.PropertyKeyTokenStore;
import org.neo4j.kernel.impl.nioneo.store.PropertyRecord;
import org.neo4j.kernel.impl.nioneo.store.PropertyStore;
import org.neo4j.kernel.impl.nioneo.store.RelationshipRecord;
import org.neo4j.kernel.impl.nioneo.store.RelationshipStore;
import org.neo4j.kernel.impl.nioneo.xa.NeoStoreProvider;
import org.neo4j.kernel.impl.util.FileUtils;
public class CreateStoreWithDuplicateProperties
{
public static void main( String[] args ) throws IOException
{
String path = "21-with-duplicate-properties";
FileUtils.deleteRecursively( new File( path ) );
GraphDatabaseFactory factory = new GraphDatabaseFactory();
GraphDatabaseService db = factory.newEmbeddedDatabase( path );
GraphDatabaseAPI api = (GraphDatabaseAPI) db;
Label label = DynamicLabel.label( "Label" );
DynamicRelationshipType relationshipType = DynamicRelationshipType.withName( "REL" );
String actualValue = "actual";
String phonyValue = "phony!";
String keyA = "keyA";
String keyB = "keyB";
String keyC = "keyC";
String keyD = "keyD";
String keyE = "keyE";
String keyF = "keyF";
try ( Transaction transaction = db.beginTx() )
{
db.schema().indexFor( label ).on( keyA ).create();
db.schema().indexFor( label ).on( keyD ).create();
transaction.success();
}
long nodeIndexedSingleId;
long nodeNotIndexedSingleId;
long nodeIndexedMultiId;
long nodeNotIndexedMultiId;
long relSingleId;
long relMultiId;
try ( Transaction transaction = db.beginTx() )
{
// Four nodes and two relationships will have duplicate properties.
// Two nodes will be in the index, the others not.
// An indexed and a non-indexed node will have multiple distinct duplicates.
// Likewise, one of the relationships will have multiple distinct duplicates.
// Another node and another relationship will be fine.
// Indexed single duplicate
Node nodeA = db.createNode( label );
nodeA.setProperty( keyA, actualValue );
nodeA.setProperty( keyB, phonyValue );
nodeA.setProperty( keyC, phonyValue );
nodeIndexedSingleId = nodeA.getId();
// Non-indexed single duplicate
Node nodeB = db.createNode();
nodeB.setProperty( keyA, actualValue );
nodeB.setProperty( keyB, actualValue );
nodeB.setProperty( keyC, actualValue );
nodeNotIndexedSingleId = nodeB.getId();
// Single duplicate
Relationship relA = nodeA.createRelationshipTo( nodeB, relationshipType );
relA.setProperty( keyA, actualValue );
relA.setProperty( keyB, actualValue );
relA.setProperty( keyC, actualValue );
relSingleId = relA.getId();
// Indexed multiple duplicates
Node nodeC = db.createNode( label );
nodeC.setProperty( keyA, "real1" );
nodeC.setProperty( keyB, "phony" );
nodeC.setProperty( keyC, "phony" );
nodeC.setProperty( keyD, "real2" );
nodeC.setProperty( keyE, "phony" );
nodeC.setProperty( keyF, "phony" );
nodeIndexedMultiId = nodeC.getId();
// Non-indexed multiple duplicate
Node nodeD = db.createNode();
nodeD.setProperty( keyA, "real1" );
nodeD.setProperty( keyB, "real1" );
nodeD.setProperty( keyC, "real1" );
nodeD.setProperty( keyD, "real2" );
nodeD.setProperty( keyE, "real2" );
nodeD.setProperty( keyF, "real2" );
nodeNotIndexedMultiId = nodeD.getId();
// Multiple duplicates
Relationship relB = nodeA.createRelationshipTo( nodeB, relationshipType );
relB.setProperty( keyA, "real1" );
relB.setProperty( keyB, "real1" );
relB.setProperty( keyC, "real1" );
relB.setProperty( keyD, "real2" );
relB.setProperty( keyE, "real2" );
relB.setProperty( keyF, "real2" );
relMultiId = relB.getId();
// No duplicates
Node nodeE = db.createNode();
nodeE.setProperty( keyA, actualValue );
nodeE.setProperty( keyB, actualValue );
nodeE.setProperty( keyC, actualValue );
// No duplicates
Relationship relC = nodeD.createRelationshipTo( nodeA, relationshipType );
relC.setProperty( keyA, actualValue );
relC.setProperty( keyB, actualValue );
relC.setProperty( keyC, actualValue );
transaction.success();
}
// (#0:Label { keyA: "actual", keyA: "phony!", keyA: "phony!" })
// (#1 { keyA: "actual", keyA: "actual", keyA: "actual" })
// (#2:Label { keyA: "real1", keyA: "phony", keyA: "phony", keyD: "real2", keyE: "phony", keyF: "phony" })
// (#3 { keyA: "real1", keyA: "phony", keyA: "phony", keyD: "real2", keyE: "phony", keyF: "phony" })
// (#4 { keyA: "actual", keyB: "actual", keyC: "actual" })
// (#0)-[#0:REL { keyA: "actual", keyA: "actual", keyA: "actual" }]->(#1)
// (#0)-[#1:REL { keyA: "real1", keyA: "phony", keyA: "phony", keyD: "real2", keyE: "phony", keyF: "phony" }]->(#1)
// (#2)-[#2:REL { keyA: "actual", keyB: "actual", keyC: "actual" }]->(#0)
DependencyResolver resolver = api.getDependencyResolver();
NeoStoreProvider neoStoreProvider = resolver.resolveDependency( NeoStoreProvider.class );
NeoStore neoStore = neoStoreProvider.evaluate();
PropertyKeyTokenStore propertyKeyTokenStore = neoStore.getPropertyKeyTokenStore();
Token tokenA = findPropertyKeyTokenFor( propertyKeyTokenStore, keyA );
Token tokenB = findPropertyKeyTokenFor( propertyKeyTokenStore, keyB );
Token tokenC = findPropertyKeyTokenFor( propertyKeyTokenStore, keyC );
Token tokenD = findPropertyKeyTokenFor( propertyKeyTokenStore, keyD );
Token tokenE = findPropertyKeyTokenFor( propertyKeyTokenStore, keyE );
Token tokenF = findPropertyKeyTokenFor( propertyKeyTokenStore, keyF );
NodeStore nodeStore = neoStore.getNodeStore();
RelationshipStore relationshipStore = neoStore.getRelationshipStore();
PropertyStore propertyStore = neoStore.getPropertyStore();
NodeRecord indexedNodeSingle = nodeStore.getRecord( nodeIndexedSingleId );
NodeRecord nonIndexedNodeSingle = nodeStore.getRecord( nodeNotIndexedSingleId );
NodeRecord indexedNodeMulti = nodeStore.getRecord( nodeIndexedMultiId );
NodeRecord nonindexedNodeMulti = nodeStore.getRecord( nodeNotIndexedMultiId );
RelationshipRecord relationshipRecordSingle = relationshipStore.getRecord( relSingleId );
RelationshipRecord relationshipRecordMulti = relationshipStore.getRecord( relMultiId );
replacePropertyKey( propertyStore, indexedNodeSingle, tokenB, tokenA );
replacePropertyKey( propertyStore, indexedNodeSingle, tokenC, tokenA );
replacePropertyKey( propertyStore, nonIndexedNodeSingle, tokenB, tokenA );
replacePropertyKey( propertyStore, nonIndexedNodeSingle, tokenC, tokenA );
replacePropertyKey( propertyStore, indexedNodeMulti, tokenB, tokenA );
replacePropertyKey( propertyStore, indexedNodeMulti, tokenC, tokenA );
replacePropertyKey( propertyStore, indexedNodeMulti, tokenE, tokenD );
replacePropertyKey( propertyStore, indexedNodeMulti, tokenF, tokenD );
replacePropertyKey( propertyStore, nonindexedNodeMulti, tokenB, tokenA );
replacePropertyKey( propertyStore, nonindexedNodeMulti, tokenC, tokenA );
replacePropertyKey( propertyStore, nonindexedNodeMulti, tokenE, tokenD );
replacePropertyKey( propertyStore, nonindexedNodeMulti, tokenF, tokenD );
replacePropertyKey( propertyStore, relationshipRecordSingle, tokenB, tokenA );
replacePropertyKey( propertyStore, relationshipRecordSingle, tokenC, tokenA );
replacePropertyKey( propertyStore, relationshipRecordMulti, tokenB, tokenA );
replacePropertyKey( propertyStore, relationshipRecordMulti, tokenC, tokenA );
replacePropertyKey( propertyStore, relationshipRecordMulti, tokenE, tokenD );
replacePropertyKey( propertyStore, relationshipRecordMulti, tokenF, tokenD );
db.shutdown();
}
private static void replacePropertyKey(
PropertyStore propertyStore,
PrimitiveRecord record,
Token original,
Token replacement )
{
long nextProp = record.getNextProp();
while ( nextProp != -1 )
{
PropertyRecord propertyRecord = propertyStore.getRecord( nextProp );
for ( PropertyBlock propertyBlock : propertyRecord.getPropertyBlocks() )
{
if ( propertyBlock.getKeyIndexId() == original.id() )
{
propertyBlock.setKeyIndexId( replacement.id() );
}
}
propertyStore.updateRecord( propertyRecord );
nextProp = propertyRecord.getNextProp();
}
}
private static Token findPropertyKeyTokenFor( PropertyKeyTokenStore propertyKeyTokenStore, String key )
{
long highestPossibleIdInUse = propertyKeyTokenStore.getHighestPossibleIdInUse();
for ( int i = 0; i <= highestPossibleIdInUse; i++ )
{
Token token = propertyKeyTokenStore.getToken( i );
if ( token.name().equals( key ) )
{
return token;
}
}
return null;
}
}
*/
| apache-2.0 |
przemyslaw-holownia/financial-manager | app/src/test/java/info/holownia/przemyslaw/financial/manager/feature/addeditaccount/presentation/AddEditAccountPresenterTest.java | 5297 | package info.holownia.przemyslaw.financial.manager.feature.addeditaccount.presentation;
import android.support.annotation.NonNull;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import info.holownia.przemyslaw.financial.manager.core.data.accounts.repository.AccountsRepository;
import info.holownia.przemyslaw.financial.manager.core.scheduler.ImmediateSchedulerProvider;
import info.holownia.przemyslaw.financial.manager.feature.accounts.domain.model.Account;
import info.holownia.przemyslaw.financial.manager.feature.addeditaccount.domain.GetAccountUseCase;
import info.holownia.przemyslaw.financial.manager.feature.addeditaccount.domain.SaveAccountUseCase;
import rx.Observable;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Created by przemek on 10/19/17.
*/
public class AddEditAccountPresenterTest {
@Mock
public AccountsRepository accountsRepository;
@Mock
public AddEditAccountContract.View view;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void createPresenter_setsPresenterToView() {
// when presenter is created in setup
AddEditAccountPresenter presenter = giveAddAccountPresenter();
// then presenter sets to the view
verify(view).setPresenter(presenter);
}
@Test
public void createAccount_savesToRepository() {
// given presenter
AddEditAccountPresenter presenter = giveAddAccountPresenter();
// and repository saves account without errors
when(accountsRepository.saveAccount(any(Account.class))).thenAnswer(new Answer<Observable<Account>>() {
@Override
public Observable<Account> answer(InvocationOnMock invocation) throws Throwable {
Account account = (Account) invocation.getArguments()[0];
return Observable.just(new Account(10L, account.getName()));
}
});
// when presenter is requested to save account
presenter.saveAccount("Bank account");
// Then account is saved in repository
verify(accountsRepository).saveAccount(any(Account.class));
// And view show account details screen
verify(view).showAccountDetails(any(Long.class));
}
@Test
public void saveAccount_noName_showsError() {
// given presenter
AddEditAccountPresenter addEditAccountPresenter = giveAddAccountPresenter();
// when presenter is requested to save account without name
addEditAccountPresenter.saveAccount("");
// then error should display
verify(view).showEmptyNameError();
}
@Test
public void updateExistingAccount_savesToRepositoryAndShowsDetails() {
// given test account
Account testAccount = new Account(1L, "Test");
// and presenter
AddEditAccountPresenter presenter = giveEditAccountPresenter(testAccount.getId());
// and repository saves account without errors
when(accountsRepository.saveAccount(any(Account.class))).thenAnswer(new Answer<Observable<Account>>() {
@Override
public Observable<Account> answer(InvocationOnMock invocation) throws Throwable {
Account account = (Account) invocation.getArguments()[0];
return Observable.just(account);
}
});
// when presenter is requested to save account
presenter.saveAccount("Bank account");
// Then account is saved in repository
verify(accountsRepository).saveAccount(any(Account.class));
// And view show account details screen
verify(view).showAccountDetails(testAccount.getId());
}
@Test
public void populateAccount_getAccountFromRepoAndUpdatesView() {
// given test account
Account testAccount = new Account(1L, "Test");
// and presenter
AddEditAccountPresenter presenter = giveEditAccountPresenter(testAccount.getId());
// and repository returns existing account without errors
when(accountsRepository.getAccount(testAccount.getId())).thenReturn(Observable.just(testAccount));
// When presenter is asked to populate existing account
presenter.populateAccount();
// Then accounts repository is asked for that account
verify(accountsRepository).getAccount(testAccount.getId());
// and view updates name
verify(view).setAccountName(testAccount.getName());
}
@NonNull
protected AddEditAccountPresenter giveAddAccountPresenter() {
return giveEditAccountPresenter(null);
}
@NonNull
protected AddEditAccountPresenter giveEditAccountPresenter(Long accountId) {
SaveAccountUseCase saveAccountUseCase = new SaveAccountUseCase(accountsRepository, new ImmediateSchedulerProvider());
GetAccountUseCase getAccountUseCase = new GetAccountUseCase(accountsRepository, new ImmediateSchedulerProvider());
return new AddEditAccountPresenter(accountId, saveAccountUseCase, getAccountUseCase, view);
}
}
| apache-2.0 |
cosmocode/cosmocode-json | src/main/java/org/json/extension/JSONEncoder.java | 1176 | /**
* Copyright 2010 CosmoCode GmbH
*
* 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.json.extension;
import org.json.JSONException;
import de.cosmocode.rendering.Renderable;
/**
* No documentation here.
*
* @deprecated use {@link Renderable}
*
* @author Willi Schoenborn
*/
@Deprecated
public interface JSONEncoder {
/**
* Encodes this instance to JSON using the given {@link JSONConstructor}.
*
* @param json the {@link JSONConstructor} to work on
* @throws JSONException if an error occurs
*/
void encodeJSON(JSONConstructor json) throws JSONException;
}
| apache-2.0 |
enketo/enketo-legacy | Code_Igniter/application/controllers/manifest.php | 14272 | <?php
/**
* Copyright 2012 Martijn van de Rijdt
*
* 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.
*/
/**
* Manifest Class
*
* @package Manifest Builder
* @author Martijn van de Rijdt
* @link
*/
class Manifest extends CI_Controller {
/*
|--------------------------------------------------------------------------
| MANIFEST BUILDER
|--------------------------------------------------------------------------
|
| Creates a manifest for offline Application Caches in Gears or HTML5 formats
|
| Works by extracting resources from the html pages that are required to
| be available offline.
|
| A 'version' string is formed by creating a hash of all resources,
| not including the html pages themselves.
|
| A version change can be forced by increasing the override variable
| or changing this to a timestamp
|
|
| NOTE: on a local test server the (sub)domain has to be included in the
| hosts file of the test server otherwise DNS will be used to get the
| contents of the html pages (with file_get_contents()).
|
|--------------------------------------------------------------------------
| force cache update
|--------------------------------------------------------------------------
*/
private $hash_manual_override = '0041'; //time();
/*
|--------------------------------------------------------------------------
| pages to be cached (urls relative to sub.example.com/)
|--------------------------------------------------------------------------
*/
private $pages = array(); //, 'modern_browsers');
/*
|--------------------------------------------------------------------------
| page to re-direct offline 404 requests to (html5 manifest 'fallback' section)
|__________________________________________________________________________
*/
private $offline = '/offline';
/*
|--------------------------------------------------------------------------
| pages to always retrieve from the server (html5 manifest 'network' section)
|--------------------------------------------------------------------------
*/
private $network = array('*');
/*
|---------------------------------------------------------------------------
*/
private $data;
private $master_page;
public function __construct()
{
parent::__construct();
$this->load->helper(array('url', 'json', 'subdomain', 'http'));
$this->load->model('Survey_model','',TRUE);
$this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));
$this->manifest_url = $this->_full_url(uri_string());
//$this->_set_context();
log_message('debug', 'Manifest Controller initialized for url: '. $this->manifest_url);
}
public function html()
{
$pages = func_get_args();
//!important the first argument is assumed to be the master entry which is implicitly cached
//and removed from the manifest as a test to solve issue with manifest updates
if(!empty($pages)) {
if (!$data = $this->cache->get($this->manifest_url)) {
log_message('debug', 'creating manifest');
$this->master_page = $pages[0];
foreach ($pages as $page) {
if (!empty($page)) {
$this->pages[] = $page;
}
}
$this->_set_data();
$data = $this->data;
if (count($data['cache']) > 0) {
$this->cache->save($this->manifest_url, $data, 60);
}
}
if (count($data['cache']) > 0 ) {
$this->load->view('html5_manifest_view.php', $data);
return;
}
}
// else return an empty manifest that can be used to remotely clear the client's applicationCache
log_message('debug', 'no pages or master page is null/not authorized');
show_404();
}
/**
* An uncached copy of the manifest (not referred to anywhere as a manifest and therefore not cached in browser)
* meant for trouble-shooting. Simply replace "html" with "test" in the manifest URL.
* Eg. "http://abcd.enketo.org/manifest/html/webform" becomes "http://abcd.enketo.org/manifest/test/webform"
*/
public function test()
{
$this->cache->delete($this->manifest_url);
$args = func_get_args();
call_user_func_array(array($this, 'html'), $args);
}
public function index()
{
show_404();
}
private function _set_data(){
//if a subdomain is present, this manifest is meant for a survey and needs to be live, launched and offline-enabled
if ( (get_subdomain() && $this->Survey_model->is_launched_live_and_offline()) || !get_subdomain()) {
$this->data['hashes'] = '';
$this->data['cache'] = $this->pages;
foreach ($this->pages as $page) {
//log_message('debug', 'checking resources on page: '.$this->_full_url($page));
$page_full_url = $this->_full_url($page.
'?manifest=true&s='.urlencode($this->session->userdata('session_id')).
'&token='.urlencode($this->encrypt->encode('localrequest')));
$result = $this->_add_resources_to_cache($page_full_url);
if (!$result) {
//if the master page is null, cancel everything and return a 404
if ($page === $this->pages[0]){
$this->data['cache'] = array();
return;
}
//remove non-existing page from manifest
$key = array_search($page, $this->data['cache']);
unset($this->data['cache'][$key]);
}
}
//remove Master page
$key = array_search($this->master_page, $this->data['cache']);
unset($this->data['cache'][$key]);
$this->data['hashes'] = md5($this->data['hashes']).'_'.$this->hash_manual_override; //hash of hashes
$this->data['network'] = $this->network;
$this->data['fallback']= $this->offline;
}
}
// function to add all direct and direct resources from html page to cache
private function _add_resources_to_cache($full_url)
{
$resources = $this->_get_resources_from_html($full_url);
//add each new resource to the cache and calculate the hash
//print_r($resources);
if (!$resources) {
return FALSE;
}
foreach ($resources as $resource) {
//log_message('debug', 'checking resource')
if (!in_array($resource, $this->data['cache']))
{
//log_message('debug', 'adding resource to cache: '.$resource);
$this->data['cache'][] = $resource;
}
}
return TRUE;
}
// get all resources used in a web page
private function _get_resources_from_html($full_url, $base=NULL)
{
//SMALL PROBLEM: ALSO COPIES RESOURCES THAT ARE COMMENTED OUT
$pattern = '/(<script|<link|<img|<audio|<video) [^>]*(src|href)="([^"]+)"/';
$index = 3; //match of 3rd set of parentheses is what we want
$resources = $this->_get_resources($full_url, $pattern, $index, $base);
if (!$resources) {
return NULL;
}
foreach ($resources as $resource_in_html) {
// if the resource is a css stylesheet, also obtain all image urls
// from the stylesheet and add these
$pattern = '/\.css/';
if (preg_match($pattern, $resource_in_html)>0) {
// resources in a css file are assumed to be relative (to the css file) and may have
// a base different from the webroot
$path_prefix = substr($resource_in_html, 0, strrpos($resource_in_html, '/')+1);
//log_message('debug', 'css path_prefix: '.$path_prefix);
// extract the resources from the css file
$resources = array_merge($resources, $this->_get_resources_from_css($resource_in_html, $path_prefix));
}
}
return $resources;
}
// extract all resources from a css file
private function _get_resources_from_css($path, $base=NULL)
{
//SMALL PROBLEM: ALSO EXTRACTS RESOURCES THAT ARE COMMENTED OUT
//doesn't do @import-ed resources
$pattern = '/url[\s]?\([\s]?[\'\"]?([^\)\'\"]+)[\'\"]?[\s]?\)/';///url\(([^)]+)\)/';
$index = 1; //match of 1st set of parentheses is what we want
return $this->_get_resources($path, $pattern, $index, $base);
}
// generic function to extract resources from a url based on a given pattern
// only goes one level deep
private function _get_resources($url, $pattern, $i, $base=NULL)
{
$content = $this->_get_content($url);
if (isset($content)) {
$this->data['hashes'] .= md5($content);
preg_match_all($pattern, $content, $result_array);
$found_resources = $result_array[$i];
$cache_resources = array();
foreach ($found_resources as $index => $resource) {
if (isset($base) && strpos($resource, '/') !== 0) {
$resource = $base . $resource;
}
if (!in_array($resource, $cache_resources)) {
$content = $this->_get_content($resource);
//if (strpos($resource, '/media/get/') === 0) log_message('debug', 'content retrieved: '.$content);
if (!empty($content)) {
$cache_resources[] = $resource;
$this->data['hashes'] .= md5($content);
} else {
log_message('error', 'resource: '.$resource.' could not be found, removed from manifest.');
//unset($resources[$index]);
}
} else {
//log_message('debug', 'resource '.$resource.' was already added');
}
}
return $cache_resources;
} else {
return NULL;
}
}
// get the content, if possible through path, otherwise url
private function _get_content($url_or_path)
{
//log_message('debug', 'getting content of '.$url_or_path);
//remove hashes
if (strpos($url_or_path, '#')) $url_or_path = substr($url_or_path, 0, strpos($url_or_path, '#'));
//add base_url for external (spoofed) media resources and prevent actually downloading by using /media/check
//knowing that (in formhub) when the media file changes it will get a new url, so the manifest will already be updated
//also note the content returned in /media/check contains the content-length of the media file
if (strpos($url_or_path, '/media/get/') === 0) {
$url_or_path = $this->_full_url(preg_replace('/\/media\/get\//', '/media/check/', $url_or_path));
}
if (strpos($url_or_path, 'http://') !== 0 && strpos($url_or_path, 'https://') !== 0) {
$rel_path = (strpos($url_or_path, '/') === 0) ? substr($url_or_path, 1) : $url_or_path;
$abs_path = constant('FCPATH'). $rel_path;
$content = (is_file($abs_path)) ? file_get_contents($abs_path) : NULL;
} else {
//$context = stream_context_create( $this->context_arr );
//$content = file_get_contents($url_or_path, FALSE, $context);
$content = file_get_contents($url_or_path);
}
if (empty($content)) {
log_message('error', 'Manifest controller failed to get contents of '.$url_or_path);
}
return $content;
}
/**
* returns a full url if relative url was provided
* if the relative url is not relative to the webroot, an alternative base can be provided
*/
private function _full_url($url, $base=NULL)
{
if(!isset($base)) {
$base = full_base_url();
}
//in case relative urls were used, prepend the base
if (strpos($url, 'http://')!==0 && strpos($url, 'https://')!==0 && $url !== '*') {
$url = $base.$url;
}
//log_message('debug', '_full_url() returns:'.$url);
return $url;
}
/**
* sets context (cookie with session identifier) for file_get_contents so credentials for form can be retrieved
* TODO: doesn't work because session is re-created every 5 minutes and uses IP address
* TODO: need to pass IP address
* from browser session (and not from a NEW session that file_get_contents would otherwise create.
*/
/*private function _set_context()
{
$opts['http']['method'] = 'GET';
$opts['http']['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
if( count( $_COOKIE ) > 0 ) {
$cookie_string = 'Cookie: ';
$i = 1;
foreach( $_COOKIE as $k => $v ) {
if( $i !== 1 ) {
$cookie_string .= '; ';
}
$cookie_string .= $k . '=' . urlencode( $v );
$i++;
}
$opts['http']['header'][] = $cookie_string;
}
$this->context_arr = $opts;
//log_message('debug', 'context for file_get_contents created from browser cookie');
}*/
}
?>
| apache-2.0 |
seniya2/reference_webui_template | src/main/java/com/polarisoffice/kaia/newtech/prototype/domain/AfterlifeAssessment.java | 96 | package com.polarisoffice.kaia.newtech.prototype.domain;
public class AfterlifeAssessment {
}
| apache-2.0 |
square/spincycle | spinc/cmd/ps_test.go | 6989 | // Copyright 2017-2019, Square, Inc.
package cmd_test
import (
"bytes"
"fmt"
"strings"
"testing"
"time"
"github.com/square/spincycle/v2/proto"
"github.com/square/spincycle/v2/spinc/app"
"github.com/square/spincycle/v2/spinc/cmd"
"github.com/square/spincycle/v2/spinc/config"
"github.com/square/spincycle/v2/test/mock"
)
func TestPs(t *testing.T) {
output := &bytes.Buffer{}
status := proto.RunningStatus{
Jobs: []proto.JobStatus{
{
RequestId: "b9uvdi8tk9kahl8ppvbg",
JobId: "jid1",
Type: "jobtype",
Name: "jobname",
StartedAt: time.Now().Add(-3 * time.Second).UnixNano(),
Status: "jobstatus",
Try: 1,
},
},
Requests: map[string]proto.Request{
"b9uvdi8tk9kahl8ppvbg": proto.Request{
Id: "b9uvdi8tk9kahl8ppvbg",
TotalJobs: 9,
Type: "requestname",
User: "owner",
FinishedJobs: 1,
},
},
}
request := proto.Request{
Id: "b9uvdi8tk9kahl8ppvbg",
Args: args,
}
rmc := &mock.RMClient{
RunningFunc: func(f proto.StatusFilter) (proto.RunningStatus, error) {
return status, nil
},
GetRequestFunc: func(id string) (proto.Request, error) {
if strings.Compare(id, "b9uvdi8tk9kahl8ppvbg") == 0 {
return request, nil
}
return proto.Request{}, nil
},
}
ctx := app.Context{
Out: output,
RMClient: rmc,
Options: config.Options{},
}
ps := cmd.NewPs(ctx)
err := ps.Run()
if err != nil {
t.Errorf("got err '%s', exepcted nil", err)
}
expectOutput := `REQUEST ID PRG USER RUNTIME TRY JOB STATUS
requestname b9uvdi8tk9kahl8ppvbg 11% owner 3s 1 jobname jobstatus
`
if output.String() != expectOutput {
fmt.Printf("got output:\n%s\nexpected:\n%s\n", output, expectOutput)
t.Error("wrong output, see above")
}
}
func TestPsVerbose(t *testing.T) {
// ps -v was removed. This test is just normal output, slightly different than
// previous test.
output := &bytes.Buffer{}
status := proto.RunningStatus{
Jobs: []proto.JobStatus{
{
RequestId: "b9uvdi8tk9kahl8ppvbg",
JobId: "jid1",
Type: "jobtype",
Name: "jobname",
StartedAt: time.Now().Add(-3 * time.Second).UnixNano(),
Status: "jobstatus",
Try: 2,
},
},
Requests: map[string]proto.Request{
"b9uvdi8tk9kahl8ppvbg": proto.Request{
Id: "b9uvdi8tk9kahl8ppvbg",
TotalJobs: 9,
Type: "requestname",
User: "owner",
FinishedJobs: 2,
},
},
}
request := proto.Request{
Id: "b9uvdi8tk9kahl8ppvbg",
Args: args,
}
rmc := &mock.RMClient{
RunningFunc: func(f proto.StatusFilter) (proto.RunningStatus, error) {
return status, nil
},
GetRequestFunc: func(id string) (proto.Request, error) {
if strings.Compare(id, "b9uvdi8tk9kahl8ppvbg") == 0 {
return request, nil
}
return proto.Request{}, nil
},
}
ctx := app.Context{
Out: output,
RMClient: rmc,
Options: config.Options{},
}
ps := cmd.NewPs(ctx)
err := ps.Run()
if err != nil {
t.Errorf("got err '%s', exepcted nil", err)
}
// There's a trailing space after "val2 ". Only required args in list order
// because that matches spec order.
expectOutput := `REQUEST ID PRG USER RUNTIME TRY JOB STATUS
requestname b9uvdi8tk9kahl8ppvbg 22% owner 3s 2 jobname jobstatus
`
if output.String() != expectOutput {
fmt.Printf("got output:\n%s\nexpected:\n%s\n", output, expectOutput)
t.Error("wrong output, see above")
}
}
func TestPsLongNames(t *testing.T) {
output := &bytes.Buffer{}
status := proto.RunningStatus{
Jobs: []proto.JobStatus{
{
RequestId: "b9uvdi8tk9kahl8ppvbg",
JobId: "jid1",
Type: "jobtype",
Name: "this-is-a-pretty-long-job-name",
StartedAt: time.Now().Add(-65 * time.Minute).UnixNano(),
Status: "but job status has no length so we should see this whole string, nothing truncated...",
Try: 999,
},
},
Requests: map[string]proto.Request{
"b9uvdi8tk9kahl8ppvbg": proto.Request{
Id: "b9uvdi8tk9kahl8ppvbg",
TotalJobs: 9,
Type: "this-is-a-rather-long-request-name",
User: "michael.engineering.manager.finch",
FinishedJobs: 9,
},
},
}
request := proto.Request{
Id: "b9uvdi8tk9kahl8ppvbg",
Args: args,
}
rmc := &mock.RMClient{
RunningFunc: func(f proto.StatusFilter) (proto.RunningStatus, error) {
return status, nil
},
GetRequestFunc: func(id string) (proto.Request, error) {
if strings.Compare(id, "b9uvdi8tk9kahl8ppvbg") == 0 {
return request, nil
}
return proto.Request{}, nil
},
}
ctx := app.Context{
Out: output,
RMClient: rmc,
Options: config.Options{},
}
ps := cmd.NewPs(ctx)
err := ps.Run()
if err != nil {
t.Errorf("got err '%s', exepcted nil", err)
}
expectOutput := `REQUEST ID PRG USER RUNTIME TRY JOB STATUS
this-is-a..uest-name b9uvdi8tk9kahl8ppvbg 100% mich..nch 1h5m0s 999 this-is-a-..g-job-name but job status has no length so we should see this whole string, nothing truncated...
`
if output.String() != expectOutput {
fmt.Printf("got output:\n%s\nexpected:\n%s\n", output, expectOutput)
t.Error("wrong output, see above")
}
}
func TestPsFilterByRequestId(t *testing.T) {
output := &bytes.Buffer{}
status := proto.RunningStatus{
Jobs: []proto.JobStatus{
{
RequestId: "b9uvdi8tk9kahl8ppvbg",
JobId: "jid1",
Type: "jobtype",
Name: "jobname",
StartedAt: time.Now().Add(-3 * time.Second).UnixNano(),
Status: "jobstatus",
Try: 1,
},
},
Requests: map[string]proto.Request{
"b9uvdi8tk9kahl8ppvbg": proto.Request{
Id: "b9uvdi8tk9kahl8ppvbg",
TotalJobs: 9,
Type: "requestname",
User: "owner",
FinishedJobs: 1,
},
},
}
request := proto.Request{
Id: "b9uvdi8tk9kahl8ppvbg",
Args: args,
}
var gotFilter proto.StatusFilter
rmc := &mock.RMClient{
RunningFunc: func(f proto.StatusFilter) (proto.RunningStatus, error) {
gotFilter = f
return status, nil
},
GetRequestFunc: func(id string) (proto.Request, error) {
if strings.Compare(id, "b9uvdi8tk9kahl8ppvbg") == 0 {
return request, nil
}
return proto.Request{}, nil
},
}
ctx := app.Context{
Out: output,
RMClient: rmc,
Options: config.Options{},
Command: config.Command{
Cmd: "ps",
Args: []string{request.Id},
},
}
ps := cmd.NewPs(ctx)
// Must call Prepare, that's where ps checks/saves the optional request ID arg
err := ps.Prepare()
if err != nil {
t.Fatal(err)
}
// Then it uses the optional request ID arg in Run
err = ps.Run()
if err != nil {
t.Fatal(err)
}
if gotFilter.RequestId != request.Id {
t.Errorf("RequestId not set in filter")
}
}
| apache-2.0 |
googleapis/synthtool | tests/fixtures/snippets/interleaved.js | 764 | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// [START interleave_snippet_1]
var line1 = 1;
// [START interleave_snippet_2]
var line2 = 2;
// [END interleave_snippet_1]
var line3 = 3;
// [END interleave_snippet_2]
| apache-2.0 |
wangqi/gameserver | admin/src/main/java/com/xinqihd/sns/gameserver/admin/i18n/ColumnNames.java | 3924 | package com.xinqihd.sns.gameserver.admin.i18n;
import java.util.HashMap;
public class ColumnNames {
private static HashMap<String, String> map = new HashMap<String, String>();
static {
map.put("profile" , "profile");
map.put("vip" , "vip");
map.put("ability" , "ability");
map.put("login" , "登陆");
map.put("config" , "配置");
map.put("wealth" , "wealth");
map.put("loc" , "位置");
map.put("tools" , "便携道具");
map.put("wears" , "wears");
map.put("count" , "count");
map.put("items" , "items");
map.put("class" , "class");
map.put("name" , "名称");
map.put("type" , "类型");
map.put("reqlv" , "reqlv");
map.put("scrollAreaX" , "scrollAreaX");
map.put("scrollAreaY" , "scrollAreaY");
map.put("scrollAreaWidth" , "scrollAreaWidth");
map.put("scrollAreaHeight" , "scrollAreaHeight");
map.put("layers" , "layers");
map.put("bgm" , "bgm");
map.put("damage" , "damage");
map.put("bosses" , "bosses");
map.put("enemies" , "enemies");
map.put("startPoints" , "startPoints");
map.put("index" , "index");
map.put("quality" , "品质");
map.put("qualityColor" , "品质颜色");
map.put("sName" , "名称");
map.put("equipType" , "装备类型");
map.put("addAttack" , "加攻击");
map.put("addDefend" , "加防御");
map.put("addAgility" , "加敏捷");
map.put("addLuck" , "加幸运");
map.put("addBlood" , "加血量");
map.put("addBloodPercent" , "加血量比例");
map.put("addThew" , "加体力");
map.put("addDamage" , "加伤害");
map.put("addSkin" , "加护甲");
map.put("sex" , "性别");
map.put("unused1" , "unused1");
map.put("unused2" , "unused2");
map.put("unused3" , "unused3");
map.put("indate1" , "indate1");
map.put("indate2" , "indate2");
map.put("indate3" , "indate3");
map.put("sign" , "sign");
map.put("lv" , "lv");
map.put("autoDirection" , "自动定位");
map.put("sAutoDirection" , "大招定位");
map.put("specialAction" , "特殊攻击");
map.put("radius" , "攻击半径");
map.put("sRadius" , "大招攻击半径");
map.put("expBlend" , "混合(不用)");
map.put("expSe" , "音效");
map.put("power" , "战斗力(未使用)");
map.put("autoDestory" , "自动伤害");
map.put("bullet" , "子弹标识");
map.put("icon" , "图标");
map.put("info" , "描述");
map.put("bubble" , "bubble");
map.put("slot" , "卡槽");
map.put("avatar" , "形象");
map.put("propInfoId" , "propInfoId");
map.put("level" , "level");
map.put("moneyType" , "货币类型");
map.put("buyPrices" , "购买价格");
map.put("banded" , "是否绑定");
map.put("discount" , "折扣");
map.put("sell" , "出售");
map.put("limitCount" , "limitCount");
map.put("limitGroup" , "limitGroup");
map.put("shopId" , "shopId");
map.put("isItem" , "isItem");
map.put("catalogs" , "商品目录");
map.put("desc" , "描述");
map.put("taskTarget" , "taskTarget");
map.put("step" , "步骤(step)");
map.put("exp" , "经验");
map.put("gold" , "金币");
map.put("ticket" , "礼券");
map.put("gongxun" , "功勋");
map.put("caifu" , "财富");
map.put("seq" , "顺序(seq)");
map.put("userLevel" , "用户等级");
map.put("script" , "脚本");
map.put("awards" , "奖励");
map.put("rival" , "rival");
map.put("typeId" , "typeId");
map.put("q" , "概率q");
map.put("rewards" , "奖励");
map.put("conditions" , "开启条件");
map.put("dayNum" , "天数");
map.put("price" , "价格");
map.put("currency" , "货币");
map.put("yuanbao" , "元宝");
map.put("isHotSale" , "是否热卖");
map.put("month" , "月");
map.put("yuanbaoPrice" , "元宝价格");
map.put("voucherPrice" , "礼券价格");
map.put("medalPrice" , "勋章价格");
}
public static String translate(String columnName) {
String name = map.get(columnName);
if ( name != null ) {
return name;
}
return columnName;
}
}
| apache-2.0 |
apache/hadoop-mapreduce | src/contrib/mrunit/src/java/org/apache/hadoop/mrunit/mapreduce/mock/MockMapContext.java | 2972 | /**
* 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.mrunit.mapreduce.mock;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.Counters;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.mapreduce.TaskType;
import org.apache.hadoop.mapreduce.task.MapContextImpl;
import org.apache.hadoop.mrunit.mock.MockOutputCollector;
import org.apache.hadoop.mrunit.types.Pair;
public class MockMapContext<KEYIN, VALUEIN, KEYOUT, VALUEOUT>
extends MapContextImpl<KEYIN, VALUEIN, KEYOUT, VALUEOUT> {
private Iterator<Pair<KEYIN, VALUEIN>> inputIter;
private Pair<KEYIN, VALUEIN> curInput;
private MockOutputCollector<KEYOUT, VALUEOUT> output;
public MockMapContext(final List<Pair<KEYIN, VALUEIN>> in,
final Counters counters) {
super(new Configuration(),
new TaskAttemptID("mrunit-jt", 0, TaskType.MAP, 0, 0),
null, null, new MockOutputCommitter(), new MockReporter(counters), null);
this.inputIter = in.iterator();
this.output = new MockOutputCollector<KEYOUT, VALUEOUT>();
}
@Override
public InputSplit getInputSplit() {
return new MockInputSplit();
}
@Override
public KEYIN getCurrentKey() {
return curInput.getFirst();
}
@Override
public VALUEIN getCurrentValue() {
return curInput.getSecond();
}
@Override
public boolean nextKeyValue() throws IOException {
if (this.inputIter.hasNext()) {
this.curInput = this.inputIter.next();
return true;
} else {
return false;
}
}
public void write(KEYOUT key, VALUEOUT value) throws IOException {
output.collect(key, value);
}
@Override
/** This method does nothing in the mock version. */
public void progress() {
}
@Override
/** This method does nothing in the mock version. */
public void setStatus(String status) {
}
/**
* @return the outputs from the MockOutputCollector back to
* the test harness.
*/
public List<Pair<KEYOUT, VALUEOUT>> getOutputs() {
return output.getOutputs();
}
}
| apache-2.0 |
Stratoscale/osmosis | cpp/Osmosis/Hash.cpp | 2702 | #include <openssl/md5.h>
#include <openssl/sha.h>
#include <boost/filesystem/path.hpp>
#include <Osmosis/Hash.h>
#include <Osmosis/Tongue.h>
#include "Common/Error.h"
#include "Osmosis/Hex.h"
namespace Osmosis
{
Hash::Hash( const struct Tongue::Hash & raw ) :
_raw( raw )
{
ASSERT( _raw.hashAlgorithm == static_cast< unsigned >( Tongue::HashAlgorithm::MD5 ) or
_raw.hashAlgorithm == static_cast< unsigned >( Tongue::HashAlgorithm::SHA1 ) );
}
Hash::Hash( const char *hex, unsigned length )
{
Hex::toBuffer( hex, length, _raw.hash, sizeof( _raw.hash ) );
if ( length == MD5_DIGEST_LENGTH * 2 )
_raw.hashAlgorithm = static_cast< unsigned >( Tongue::HashAlgorithm::MD5 );
else if ( length == SHA_DIGEST_LENGTH * 2 )
_raw.hashAlgorithm = static_cast< unsigned >( Tongue::HashAlgorithm::SHA1 );
else
THROW( Error, "Hash hex strings can be only 32 characters for MD5, or 40 for SHA1, but "
"string " << std::string( hex, length ) << " is " << length );
}
Hash::Hash( const std::string & hex ) : Hash( hex.c_str(), hex.size() ) {}
Hash::Hash() {}
boost::filesystem::path Hash::relativeFilename() const
{
char name[ 64 ];
snprintf( name, sizeof( name ), "%02x", _raw.hash[ 0 ] );
boost::filesystem::path result( name );
snprintf( name, sizeof( name ), "%02x", _raw.hash[ 1 ] );
result /= name;
Hex::fromBuffer( _raw.hash + 2, bytesCount() - 2, name, sizeof( name ) );
result /= name;
return result;
}
Tongue::HashAlgorithm Hash::algorithm() const
{
return static_cast< Tongue::HashAlgorithm >( _raw.hashAlgorithm );
}
const unsigned char * Hash::bytes() const
{
return _raw.hash;
}
unsigned Hash::bytesCount() const
{
ASSERT( _raw.hashAlgorithm == static_cast< unsigned >( Tongue::HashAlgorithm::MD5 ) or
_raw.hashAlgorithm == static_cast< unsigned >( Tongue::HashAlgorithm::SHA1 ) );
return ( _raw.hashAlgorithm == static_cast< unsigned >( Tongue::HashAlgorithm::MD5 ) ) ? 16 : 20;
}
std::ostream & operator<<( std::ostream & os, const Hash & hash )
{
char buffer[ 64 ];
Hex::fromBuffer( hash._raw.hash, hash.bytesCount(), buffer, sizeof( buffer ) );
os << buffer;
return os;
}
const Tongue::Hash & Hash::raw() const
{
return _raw;
}
bool operator == ( const Hash & first, const Hash & other )
{
return first._raw.hashAlgorithm == other._raw.hashAlgorithm and
memcmp( first._raw.hash, other._raw.hash, first.bytesCount() ) == 0;
}
bool operator != ( const Hash & first, const Hash & other )
{
return not (first == other);
}
bool operator < ( const Hash & first, const Hash & other )
{
return first.value() < other.value();
}
unsigned long Hash::value() const
{
return * reinterpret_cast< const unsigned long * >( & _raw );
}
} // namespace Osmosis
| apache-2.0 |
tomgarcia/micromouse2016 | libs/pid.cpp | 625 | #include "pid.h"
#include "float.h"
Pid::Pid(double P, double I, double D)
: P(P), I(I), D(D)
{
prev_error = 0;
integral = 0;
}
double Pid::correction(double error)
{
derivative = error - prev_error;
prev_error = error;
if(error > 0 && integral >= DBL_MAX - error) {
integral = DBL_MAX;
} else if(error < 0 && integral <= -DBL_MAX - error) {
integral = -DBL_MAX;
} else {
integral += error;
}
return P * error + I * integral + D * derivative;
}
void Pid::reset()
{
integral = 0;
prev_error = 0;
}
double Pid::get_derivative()
{
return derivative;
}
| apache-2.0 |
wimarsha93/Digital-Pulz-for-Hospitals | HIS_Latest_Project_29-07-2016/OPD/Pearson_OPD/application/controllers/allergies_c.php | 5476 | <?php
session_start();
class allergies_c extends CI_Controller {
var $_site_base_url = SITE_BASE_URL;
public function __construct() {
parent::__construct();
}
public function index() {
}
public function view() {
}
public function add($pid, $visitid, $status = '0') {
if (isset($_SESSION["user"])) {
if ($_SESSION["user"] == -1) {
redirect($this->_site_base_url);
}
} else {
redirect($this->_site_base_url);
}
$data['status'] = $status;
$data['pid'] = $pid;
$data['visitid'] = $visitid;
$data['title'] = 'Add Allergy';
$this->load->view('Components/headerInward', $data);
// loading left side navigation
$data['leftnavpage'] = '';
$this->load->view('Components/left_navbar', $data);
//************************************************************************************
// show patient profile mini
$this->load->model('PatientModel', 'patient');
$this->patient->set_pid($pid);
// $data['allergyList']= json_decode($this->patient->getAlleryList());
$data['pprofile'] = json_decode($this->patient->getPatient());
//$this->load->view('patient_profile_mini_v', $data);
//****************************************************************************
$data['allergyList']= json_decode($this->patient->getAlleryList());
$this->load->view('allergy_m_v', $data);
/* $this->load->library('template');
$this->template->title('Add Allergy');
$this->template
->set_layout('panellayout')
->build('allergy_m_v',$data);*/
$this->load->view('Components/bottom');
}
public function edit($pid, $alid, $status = '0') {
if (isset($_SESSION["user"])) {
if ($_SESSION["user"] == -1) {
redirect($this->_site_base_url);
}
} else {
redirect($this->_site_base_url);
}
$data['status'] = $status;
$data['pid'] = $pid;
$data['alid'] = $alid;
$data['visitid'] = '0';
$data['title'] = 'Edit Allergy';
$this->load->view('headerInward', $data);
// loading left side navigation
$data['leftnavpage'] = '';
$this->load->view('left_navbar_v', $data);
//************************************************************************************
// show patient profile mini
$this->load->model('PatientModel', 'patient');
$this->patient->set_pid($pid);
$data['pprofile'] = json_decode($this->patient->getPatient());
$this->load->view('patient_profile_mini_v', $data);
//****************************************************************************
// load data for the selected allergy
$this->load->model('AllergyModel', 'allergy');
$this->allergy->set_allergyid($alid);
$data['allergy'] = json_decode($this->allergy->getAllergy());
//****************************************************************************
$this->load->library('template');
$this->template->title('Add Allergy');
$this->template
->set_layout('panellayout')
->build('visit_m_v',$data);
$this->load->view('allergy_m_v', $data);
$this->load->view('bottom');
}
public function save($pid, $visitid) {
if (isset($_SESSION["user"])) {
if ($_SESSION["user"] == -1) {
redirect($this->_site_base_url);
}
} else {
redirect($this->_site_base_url);
}
$this->load->model('AllergyModel', 'allergy');
$this->allergy->set_pid($pid);
$this->allergy->set_name($this->input->post('alname'));
$this->allergy->set_status($this->input->post('status'));
$this->allergy->set_remarks($this->input->post('remarks'));
$this->allergy->set_userid($this->session->userdata('userid'));
$this->allergy->set_active(1);
$this->allergy->set_visitid($visitid);
$data['status'] = $this->allergy->addAllergy();
$this->add($pid, $visitid, $data['status']);
}
public function update($pid, $alid) {
if (isset($_SESSION["user"])) {
if ($_SESSION["user"] == -1) {
redirect($this->_site_base_url);
}
} else {
redirect($this->_site_base_url);
}
$this->load->model('AllergyModel', 'allergy');
$this->allergy->set_allergyid($alid);
$this->allergy->set_name($this->input->post('alname'));
$this->allergy->set_status($this->input->post('status'));
$this->allergy->set_remarks($this->input->post('remarks'));
$this->allergy->set_userid($this->session->userdata('userid'));
$this->allergy->set_active($this->input->post('active'));
$data['status'] = $this->allergy->updateAllergy();
$this->edit($pid, $alid, $data['status']);
}
function getAllergyList() {
$this->load->library('curl');
$_resultFromService = $this->curl->simple_get('http://localhost:8080/HIS_API/rest/LiveSearch/allergyLivesearch');
$_resultsAfterDecode = json_decode($_resultFromService, true);
echo json_encode($_resultsAfterDecode);
}
}
?> | apache-2.0 |
infinitiessoft/nova2.0-api | src/main/java/com/infinities/nova/exception/OnsetFileLimitExceededException.java | 1198 | /*******************************************************************************
* Copyright 2015 InfinitiesSoft Solutions Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package com.infinities.nova.exception;
public class OnsetFileLimitExceededException extends QuotaError {
/**
*
*/
private static final long serialVersionUID = 1L;
public OnsetFileLimitExceededException() {
this(null);
}
public OnsetFileLimitExceededException(String message, Object... args) {
super(message, args);
}
@Override
public String getMsgFmt() {
return "Personality file limit exceeded";
}
}
| apache-2.0 |
hohhots/materialize-minwei-mongol-class | gulpfile.babel.js | 13242 | /**
*
* Web Starter Kit
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*
*/
'use strict';
// This gulpfile makes use of new JavaScript features.
// Babel handles this without us having to do anything. It just works.
// You can read more about the new JavaScript features here:
// https://babeljs.io/docs/learn-es2015/
import path from 'path';
import gulp from 'gulp';
import del from 'del';
import runSequence from 'run-sequence';
import browserSync from 'browser-sync';
import swPrecache from 'sw-precache';
import gulpLoadPlugins from 'gulp-load-plugins';
import {output as pagespeed} from 'psi';
import pkg from './package.json';
import htmlbuild from 'gulp-htmlbuild';
import jsonminify from 'gulp-jsonminify';
import rev from 'gulp-rev';
import jsonfile from 'jsonfile';
import replace from 'gulp-replace';
const $ = gulpLoadPlugins();
const reload = browserSync.reload;
const mainJs = 'main.js';
const mainCss = 'main.css';
// Replace js and css block with one file
gulp.task('htmlblocks', () =>
gulp.src(['app/index.html'])
.pipe(htmlbuild({
// build js with preprocessor
js: htmlbuild.preprocess.js(block => {
block.end('scripts/' + mainJs);
}),
css: htmlbuild.preprocess.css(block => {
block.end('styles/' + mainCss);
})
}))
.pipe($.newer('.tmp'))
.pipe(gulp.dest('.tmp'))
.pipe($.htmlmin({
removeComments: true,
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
removeEmptyAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
removeOptionalTags: true
}))
// Output files
.pipe($.size({title: 'index.html', showFiles: true}))
.pipe(gulp.dest('dist'))
);
gulp.task('rename', ['htmlblocks'], () => {
const file = 'dist/rev-manifest.json';
const js = new RegExp(mainJs,"g");
const css = new RegExp(mainCss,"g");
return jsonfile.readFile(file, function (err, obj) {
if (err) console.error(err)
gulp.src(['dist/index.html'])
.pipe(replace(js, obj[mainJs]))
.pipe(replace(css, obj[mainCss]))
.pipe(gulp.dest('dist'));
})
});
// Lint JavaScript
gulp.task('lint', () =>
gulp.src(['app/scripts/**/*.js', '!node_modules/**'])
.pipe($.eslint())
.pipe($.eslint.format())
.pipe($.if(!browserSync.active, $.eslint.failAfterError()))
);
// Optimize images
gulp.task('images', ['audios','videos'], () =>{
// css images move to styles directory
gulp.src([
'app/scripts/levelshome/images/grassland.jpeg'
])
.pipe($.cache($.imagemin({
progressive: true,
interlaced: true
})))
.pipe($.size({title: 'css images'}))
.pipe(gulp.dest('dist/styles/images'));
return gulp.src([
'app/**/*.{png,gif,jpg,jpeg}',
'!app/node_modules/**/*'
])
.pipe($.cache($.imagemin({
progressive: true,
interlaced: true
})))
.pipe($.size({title: 'images'}))
.pipe(gulp.dest('dist'));
});
// copy audios
gulp.task('audios', () =>
gulp.src([
'app/**/*.{ogg,mp3}',
'!app/node_modules/**/*'
])
.pipe($.size({title: 'audio'}))
.pipe(gulp.dest('dist'))
);
// copy videos
gulp.task('videos', () =>
gulp.src([
'app/**/*.{ogv,webm}',
'!app/node_modules/**/*'
])
.pipe($.size({title: 'video'}))
.pipe(gulp.dest('dist'))
);
gulp.task('jsons', function () {
return gulp.src([
'app/**/*.json',
'!app/node_modules/**/*'
])
.pipe(jsonminify())
.pipe(gulp.dest('dist'));
});
// Copy all files at the root level (app)
gulp.task('copy', () =>
gulp.src([
'app/*',
'!app/index.html',
'!app/node_modules'
], {
dot: true
})
.pipe($.size({title: 'copy'}))
.pipe(gulp.dest('dist'))
);
// Compile and automatically prefix stylesheets
gulp.task('styles', () => {
const AUTOPREFIXER_BROWSERS = [
'ie >= 10',
'ie_mob >= 10',
'ff >= 30',
'chrome >= 34',
'safari >= 7',
'opera >= 23',
'ios >= 7',
'android >= 4.4',
'bb >= 10'
];
gulp.src([
'node_modules/font-awesome/fonts/*',
'app/scripts/fonts/*'
])
.pipe(gulp.dest('dist/fonts'));
// For best performance, don't add Sass partials to `gulp.src`
return gulp.src([
'node_modules/font-awesome/css/font-awesome.min.css',
'app/styles/**/*.css',
'app/scripts/**/*.css'
])
.pipe($.concat(mainCss))
.pipe($.newer('.tmp/styles'))
.pipe(gulp.dest('.tmp/styles'))
.pipe($.sass({
precision: 10
}).on('error', $.sass.logError))
.pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
// Concatenate and minify styles
.pipe($.cssnano())
.pipe($.size({title: 'main styles'}))
.pipe(rev())
.pipe(gulp.dest('dist/styles'))
.pipe(rev.manifest('dist/rev-manifest.json', {
merge: true
}))
.pipe(gulp.dest(''));
});
// Concatenate and minify JavaScript. Optionally transpiles ES2015 code to ES5.
// to enable ES2015 support remove the line `"only": "gulpfile.babel.js",` in the
// `.babelrc` file.
gulp.task('scripts', () =>
gulp.src([
// modules first
'node_modules/jquery/dist/jquery.min.js',
'node_modules/angular/angular.min.js',
'node_modules/angular-resource/angular-resource.min.js',
'node_modules/angular-ui-router/release/angular-ui-router.min.js',
'app/scripts/app.js',
'app/scripts/rootController.js',
'app/scripts/core/config.js',
'app/scripts/core/json.js',
'app/scripts/core/anchorScroll.js',
'app/scripts/core/util.js',
'app/scripts/root/root.component.js',
'app/scripts/header/header.component.js',
'app/scripts/home/home.component.js',
'app/scripts/levelshome/levelshome.component.js',
'app/scripts/levelshome/levels/levels.component.js',
'app/scripts/levelshome/levels/books/books.component.js' ,
'app/scripts/category/category.component.js',
'app/scripts/category/alphabet/origin/alphabetorigin.component.js',
'app/scripts/category/alphabet/origin/practice/originpractice.component.js',
'app/scripts/category/alphabet/origin/originRandom/originRandom.component.js',
'app/scripts/category/alphabet/list/alphabetlist.component.js',
'app/scripts/category/alphabet/list/practice/listpractice.component.js',
'app/scripts/category/alphabet/list/listRandom/listRandom.component.js',
'app/scripts/category/alphabet/variant/alphabetvariant.component.js',
'app/scripts/category/alphabet/variant/practice/variantpractice.component.js',
'app/scripts/category/alphabet/variant/variantRandom/variantRandom.component.js',
'app/scripts/category/word/begin/wordBegin.component.js',
'app/scripts/category/word/begin/practice/wordbeginpractice.component.js',
'app/scripts/category/ebook/begin/ebookBegin.component.js',
'app/scripts/class/class.component.js',
'app/scripts/lesson/lesson.component.js',
'app/scripts/footer/footer.component.js',
'app/scripts/player/player.module.js',
'app/scripts/player/simplePlayer/simplePlayer.component.js',
'app/scripts/filter/filter.module.js',
'app/scripts/filter/alphaOriginFilter/alphaOriginFilter.component.js',
'app/scripts/word/word.module.js',
'app/scripts/word/word.component.js',
'app/scripts/word/word.config.js',
'app/scripts/player/wordPlayer/wordPlayer.component.js',
'app/scripts/word/input/mwordInput.component.js',
'app/scripts/ime/ime.module.js',
'app/scripts/ime/word/wordIme.component.js',
'app/scripts/player/audioPlayer/audioPlayer.service.js',
'app/scripts/serviceworker.js'
])
.pipe($.uglify({mangle: false}))
.pipe($.concat(mainJs))
.pipe($.newer('dist/scripts'))
.pipe($.size({title: 'main scripts'}))
.pipe(rev())
.pipe(gulp.dest('dist/scripts'))
.pipe(rev.manifest('dist/rev-manifest.json', {
merge: true
}))
.pipe(gulp.dest(''))
);
// Scan your HTML for assets & optimize them
gulp.task('html', () => {
return gulp.src([
'app/**/*.html',
'!app/index.html',
'!app/node_modules/**/*'
])
.pipe($.useref({
searchPath: '{app}',
noAssets: true
}))
// Minify any HTML
.pipe($.htmlmin({
removeComments: true,
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
removeEmptyAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
removeOptionalTags: true
}))
// Output files
.pipe($.if('*.html', $.size({title: 'html', showFiles: true})))
.pipe(gulp.dest('dist'));
});
// Clean output directory
gulp.task('clean', () => del(['.tmp/*', 'dist/*', '!dist/.git'], {dot: true}));
// Watch files for changes & reload
gulp.task('serve', ['scripts', 'styles'], () => {
browserSync({
notify: false,
// Customize the Browsersync console logging prefix
logPrefix: 'WSK',
// Allow scroll syncing across breakpoints
scrollElementMapping: ['main', '.mdl-layout'],
// Run as an https by uncommenting 'https: true'
// Note: this uses an unsigned certificate which on first access
// will present a certificate warning in the browser.
// https: true,
server: ['.tmp', 'app'],
port: 3000
});
gulp.watch(['app/**/*.{html,json,jpg,png}'], reload);
gulp.watch(['app/**/*.{scss,css}'], ['styles', reload]);
gulp.watch(['app/scripts/**/*.js'], ['lint', 'scripts', reload]);
gulp.watch(['app/images/**/*'], reload);
});
// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], () =>
browserSync({
notify: false,
logPrefix: 'WSK',
// Allow scroll syncing across breakpoints
scrollElementMapping: ['main', '.mdl-layout'],
// Run as an https by uncommenting 'https: true'
// Note: this uses an unsigned certificate which on first access
// will present a certificate warning in the browser.
// https: true,
server: 'dist',
port: 3001
})
);
// Build production files, the default task
gulp.task('default', ['clean', 'scripts'], cb =>
runSequence(
'styles',
// ['lint', 'html', 'scripts', 'images', 'copy'],
['html', 'images', 'jsons', 'rename', 'copy'],
'generate-service-worker',
cb
)
);
// Run PageSpeed Insights
gulp.task('pagespeed', cb =>
// Update the below URL to the public URL of your site
pagespeed('example.com', {
//strategy: 'mobile' and 'desktop'
strategy: 'desktop'
// By default we use the PageSpeed Insights free (no API key) tier.
// Use a Google Developer API key if you have one: http://goo.gl/RkN0vE
// key: 'YOUR_API_KEY'
}, cb)
);
// Copy over the scripts that are used in importScripts as part of the generate-service-worker task.
gulp.task('copy-sw-scripts', () => {
return gulp.src(['node_modules/sw-toolbox/sw-toolbox.js', 'app/scripts/sw/runtime-caching.js'])
.pipe(gulp.dest('dist/scripts/sw'));
});
// See http://www.html5rocks.com/en/tutorials/service-worker/introduction/ for
// an in-depth explanation of what service workers are and why you should care.
// Generate a service worker file that will provide offline functionality for
// local resources. This should only be done for the 'dist' directory, to allow
// live reload to work as expected when serving from the 'app' directory.
gulp.task('generate-service-worker', ['copy-sw-scripts'], () => {
const rootDir = 'dist';
//const rootDir = '';
const filepath = path.join(rootDir, 'service-worker.js');
return swPrecache.write(filepath, {
// Used to avoid cache conflicts when serving on localhost.
cacheId: pkg.name || 'web-starter-kit',
// sw-toolbox.js needs to be listed first. It sets up methods used in runtime-caching.js.
importScripts: [
'scripts/sw/sw-toolbox.js',
'scripts/sw/runtime-caching.js'
],
staticFileGlobs: [
// Add/remove glob patterns to match your directory setup.
// `${rootDir}/images/**/*`,
// `${rootDir}/scripts/**/*.js`,
// `${rootDir}/styles/**/*.css`,
// `${rootDir}/*.{html,json}`
`${rootDir}/**/*.{html,js,woff,woff2}`,
],
// Translates a static file path to the relative URL that it's served from.
// This is '/' rather than path.sep because the paths returned from
// glob always use '/'.
stripPrefix: rootDir + '/'
});
});
// Load custom tasks from the `tasks` directory
// Run: `npm install --save-dev require-dir` from the command-line
// try { require('require-dir')('tasks'); } catch (err) { console.error(err); }
| apache-2.0 |
josdem/client-control | messengine/src/main/java/com/all/messengine/Message.java | 11749 | /**
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2011 Eric Haddad Koenig
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.all.messengine;
public interface Message<T> {
String getProperty(String key);
void putProperty(String key, String value);
String getType();
T getBody();
}
| apache-2.0 |
hurricup/intellij-community | java/debugger/impl/src/com/intellij/debugger/impl/DebuggerManagerImpl.java | 23558 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.impl;
import com.intellij.debugger.*;
import com.intellij.debugger.apiAdapters.TransportServiceWrapper;
import com.intellij.debugger.engine.*;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.debugger.ui.GetJPDADialog;
import com.intellij.debugger.ui.breakpoints.BreakpointManager;
import com.intellij.debugger.ui.tree.render.BatchEvaluator;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.ExecutionResult;
import com.intellij.execution.configurations.JavaParameters;
import com.intellij.execution.configurations.RemoteConnection;
import com.intellij.execution.process.KillableColoredProcessHandler;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.components.StoragePathMacros;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.EditorColorsListener;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.JdkUtil;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.ex.JavaSdkUtil;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.util.EventDispatcher;
import com.intellij.util.Function;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.util.*;
import java.util.jar.Attributes;
import java.util.stream.Stream;
@State(name = "DebuggerManager", storages = {@Storage(StoragePathMacros.WORKSPACE_FILE)})
public class DebuggerManagerImpl extends DebuggerManagerEx implements PersistentStateComponent<Element> {
private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.impl.DebuggerManagerImpl");
private final Project myProject;
private final HashMap<ProcessHandler, DebuggerSession> mySessions = new HashMap<>();
private final BreakpointManager myBreakpointManager;
private final List<NameMapper> myNameMappers = ContainerUtil.createLockFreeCopyOnWriteList();
private final List<Function<DebugProcess, PositionManager>> myCustomPositionManagerFactories = new SmartList<>();
private final EventDispatcher<DebuggerManagerListener> myDispatcher = EventDispatcher.create(DebuggerManagerListener.class);
private final MyDebuggerStateManager myDebuggerStateManager = new MyDebuggerStateManager();
private final DebuggerContextListener mySessionListener = new DebuggerContextListener() {
@Override
public void changeEvent(@NotNull DebuggerContextImpl newContext, DebuggerSession.Event event) {
final DebuggerSession session = newContext.getDebuggerSession();
if (event == DebuggerSession.Event.PAUSE && myDebuggerStateManager.myDebuggerSession != session) {
// if paused in non-active session; switch current session
myDebuggerStateManager.setState(newContext, session != null? session.getState() : DebuggerSession.State.DISPOSED, event, null);
return;
}
if (myDebuggerStateManager.myDebuggerSession == session) {
myDebuggerStateManager.fireStateChanged(newContext, event);
}
if (event == DebuggerSession.Event.ATTACHED) {
myDispatcher.getMulticaster().sessionAttached(session);
}
else if (event == DebuggerSession.Event.DETACHED) {
myDispatcher.getMulticaster().sessionDetached(session);
}
else if (event == DebuggerSession.Event.DISPOSE) {
dispose(session);
if (myDebuggerStateManager.myDebuggerSession == session) {
myDebuggerStateManager
.setState(DebuggerContextImpl.EMPTY_CONTEXT, DebuggerSession.State.DISPOSED, DebuggerSession.Event.DISPOSE, null);
}
}
}
};
@NonNls private static final String DEBUG_KEY_NAME = "idea.xdebug.key";
@Override
public void addClassNameMapper(final NameMapper mapper) {
myNameMappers.add(mapper);
}
@Override
public void removeClassNameMapper(final NameMapper mapper) {
myNameMappers.remove(mapper);
}
@Override
public String getVMClassQualifiedName(@NotNull final PsiClass aClass) {
for (NameMapper nameMapper : myNameMappers) {
final String qName = nameMapper.getQualifiedName(aClass);
if (qName != null) {
return qName;
}
}
return aClass.getQualifiedName();
}
@Override
public void addDebuggerManagerListener(DebuggerManagerListener listener) {
myDispatcher.addListener(listener);
}
@Override
public void removeDebuggerManagerListener(DebuggerManagerListener listener) {
myDispatcher.removeListener(listener);
}
public DebuggerManagerImpl(Project project, StartupManager startupManager, EditorColorsManager colorsManager) {
myProject = project;
myBreakpointManager = new BreakpointManager(myProject, startupManager, this);
if (!project.isDefault()) {
colorsManager.addEditorColorsListener(new EditorColorsListener() {
@Override
public void globalSchemeChange(EditorColorsScheme scheme) {
getBreakpointManager().updateBreakpointsUI();
}
}, project);
}
}
@Nullable
@Override
public DebuggerSession getSession(DebugProcess process) {
ApplicationManager.getApplication().assertIsDispatchThread();
for (final DebuggerSession debuggerSession : getSessions()) {
if (process == debuggerSession.getProcess()) return debuggerSession;
}
return null;
}
@NotNull
@Override
public Collection<DebuggerSession> getSessions() {
synchronized (mySessions) {
final Collection<DebuggerSession> values = mySessions.values();
return values.isEmpty() ? Collections.emptyList() : new ArrayList<>(values);
}
}
@Override
public void disposeComponent() {
}
@Override
public void initComponent() {
}
@Override
public void projectClosed() {
}
@Override
public void projectOpened() {
myBreakpointManager.init();
}
@Nullable
@Override
public Element getState() {
Element state = new Element("state");
myBreakpointManager.writeExternal(state);
return state;
}
@Override
public void loadState(Element state) {
myBreakpointManager.readExternal(state);
}
public void writeExternal(Element element) throws WriteExternalException {
myBreakpointManager.writeExternal(element);
}
/**
* @deprecated to be removed with {@link DebuggerManager#registerPositionManagerFactory(Function)}
*/
@Deprecated
public Stream<Function<DebugProcess, PositionManager>> getCustomPositionManagerFactories() {
return myCustomPositionManagerFactories.stream();
}
@Override
@Nullable
public DebuggerSession attachVirtualMachine(@NotNull DebugEnvironment environment) throws ExecutionException {
ApplicationManager.getApplication().assertIsDispatchThread();
DebugProcessEvents debugProcess = new DebugProcessEvents(myProject);
DebuggerSession session = DebuggerSession.create(environment.getSessionName(), debugProcess, environment);
ExecutionResult executionResult = session.getProcess().getExecutionResult();
if (executionResult == null) {
return null;
}
session.getContextManager().addListener(mySessionListener);
getContextManager()
.setState(DebuggerContextUtil.createDebuggerContext(session, session.getContextManager().getContext().getSuspendContext()),
session.getState(), DebuggerSession.Event.CONTEXT, null);
final ProcessHandler processHandler = executionResult.getProcessHandler();
synchronized (mySessions) {
mySessions.put(processHandler, session);
}
if (!(processHandler instanceof RemoteDebugProcessHandler)) {
// add listener only to non-remote process handler:
// on Unix systems destroying process does not cause VMDeathEvent to be generated,
// so we need to call debugProcess.stop() explicitly for graceful termination.
// RemoteProcessHandler on the other hand will call debugProcess.stop() as a part of destroyProcess() and detachProcess() implementation,
// so we shouldn't add the listener to avoid calling stop() twice
processHandler.addProcessListener(new ProcessAdapter() {
@Override
public void processWillTerminate(ProcessEvent event, boolean willBeDestroyed) {
final DebugProcessImpl debugProcess = getDebugProcess(event.getProcessHandler());
if (debugProcess != null) {
// if current thread is a "debugger manager thread", stop will execute synchronously
// it is KillableColoredProcessHandler responsibility to terminate VM
debugProcess.stop(willBeDestroyed && !(event.getProcessHandler() instanceof KillableColoredProcessHandler));
// wait at most 10 seconds: the problem is that debugProcess.stop() can hang if there are troubles in the debuggee
// if processWillTerminate() is called from AWT thread debugProcess.waitFor() will block it and the whole app will hang
if (!DebuggerManagerThreadImpl.isManagerThread()) {
if (SwingUtilities.isEventDispatchThread()) {
ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> {
ProgressManager.getInstance().getProgressIndicator().setIndeterminate(true);
debugProcess.waitFor(10000);
}, "Waiting For Debugger Response", false, debugProcess.getProject());
}
else {
debugProcess.waitFor(10000);
}
}
}
}
});
}
myDispatcher.getMulticaster().sessionCreated(session);
if (debugProcess.isDetached() || debugProcess.isDetaching()) {
session.dispose();
return null;
}
if (environment.isRemote()) {
// optimization: that way BatchEvaluator will not try to lookup the class file in remote VM
// which is an expensive operation when executed first time
debugProcess.putUserData(BatchEvaluator.REMOTE_SESSION_KEY, Boolean.TRUE);
}
return session;
}
@Override
public DebugProcessImpl getDebugProcess(final ProcessHandler processHandler) {
synchronized (mySessions) {
DebuggerSession session = mySessions.get(processHandler);
return session != null ? session.getProcess() : null;
}
}
@SuppressWarnings("UnusedDeclaration")
@Nullable
public DebuggerSession getDebugSession(final ProcessHandler processHandler) {
synchronized (mySessions) {
return mySessions.get(processHandler);
}
}
@Override
public void addDebugProcessListener(final ProcessHandler processHandler, final DebugProcessListener listener) {
DebugProcessImpl debugProcess = getDebugProcess(processHandler);
if (debugProcess != null) {
debugProcess.addDebugProcessListener(listener);
}
else {
processHandler.addProcessListener(new ProcessAdapter() {
@Override
public void startNotified(ProcessEvent event) {
DebugProcessImpl debugProcess = getDebugProcess(processHandler);
if (debugProcess != null) {
debugProcess.addDebugProcessListener(listener);
}
processHandler.removeProcessListener(this);
}
});
}
}
@Override
public void removeDebugProcessListener(final ProcessHandler processHandler, final DebugProcessListener listener) {
DebugProcessImpl debugProcess = getDebugProcess(processHandler);
if (debugProcess != null) {
debugProcess.removeDebugProcessListener(listener);
}
else {
processHandler.addProcessListener(new ProcessAdapter() {
@Override
public void startNotified(ProcessEvent event) {
DebugProcessImpl debugProcess = getDebugProcess(processHandler);
if (debugProcess != null) {
debugProcess.removeDebugProcessListener(listener);
}
processHandler.removeProcessListener(this);
}
});
}
}
@Override
public boolean isDebuggerManagerThread() {
return DebuggerManagerThreadImpl.isManagerThread();
}
@Override
@NotNull
public String getComponentName() {
return "DebuggerManager";
}
@NotNull
@Override
public BreakpointManager getBreakpointManager() {
return myBreakpointManager;
}
@NotNull
@Override
public DebuggerContextImpl getContext() {
return getContextManager().getContext();
}
@NotNull
@Override
public DebuggerStateManager getContextManager() {
return myDebuggerStateManager;
}
@Override
public void registerPositionManagerFactory(final Function<DebugProcess, PositionManager> factory) {
myCustomPositionManagerFactories.add(factory);
}
@Override
public void unregisterPositionManagerFactory(final Function<DebugProcess, PositionManager> factory) {
myCustomPositionManagerFactories.remove(factory);
}
private static boolean hasWhitespace(String string) {
int length = string.length();
for (int i = 0; i < length; i++) {
if (Character.isWhitespace(string.charAt(i))) {
return true;
}
}
return false;
}
/* Remoting */
private static void checkTargetJPDAInstalled(JavaParameters parameters) throws ExecutionException {
final Sdk jdk = parameters.getJdk();
if (jdk == null) {
throw new ExecutionException(DebuggerBundle.message("error.jdk.not.specified"));
}
final JavaSdkVersion version = JavaSdk.getInstance().getVersion(jdk);
String versionString = jdk.getVersionString();
if (version == JavaSdkVersion.JDK_1_0 || version == JavaSdkVersion.JDK_1_1) {
throw new ExecutionException(DebuggerBundle.message("error.unsupported.jdk.version", versionString));
}
if (SystemInfo.isWindows && version == JavaSdkVersion.JDK_1_2) {
final VirtualFile homeDirectory = jdk.getHomeDirectory();
if (homeDirectory == null || !homeDirectory.isValid()) {
throw new ExecutionException(DebuggerBundle.message("error.invalid.jdk.home", versionString));
}
//noinspection HardCodedStringLiteral
File dllFile = new File(
homeDirectory.getPath().replace('/', File.separatorChar) + File.separator + "bin" + File.separator + "jdwp.dll"
);
if (!dllFile.exists()) {
GetJPDADialog dialog = new GetJPDADialog();
dialog.show();
throw new ExecutionException(DebuggerBundle.message("error.debug.libraries.missing"));
}
}
}
/**
* for Target JDKs versions 1.2.x - 1.3.0 the Classic VM should be used for debugging
*/
private static boolean shouldForceClassicVM(Sdk jdk) {
if (SystemInfo.isMac) {
return false;
}
if (jdk == null) return false;
String version = JdkUtil.getJdkMainAttribute(jdk, Attributes.Name.IMPLEMENTATION_VERSION);
if (version == null || StringUtil.compareVersionNumbers(version, "1.4") >= 0) {
return false;
}
if (version.startsWith("1.2") && SystemInfo.isWindows) {
return true;
}
version += ".0";
if (version.startsWith("1.3.0") && SystemInfo.isWindows) {
return true;
}
if ((version.startsWith("1.3.1_07") || version.startsWith("1.3.1_08")) && SystemInfo.isWindows) {
return false; // fixes bug for these JDKs that it cannot start with -classic option
}
return DebuggerSettings.getInstance().FORCE_CLASSIC_VM;
}
@SuppressWarnings({"HardCodedStringLiteral"})
public static RemoteConnection createDebugParameters(final JavaParameters parameters,
final boolean debuggerInServerMode,
int transport, final String debugPort,
boolean checkValidity)
throws ExecutionException {
if (checkValidity) {
checkTargetJPDAInstalled(parameters);
}
final boolean useSockets = transport == DebuggerSettings.SOCKET_TRANSPORT;
String address = "";
if (StringUtil.isEmptyOrSpaces(debugPort)) {
try {
address = DebuggerUtils.getInstance().findAvailableDebugAddress(useSockets);
}
catch (ExecutionException e) {
if (checkValidity) {
throw e;
}
}
}
else {
address = debugPort;
}
final TransportServiceWrapper transportService = TransportServiceWrapper.getTransportService(useSockets);
final String debugAddress = debuggerInServerMode && useSockets ? "127.0.0.1:" + address : address;
String debuggeeRunProperties = "transport=" + transportService.transportId() + ",address=" + debugAddress;
if (debuggerInServerMode) {
debuggeeRunProperties += ",suspend=y,server=n";
}
else {
debuggeeRunProperties += ",suspend=n,server=y";
}
if (hasWhitespace(debuggeeRunProperties)) {
debuggeeRunProperties = "\"" + debuggeeRunProperties + "\"";
}
final String _debuggeeRunProperties = debuggeeRunProperties;
ApplicationManager.getApplication().runReadAction(() -> {
JavaSdkUtil.addRtJar(parameters.getClassPath());
final Sdk jdk = parameters.getJdk();
final boolean forceClassicVM = shouldForceClassicVM(jdk);
final boolean forceNoJIT = shouldForceNoJIT(jdk);
final String debugKey = System.getProperty(DEBUG_KEY_NAME, "-Xdebug");
final boolean needDebugKey = shouldAddXdebugKey(jdk) || !"-Xdebug".equals(debugKey) /*the key is non-standard*/;
if (forceClassicVM || forceNoJIT || needDebugKey || !isJVMTIAvailable(jdk)) {
parameters.getVMParametersList().replaceOrPrepend("-Xrunjdwp:", "-Xrunjdwp:" + _debuggeeRunProperties);
}
else {
// use newer JVMTI if available
parameters.getVMParametersList().replaceOrPrepend("-Xrunjdwp:", "");
parameters.getVMParametersList().replaceOrPrepend("-agentlib:jdwp=", "-agentlib:jdwp=" + _debuggeeRunProperties);
}
if (forceNoJIT) {
parameters.getVMParametersList().replaceOrPrepend("-Djava.compiler=", "-Djava.compiler=NONE");
parameters.getVMParametersList().replaceOrPrepend("-Xnoagent", "-Xnoagent");
}
if (needDebugKey) {
parameters.getVMParametersList().replaceOrPrepend(debugKey, debugKey);
}
else {
// deliberately skip outdated parameter because it can disable full-speed debugging for some jdk builds
// see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6272174
parameters.getVMParametersList().replaceOrPrepend("-Xdebug", "");
}
parameters.getVMParametersList().replaceOrPrepend("-classic", forceClassicVM ? "-classic" : "");
});
return new RemoteConnection(useSockets, "127.0.0.1", address, debuggerInServerMode);
}
private static boolean shouldForceNoJIT(Sdk jdk) {
if (DebuggerSettings.getInstance().DISABLE_JIT) {
return true;
}
if (jdk != null) {
final String version = JdkUtil.getJdkMainAttribute(jdk, Attributes.Name.IMPLEMENTATION_VERSION);
if (version != null && (version.startsWith("1.2") || version.startsWith("1.3"))) {
return true;
}
}
return false;
}
private static boolean shouldAddXdebugKey(Sdk jdk) {
if (jdk == null) {
return true; // conservative choice
}
if (DebuggerSettings.getInstance().DISABLE_JIT) {
return true;
}
//if (ApplicationManager.getApplication().isUnitTestMode()) {
// need this in unit tests to avoid false alarms when comparing actual output with expected output
//return true;
//}
final String version = JdkUtil.getJdkMainAttribute(jdk, Attributes.Name.IMPLEMENTATION_VERSION);
return version == null ||
//version.startsWith("1.5") ||
version.startsWith("1.4") ||
version.startsWith("1.3") ||
version.startsWith("1.2") ||
version.startsWith("1.1") ||
version.startsWith("1.0");
}
private static boolean isJVMTIAvailable(Sdk jdk) {
if (jdk == null) {
return false; // conservative choice
}
final String version = JdkUtil.getJdkMainAttribute(jdk, Attributes.Name.IMPLEMENTATION_VERSION);
if (version == null) {
return false;
}
return !(version.startsWith("1.4") ||
version.startsWith("1.3") ||
version.startsWith("1.2") ||
version.startsWith("1.1") ||
version.startsWith("1.0"));
}
public static RemoteConnection createDebugParameters(final JavaParameters parameters,
GenericDebuggerRunnerSettings settings,
boolean checkValidity)
throws ExecutionException {
return createDebugParameters(parameters, settings.LOCAL, settings.getTransport(), settings.getDebugPort(), checkValidity);
}
private static class MyDebuggerStateManager extends DebuggerStateManager {
private DebuggerSession myDebuggerSession;
@NotNull
@Override
public DebuggerContextImpl getContext() {
return myDebuggerSession == null ? DebuggerContextImpl.EMPTY_CONTEXT : myDebuggerSession.getContextManager().getContext();
}
@Override
public void setState(@NotNull final DebuggerContextImpl context, DebuggerSession.State state, DebuggerSession.Event event, String description) {
ApplicationManager.getApplication().assertIsDispatchThread();
myDebuggerSession = context.getDebuggerSession();
if (myDebuggerSession != null) {
myDebuggerSession.getContextManager().setState(context, state, event, description);
}
else {
fireStateChanged(context, event);
}
}
}
private void dispose(DebuggerSession session) {
ProcessHandler processHandler = session.getProcess().getProcessHandler();
synchronized (mySessions) {
DebuggerSession removed = mySessions.remove(processHandler);
LOG.assertTrue(removed != null);
myDispatcher.getMulticaster().sessionRemoved(session);
}
}
}
| apache-2.0 |
asha-nepal/AshaFusionCross | src/web/forms/editor/FormAdder.js | 1983 | /* @flow */
import React from 'react';
import Modal from '../../components/Modal';
import {
TextInputComponent,
} from '../fields';
type Props = {
onFormAdd: (id: string, label: string) => void,
className?: string,
}
export default class extends React.Component {
constructor(props: Props) {
super(props);
this.state = {
isModalOpen: false,
newFormId: '',
newFormLabel: '',
};
}
state: {
isModalOpen: boolean,
newFormId: string,
newFormLabel: string,
}
props: Props
render() {
const {
onFormAdd,
className,
} = this.props;
return (
<span className={className}>
<a
className="button is-primary"
onClick={e => {
e.preventDefault();
this.setState({ isModalOpen: true });
}}
>Add new form</a>
<Modal
isOpen={this.state.isModalOpen}
onClose={() => this.setState({ isModalOpen: false })}
>
<div className="box">
<TextInputComponent
label="ID"
value={this.state.newFormId}
onChange={newFormId => this.setState({ newFormId })}
/>
<TextInputComponent
label="Label"
value={this.state.newFormLabel}
onChange={newFormLabel => this.setState({ newFormLabel })}
/>
<p className="control">
<label className="label"> </label>
<a
className="button"
onClick={e => {
e.preventDefault();
onFormAdd(this.state.newFormId, this.state.newFormLabel);
this.setState({
isModalOpen: false,
newFormId: '',
newFormLabel: '',
});
}}
>Add new form</a>
</p>
</div>
</Modal>
</span>
);
}
}
| apache-2.0 |
Pathfinder-Fr/YAFNET | yafsrc/YAF.Types/Interfaces/IRequireStartupServices.cs | 1173 | /* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2020 Ingo Herbote
* https://www.yetanotherforum.net/
*
* 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
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Types.Interfaces
{
/// <summary>
/// Marker interface for a page that requires startup services.
/// </summary>
public interface IRequireStartupServices
{
}
} | apache-2.0 |
icza/sc2gears | src-sc2gearsdb/hu/belicza/andras/sc2gearsdb/apiuser/client/beans/ApiUserInfo.java | 2629 | /*
* Project Sc2gears
*
* Copyright (c) 2010 Andras Belicza <iczaaa@gmail.com>
*
* This software is the property of Andras Belicza.
* Copying, modifying, distributing, refactoring without the authors permission
* is prohibited and protected by Law.
*/
package hu.belicza.andras.sc2gearsdb.apiuser.client.beans;
import java.util.Date;
import java.util.List;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
*
* @author Andras Belicza
*/
public class ApiUserInfo implements IsSerializable {
private String userNickname;
private String userName;
private boolean hasApiAccount;
private String loginUrl;
private String logoutUrl;
private Date lastVisit;
private String repParserEngineVer;
private boolean admin;
/** Google account to access in case we're viewing someone else's account; <code>null</code> otherwise. */
private String sharedApiAccount;
/** List of shared API accounts. The first element is always us. */
private List< String > sharedAccounts;
public void setUserNickname( String userNickname ) {
this.userNickname = userNickname;
}
public String getUserNickname() {
return userNickname;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setHasApiAccount(boolean hasApiAccount) {
this.hasApiAccount = hasApiAccount;
}
public boolean isHasApiAccount() {
return hasApiAccount;
}
public String getLoginUrl() {
return loginUrl;
}
public void setLoginUrl(String loginUrl) {
this.loginUrl = loginUrl;
}
public String getLogoutUrl() {
return logoutUrl;
}
public void setLogoutUrl(String logoutUrl) {
this.logoutUrl = logoutUrl;
}
public void setLastVisit(Date lastVisit) {
this.lastVisit = new Date( lastVisit.getTime() );
}
public Date getLastVisit() {
return lastVisit;
}
public String getRepParserEngineVer() {
return repParserEngineVer;
}
public void setRepParserEngineVer(String repParserEngineVer) {
this.repParserEngineVer = repParserEngineVer;
}
public String getSharedApiAccount() {
return sharedApiAccount;
}
public void setSharedApiAccount(String sharedApiAccount) {
this.sharedApiAccount = sharedApiAccount;
}
public boolean isAdmin() {
return admin;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
public List< String > getSharedAccounts() {
return sharedAccounts;
}
public void setSharedAccounts(List< String > sharedAccounts) {
this.sharedAccounts = sharedAccounts;
}
}
| apache-2.0 |
hwxiasn/archetypes | ygb/ygb-account-impl/src/main/java/com/qingbo/ginkgo/ygb/account/inner/impl/AccountDoServiceImpl.java | 6342 | package com.qingbo.ginkgo.ygb.account.inner.impl;
import java.math.BigDecimal;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.qingbo.ginkgo.ygb.account.entity.AccountLog;
import com.qingbo.ginkgo.ygb.account.entity.SubAccount;
import com.qingbo.ginkgo.ygb.account.enums.AccountLogType;
import com.qingbo.ginkgo.ygb.account.inner.AccountDoService;
import com.qingbo.ginkgo.ygb.account.repository.AccountLogRepository;
import com.qingbo.ginkgo.ygb.account.repository.SubAccountRepository;
import com.qingbo.ginkgo.ygb.common.result.Result;
import com.qingbo.ginkgo.ygb.common.util.ErrorMessage;
import com.qingbo.ginkgo.ygb.common.util.ServiceRequester;
import com.qingbo.ginkgo.ygb.customer.service.CustomerService;
@Service("accountDoService")
public class AccountDoServiceImpl implements AccountDoService {
private Logger logger = LoggerFactory.getLogger(getClass());
private ErrorMessage errors = new ErrorMessage("account-error.properties");
@Autowired private AccountLogRepository accountLogRepository;
@Autowired private SubAccountRepository subAccountRepository;
@Autowired private CustomerService customerService;
@Override
public synchronized Result<Boolean> execute(Long accountLogId) {
if(accountLogId==null || accountLogId<1) return errors.newFailure("ACT0201", accountLogId);
AccountLog accountLog = accountLogRepository.findOne(accountLogId);
if(accountLog.isDeleted()) return errors.newFailure("ACT0202", accountLogId);
if(accountLog.isExecuted()) return errors.newFailure("ACT0203", accountLogId);
AccountLogType accountLogType = AccountLogType.getByCode(accountLog.getType());
if(accountLogType==null) return errors.newFailure("ACT0213", accountLog, accountLog.getType());
Long subAccountId = accountLog.getSubAccountId();
if(subAccountId==null || subAccountId<1) return errors.newFailure("ACT0205", accountLogId, subAccountId);
SubAccount subAccount = subAccountRepository.findOne(accountLog.getSubAccountId());
BigDecimal balance = accountLog.getBalance();
if(balance==null || balance.compareTo(BigDecimal.ZERO)<=0) return errors.newFailure("ACT0206", accountLogId, balance);
BigDecimal newBalance = null, newFreezeBalance = null;
switch(accountLogType) {
case IN:
newBalance = subAccount.getBalance()!=null ? subAccount.getBalance().add(balance) : balance;
subAccount.setBalance(newBalance);
subAccount = subAccountRepository.save(subAccount);
logger.info("account_log.id="+accountLogId+", account_id="+subAccount.getAccountId()+", sub_account_id="+subAccountId+" deposit "+accountLog.getBalance());
break;
case OUT:
if(subAccount.getBalance()==null || subAccount.getBalance().compareTo(balance)<0)
return errors.newFailure("ACT0208", accountLogId, balance, subAccount.getBalance());
newBalance = subAccount.getBalance().subtract(balance);
subAccount.setBalance(newBalance);
subAccount = subAccountRepository.save(subAccount);
logger.info("account_log.id="+accountLogId+", account_id="+subAccount.getAccountId()+", sub_account_id="+subAccountId+" withdraw "+accountLog.getBalance());
break;
case FREEZE:
if(subAccount.getBalance()==null || subAccount.getBalance().compareTo(balance)<0)
return errors.newFailure("ACT0210", accountLogId, balance, subAccount.getBalance());
newBalance = subAccount.getBalance().subtract(balance);
newFreezeBalance = subAccount.getFreezeBalance().add(balance);
subAccount.setBalance(newBalance);
subAccount.setFreezeBalance(newFreezeBalance);
subAccount = subAccountRepository.save(subAccount);
logger.info("account_log.id="+accountLogId+", account_id="+subAccount.getAccountId()+", sub_account_id="+subAccountId+" freeze "+accountLog.getBalance());
break;
case UNFREEZE:
if(subAccount.getFreezeBalance()==null || subAccount.getFreezeBalance().compareTo(balance)<0)
return errors.newFailure("ACT0212", accountLogId, balance, subAccount.getFreezeBalance());
newBalance = subAccount.getBalance().add(balance);
newFreezeBalance = subAccount.getFreezeBalance().subtract(balance);
subAccount.setBalance(newBalance);
subAccount.setFreezeBalance(newFreezeBalance);
subAccount = subAccountRepository.save(subAccount);
logger.info("account_log.id="+accountLogId+", account_id="+subAccount.getAccountId()+", sub_account_id="+subAccountId+" unfreeze "+accountLog.getBalance());
break;
}
accountLog.setExecuted(true);
accountLog.setAccountBalance2(subAccount.getBalance());
accountLog.setAccountFreezeBalance2(subAccount.getFreezeBalance());
accountLog = accountLogRepository.save(accountLog);
if(AccountLogType.IN.getCode().equals(accountLogType) || AccountLogType.OUT.getCode().equals(accountLogType)) {
notifyAccountLog(subAccount, accountLog);//收支变化时通知日志和余额
}
return Result.newSuccess(true);
}
public void notifyAccountLog(SubAccount subAccount, AccountLog accountLog) {
Result<Boolean> isWbossUser = customerService.isWbossUser(subAccount.getAccountId());
if(isWbossUser.hasObject() && isWbossUser.getObject()) {
Map<String, String> params = ServiceRequester.paramsWithSecret();
params.put("method", "accountLog");
Map<String, String> accountLogMap = ServiceRequester.convert(accountLog);
params.putAll(accountLogMap);
JSONObject request = ServiceRequester.request(ServiceRequester.serviceWboss+"account", params);
logger.info("notify accountLog "+accountLog.getId()+": "+request);
params = ServiceRequester.paramsWithSecret();
params.put("method", "balance");
params.put("userId", String.valueOf(subAccount.getAccountId()));
params.put("subAccountId", String.valueOf(subAccount.getId()));
params.put("balance", subAccount.getBalance().toPlainString());
params.put("freezeBalance", subAccount.getFreezeBalance().toPlainString());
ServiceRequester.request(ServiceRequester.serviceWboss+"account", params);
logger.info("notify balance "+accountLog.getId()+": "+request);
}
}
}
| apache-2.0 |
JaviMerino/lisa | libs/utils/analysis/frequency_analysis.py | 24894 | # SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2015, ARM Limited and 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.
#
""" Frequency Analysis Module """
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import pandas as pd
import pylab as pl
import operator
from trappy.utils import listify
from devlib.utils.misc import memoized
from collections import namedtuple
from analysis_module import AnalysisModule
# Configure logging
import logging
NON_IDLE_STATE = 4294967295
ResidencyTime = namedtuple('ResidencyTime', ['total', 'active'])
ResidencyData = namedtuple('ResidencyData', ['label', 'residency'])
class FrequencyAnalysis(AnalysisModule):
"""
Support for plotting Frequency Analysis data
:param trace: input Trace object
:type trace: :mod:`libs.utils.Trace`
"""
def __init__(self, trace):
super(FrequencyAnalysis, self).__init__(trace)
###############################################################################
# DataFrame Getter Methods
###############################################################################
def _dfg_cpu_frequency_residency(self, cpu, total=True):
"""
Get per-CPU frequency residency, i.e. amount of
time CPU `cpu` spent at each frequency.
:param cpu: CPU ID
:type cpu: int
:param total: if true returns the "total" time, otherwise the "active"
time is returned
:type total: bool
:returns: :mod:`pandas.DataFrame` - "total" or "active" time residency
at each frequency.
"""
residency = self._getCPUFrequencyResidency(cpu)
if not residency:
return None
if total:
return residency.total
return residency.active
def _dfg_cluster_frequency_residency(self, cluster, total=True):
"""
Get per-Cluster frequency residency, i.e. amount of time CLUSTER
`cluster` spent at each frequency.
:param cluster: this can be either a single CPU ID or a list of CPU IDs
belonging to a cluster or the cluster name as specified in the
platform description
:type cluster: str or int or list(int)
:param total: if true returns the "total" time, otherwise the "active"
time is returned
:type total: bool
:returns: :mod:`pandas.DataFrame` - "total" or "active" time residency
at each frequency.
"""
residency = self._getClusterFrequencyResidency(cluster)
if not residency:
return None
if total:
return residency.total
return residency.active
###############################################################################
# Plotting Methods
###############################################################################
def plotClusterFrequencies(self, title='Clusters Frequencies'):
"""
Plot frequency trend for all clusters. If sched_overutilized events are
available, the plots will also show the intervals of time where the
cluster was overutilized.
:param title: user-defined plot title
:type title: str
"""
if not self._trace.hasEvents('cpu_frequency'):
logging.warn('Events [cpu_frequency] not found, plot DISABLED!')
return
df = self._dfg_trace_event('cpu_frequency')
pd.options.mode.chained_assignment = None
# Extract LITTLE and big clusters frequencies
# and scale them to [MHz]
if len(self._platform['clusters']['little']):
lfreq = df[df.cpu == self._platform['clusters']['little'][-1]]
lfreq['frequency'] = lfreq['frequency']/1e3
else:
lfreq = []
if len(self._platform['clusters']['big']):
bfreq = df[df.cpu == self._platform['clusters']['big'][-1]]
bfreq['frequency'] = bfreq['frequency']/1e3
else:
bfreq = []
# Compute AVG frequency for LITTLE cluster
avg_lfreq = 0
if len(lfreq) > 0:
lfreq['timestamp'] = lfreq.index
lfreq['delta'] = (lfreq['timestamp'] -lfreq['timestamp'].shift()).fillna(0).shift(-1)
lfreq['cfreq'] = (lfreq['frequency'] * lfreq['delta']).fillna(0)
timespan = lfreq.iloc[-1].timestamp - lfreq.iloc[0].timestamp
avg_lfreq = lfreq['cfreq'].sum()/timespan
# Compute AVG frequency for big cluster
avg_bfreq = 0
if len(bfreq) > 0:
bfreq['timestamp'] = bfreq.index
bfreq['delta'] = (bfreq['timestamp'] - bfreq['timestamp'].shift()).fillna(0).shift(-1)
bfreq['cfreq'] = (bfreq['frequency'] * bfreq['delta']).fillna(0)
timespan = bfreq.iloc[-1].timestamp - bfreq.iloc[0].timestamp
avg_bfreq = bfreq['cfreq'].sum()/timespan
pd.options.mode.chained_assignment = 'warn'
# Setup a dual cluster plot
fig, pltaxes = plt.subplots(2, 1, figsize=(16, 8))
plt.suptitle(title, y=.97, fontsize=16, horizontalalignment='center')
# Plot Cluster frequencies
axes = pltaxes[0]
axes.set_title('big Cluster')
if avg_bfreq > 0:
axes.axhline(avg_bfreq, color='r', linestyle='--', linewidth=2)
axes.set_ylim(
(self._platform['freqs']['big'][0] - 100000)/1e3,
(self._platform['freqs']['big'][-1] + 100000)/1e3
)
if len(bfreq) > 0:
bfreq['frequency'].plot(style=['r-'], ax=axes,
drawstyle='steps-post', alpha=0.4)
else:
logging.warn('NO big CPUs frequency events to plot')
axes.set_xlim(self._trace.x_min, self._trace.x_max)
axes.set_ylabel('MHz')
axes.grid(True)
axes.set_xticklabels([])
axes.set_xlabel('')
self._trace.analysis.status.plotOverutilized(axes)
axes = pltaxes[1]
axes.set_title('LITTLE Cluster')
if avg_lfreq > 0:
axes.axhline(avg_lfreq, color='b', linestyle='--', linewidth=2)
axes.set_ylim(
(self._platform['freqs']['little'][0] - 100000)/1e3,
(self._platform['freqs']['little'][-1] + 100000)/1e3
)
if len(lfreq) > 0:
lfreq['frequency'].plot(style=['b-'], ax=axes,
drawstyle='steps-post', alpha=0.4)
else:
logging.warn('NO LITTLE CPUs frequency events to plot')
axes.set_xlim(self._trace.x_min, self._trace.x_max)
axes.set_ylabel('MHz')
axes.grid(True)
self._trace.analysis.status.plotOverutilized(axes)
# Save generated plots into datadir
figname = '{}/{}cluster_freqs.png'\
.format(self._trace.plots_dir, self._trace.plots_prefix)
pl.savefig(figname, bbox_inches='tight')
logging.info('LITTLE cluster average frequency: %.3f GHz',
avg_lfreq/1e3)
logging.info('big cluster average frequency: %.3f GHz',
avg_bfreq/1e3)
return (avg_lfreq/1e3, avg_bfreq/1e3)
def plotCPUFrequencyResidency(self, cpus=None, pct=False, active=False):
"""
Plot per-CPU frequency residency. big CPUs are plotted first and then
LITTLEs.
Requires the following trace events:
- cpu_frequency
- cpu_idle
:param cpus: List of cpus. By default plot all CPUs
:type cpus: list(str)
:param pct: plot residencies in percentage
:type pct: bool
:param active: for percentage plot specify whether to plot active or
total time. Default is TOTAL time
:type active: bool
"""
if not self._trace.hasEvents('cpu_frequency'):
logging.warn('Events [cpu_frequency] not found, plot DISABLED!')
return
if not self._trace.hasEvents('cpu_idle'):
logging.warn('Events [cpu_idle] not found, plot DISABLED!')
return
if cpus is None:
# Generate plots only for available CPUs
cpufreq_data = self._dfg_trace_event('cpu_frequency')
_cpus = range(cpufreq_data.cpu.max()+1)
else:
_cpus = listify(cpus)
# Split between big and LITTLE CPUs ordered from higher to lower ID
_cpus.reverse()
big_cpus = [c for c in _cpus if c in self._platform['clusters']['big']]
little_cpus = [c for c in _cpus if c in
self._platform['clusters']['little']]
_cpus = big_cpus + little_cpus
# Precompute active and total time for each CPU
residencies = []
xmax = 0.0
for cpu in _cpus:
res = self._getCPUFrequencyResidency(cpu)
residencies.append(ResidencyData('CPU{}'.format(cpu), res))
max_time = res.total.max().values[0]
if xmax < max_time:
xmax = max_time
self._plotFrequencyResidency(residencies, 'cpu', xmax, pct, active)
def plotClusterFrequencyResidency(self, clusters=None,
pct=False, active=False):
"""
Plot the frequency residency in a given cluster, i.e. the amount of
time cluster `cluster` spent at frequency `f_i`. By default, both 'big'
and 'LITTLE' clusters data are plotted.
Requires the following trace events:
- cpu_frequency
- cpu_idle
:param clusters: name of the clusters to be plotted (all of them by
default)
:type clusters: str ot list(str)
:param pct: plot residencies in percentage
:type pct: bool
:param active: for percentage plot specify whether to plot active or
total time. Default is TOTAL time
:type active: bool
"""
if not self._trace.hasEvents('cpu_frequency'):
logging.warn('Events [cpu_frequency] not found, plot DISABLED!')
return
if not self._trace.hasEvents('cpu_idle'):
logging.warn('Events [cpu_idle] not found, plot DISABLED!')
return
# Assumption: all CPUs in a cluster run at the same frequency, i.e. the
# frequency is scaled per-cluster not per-CPU. Hence, we can limit the
# cluster frequencies data to a single CPU
if not self._trace.freq_coherency:
logging.warn('Cluster frequency is not coherent, plot DISABLED!')
return
# Sanitize clusters
if clusters is None:
_clusters = self._platform['clusters'].keys()
else:
_clusters = listify(clusters)
# Precompute active and total time for each cluster
residencies = []
xmax = 0.0
for cluster in _clusters:
res = self._getClusterFrequencyResidency(
self._platform['clusters'][cluster.lower()])
residencies.append(ResidencyData('{} Cluster'.format(cluster),
res))
max_time = res.total.max().values[0]
if xmax < max_time:
xmax = max_time
self._plotFrequencyResidency(residencies, 'cluster', xmax, pct, active)
###############################################################################
# Utility Methods
###############################################################################
@memoized
def _getCPUActiveSignal(self, cpu):
"""
Build a square wave representing the active (i.e. non-idle) CPU time,
i.e.:
cpu_active[t] == 1 if at least one CPU is reported to be
non-idle by CPUFreq at time t
cpu_active[t] == 0 otherwise
:param cpu: CPU ID
:type cpu: int
"""
if not self._trace.hasEvents('cpu_idle'):
logging.warn('Events [cpu_idle] not found, '
'cannot compute CPU active signal!')
return None
idle_df = self._dfg_trace_event('cpu_idle')
cpu_df = idle_df[idle_df.cpu_id == cpu]
cpu_active = cpu_df.state.apply(
lambda s: 1 if s == NON_IDLE_STATE else 0
)
start_time = 0.0
if not self._trace.ftrace.normalized_time:
start_time = self._trace.ftrace.basetime
if cpu_active.index[0] != start_time:
entry_0 = pd.Series(cpu_active.iloc[0] ^ 1, index=[start_time])
cpu_active = pd.concat([entry_0, cpu_active])
return cpu_active
@memoized
def _getClusterActiveSignal(self, cluster):
"""
Build a square wave representing the active (i.e. non-idle) cluster
time, i.e.:
cluster_active[t] == 1 if at least one CPU is reported to be
non-idle by CPUFreq at time t
cluster_active[t] == 0 otherwise
:param cluster: list of CPU IDs belonging to a cluster
:type cluster: list(int)
"""
cpu_active = {}
for cpu in cluster:
cpu_active[cpu] = self._getCPUActiveSignal(cpu)
active = pd.DataFrame(cpu_active)
active.fillna(method='ffill', inplace=True)
# Cluster active is the OR between the actives on each CPU
# belonging to that specific cluster
cluster_active = reduce(
operator.or_,
[cpu_active.astype(int) for _, cpu_active in
active.iteritems()]
)
return cluster_active
@memoized
def _getClusterFrequencyResidency(self, cluster):
"""
Get a DataFrame with per cluster frequency residency, i.e. amount of
time spent at a given frequency in each cluster.
:param cluster: this can be either a single CPU ID or a list of CPU IDs
belonging to a cluster or the cluster name as specified in the
platform description
:type cluster: str or int or list(int)
:returns: namedtuple(ResidencyTime) - tuple of total and active time
dataframes
:raises: KeyError
"""
if not self._trace.hasEvents('cpu_frequency'):
logging.warn('Events [cpu_frequency] not found, '
'frequency residency computation not possible!')
return None
if not self._trace.hasEvents('cpu_idle'):
logging.warn('Events [cpu_idle] not found, '
'frequency residency computation not possible!')
return None
if isinstance(cluster, str):
try:
_cluster = self._platform['clusters'][cluster.lower()]
except KeyError:
logging.warn('%s cluster not found!', cluster)
return None
else:
_cluster = listify(cluster)
freq_df = self._dfg_trace_event('cpu_frequency')
# Assumption: all CPUs in a cluster run at the same frequency, i.e. the
# frequency is scaled per-cluster not per-CPU. Hence, we can limit the
# cluster frequencies data to a single CPU. This assumption is verified
# by the Trace module when parsing the trace.
if len(_cluster) > 1 and not self._trace.freq_coherency:
logging.warn('Cluster frequency is NOT coherent,'
'cannot compute residency!')
return None
cluster_freqs = freq_df[freq_df.cpu == _cluster[0]]
# Compute TOTAL Time
time_intervals = cluster_freqs.index[1:] - cluster_freqs.index[:-1]
total_time = pd.DataFrame({
'time': time_intervals,
'frequency': [f/1000.0 for f in cluster_freqs.iloc[:-1].frequency]
})
total_time = total_time.groupby(['frequency']).sum()
# Compute ACTIVE Time
cluster_active = self._getClusterActiveSignal(_cluster)
# In order to compute the active time spent at each frequency we
# multiply 2 square waves:
# - cluster_active, a square wave of the form:
# cluster_active[t] == 1 if at least one CPU is reported to be
# non-idle by CPUFreq at time t
# cluster_active[t] == 0 otherwise
# - freq_active, square wave of the form:
# freq_active[t] == 1 if at time t the frequency is f
# freq_active[t] == 0 otherwise
available_freqs = sorted(cluster_freqs.frequency.unique())
new_idx = sorted(cluster_freqs.index.tolist() +
cluster_active.index.tolist())
cluster_freqs = cluster_freqs.reindex(new_idx, method='ffill')
cluster_active = cluster_active.reindex(new_idx, method='ffill')
nonidle_time = []
for f in available_freqs:
freq_active = cluster_freqs.frequency.apply(
lambda x: 1 if x == f else 0
)
active_t = cluster_active * freq_active
# Compute total time by integrating the square wave
nonidle_time.append(self._trace.integrate_square_wave(active_t))
active_time = pd.DataFrame({'time': nonidle_time},
index=[f/1000.0 for f in available_freqs])
active_time.index.name = 'frequency'
return ResidencyTime(total_time, active_time)
def _getCPUFrequencyResidency(self, cpu):
"""
Get a DataFrame with per-CPU frequency residency, i.e. amount of
time CPU `cpu` spent at each frequency. Both total and active times
will be computed.
:param cpu: CPU ID
:type cpu: int
:returns: namedtuple(ResidencyTime) - tuple of total and active time
dataframes
"""
return self._getClusterFrequencyResidency(cpu)
def _plotFrequencyResidencyAbs(self, axes, residency, n_plots,
is_first, is_last, xmax, title=''):
"""
Private method to generate frequency residency plots.
:param axes: axes over which to generate the plot
:type axes: matplotlib.axes.Axes
:param residency: tuple of total and active time dataframes
:type residency: namedtuple(ResidencyTime)
:param n_plots: total number of plots
:type n_plots: int
:param is_first: if True this is the first plot
:type is_first: bool
:param is_last: if True this is the last plot
:type is_last: bool
:param xmax: x-axes higher bound
:param xmax: double
:param title: title of this subplot
:type title: str
"""
yrange = 0.4 * max(6, len(residency.total)) * n_plots
residency.total.plot.barh(ax=axes, color='g',
legend=False, figsize=(16, yrange))
residency.active.plot.barh(ax=axes, color='r',
legend=False, figsize=(16, yrange))
axes.set_xlim(0, 1.05*xmax)
axes.set_ylabel('Frequency [MHz]')
axes.set_title(title)
axes.grid(True)
if is_last:
axes.set_xlabel('Time [s]')
else:
axes.set_xticklabels([])
if is_first:
# Put title on top of the figure. As of now there is no clean way
# to make the title appear always in the same position in the
# figure because figure heights may vary between different
# platforms (different number of OPPs). Hence, we use annotation
legend_y = axes.get_ylim()[1]
axes.annotate('OPP Residency Time', xy=(0, legend_y),
xytext=(-50, 45), textcoords='offset points',
fontsize=18)
axes.annotate('GREEN: Total', xy=(0, legend_y),
xytext=(-50, 25), textcoords='offset points',
color='g', fontsize=14)
axes.annotate('RED: Active', xy=(0, legend_y),
xytext=(50, 25), textcoords='offset points',
color='r', fontsize=14)
def _plotFrequencyResidencyPct(self, axes, residency_df, label,
n_plots, is_first, is_last, res_type):
"""
Private method to generate PERCENTAGE frequency residency plots.
:param axes: axes over which to generate the plot
:type axes: matplotlib.axes.Axes
:param residency_df: residency time dataframe
:type residency_df: :mod:`pandas.DataFrame`
:param label: label to be used for percentage residency dataframe
:type label: str
:param n_plots: total number of plots
:type n_plots: int
:param is_first: if True this is the first plot
:type is_first: bool
:param is_first: if True this is the last plot
:type is_first: bool
:param res_type: type of residency, either TOTAL or ACTIVE
:type title: str
"""
# Compute sum of the time intervals
duration = residency_df.time.sum()
residency_pct = pd.DataFrame(
{label: residency_df.time.apply(lambda x: x*100/duration)},
index=residency_df.index
)
yrange = 3 * n_plots
residency_pct.T.plot.barh(ax=axes, stacked=True, figsize=(16, yrange))
axes.legend(loc='lower center', ncol=7)
axes.set_xlim(0, 100)
axes.grid(True)
if is_last:
axes.set_xlabel('Residency [%]')
else:
axes.set_xticklabels([])
if is_first:
legend_y = axes.get_ylim()[1]
axes.annotate('OPP {} Residency Time'.format(res_type),
xy=(0, legend_y), xytext=(-50, 35),
textcoords='offset points', fontsize=18)
def _plotFrequencyResidency(self, residencies, entity_name, xmax,
pct, active):
"""
Generate Frequency residency plots for the given entities.
:param residencies:
:type residencies: namedtuple(ResidencyData) - tuple containing:
1) as first element, a label to be used as subplot title
2) as second element, a namedtuple(ResidencyTime)
:param entity_name: name of the entity ('cpu' or 'cluster') used in the
figure name
:type entity_name: str
:param xmax: upper bound of x-axes
:type xmax: double
:param pct: plot residencies in percentage
:type pct: bool
:param active: for percentage plot specify whether to plot active or
total time. Default is TOTAL time
:type active: bool
"""
n_plots = len(residencies)
gs = gridspec.GridSpec(n_plots, 1)
fig = plt.figure()
figtype = ""
for idx, data in enumerate(residencies):
if data.residency is None:
plt.close(fig)
return
axes = fig.add_subplot(gs[idx])
is_first = idx == 0
is_last = idx+1 == n_plots
if pct and active:
self._plotFrequencyResidencyPct(axes, data.residency.active,
data.label, n_plots,
is_first, is_last,
'ACTIVE')
figtype = "_pct_active"
continue
if pct:
self._plotFrequencyResidencyPct(axes, data.residency.total,
data.label, n_plots,
is_first, is_last,
'TOTAL')
figtype = "_pct_total"
continue
self._plotFrequencyResidencyAbs(axes, data.residency,
n_plots, is_first,
is_last, xmax,
title=data.label)
figname = '{}/{}{}_freq_residency{}.png'\
.format(self._trace.plots_dir,
self._trace.plots_prefix,
entity_name, figtype)
pl.savefig(figname, bbox_inches='tight')
# vim :set tabstop=4 shiftwidth=4 expandtab
| apache-2.0 |
ecabrerar/AirAlliance | src/main/java/org/ecabrerar/examples/airalliance/jaxb/data/Sector.java | 1501 | /*
* Copyright 2014 ecabrerar.
*
* 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.ecabrerar.examples.airalliance.jaxb.data;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
/**
* This is a Sector helper class. Instance of this class can store Sector information.
* @author ecabrerar
*/
@XmlRootElement(name="sector")
@XmlAccessorType(XmlAccessType.FIELD)
public class Sector {
private int id;
private String sector;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the sector
*/
public String getSector() {
return sector;
}
/**
* @param sector the sector to set
*/
public void setSector(String sector) {
this.sector = sector;
}
}
| apache-2.0 |
schmittjoh/php-stubs | res/php/eio/functions/eio-set-min-parallel.php | 162 | <?php
/**
* Set minimum parallel thread number
*
* @phpstub
*
* @param string $nthreads
*
* @return void
*/
function eio_set_min_parallel($nthreads)
{
} | apache-2.0 |
ivarptr/clobaframe | source/setting/src/main/java/org/archboy/clobaframe/setting/global/impl/DefaultGlobalSettingProvider.java | 3495 | package org.archboy.clobaframe.setting.global.impl;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.archboy.clobaframe.setting.SettingProvider;
import org.archboy.clobaframe.setting.application.ApplicationSetting;
import org.archboy.clobaframe.setting.global.GlobalSettingProvider;
import org.archboy.clobaframe.setting.support.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
/**
*
* @author yang
*/
@Named
public class DefaultGlobalSettingProvider implements GlobalSettingProvider { //, InitializingBean {
//, ResourceLoaderAware {
public static final String NAME = "defaultGlobalSetting";
@Inject
private ResourceLoader resourceLoader;
@Autowired(required = false)
private ApplicationSetting applicationSetting;
//private static final String DEFAULT_GLOBAL_SETTING_FILE_NAME = "classpath:global.properties";
public static final String DEFAULT_GLOBAL_SETTING_FILE_NAME = "";
public static final String SETTING_KEY_GLOBAL_SETTING_FILE_NAME = "clobaframe.setting.defaultGlobalSettingFileName";
@Value("${" + SETTING_KEY_GLOBAL_SETTING_FILE_NAME + ":" + DEFAULT_GLOBAL_SETTING_FILE_NAME + "}")
public String defaultGlobalSettingFileName;
private final Logger logger = LoggerFactory.getLogger(DefaultGlobalSettingProvider.class);
// public void setDefaultGlobalSettingFileName(String defaultGlobalSettingFileName) {
// this.defaultGlobalSettingFileName = defaultGlobalSettingFileName;
// }
//@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public void setDefaultGlobalSettingFileName(String defaultGlobalSettingFileName) {
this.defaultGlobalSettingFileName = defaultGlobalSettingFileName;
}
@Override
public String getName() {
return NAME;
}
@Override
public int getOrder() {
return SettingProvider.PRIORITY_LOWER;
}
@PostConstruct
public void init() throws Exception {
if (StringUtils.isEmpty(defaultGlobalSettingFileName)) {
if (applicationSetting != null) {
defaultGlobalSettingFileName = (String)applicationSetting.getValue(
SETTING_KEY_GLOBAL_SETTING_FILE_NAME,
DEFAULT_GLOBAL_SETTING_FILE_NAME);
}
}
}
@Override
public Map<String, Object> list() {
if (StringUtils.isEmpty(defaultGlobalSettingFileName)){
return new LinkedHashMap<String, Object>();
}
Resource resource = resourceLoader.getResource(defaultGlobalSettingFileName);
if (!resource.exists()) {
logger.error("Default global setting [{}] not found.", resource.getFilename());
return new LinkedHashMap<String, Object>();
}
logger.info("Loading default global setting [{}]", resource.getFilename());
InputStream in = null;
try{
in = resource.getInputStream();
return Utils.readProperties(in);
}catch(IOException e) {
throw new RuntimeException(
String.format("Load default global setting [%s] failed.",
resource.getFilename()), e);
}finally {
IOUtils.closeQuietly(in);
}
}
}
| apache-2.0 |
martinjirku/olManager | src/map/MapModel.js | 1306 | 'use strict';
var OlModel = require('../core/OlModel.js');
var eventedMixin = require('../core/eventedMixin');
var $ = require('../utils/jquery');
module.exports = OlModel.inheritWith(function(base, baseCtor){
return {
constructor: function(options){
baseCtor.call(this);
this.name = 'OlMapModel';
this.initObjectProperties()
.setOptions(options);
}
, initObjectProperties: function(){
var prop = this.prop = {
_element: null
};
Object.defineProperties(this,{
element: {
configurable: true
, enumerable: true
, set: function(newValue){
var oldValue = prop._element;
if(typeof newValue === 'string'){
var $element = $(newValue);
if($element.length > 0){
prop._element = $element[0];
}
} else {
prop._element = newValue;
}
if(oldValue !== prop._element) {
this.trigger('value:element', prop._element);
}
}
, get: function(){
return prop._element;
}
}
});
return this;
}
, setOptions: function(options){
if(!options) {
return this;
}
if(options.mapSelector){
this.element = options.mapSelector;
} else if (options.mapId) {
this.element = '#' + options.mapId;
}
return this;
}
};
}).define(eventedMixin); | apache-2.0 |
il9ue/cockroach | acceptance/put_test.go | 2231 | // Copyright 2015 The Cockroach 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.
//
// Author: Peter Mattis (peter@cockroachlabs.com)
package acceptance
import (
"fmt"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach/acceptance/cluster"
"github.com/cockroachdb/cockroach/util/log"
"github.com/cockroachdb/cockroach/util/randutil"
)
// TestPut starts up an N node cluster and runs N workers that write
// to independent keys.
func TestPut(t *testing.T) {
runTestOnConfigs(t, testPutInner)
}
func testPutInner(t *testing.T, c cluster.Cluster, cfg cluster.TestConfig) {
db, dbStopper := makeClient(t, c.ConnString(0))
defer dbStopper.Stop()
errs := make(chan error, c.NumNodes())
start := time.Now()
deadline := start.Add(cfg.Duration)
var count int64
for i := 0; i < c.NumNodes(); i++ {
go func() {
r, _ := randutil.NewPseudoRand()
value := randutil.RandBytes(r, 8192)
for time.Now().Before(deadline) {
k := atomic.AddInt64(&count, 1)
v := value[:r.Intn(len(value))]
if pErr := db.Put(fmt.Sprintf("%08d", k), v); pErr != nil {
errs <- pErr.GoError()
return
}
}
errs <- nil
}()
}
for i := 0; i < c.NumNodes(); {
baseCount := atomic.LoadInt64(&count)
select {
case <-stopper:
t.Fatalf("interrupted")
case err := <-errs:
if err != nil {
t.Fatal(err)
}
i++
case <-time.After(1 * time.Second):
// Periodically print out progress so that we know the test is still
// running.
loadedCount := atomic.LoadInt64(&count)
log.Infof("%d (%d/s)", loadedCount, loadedCount-baseCount)
c.Assert(t)
}
}
elapsed := time.Since(start)
log.Infof("%d %.1f/sec", count, float64(count)/elapsed.Seconds())
}
| apache-2.0 |
xehoth/OnlineJudgeCodes | BZOJ/BZOJ4809.cpp | 841 | #include <cstdio>
inline int nextInt() {
int r = 0;
int c = getchar_unlocked();
for (; c < 48; c = getchar_unlocked())
;
for (; c > 47; c = getchar_unlocked()) r = r * 10 + c - 48;
return r;
}
const int MAXN = 20;
typedef unsigned long long ull;
int n, ans, map[MAXN][MAXN];
inline void search(int x, ull a, ull b, ull c) {
if (x == n)
++ans;
else {
ull d = a | b | c;
for (register int y = 0; y < n; ++y)
if (!map[x][y] && !((d >> y) & 1))
search(x + 1, (a | (1ULL << y)), (b | (1ULL << y)) >> 1,
(c | (1ULL << y)) << 1);
}
}
int main() {
n = nextInt();
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) map[i][j] = nextInt();
search(0, 0, 0, 0);
printf("%d\n", ans);
return 0;
} | apache-2.0 |
ilopez/GamePerformanceReporter.Client | GamePerfReporter/Upload.Designer.cs | 4894 | namespace GamePerfReporter
{
partial class Upload
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.pbUpload = new System.Windows.Forms.ProgressBar();
this.pbPrep = new System.Windows.Forms.ProgressBar();
this.bCancel = new System.Windows.Forms.Button();
this.bgWorker = new System.ComponentModel.BackgroundWorker();
this.tbUploadLog = new System.Windows.Forms.TextBox();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.pbUpload);
this.groupBox1.Controls.Add(this.pbPrep);
this.groupBox1.ForeColor = System.Drawing.Color.White;
this.groupBox1.Location = new System.Drawing.Point(13, 172);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(259, 84);
this.groupBox1.TabIndex = 1;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Status";
//
// pbUpload
//
this.pbUpload.Location = new System.Drawing.Point(7, 50);
this.pbUpload.Name = "pbUpload";
this.pbUpload.Size = new System.Drawing.Size(246, 23);
this.pbUpload.TabIndex = 1;
//
// pbPrep
//
this.pbPrep.Location = new System.Drawing.Point(7, 20);
this.pbPrep.Name = "pbPrep";
this.pbPrep.Size = new System.Drawing.Size(246, 23);
this.pbPrep.TabIndex = 0;
//
// bCancel
//
this.bCancel.Location = new System.Drawing.Point(103, 262);
this.bCancel.Name = "bCancel";
this.bCancel.Size = new System.Drawing.Size(75, 23);
this.bCancel.TabIndex = 2;
this.bCancel.Text = "Cancel";
this.bCancel.UseVisualStyleBackColor = true;
//
// bgWorker
//
this.bgWorker.WorkerReportsProgress = true;
this.bgWorker.WorkerSupportsCancellation = true;
this.bgWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bgWorker1_DoWork);
this.bgWorker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.bgWorker1_ProgressChanged);
//
// tbUploadLog
//
this.tbUploadLog.BackColor = System.Drawing.Color.Black;
this.tbUploadLog.ForeColor = System.Drawing.Color.White;
this.tbUploadLog.Location = new System.Drawing.Point(13, 13);
this.tbUploadLog.Multiline = true;
this.tbUploadLog.Name = "tbUploadLog";
this.tbUploadLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.tbUploadLog.Size = new System.Drawing.Size(259, 153);
this.tbUploadLog.TabIndex = 3;
//
// Upload
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.Black;
this.ClientSize = new System.Drawing.Size(284, 299);
this.Controls.Add(this.tbUploadLog);
this.Controls.Add(this.bCancel);
this.Controls.Add(this.groupBox1);
this.Name = "Upload";
this.Text = "Upload";
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.ProgressBar pbUpload;
private System.Windows.Forms.ProgressBar pbPrep;
private System.Windows.Forms.Button bCancel;
private System.ComponentModel.BackgroundWorker bgWorker;
private System.Windows.Forms.TextBox tbUploadLog;
}
} | apache-2.0 |
cafjs/caf_deploy | lib/plug_deploy_kubernetes.js | 6100 | // Modifications copyright 2020 Caf.js Labs and contributors
/*!
Copyright 2013 Hewlett-Packard Development Company, L.P.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
'use strict';
/**
* Deploys applications on Kubernetes on behalf of CAs.
*
* The name of this component in framework.json should be 'deploy'
*
* Properties:
*
* See type `deploymentSpecType` in file `types.js`
*
* @module caf_deploy/plug_deploy_kubernetes
* @augments external:caf_components/gen_plug
*/
const caf_core = require('caf_core');
const caf_comp = caf_core.caf_components;
const myUtils = caf_comp.myUtils;
const genPlug = caf_comp.gen_plug;
const genCron = caf_comp.gen_cron;
const deploy_util = require('./plug_deploy_util_k8s');
const deploy_templates = require('./plug_deploy_templates_k8s');
const types = require('./types');
exports.newInstance = async function($, spec) {
try {
let appsStatus = {};
types.checkSpec(spec.env);
const cronSpec = {
name: spec.name + '_cron__',
module: 'gen_cron', // module ignored
env: {interval: spec.env.refreshInterval}
};
const updateCron = genCron.create(null, cronSpec);
const that = genPlug.create($, spec);
const deployTemplates = deploy_templates.newTemplates($, spec.env);
const deployUtil = await deploy_util.newUtil($, spec.env,
deployTemplates);
that.__ca_createApp__ = async function(createOptions) {
await that.__ca_statAll__();
if (appsStatus[createOptions.id]) {
// already deployed, ignore to make call idempotent.
return [];
} else {
const props = deployTemplates.createProps(createOptions);
await deployUtil.createRedis(props.redis);
return deployUtil.createAppProcess(props.app);
}
};
that.__ca_updateApp__ = async function(updateOptions) {
if (!updateOptions.currentProps.redis.isDedicatedVolume &&
(updateOptions.currentProps.app.instances >
spec.env.redis.maxNFSInstances)) {
await that.__ca_upgradeToDedicatedDisk__(updateOptions.id);
// refresh props
await that.__ca_statAll__();
const deployed = that.__ca_statApp__(updateOptions.id);
updateOptions.currentProps = deployed.props;
}
const props = deployTemplates.updateProps(updateOptions);
if (props.redis) {
await deployUtil.updateRedis(props.redis);
}
if (props.app) {
return deployUtil.updateAppProcess(props.app);
} else {
return [];
}
};
that.__ca_changeImage__ = function(changeImageOptions) {
const props = deployTemplates.changeImageProps(changeImageOptions);
if (props.app) {
return deployUtil.updateAppProcess(props.app);
} else {
return [];
}
};
that.__ca_statApp__ = (id) => appsStatus[id];
that.__ca_restartApp__ = (id) => deployUtil.restartApp(id);
that.__ca_upgradeToDedicatedDisk__ = async function(id) {
await that.__ca_statAll__();
if (!appsStatus[id]) {
throw new Error(`Missing app ${id} cannot upgrade disk`);
}
if (!appsStatus[id].props) {
throw new Error(`Missing props for ${id} cannot upgrade disk`);
}
if (appsStatus[id].props.redis.isDedicatedVolume) {
throw new Error('Already dedicated, cannot upgrade disk');
}
const props = myUtils.deepClone(appsStatus[id].props);
props.redis.isDedicatedVolume = true;
await deployUtil.upgradeToDedicatedDisk(props.redis);
return deployUtil.updateProps(id, props);
};
that.__ca_deleteApp__ = async function(deleteOptions) {
// Always try to delete, even if we don't see it...
await deployUtil.deleteAppProcess(deleteOptions);
return deployUtil.deleteRedis(deleteOptions);
};
that.__ca_statAll__ = async function() {
const apps = await deployUtil.statAll();
if (Array.isArray(apps)) {
appsStatus = {};
apps.forEach(function(x) {
if (typeof x.id === 'string') {
appsStatus[x.id] = x;
} else {
$._ && $._.$.log && $._.$.log.debug('No app id: ' +
JSON.stringify(x));
}
});
return appsStatus;
} else {
$._ && $._.$.log && $._.$.log.debug('Got invalid app update: ' +
JSON.stringify(apps));
throw new Error('Got invalid apps update:' +
JSON.stringify(apps));
}
};
const super__ca_shutdown__ = myUtils.superior(that, '__ca_shutdown__');
that.__ca_shutdown__ = function(data, cb) {
updateCron && updateCron.__ca_stop__();
super__ca_shutdown__(data, cb);
};
await that.__ca_statAll__();
updateCron.__ca_start__(that.__ca_statAll__);
return [null, that];
} catch (err) {
return [err];
}
};
| apache-2.0 |
janebeckman/gpdb | gpMgmt/test/behave/mgmt_utils/steps/mgmt_utils.py | 220049 | import fnmatch
import getpass
import glob
import gzip
import json
import yaml
try:
import pexpect
except:
print "The pexpect module could not be imported."
import os
import platform
import shutil
import socket
import tarfile
import tempfile
import thread
import json
import csv
import subprocess
import commands
import signal
from collections import defaultdict
from datetime import datetime
from time import sleep
from behave import given, when, then
from gppylib.commands.gp import SegmentStart, GpStandbyStart
from gppylib.commands.unix import findCmdInPath
from gppylib.operations.backup_utils import Context
from gppylib.operations.dump import get_partition_state
from gppylib.operations.startSegments import MIRROR_MODE_MIRRORLESS
from gppylib.operations.unix import ListRemoteFilesByPattern, CheckRemoteFile
from test.behave_utils.gpfdist_utils.gpfdist_mgmt import Gpfdist
from test.behave_utils.utils import *
from test.behave_utils.PgHba import PgHba, Entry
from gppylib.commands.base import Command, REMOTE
labels_json = '/tmp/old_to_new_timestamp_labels.json'
timestamp_json = '/tmp/old_to_new_timestamps.json'
global_labels = {}
global_timestamps = {}
master_data_dir = os.environ.get('MASTER_DATA_DIRECTORY')
if master_data_dir is None:
raise Exception('Please set MASTER_DATA_DIRECTORY in environment')
def _write_timestamp_to_json(context):
scenario_name = context._stack[0]['scenario'].name
timestamp = get_timestamp_from_output(context)
if not global_timestamps.has_key(scenario_name):
global_timestamps[scenario_name] = list()
global_timestamps[scenario_name].append(timestamp)
with open(timestamp_json, 'w') as outfile:
json.dump(global_timestamps, outfile)
def _write_label_to_json(context, label_key, label):
timestamp = get_timestamp_from_output(context)
if not global_labels.has_key(label_key):
global_labels[label_key] = {}
global_labels[label_key][label] = timestamp
with open(labels_json, 'w') as outfile:
json.dump(global_labels, outfile)
def _read_timestamp_from_json(context):
scenario_name = context._stack[0]['scenario'].name
with open(timestamp_json, 'r') as infile:
return json.load(infile)[scenario_name]
def _read_label_from_json(context, label_key):
with open(labels_json, 'r') as infile:
return json.load(infile)[label_key]
@given('the old database is started')
def impl(context):
command = 'gpstop -a -M fast'
run_gpcommand(context, command)
new_greenplum_path = "%s/greenplum_path.sh" % os.environ['GPHOME']
os.environ['NEW_GREENPLUM_PATH'] = new_greenplum_path
old_greenplum_path = "/data/greenplum-db-old/greenplum_path.sh"
command = ['bash', '-c', 'source %s && env' % old_greenplum_path]
proc = subprocess.Popen(command, stdout=subprocess.PIPE)
for line in proc.stdout:
(key, _, value) = line.partition("=")
os.environ[key] = value.strip()
proc.communicate()
command = 'gpstart -a'
run_gpcommand(context, command)
# Wait for database to come up, to prevent race conditions in later tests
cmd = Command(name="check if database is up", cmdStr="psql -l")
for i in range(30):
sleep(10)
cmd.run()
if cmd.get_return_code() == 0:
return
raise Exception("Database did not start up within 5 minutes`")
@given('the new database is started')
def impl(context):
command = 'gpstop -a -M fast'
run_gpcommand(context, command)
new_greenplum_path = os.environ['NEW_GREENPLUM_PATH']
command = ['bash', '-c', 'source %s && env' % new_greenplum_path]
proc = subprocess.Popen(command, stdout=subprocess.PIPE)
for line in proc.stdout:
(key, _, value) = line.partition("=")
os.environ[key] = value.strip()
proc.communicate()
command = 'gpstart -a'
run_gpcommand(context, command)
# Wait for database to come up, to prevent race conditions in later tests
cmd = Command(name="check if database is up", cmdStr="psql -l")
for i in range(30):
sleep(10)
cmd.run()
if cmd.get_return_code() == 0:
return
raise Exception("Database did not start up within 5 minutes`")
@given('the old timestamps are read from json')
def impl(context):
json_timestamps = _read_timestamp_from_json(context)
context.backup_timestamp = json_timestamps[-1]
context.inc_backup_timestamps = json_timestamps[1:]
context.backup_subdir = json_timestamps[-1][:8]
context.full_backup_timestamp = json_timestamps[0]
@given('the timestamp labels for scenario "{scenario_number}" are read from json')
def impl(context, scenario_number):
label_key = 'timestamp_labels' + scenario_number
global_labels[label_key] = _read_label_from_json(context, label_key)
@given('the cluster config is generated with data_checksums "{checksum_toggle}"')
def impl(context, checksum_toggle):
stop_database(context)
cmd = """
cd ../gpAux/gpdemo; \
export MASTER_DEMO_PORT={master_port} && \
export DEMO_PORT_BASE={port_base} && \
export NUM_PRIMARY_MIRROR_PAIRS={num_primary_mirror_pairs} && \
export WITH_MIRRORS={with_mirrors} && \
./demo_cluster.sh -d && ./demo_cluster.sh -c && \
env EXTRA_CONFIG="HEAP_CHECKSUM={checksum_toggle}" ONLY_PREPARE_CLUSTER_ENV=true ./demo_cluster.sh
""".format(master_port=os.getenv('MASTER_PORT', 15432),
port_base=os.getenv('PORT_BASE', 25432),
num_primary_mirror_pairs=os.getenv('NUM_PRIMARY_MIRROR_PAIRS', 3),
with_mirrors='true',
checksum_toggle=checksum_toggle)
run_command(context, cmd)
if context.ret_code != 0:
raise Exception('%s' % context.error_message)
@given('the database is running')
@then('the database is running')
def impl(context):
start_database_if_not_started(context)
if has_exception(context):
raise context.exception
@given('the database is initialized with checksum "{checksum_toggle}"')
def impl(context, checksum_toggle):
is_ok = check_database_is_running(context)
if is_ok:
run_command(context, "gpconfig -s data_checksums")
if context.ret_code != 0:
raise Exception("cannot run gpconfig: %s, stdout: %s" % (context.error_message, context.stdout_message))
try:
# will throw
check_stdout_msg(context, "Values on all segments are consistent")
check_stdout_msg(context, "Master value: %s" % checksum_toggle)
check_stdout_msg(context, "Segment value: %s" % checksum_toggle)
except:
is_ok = False
if not is_ok:
stop_database(context)
cmd = """
cd ../gpAux/gpdemo; \
export MASTER_DEMO_PORT={master_port} && \
export DEMO_PORT_BASE={port_base} && \
export NUM_PRIMARY_MIRROR_PAIRS={num_primary_mirror_pairs} && \
export WITH_MIRRORS={with_mirrors} && \
./demo_cluster.sh -d && ./demo_cluster.sh -c && \
env EXTRA_CONFIG="HEAP_CHECKSUM={checksum_toggle}" ./demo_cluster.sh
""".format(master_port=os.getenv('MASTER_PORT', 15432),
port_base=os.getenv('PORT_BASE', 25432),
num_primary_mirror_pairs=os.getenv('NUM_PRIMARY_MIRROR_PAIRS', 3),
with_mirrors='true',
checksum_toggle=checksum_toggle)
run_command(context, cmd)
if context.ret_code != 0:
raise Exception('%s' % context.error_message)
@given('the database is not running')
@when('the database is not running')
def impl(context):
stop_database_if_started(context)
if has_exception(context):
raise context.exception
@given('the database is "{version}" with dburl "{dbconn}"')
def impl(context, dbconn, version):
command = '%s -t -q -c \'select version();\'' % (dbconn)
(rc, out, err) = run_cmd(command)
if not ('Greenplum Database ' + version) in out:
print 'version %s does not match current gpdb version %s' % (version, out)
@given('database "{dbname}" exists')
@then('database "{dbname}" exists')
def impl(context, dbname):
create_database_if_not_exists(context, dbname)
@given('database "{dbname}" is created if not exists on host "{HOST}" with port "{PORT}" with user "{USER}"')
@then('database "{dbname}" is created if not exists on host "{HOST}" with port "{PORT}" with user "{USER}"')
def impl(context, dbname, HOST, PORT, USER):
host = os.environ.get(HOST)
port = 0 if os.environ.get(PORT) == None else int(os.environ.get(PORT))
user = os.environ.get(USER)
create_database_if_not_exists(context, dbname, host, port, user)
@when('the database "{dbname}" does not exist')
@given('the database "{dbname}" does not exist')
@then('the database "{dbname}" does not exist')
def impl(context, dbname):
drop_database_if_exists(context, dbname)
@when('the database "{dbname}" does not exist on host "{HOST}" with port "{PORT}" with user "{USER}"')
@given('the database "{dbname}" does not exist on host "{HOST}" with port "{PORT}" with user "{USER}"')
@then('the database "{dbname}" does not exist on host "{HOST}" with port "{PORT}" with user "{USER}"')
def impl(context, dbname, HOST, PORT, USER):
host = os.environ.get(HOST)
port = int(os.environ.get(PORT))
user = os.environ.get(USER)
drop_database_if_exists(context, dbname, host, port, user)
@given('the database "{dbname}" does not exist with connection "{dbconn}"')
@when('the database "{dbname}" does not exist with connection "{dbconn}"')
@then('the database "{dbname}" does not exist with connection "{dbconn}"')
def impl(context, dbname, dbconn):
command = '%s -c \'drop database if exists %s;\'' % (dbconn, dbname)
run_command(context, command)
@given('the database "{dbname}" exists with connection "{dbconn}"')
@when('the database "{dbname}" exists with connection "{dbconn}"')
@then('the database "{dbname}" exists with connection "{dbconn}"')
def impl(context, dbname, dbconn):
command = '%s -c \'create database %s;\'' % (dbconn, dbname)
run_command(context, command)
def get_segment_hostlist():
gparray = GpArray.initFromCatalog(dbconn.DbURL())
segment_hostlist = sorted(gparray.get_hostlist(includeMaster=False))
if not segment_hostlist:
raise Exception('segment_hostlist was empty')
return segment_hostlist
@given('we have determined the first segment hostname')
def impl(context):
segment_hostlist = get_segment_hostlist()
context.first_segment_hostname = segment_hostlist[0]
@given('{nic} on the first segment host is {nic_status}')
@then('{nic} on the first segment host is {nic_status}')
def impl(context, nic, nic_status):
if nic_status.strip() == 'down':
bring_nic_down(context.first_segment_hostname, nic)
elif nic_status.strip() == 'up':
bring_nic_up(context.first_segment_hostname, nic)
else:
raise Exception('Invalid nic status in feature file %s' % nic_status)
@when('an insert on "{table}" in "{dbname}" is rolled back')
def impl(context, table, dbname):
with dbconn.connect(dbconn.DbURL(dbname=dbname)) as conn:
insert_sql = """INSERT INTO %s values (1)""" % table
dbconn.execSQL(conn, insert_sql)
conn.rollback()
@when('a truncate on "{table}" in "{dbname}" is rolled back')
def impl(context, table, dbname):
with dbconn.connect(dbconn.DbURL(dbname=dbname)) as conn:
insert_sql = """TRUNCATE table %s""" % table
dbconn.execSQL(conn, insert_sql)
conn.rollback()
@when('an alter on "{table}" in "{dbname}" is rolled back')
def impl(context, table, dbname):
with dbconn.connect(dbconn.DbURL(dbname=dbname)) as conn:
insert_sql = """ALTER TABLE %s add column cnew int default 0""" % table
dbconn.execSQL(conn, insert_sql)
conn.rollback()
@given('the user truncates "{table_list}" tables in "{dbname}"')
@when('the user truncates "{table_list}" tables in "{dbname}"')
@then('the user truncates "{table_list}" tables in "{dbname}"')
def impl(context, table_list, dbname):
if not table_list:
raise Exception('Table list is empty')
tables = table_list.split(',')
for t in tables:
truncate_table(dbname, t.strip())
@given('there is a "{tabletype}" table "{table_name}" with compression "{compression_type}" in "{dbname}" with data')
@when('there is a "{tabletype}" table "{table_name}" with compression "{compression_type}" in "{dbname}" with data')
@then('there is a "{tabletype}" table "{table_name}" with compression "{compression_type}" in "{dbname}" with data')
def impl(context, tabletype, table_name, compression_type, dbname):
populate_regular_table_data(context, tabletype, table_name, compression_type, dbname, with_data=True)
@given(
'there is a "{tabletype}" table "{table_name}" with compression "{compression_type}" in "{dbname}" with data "{with_data}" on host "{HOST}" with port "{PORT}" with user "{USER}"')
@when(
'there is a "{tabletype}" table "{table_name}" with compression "{compression_type}" in "{dbname}" with data "{with_data}" on host "{HOST}" with port "{PORT}" with user "{USER}"')
@then(
'there is a "{tabletype}" table "{table_name}" with compression "{compression_type}" in "{dbname}" with data "{with_data}" on host "{HOST}" with port "{PORT}" with user "{USER}"')
def impl(context, tabletype, table_name, compression_type, dbname, with_data, HOST, PORT, USER):
host = os.environ.get(HOST)
port = int(os.environ.get(PORT))
user = os.environ.get(USER)
with_data = bool(with_data)
populate_regular_table_data(context, tabletype, table_name, compression_type, dbname, 10, with_data, host, port,
user)
@when('the partition table "{table_name}" in "{dbname}" is populated with similar data')
def impl(context, table_name, dbname):
populate_partition_diff_data_same_eof(table_name, dbname)
@given('the partition table "{table_name}" in "{dbname}" is populated with same data')
def impl(context, table_name, dbname):
populate_partition_same_data(table_name, dbname)
@given(
'there is a "{tabletype}" table "{table_name}" with index "{indexname}" compression "{compression_type}" in "{dbname}" with data')
def impl(context, tabletype, table_name, compression_type, indexname, dbname):
create_database_if_not_exists(context, dbname)
drop_table_if_exists(context, table_name=table_name, dbname=dbname)
if compression_type == "None":
create_partition(context, table_name, tabletype, dbname, compression_type=None, partition=False)
else:
create_partition(context, table_name, tabletype, dbname, compression_type, partition=False)
create_indexes(context, table_name, indexname, dbname)
@given(
'there is a "{tabletype}" partition table "{table_name}" with compression "{compression_type}" in "{dbname}" with data')
@then(
'there is a "{tabletype}" partition table "{table_name}" with compression "{compression_type}" in "{dbname}" with data')
def impl(context, tabletype, table_name, compression_type, dbname):
create_database_if_not_exists(context, dbname)
drop_table_if_exists(context, table_name=table_name, dbname=dbname)
if compression_type == "None":
create_partition(context, tablename=table_name, storage_type=tabletype, dbname=dbname, with_data=True)
else:
create_partition(context, tablename=table_name, storage_type=tabletype, dbname=dbname, with_data=True,
compression_type=compression_type)
@given('there is a mixed storage partition table "{tablename}" in "{dbname}" with data')
def impl(context, tablename, dbname):
create_database_if_not_exists(context, dbname)
drop_table_if_exists(context, table_name=tablename, dbname=dbname)
create_mixed_storage_partition(context, tablename, dbname)
@given(
'there is a partition table "{tablename}" has external partitions of gpfdist with file "{filename}" on port "{port}" in "{dbname}" with data')
def impl(context, tablename, dbname, filename, port):
create_database_if_not_exists(context, dbname)
drop_table_if_exists(context, table_name=tablename, dbname=dbname)
create_external_partition(context, tablename, dbname, port, filename)
@given('"{dbname}" does not exist')
def impl(context, dbname):
drop_database(context, dbname)
@given('{env_var} environment variable is not set')
def impl(context, env_var):
if not hasattr(context, 'orig_env'):
context.orig_env = dict()
context.orig_env[env_var] = os.environ.get(env_var)
if env_var in os.environ:
del os.environ[env_var]
@given('there are no "{tmp_file_prefix}" tempfiles')
def impl(context, tmp_file_prefix):
if tmp_file_prefix is not None and tmp_file_prefix:
run_command(context, 'rm -f /tmp/%s*' % tmp_file_prefix)
else:
raise Exception('Invalid call to temp file removal %s' % tmp_file_prefix)
@then('{env_var} environment variable should be restored')
def impl(context, env_var):
if not hasattr(context, 'orig_env'):
raise Exception('%s can not be reset' % env_var)
if env_var not in context.orig_env:
raise Exception('%s can not be reset.' % env_var)
os.environ[env_var] = context.orig_env[env_var]
del context.orig_env[env_var]
@when('the table names in "{dbname}" is stored')
@then('the table names in "{dbname}" is stored')
def impl(context, dbname):
context.table_names = get_table_names(dbname)
@given('the user runs "{command}"')
@when('the user runs "{command}"')
@then('the user runs "{command}"')
def impl(context, command):
if 'gpcrondump' in command:
command = append_storage_config_to_backup_command(context, command)
elif 'gpdbrestore' in command:
command = append_storage_config_to_restore_command(context, command)
run_gpcommand(context, command)
@given('the user asynchronously runs "{command}" and the process is saved')
@when('the user asynchronously runs "{command}" and the process is saved')
@then('the user asynchronously runs "{command}" and the process is saved')
def impl(context, command):
run_gpcommand_async(context, command)
@given('the async process finished with a return code of {ret_code}')
@when('the async process finished with a return code of {ret_code}')
@then('the async process finished with a return code of {ret_code}')
def impl(context, ret_code):
rc, stdout_value, stderr_value = context.asyncproc.communicate2()
if rc != int(ret_code):
raise Exception("return code of the async proccess didn't match:\n"
"rc: %s\n"
"stdout: %s\n"
"stderr: %s" % (rc, stdout_value, stderr_value))
@given('a user runs "{command}" with gphome "{gphome}"')
@when('a user runs "{command}" with gphome "{gphome}"')
@then('a user runs "{command}" with gphome "{gphome}"')
def impl(context, command, gphome):
masterhost = get_master_hostname()[0][0]
cmd = Command(name='Remove archive gppkg',
cmdStr=command,
ctxt=REMOTE,
remoteHost=masterhost,
gphome=gphome)
cmd.run()
context.ret_code = cmd.get_return_code()
@given('the user runs command "{command}"')
@when('the user runs command "{command}"')
@then('the user runs command "{command}"')
def impl(context, command):
run_command(context, command)
@when('the user runs async command "{command}"')
def impl(context, command):
run_async_command(context, command)
@given('the user puts cluster on "{HOST}" "{PORT}" "{USER}" in "{transition}"')
@when('the user puts cluster on "{HOST}" "{PORT}" "{USER}" in "{transition}"')
@then('the user puts cluster on "{HOST}" "{PORT}" "{USER}" in "{transition}"')
def impl(context, HOST, PORT, USER, transition):
host = os.environ.get(HOST)
user = os.environ.get(USER)
port = os.environ.get(PORT)
source_file = os.path.join(os.environ.get('GPHOME'), 'greenplum_path.sh')
master_dd = os.environ.get('MASTER_DATA_DIRECTORY')
export_mdd = 'export MASTER_DATA_DIRECTORY=%s;export PGPORT=%s' % (master_dd, port)
# reset all fault inject entry if exists
command = 'gpfaultinjector -f all -m async -y reset -r primary -H ALL'
run_command_remote(context, command, host, source_file, export_mdd)
command = 'gpfaultinjector -f all -m async -y resume -r primary -H ALL'
run_command_remote(context, command, host, source_file, export_mdd)
trigger_transition = "psql -d template1 -h %s -U %s -p %s -c 'drop table if exists trigger;'" % (host, user, port)
if transition == 'ct':
command = 'gpfaultinjector -f filerep_consumer -m async -y fault -r primary -H ALL'
run_command_remote(context, command, host, source_file, export_mdd)
run_command(context, trigger_transition)
wait_till_change_tracking_transition(host, port, user)
if transition == 'resync':
command = 'gpfaultinjector -f filerep_consumer -m async -y fault -r primary -H ALL'
run_command_remote(context, command, host, source_file, export_mdd)
run_command(context, trigger_transition)
wait_till_change_tracking_transition(host, port, user)
command = 'gpfaultinjector -f filerep_resync -m async -y suspend -r primary -H ALL'
run_command_remote(context, command, host, source_file, export_mdd)
run_command_remote(context, 'gprecoverseg -a', host, source_file, export_mdd)
wait_till_resync_transition(host, port, user)
if transition == 'sync':
run_command_remote(context, 'gpstop -air', host, source_file, export_mdd)
run_command_remote(context, 'gprecoverseg -a', host, source_file, export_mdd)
wait_till_insync_transition(host, port, user)
run_command_remote(context, 'gprecoverseg -ar', host, source_file, export_mdd)
@given('the user runs workload under "{dir}" with connection "{dbconn}"')
@when('the user runs workload under "{dir}" with connection "{dbconn}"')
def impl(context, dir, dbconn):
for file in os.listdir(dir):
if file.endswith('.sql'):
command = '%s -f %s' % (dbconn, os.path.join(dir, file))
run_command(context, command)
@given(
'the user "{USER}" creates filespace_config file for "{fs_name}" on host "{HOST}" with gpdb port "{PORT}" and config "{config_file}" in "{dir}" directory')
@then(
'the user "{USER}" creates filespace_config file for "{fs_name}" on host "{HOST}" with gpdb port "{PORT}" and config "{config_file}" in "{dir}" directory')
def impl(context, USER, HOST, PORT, fs_name, config_file, dir):
user = os.environ.get(USER)
host = os.environ.get(HOST)
port = os.environ.get(PORT)
if not dir.startswith("/"):
dir = os.environ.get(dir)
config_file_path = dir + "/" + config_file
create_gpfilespace_config(host, port, user, fs_name, config_file_path, dir)
@given(
'the user "{USER}" creates filespace on host "{HOST}" with gpdb port "{PORT}" and config "{config_file}" in "{dir}" directory')
@when(
'the user "{USER}" creates filespace on host "{HOST}" with gpdb port "{PORT}" and config "{config_file}" in "{dir}" directory')
def impl(context, USER, HOST, PORT, config_file, dir):
user = os.environ.get(USER)
host = os.environ.get(HOST)
port = os.environ.get(PORT)
if not dir.startswith("/"):
dir = os.environ.get(dir)
config_file_path = dir + "/" + config_file
cmdStr = 'gpfilespace -h %s -p %s -U %s -c "%s"' % (host, port, user, config_file_path)
run_command(context, cmdStr)
@given('the user modifies the external_table.sql file "{filepath}" with host "{HOST}" and port "{port}"')
@when('the user modifies the external_table.sql file "{filepath}" with host "{HOST}" and port "{port}"')
def impl(context, filepath, HOST, port):
host = os.environ.get(HOST)
substr = host + ':' + port
modify_sql_file(filepath, substr)
@given('the user starts the gpfdist on host "{HOST}" and port "{port}" in work directory "{dir}" from remote "{ctxt}"')
@then('the user starts the gpfdist on host "{HOST}" and port "{port}" in work directory "{dir}" from remote "{ctxt}"')
def impl(context, HOST, port, dir, ctxt):
host = os.environ.get(HOST)
remote_gphome = os.environ.get('GPHOME')
if not dir.startswith("/"):
dir = os.environ.get(dir)
gp_source_file = os.path.join(remote_gphome, 'greenplum_path.sh')
gpfdist = Gpfdist('gpfdist on host %s' % host, dir, port, os.path.join(dir, 'gpfdist.pid'), int(ctxt), host,
gp_source_file)
gpfdist.startGpfdist()
@given('the user stops the gpfdist on host "{HOST}" and port "{port}" in work directory "{dir}" from remote "{ctxt}"')
@then('the user stops the gpfdist on host "{HOST}" and port "{port}" in work directory "{dir}" from remote "{ctxt}"')
def impl(context, HOST, port, dir, ctxt):
host = os.environ.get(HOST)
remote_gphome = os.environ.get('GPHOME')
if not dir.startswith("/"):
dir = os.environ.get(dir)
gp_source_file = os.path.join(remote_gphome, 'greenplum_path.sh')
gpfdist = Gpfdist('gpfdist on host %s' % host, dir, port, os.path.join(dir, 'gpfdist.pid'), int(ctxt), host,
gp_source_file)
gpfdist.cleanupGpfdist()
def run_valgrind_command(context, command, suppressions_file):
current_path = os.path.realpath(__file__)
current_dir = os.path.dirname(current_path)
cmd_text = "valgrind --suppressions=%s/%s %s" % (current_dir, suppressions_file, command)
run_command(context, cmd_text)
for line in context.error_message.splitlines():
if 'ERROR SUMMARY' in line:
if '0 errors from 0 contexts' not in line:
raise Exception('Output: %s' % context.error_message)
else:
return
raise Exception('Could not find "ERROR SUMMARY" in %s' % context.error_message)
@then('the user runs valgrind with "{command}" and options "{options}"')
@when('the user runs valgrind with "{command}" and options "{options}"')
def impl(context, command, options):
port = os.environ.get('PGPORT')
user = getpass.getuser()
if hasattr(context, 'backup_timestamp'):
ts = context.backup_timestamp
bnr_tool = command.split()[0].strip()
if bnr_tool == 'gp_dump':
command_str = command
elif bnr_tool == 'gp_dump_agent':
command_str = command + ' -p %s' % port
elif bnr_tool == 'gp_restore':
command_str = "%s %s --gp-k %s --gp-d db_dumps/%s --gp-r db_dumps/%s" % (
command, options, context.backup_timestamp, context.backup_timestamp[0:8], context.backup_timestamp[0:8])
elif bnr_tool == 'gp_restore_agent':
command_str = "%s %s --gp-k %s --gp-d db_dumps/%s -p %s -U %s --target-host localhost " \
"--target-port %s db_dumps/%s/gp_dump_-1_1_%s_post_data.gz" % (
command, options, ts, ts[0:8], port, user, port, ts[0:8], ts)
command_str = append_storage_config_to_restore_command(context, command_str)
run_valgrind_command(context, command_str, "valgrind_suppression.txt")
@when('the timestamp key is stored')
def impl(context):
stdout = context.stdout_message
for line in stdout.splitlines():
if '--gp-k' in line:
pat = re.compile('.* --gp-k=([0-9]{14}).*')
m = pat.search(line)
if not m:
raise Exception('Timestamp key not found')
context.timestamp_key = m.group(1)
return
@then('{command} should print "{err_msg}" error message')
def impl(context, command, err_msg):
check_err_msg(context, err_msg)
@then('{command} should print "{out_msg}" to stdout')
def impl(context, command, out_msg):
check_stdout_msg(context, out_msg)
@then('{command} should not print "{out_msg}" to stdout')
def impl(context, command, out_msg):
check_string_not_present_stdout(context, out_msg)
@then('{command} should print "{out_msg}" to stdout {num} times')
def impl(context, command, out_msg, num):
msg_list = context.stdout_message.split('\n')
msg_list = [x.strip() for x in msg_list]
count = msg_list.count(out_msg)
if count != int(num):
raise Exception("Expected %s to occur %s times. Found %d" % (out_msg, num, count))
@given('{command} should return a return code of {ret_code}')
@when('{command} should return a return code of {ret_code}')
@then('{command} should return a return code of {ret_code}')
def impl(context, command, ret_code):
check_return_code(context, ret_code)
@given('{command} should not return a return code of {ret_code}')
@when('{command} should not return a return code of {ret_code}')
@then('{command} should not return a return code of {ret_code}')
def impl(context, command, ret_code):
check_not_return_code(context, ret_code)
@then('an "{ex_type}" should be raised')
def impl(context, ex_type):
if not context.exception:
raise Exception('An exception was expected but was not thrown')
typ = context.exception.__class__.__name__
if typ != ex_type:
raise Exception('got exception of type "%s" but expected type "%s"' % (typ, ex_type))
@given('database "{dbname}" health check should pass on table "{tablename}"')
@when('database "{dbname}" health check should pass on table "{tablename}"')
@then('database "{dbname}" health check should pass on table "{tablename}"')
def impl(context, dbname, tablename):
drop_database_if_exists(context, dbname)
create_database(context, dbname)
create_int_table(context, tablename, dbname=dbname)
drop_database(context, dbname)
@given('the segments are synchronized')
@when('the segments are synchronized')
@then('the segments are synchronized')
def impl(context):
times = 60
sleeptime = 10
for i in range(times):
if are_segments_synchronized():
return
time.sleep(sleeptime)
raise Exception('segments are not in sync after %d seconds' % (times * sleeptime))
@when('at least one segment is resynchronized')
@then('at least one segment is resynchronized')
@given('at least one segment is resynchronized')
def impl(context):
times = 30
sleeptime = 10
for i in range(times):
if is_any_segment_resynchronized():
return
time.sleep(sleeptime)
raise Exception('segments are not in resync after %d seconds' % (times * sleeptime))
@when('table "{table_list}" is assumed to be in dirty state in "{dbname}"')
@then('table "{table_list}" is assumed to be in dirty state in "{dbname}"')
@given('table "{table_list}" is assumed to be in dirty state in "{dbname}"')
def impl(context, table_list, dbname):
tables = table_list.split(',')
for t in tables:
modify_data(context, t.strip(), dbname)
backup_data(context, t.strip(), dbname)
get_distribution_policy(dbname)
@given('all the data from "{dbname}" is saved for verification')
@when('all the data from "{dbname}" is saved for verification')
@then('all the data from "{dbname}" is saved for verification')
def impl(context, dbname):
backup_db_data(context, dbname)
@then(
'partition "{partition}" of partition table "{table_list}" is assumed to be in dirty state in "{dbname}" in schema "{schema}"')
@when(
'partition "{partition}" of partition table "{table_list}" is assumed to be in dirty state in "{dbname}" in schema "{schema}"')
@given(
'partition "{partition}" of partition table "{table_list}" is assumed to be in dirty state in "{dbname}" in schema "{schema}"')
@then(
'partition "{partition}" in partition level "{partitionlevel}" of partition table "{table_list}" is assumed to be in dirty state in "{dbname}" in schema "{schema}"')
@when(
'partition "{partition}" in partition level "{partitionlevel}" of partition table "{table_list}" is assumed to be in dirty state in "{dbname}" in schema "{schema}"')
@given(
'partition "{partition}" in partition level "{partitionlevel}" of partition table "{table_list}" is assumed to be in dirty state in "{dbname}" in schema "{schema}"')
def impl(context, partition, table_list, dbname, schema, partitionlevel=1):
tables = table_list.split(',')
for t in tables:
part_t = get_partition_names(schema, t.strip(), dbname, partitionlevel, partition)
if len(part_t) < 1 or len(part_t[0]) < 1:
print part_t
dirty_table_name = part_t[0][0].strip()
modify_partition_data(context, dirty_table_name, dbname, int(partition))
backup_data(context, dirty_table_name, dbname)
def validate_timestamp(ts):
try:
int_ts = int(ts)
except Exception as e:
raise Exception('Timestamp is not valid %s' % ts)
if len(ts) != 14:
raise Exception('Timestamp is invalid %s' % ts)
@when('the subdir from gpcrondump is stored')
@then('the subdir from gpcrondump is stored')
def impl(context):
stdout = context.stdout_message
for line in stdout.splitlines():
if 'Dump subdirectory' in line:
log_msg, delim, subdir = line.partition('=')
context.backup_subdir = subdir.strip()
return
raise Exception('Dump subdirectory not found %s' % stdout)
def get_timestamp_from_output(context):
ts = None
stdout = context.stdout_message
for line in stdout.splitlines():
if 'Timestamp key = ' in line:
log_msg, delim, timestamp = line.partition('=')
ts = timestamp.strip()
validate_timestamp(ts)
return ts
raise Exception('Timestamp not found %s' % stdout)
@given('the full backup timestamp from gpcrondump is stored')
@when('the full backup timestamp from gpcrondump is stored')
@then('the full backup timestamp from gpcrondump is stored')
def impl(context):
context.full_backup_timestamp = get_timestamp_from_output(context)
_write_timestamp_to_json(context)
@when('the timestamp from gpcrondump is stored')
@then('the timestamp from gpcrondump is stored')
def impl(context):
context.backup_timestamp = get_timestamp_from_output(context)
_write_timestamp_to_json(context)
@when('the timestamp is labeled "{lbl}"')
def impl(context, lbl):
if not 'timestamp_labels' in global_labels:
global_labels['timestamp_labels'] = {}
global_labels['timestamp_labels'][lbl] = get_timestamp_from_output(context)
@when('the timestamp for scenario "{scenario_number}" is labeled "{lbl}"')
def impl(context, scenario_number, lbl):
labels_key = 'timestamp_labels' + scenario_number
if not labels_key in global_labels:
global_labels[labels_key] = {}
global_labels[labels_key][lbl] = get_timestamp_from_output(context)
_write_label_to_json(context, labels_key, lbl)
@given('there is a list to store the incremental backup timestamps')
def impl(context):
context.inc_backup_timestamps = []
@then('the timestamp from gpcrondump is stored in a list')
@when('the timestamp from gpcrondump is stored in a list')
def impl(context):
context.backup_timestamp = get_timestamp_from_output(context)
context.inc_backup_timestamps.append(context.backup_timestamp)
_write_timestamp_to_json(context)
@when('the timestamp for database dumps "{db_list}" are stored')
def impl(context, db_list):
context.db_timestamps = get_timestamp_from_output_for_db(context)
scenario_name = context._stack[0]['scenario'].name
if not global_timestamps.has_key(scenario_name):
global_timestamps[scenario_name] = list()
global_timestamps[scenario_name].append(context.db_timestamps.values())
with open(timestamp_json, 'w') as outfile:
json.dump(global_timestamps, outfile)
def get_timestamp_from_output_for_db(context):
db_timestamps = {}
ts = None
database = None
stdout = context.stdout_message
for line in stdout.splitlines():
if 'Target database' in line:
log_msg, delim, database = line.partition('=')
db = database.strip()
elif 'Dump key ' in line:
log_msg, delim, timestamp = line.partition('=')
ts = timestamp.strip()
validate_timestamp(ts)
# TODO: database could be an empty string; need to check result of line.partition()
if database is None:
raise Exception('Database not found for timestamp "%s"' % ts)
db_timestamps[db] = ts
database = None
if not db_timestamps:
raise Exception('No Timestamps found')
return db_timestamps
@then('verify data integrity of database "{dbname}" between source and destination system, work-dir "{dirname}"')
def impl(context, dbname, dirname):
dbconn_src = 'psql -p $GPTRANSFER_SOURCE_PORT -h $GPTRANSFER_SOURCE_HOST -U $GPTRANSFER_SOURCE_USER -d %s' % dbname
dbconn_dest = 'psql -p $GPTRANSFER_DEST_PORT -h $GPTRANSFER_DEST_HOST -U $GPTRANSFER_DEST_USER -d %s' % dbname
for filename in os.listdir(dirname):
if filename.endswith('.sql'):
filename_prefix = os.path.splitext(filename)[0]
ans_file_path = os.path.join(dirname, filename_prefix + '.ans')
out_file_path = os.path.join(dirname, filename_prefix + '.out')
diff_file_path = os.path.join(dirname, filename_prefix + '.diff')
# run the command to get the exact data from the source system
command = '%s -f %s > %s' % (dbconn_src, os.path.join(dirname, filename), ans_file_path)
run_command(context, command)
# run the command to get the data from the destination system, locally
command = '%s -f %s > %s' % (dbconn_dest, os.path.join(dirname, filename), out_file_path)
run_command(context, command)
gpdiff_cmd = 'gpdiff.pl -w -I NOTICE: -I HINT: -I CONTEXT: -I GP_IGNORE: --gpd_init=test/behave/mgmt_utils/steps/data/global_init_file %s %s > %s' % (
ans_file_path, out_file_path, diff_file_path)
run_command(context, gpdiff_cmd)
if context.ret_code != 0:
with open(diff_file_path, 'r') as diff_file:
diff_file_contents = diff_file.read()
raise Exception(
"Found difference between source and destination system, see %s. \n Diff contents: \n %s" % (
diff_file_path, diff_file_contents))
@then('run post verifying workload under "{dirname}"')
def impl(context, dirname):
for filename in os.listdir(dirname):
if filename.endswith('.sql'):
filename_prefix = os.path.splitext(filename)[0]
ans_file_path = os.path.join(dirname, filename_prefix + '.ans')
out_file_path = os.path.join(dirname, filename_prefix + '.out')
diff_file_path = os.path.join(dirname, filename_prefix + '.diff')
# run the command to get the data from the destination system, locally
dbconn = 'psql -d template1 -p $GPTRANSFER_DEST_PORT -U $GPTRANSFER_DEST_USER -h $GPTRANSFER_DEST_HOST'
command = '%s -f %s > %s' % (dbconn, os.path.join(dirname, filename), out_file_path)
run_command(context, command)
gpdiff_cmd = 'gpdiff.pl -w -I NOTICE: -I HINT: -I CONTEXT: -I GP_IGNORE: --gpd_init=test/behave/mgmt_utils/steps/data/global_init_file %s %s > %s' % (
ans_file_path, out_file_path, diff_file_path)
run_command(context, gpdiff_cmd)
for filename in os.listdir(dirname):
full_filename_path = os.path.join(dirname, filename)
if filename.endswith('.diff') and os.path.getsize(full_filename_path) > 0:
with open(full_filename_path, 'r') as diff_file:
diff_file_contents = diff_file.read()
# if there is some difference generated into the diff file, raise expception
raise Exception(
"Found difference between source and destination system, see %s. \n Diff contents: \n %s" % (
full_filename_path, diff_file_contents))
@then('verify that the incremental file has the stored timestamp')
def impl(context):
dump_dir = get_dump_dir(context, "")
inc_file_name = 'gp_dump_%s_increments' % context.full_backup_timestamp
subdirectory = context.full_backup_timestamp[0:8]
full_path = os.path.join(dump_dir, subdirectory, inc_file_name)
if not os.path.isfile(full_path):
raise Exception("Can not find increments file: %s" % full_path)
contents = ""
with open(full_path) as fd:
contents = fd.read().strip()
if context.backup_timestamp != contents:
raise Exception(
"The increments file '%s' does not contain the timestamp %s" % (full_path, context.backup_timestamp))
def check_increments_file_for_list(context, location):
dump_dir = get_dump_dir(context, location)
inc_file_name = 'gp_dump_%s_increments' % context.full_backup_timestamp
subdirectory = context.full_backup_timestamp[0:8]
full_path = os.path.join(dump_dir, subdirectory, inc_file_name)
if not os.path.isfile(full_path):
raise Exception("Can not find increments file: %s" % full_path)
found_timestamps = []
contents = ""
with open(full_path) as fd:
contents = fd.read()
for line in contents.splitlines():
line = line.strip()
if not line:
continue
found_timestamps.append(line)
found_timestamps = sorted(found_timestamps)
context.inc_backup_timestamps = sorted(context.inc_backup_timestamps)
if found_timestamps != context.inc_backup_timestamps:
print "Found timestamps: "
print found_timestamps
print "Expected timestamps: "
print context.inc_backup_timestamps
raise Exception("Expected timestamps not found")
@then('verify that the incremental file in "{location}" has all the stored timestamps')
def impl(context, location):
check_increments_file_for_list(context, location)
@then('verify that the incremental file has all the stored timestamps')
def impl(context):
check_increments_file_for_list(context, master_data_dir)
@then('verify that the plan file is created for the latest timestamp')
def impl(context):
context.inc_backup_timestamps = sorted(context.inc_backup_timestamps)
latest_ts = context.inc_backup_timestamps[-1]
plan_file_dir = get_dump_dir(context, master_data_dir) + '/' + latest_ts[0:8]
plan_file_count = len(glob.glob('/%s/*%s*_plan' % (plan_file_dir, latest_ts)))
if plan_file_count != 1:
raise Exception('Expected only one plan file, found %s' % plan_file_count)
filename = '%s/gp_restore_%s_plan' % (plan_file_dir, latest_ts)
if not os.path.exists(filename):
raise Exception('Plan file %s not created for the latest timestamp' % filename)
def get_dump_dir(context, directory):
dump_dir = directory.strip() if len(directory.strip()) != 0 else master_data_dir
if use_ddboost():
dump_dir = os.path.join(dump_dir, context._root['ddboost_backupdir'])
else:
dump_dir = os.path.join(dump_dir, 'db_dumps')
return dump_dir
@when('the state files are generated under "{directory}" for stored "{backup_type}" timestamp')
@then('the state files are generated under "{directory}" for stored "{backup_type}" timestamp')
def impl(context, directory, backup_type):
dump_dir = get_dump_dir(context, directory)
if backup_type == 'full':
timestamp = context.full_backup_timestamp
else:
timestamp = context.backup_timestamp
ao_state_filename = "%s/%s/gp_dump_%s_ao_state_file" % (dump_dir, timestamp[0:8], timestamp)
co_state_filename = "%s/%s/gp_dump_%s_co_state_file" % (dump_dir, timestamp[0:8], timestamp)
if not os.path.exists(ao_state_filename):
raise Exception('AO state file %s not generated' % ao_state_filename)
if not os.path.exists(co_state_filename):
raise Exception('CO state file %s not generated' % co_state_filename)
verify_integer_tuple_counts(context, ao_state_filename)
verify_integer_tuple_counts(context, co_state_filename)
@then('the "{file_type}" files are generated under "{dirname}" for stored "{backup_type}" timestamp')
def impl(context, file_type, dirname, backup_type):
dump_dir = get_dump_dir(context, dirname)
if backup_type == 'full':
timestamp = context.full_backup_timestamp
else:
timestamp = context.backup_timestamp
last_operation_filename = "%s/%s/gp_dump_%s_last_operation" % (dump_dir, timestamp[0:8], timestamp)
if not os.path.exists(last_operation_filename):
raise Exception('Last operation file %s not generated' % last_operation_filename)
@when('the user runs gpdbrestore -e with the stored timestamp')
@then('the user runs gpdbrestore -e with the stored timestamp')
def impl(context):
command = 'gpdbrestore -e -t %s -a' % context.backup_timestamp
command = append_storage_config_to_restore_command(context, command)
run_gpcommand(context, command)
@then('the user runs gpdbrestore -e with the stored timestamp and options "{options}"')
@when('the user runs gpdbrestore -e with the stored timestamp and options "{options}"')
def impl(context, options):
command = 'gpdbrestore -e -t %s %s -a' % (context.backup_timestamp, options)
command = append_storage_config_to_restore_command(context, command)
run_gpcommand(context, command)
@then('the user runs gpdbrestore -e with the stored full timestamp and options "{options}"')
@when('the user runs gpdbrestore -e with the stored full timestamp and options "{options}"')
def impl(context, options):
command = 'gpdbrestore -e -t %s %s -a' % (context.full_backup_timestamp, options)
command = append_storage_config_to_restore_command(context, command)
run_gpcommand(context, command)
@then('the user runs gpdbrestore -e with the date directory')
@when('the user runs gpdbrestore -e with the date directory')
def impl(context):
command = 'gpdbrestore -e -b %s -a' % (context.backup_timestamp[0:8])
command = append_storage_config_to_restore_command(context, command)
run_gpcommand(context, command)
@when('the user runs gpdbrestore without -e with the stored timestamp and options "{options}"')
def impl(context, options):
command = 'gpdbrestore -t %s %s -a' % (context.backup_timestamp, options)
command = append_storage_config_to_restore_command(context, command)
run_gpcommand(context, command)
@then('verify that there is no table "{tablename}" in "{dbname}"')
def impl(context, tablename, dbname):
dbname = replace_special_char_env(dbname)
tablename = replace_special_char_env(tablename)
if check_table_exists(context, dbname=dbname, table_name=tablename):
raise Exception("Table '%s' still exists when it should not" % tablename)
@then('verify that there is no view "{viewname}" in "{dbname}"')
def impl(context, viewname, dbname):
if check_table_exists(context, dbname=dbname, table_name=viewname, table_type='view'):
raise Exception("View '%s' still exists when it should not" % viewname)
@then('verify that there is no procedural language "{planguage}" in "{dbname}"')
def impl(context, planguage, dbname):
if check_pl_exists(context, dbname=dbname, lan_name=planguage):
raise Exception("Procedural Language '%s' still exists when it should not" % planguage)
@then('verify that there is a constraint "{conname}" in "{dbname}"')
def impl(context, conname, dbname):
if not check_constraint_exists(context, dbname=dbname, conname=conname):
raise Exception("Constraint '%s' does not exist when it should" % conname)
@then('verify that there is a rule "{rulename}" in "{dbname}"')
def impl(context, rulename, dbname):
if not check_rule_exists(context, dbname=dbname, rulename=rulename):
raise Exception("Rule '%s' does not exist when it should" % rulename)
@then('verify that there is a trigger "{triggername}" in "{dbname}"')
def impl(context, triggername, dbname):
if not check_trigger_exists(context, dbname=dbname, triggername=triggername):
raise Exception("Trigger '%s' does not exist when it should" % triggername)
@then('verify that there is an index "{indexname}" in "{dbname}"')
def impl(context, indexname, dbname):
if not check_index_exists(context, dbname=dbname, indexname=indexname):
raise Exception("Index '%s' does not exist when it should" % indexname)
@then('verify that there is a "{table_type}" table "{tablename}" in "{dbname}"')
def impl(context, table_type, tablename, dbname):
if not check_table_exists(context, dbname=dbname, table_name=tablename, table_type=table_type):
raise Exception("Table '%s' of type '%s' does not exist when expected" % (tablename, table_type))
@then(
'verify that there is partition "{partition}" of "{table_type}" partition table "{tablename}" in "{dbname}" in "{schemaname}"')
def impl(context, partition, table_type, tablename, dbname, schemaname):
if not check_partition_table_exists(context, dbname=dbname, schemaname=schemaname, table_name=tablename,
table_type=table_type, part_level=1, part_number=partition):
raise Exception("Partition %s for table '%s' of type '%s' does not exist when expected" % (
partition, tablename, table_type))
@then(
'verify that there is partition "{partition}" of mixed partition table "{tablename}" with storage_type "{storage_type}" in "{dbname}" in "{schemaname}"')
@then(
'verify that there is partition "{partition}" in partition level "{partitionlevel}" of mixed partition table "{tablename}" with storage_type "{storage_type}" in "{dbname}" in "{schemaname}"')
def impl(context, partition, tablename, storage_type, dbname, schemaname, partitionlevel=1):
part_t = get_partition_names(schemaname, tablename, dbname, partitionlevel, partition)
partname = part_t[0][0].strip()
validate_storage_type(context, partname, storage_type, dbname)
@given('there is a function "{functionname}" in "{dbname}"')
def impl(context, functionname, dbname):
SQL = """CREATE FUNCTION %s(a integer, b integer)
RETURNS integer AS $$
if a > b:
return a
return b
$$ LANGUAGE plpythonu;""" % functionname
execute_sql(dbname, SQL)
@then('verify that storage_types of the partition table "{tablename}" are as expected in "{dbname}"')
def impl(context, tablename, dbname):
validate_mixed_partition_storage_types(context, tablename, dbname)
@then(
'data for partition table "{table_name}" with partition level "{part_level}" is distributed across all segments on "{dbname}"')
def impl(context, table_name, part_level, dbname):
validate_part_table_data_on_segments(context, table_name, part_level, dbname)
@then('data for table "{table_name}" is distributed across all segments on "{dbname}"')
def impl(context, table_name, dbname):
validate_table_data_on_segments(context, table_name, dbname)
@then('verify that the data of the {filename} under "{directory}" in "{dbname}" is validated after restore')
def impl(context, filename, dbname, directory):
dump_dir = get_dump_dir(context, directory)
if filename == 'dirty tables':
dirty_list_filename = '%s/%s/gp_dump_%s_dirty_list' % (
dump_dir, context.backup_timestamp[0:8], context.backup_timestamp)
elif filename == 'table_filter_file':
dirty_list_filename = os.path.join(os.getcwd(), filename)
if not os.path.exists(dirty_list_filename):
raise Exception('Dirty list filename %s does not exist' % dirty_list_filename)
with open(dirty_list_filename) as fd:
tables = fd.readlines()
for table in tables:
validate_restore_data(context, table.strip(), dbname)
@then('verify that the distribution policy of all the tables in "{dbname}" are validated after restore')
def impl(context, dbname):
validate_distribution_policy(context, dbname)
@then('verify that tables "{table_list}" in "{dbname}" has no rows')
def impl(context, table_list, dbname):
tables = [t.strip() for t in table_list.split(',')]
for t in tables:
check_empty_table(t, dbname)
@then('verify that table "{tname}" in "{dbname}" has "{nrows}" rows')
def impl(context, tname, dbname, nrows):
check_row_count(tname, dbname, int(nrows))
@then(
'verify that table "{src_tname}" in database "{src_dbname}" of source system has same data with table "{dest_tname}" in database "{dest_dbname}" of destination system with options "{options}"')
def impl(context, src_tname, src_dbname, dest_tname, dest_dbname, options):
match_table_select(context, src_tname, src_dbname, dest_tname, dest_dbname, options)
@then(
'verify that table "{src_tname}" in database "{src_dbname}" of source system has same data with table "{dest_tname}" in database "{dest_dbname}" of destination system with order by "{orderby}"')
def impl(context, src_tname, src_dbname, dest_tname, dest_dbname, orderby):
match_table_select(context, src_tname, src_dbname, dest_tname, dest_dbname, orderby)
@then('verify that partitioned tables "{table_list}" in "{dbname}" have {num_parts} partitions')
@then(
'verify that partitioned tables "{table_list}" in "{dbname}" have {num_parts} partitions in partition level "{partitionlevel}"')
def impl(context, table_list, dbname, num_parts, partitionlevel=1):
num_parts = int(num_parts.strip())
tables = [t.strip() for t in table_list.split(',')]
for t in tables:
names = get_partition_tablenames(t, dbname, partitionlevel)
if len(names) != num_parts:
raise Exception("%s.%s should have %d partitions but has %d" % (dbname, t, num_parts, len(names)))
# raise exception if tname does not have X empty partitions
def check_x_empty_parts(dbname, tname, x):
num_empty = 0
parts = get_partition_tablenames(tname, dbname)
for part in parts:
p = part[0]
try:
check_empty_table(p, dbname)
num_empty += 1
except Exception as e:
print e
if num_empty != x:
raise Exception("%s.%s has %d empty partitions and should have %d" % (dbname, tname, num_empty, x))
@then('the user runs gpdbrestore with "{opt}" option in path "{path}"')
def impl(context, opt, path):
command = 'gpdbrestore -e -a %s localhost:%s/db_dumps/%s --verbose' % (opt, path, context.backup_subdir)
run_gpcommand(context, command)
@then('all files for full backup have been removed in path "{path}"')
def impl(context, path):
path = path if len(path.strip()) != 0 else master_data_dir
file_pattern = "*_%s*" % context.full_backup_timestamp
dir = "%s/db_dumps/%s" % (path, context.backup_subdir)
cleanup_cmd = "rm -f %s/%s" % (dir, file_pattern)
run_command(context, cleanup_cmd)
if context.exception:
raise context.exception
@given('there are no backup files')
@then('there are no backup files')
@when('there are no backup files')
def impl(context):
cleanup_backup_files(context, 'template1')
@given('the backup files in "{location}" are deleted')
@when('the backup files in "{location}" are deleted')
@then('the backup files in "{location}" are deleted')
def impl(context, location):
cleanup_backup_files(context, 'template1', location)
@then('there are no report files in the master data directory')
def impl(context):
cleanup_report_files(context, master_data_dir)
@when('verify that partitioned tables "{table_list}" in "{dbname}" has {num_parts} empty partitions')
@then('verify that partitioned tables "{table_list}" in "{dbname}" has {num_parts} empty partitions')
def impl(context, table_list, dbname, num_parts):
expected_num_parts = int(num_parts.strip())
tables = [t.strip() for t in table_list.split(',')]
for t in tables:
check_x_empty_parts(dbname, t, expected_num_parts)
@given('a backup file of tables "{table_list}" in "{dbname}" exists for validation')
@when('a backup file of tables "{table_list}" in "{dbname}" exists for validation')
@then('a backup file of tables "{table_list}" in "{dbname}" exists for validation')
def impl(context, table_list, dbname):
tables = [t.strip() for t in table_list.split(',')]
for t in tables:
backup_data(context, t.strip(), dbname)
@when(
'verify that there is a table "{tablename}" of "{tabletype}" type in "{dbname}" with same data as table "{backedup_table}"')
@then(
'verify that there is a table "{tablename}" of "{tabletype}" type in "{dbname}" with same data as table "{backedup_table}"')
def impl(context, tablename, tabletype, dbname, backedup_table):
if not check_table_exists(context, dbname=dbname, table_name=tablename, table_type=tabletype):
raise Exception("Table '%s' does not exist when it should" % tablename)
validate_restore_data(context, tablename, dbname, backedup_table)
@when('check that there is a "{table_type}" table "{tablename}" in "{dbname}" with same data from "{backedup_dbname}"')
@then('check that there is a "{table_type}" table "{tablename}" in "{dbname}" with same data from "{backedup_dbname}"')
def impl(context, table_type, tablename, dbname, backedup_dbname):
if not check_table_exists(context, dbname=dbname, table_name=tablename, table_type=table_type):
raise Exception("Table '%s' does not exist when it should" % tablename)
validate_restore_data(context, tablename, dbname, None, backedup_dbname)
@when('verify that there is a "{table_type}" table "{tablename}" in "{dbname}" with data')
@then('verify that there is a "{table_type}" table "{tablename}" in "{dbname}" with data')
def impl(context, table_type, tablename, dbname):
if not check_table_exists(context, dbname=dbname, table_name=tablename, table_type=table_type):
raise Exception("Table '%s' does not exist when it should" % tablename)
validate_restore_data(context, tablename, dbname)
@given('schema "{schema_list}" exists in "{dbname}"')
@then('schema "{schema_list}" exists in "{dbname}"')
def impl(context, schema_list, dbname):
schemas = [s.strip() for s in schema_list.split(',')]
for s in schemas:
drop_schema_if_exists(context, s.strip(), dbname)
create_schema(context, s.strip(), dbname)
@then('the temporary file "{filename}" is removed')
def impl(context, filename):
if os.path.exists(filename):
os.remove(filename)
@then('the temporary table file "{filename}" is removed')
def impl(context, filename):
table_file = 'test/behave/mgmt_utils/steps/data/gptransfer/%s' % filename
if os.path.exists(table_file):
os.remove(table_file)
def create_table_file_locally(context, filename, table_list, location=os.getcwd()):
tables = table_list.split('|')
file_path = os.path.join(location, filename)
with open(file_path, 'w') as fp:
for t in tables:
fp.write(t + '\n')
context.filename = file_path
@given('there is a file "{filename}" with tables "{table_list}"')
@then('there is a file "{filename}" with tables "{table_list}"')
def impl(context, filename, table_list):
create_table_file_locally(context, filename, table_list)
@given('there is a fake pg_aoseg table named "{table}" in "{dbname}"')
def impl(context, table, dbname):
create_fake_pg_aoseg_table(context, table, dbname)
def verify_file_contents(context, file_type, file_dir, text_find, should_contain=True):
if not hasattr(context, "dump_prefix"):
context.dump_prefix = ''
if file_type == 'pg_dump_log':
fn = 'pg_dump_log'
context.backup_timestamp = '0'
elif file_type == 'report':
fn = '%sgp_dump_%s.rpt' % (context.dump_prefix, context.backup_timestamp)
elif file_type == 'status':
fn = '%sgp_dump_status_*_1_%s' % (context.dump_prefix, context.backup_timestamp)
elif file_type == 'filter':
fn = '%sgp_dump_%s_filter' % (context.dump_prefix, context.backup_timestamp)
elif file_type == "statistics":
fn = '%sgp_statistics_*_1_%s' % (context.dump_prefix, context.backup_timestamp)
elif file_type == 'schema':
fn = '%sgp_dump_%s_schema' % (context.dump_prefix, context.backup_timestamp)
elif file_type == 'cdatabase':
fn = '%sgp_cdatabase_*_1_%s' % (context.dump_prefix, context.backup_timestamp)
elif file_type == 'dump':
fn = '%sgp_dump_*_1_%s.gz' % (context.dump_prefix, context.backup_timestamp)
file_dir = get_dump_dir(context, file_dir)
subdirectory = context.backup_timestamp[0:8]
if file_type == 'pg_dump_log':
full_path = os.path.join(file_dir, fn)
else:
full_path = glob.glob(os.path.join(file_dir, subdirectory, fn))[0]
if not os.path.isfile(full_path):
raise Exception("Can not find %s file: %s" % (file_type, full_path))
contents = ""
if file_type == 'dump':
fd = gzip.open(full_path)
else:
fd = open(full_path)
contents = fd.read()
fd.close()
if should_contain and not text_find in contents:
raise Exception("Did not find '%s' in file %s" % (text_find, full_path))
elif not should_contain and text_find in contents:
raise Exception("Found '%s' in file '%s'" % (text_find, full_path))
@then('verify that the "{file_type}" file in "{file_dir}" dir contains "{text_find}"')
def impl(context, file_type, file_dir, text_find):
verify_file_contents(context, file_type, file_dir, text_find)
@then('verify that the "{file_type}" file in "{file_dir}" dir does not contain "{text_find}"')
def impl(context, file_type, file_dir, text_find):
verify_file_contents(context, file_type, file_dir, text_find, should_contain=False)
@then('the timestamp in the report file should be same as timestamp key')
def impl(context):
if not hasattr(context, 'timestamp_key'):
raise Exception('Unable to find timestamp key in context')
if hasattr(context, 'backup_dir'):
report_file = os.path.join(context.backup_dir, 'db_dumps', '%s' % (context.timestamp_key[0:8]),
'gp_dump_%s.rpt' % context.timestamp_key)
else:
report_file = os.path.join(master_data_dir, 'db_dumps', '%s' % (context.timestamp_key[0:8]),
'gp_dump_%s.rpt' % context.timestamp_key)
with open(report_file) as rpt:
for line in rpt:
if line.startswith('Timestamp Key'):
timestamp_key = line.split(':')[-1].strip()
if timestamp_key != context.timestamp_key:
raise Exception('Expected timestamp key to be %s, but found %s in report file %s' % (
context.timestamp_key, timestamp_key, report_file))
@then('there should be dump files with filename having timestamp key in "{dbname}"')
def impl(context, dbname):
if not hasattr(context, 'timestamp_key'):
raise Exception('Unable to find timestamp key in context')
master_hostname = get_master_hostname(dbname)
results = get_hosts_and_datadirs(dbname)
for (host, datadir) in results:
if host == master_hostname:
if hasattr(context, 'backup_dir'):
dump_dir = os.path.join(context.backup_dir, 'db_dumps', '%s' % (context.timestamp_key[0:8]))
else:
dump_dir = os.path.join(master_data_dir, 'db_dumps', '%s' % (context.timestamp_key[0:8]))
master_dump_files = ['%s/gp_dump_-1_1_%s' % (dump_dir, context.timestamp_key),
'%s/gp_dump_status_-1_1_%s' % (dump_dir, context.timestamp_key),
'%s/gp_cdatabase_-1_1_%s' % (dump_dir, context.timestamp_key),
'%s/gp_dump_-1_1_%s_post_data' % (dump_dir, context.timestamp_key)]
for dump_file in master_dump_files:
cmd = Command('check for dump files', 'ls -1 %s | wc -l' % (dump_file))
cmd.run(validateAfter=True)
if int(cmd.get_stdout()) != 1:
raise Exception('Dump file %s not found after gp_dump on host %s' % (dump_file, host))
else:
if hasattr(context, 'backup_dir'):
dump_dir = os.path.join(context.backup_dir, 'db_dumps', '%s' % (context.timestamp_key[0:8]))
else:
dump_dir = os.path.join(datadir, 'db_dumps', '%s' % (context.timestamp_key[0:8]))
segment_dump_files = ['%s/gp_dump_*_*_%s' % (dump_dir, context.timestamp_key),
'%s/gp_dump_status_*_*_%s' % (dump_dir, context.timestamp_key)]
for dump_file in segment_dump_files:
cmd = Command('check for dump files', 'ls -1 %s | wc -l' % (dump_file), ctxt=REMOTE, remoteHost=host)
cmd.run(validateAfter=True)
if int(cmd.get_stdout()) != 1:
raise Exception('Dump file %s not found after gp_dump on host %s' % (dump_file, host))
@then('"{filetype}" file should not be created under "{directory}"')
def impl(context, filetype, directory):
if not hasattr(context, 'backup_timestamp'):
raise Exception('Unable to find out the %s because backup timestamp has not been stored' % filetype)
if filetype == "dirty_list":
filename = 'gp_dump_%s_dirty_list' % context.backup_timestamp
elif filetype == "plan":
filename = 'gp_restore_%s_plan' % context.backup_timestamp
elif filetype == 'pipes':
filename = 'gp_dump_%s_pipes' % context.backup_timestamp
elif filetype == 'regular_files':
filename = 'gp_dump_%s_regular_files' % context.backup_timestamp
else:
raise Exception("Unknown filetype '%s' specified" % filetype)
dump_dir = get_dump_dir(context, directory)
file_path = os.path.join(dump_dir, context.backup_timestamp[0:8], filename)
if os.path.exists(file_path):
raise Exception("File path %s should not exist for filetype '%s'" % (file_path, filetype))
def get_plan_filename(context):
filename = 'gp_restore_%s_plan' % context.backup_timestamp
return os.path.join(master_data_dir, 'db_dumps', context.backup_timestamp[0:8], filename)
def get_dirty_list_filename(context, backup_dir=None):
if not backup_dir:
backup_dir = master_data_dir
if not hasattr(context, "dump_prefix"):
context.dump_prefix = ''
filename = '%sgp_dump_%s_dirty_list' % (context.dump_prefix, context.backup_timestamp)
return os.path.join(backup_dir, 'db_dumps', context.backup_timestamp[0:8], filename)
@then('plan file should match "{filename}"')
def impl(context, filename):
current_path = os.path.realpath(__file__)
current_dir = os.path.dirname(current_path)
golden_filename = "%s/%s" % (current_dir, filename)
generated_filename = get_plan_filename(context)
diff_files(golden_filename, generated_filename)
def parse_plan_file(filename):
plan = {}
with open(filename) as fd:
for line in fd:
parts = line.partition(":")
ts = parts[0].strip()
if ts not in plan:
plan[ts] = set()
tables = parts[2].split(",")
for t in tables:
if t not in plan[ts]:
plan[ts].add(t.strip())
return plan
def modify_plan_with_labels(context, expected_plan, scenario_number=""):
labels_key = 'timestamp_labels' + scenario_number
newplan = {}
for k in expected_plan:
if k not in global_labels[labels_key]:
raise Exception("Label '%s' not specified in behave test" % k)
ts = global_labels[labels_key][k]
newplan[ts] = expected_plan[k]
return newplan
def compare_plans(expected, actual):
expected_keys = expected.keys()
actual_keys = actual.keys()
if len(expected_keys) != len(actual_keys):
raise Exception(
"Expected plan has %s timestamps actual plan has %s timestamps" % (len(expected_keys), len(actual_keys)))
for k in expected:
if k not in actual:
raise Exception("Expected timestamp in plan and did not find it: %s " % k)
expected_tables = sorted(expected[k])
actual_tables = sorted(actual[k])
if expected_tables != actual_tables:
print "Expected plan: %s" % expected
print "Actual plan: %s" % actual
raise Exception("Tables in plan for timestamp '%s' do not match expected tables" % k)
@then('the plan file is validated against "{expected_plan}"')
def impl(context, expected_plan):
context.restore_plan = parse_plan_file(get_plan_filename(context))
current_path = os.path.realpath(__file__)
current_dir = os.path.dirname(current_path)
expected_file = '%s/%s' % (current_dir, expected_plan)
expected_plan = parse_plan_file(expected_file)
expected_plan = modify_plan_with_labels(context, expected_plan)
compare_plans(expected_plan, context.restore_plan)
@then('the plan file for scenario "{scenario_number}" is validated against "{expected_plan}"')
def impl(context, scenario_number, expected_plan):
context.restore_plan = parse_plan_file(get_plan_filename(context))
current_path = os.path.realpath(__file__)
current_dir = os.path.dirname(current_path)
expected_file = '%s/%s' % (current_dir, expected_plan)
expected_plan = parse_plan_file(expected_file)
expected_plan = modify_plan_with_labels(context, expected_plan, scenario_number)
compare_plans(expected_plan, context.restore_plan)
@then('there should be "{numtimestamps}" timestamps in the plan file')
def impl(context, numtimestamps):
num = int(numtimestamps)
if len(context.restore_plan) != num:
raise Exception("Expected %d timestamps and found %d in restore plan" % (num, len(context.restore_plan)))
@then('restore plan for timestamp "{ts}" should contain "{numtables}" tables')
def impl(context, ts, numtables):
num = int(numtables)
if ts not in context.restore_plan:
raise Exception("Timestamp label '%s' not found in restore plan" % ts)
@then('"{filetype}" file is removed under "{directory}"')
def impl(context, filetype, directory):
if not hasattr(context, 'backup_timestamp'):
raise Exception('Backup timestamp has not been stored')
if filetype == "dirty_list":
filename = 'gp_dump_%s_dirty_list' % context.backup_timestamp
elif filetype == "plan":
filename = 'gp_restore_%s_plan' % context.backup_timestamp
elif filetype == "global":
filename = 'gp_global_*_1_%s' % context.backup_timestamp
elif filetype == "report":
filename = 'gp_dump_%s.rpt' % context.backup_timestamp
elif filetype == "dump":
filename = 'gp_dump_*_1_%s.gz' % context.backup_timestamp
else:
raise Exception("Unknown filetype '%s' specified" % filetype)
dump_dir = get_dump_dir(context, directory)
file_path = glob.glob(os.path.join(dump_dir, context.backup_timestamp[0:8], filename))[0]
if os.path.exists(file_path):
os.remove(file_path)
@when('"{filetype}" file should be created under "{directory}"')
@then('"{filetype}" file should be created under "{directory}"')
def impl(context, filetype, directory):
if not hasattr(context, "dump_prefix"):
context.dump_prefix = ''
if not hasattr(context, 'backup_timestamp'):
raise Exception('Backup timestamp has not been stored')
if filetype == "dirty_list":
filename = 'gp_dump_%s_dirty_list' % context.backup_timestamp
elif filetype == "plan":
filename = 'gp_restore_%s_plan' % context.backup_timestamp
elif filetype == "global":
filename = 'gp_global_*_1_%s' % context.backup_timestamp
elif filetype == "statistics":
filename = 'gp_statistics_*_1_%s' % context.backup_timestamp
elif filetype == 'pipes':
filename = 'gp_dump_%s_pipes' % context.backup_timestamp
elif filetype == 'regular_files':
filename = 'gp_dump_%s_regular_files' % context.backup_timestamp
elif filetype == '_filter':
filename = 'gp_dump_%s_filter' % context.backup_timestamp
elif filetype == '_schema':
filename = 'gp_dump_%s_schema' % context.backup_timestamp
elif filetype == 'table':
filename = 'gp_dump_%s_table' % context.backup_timestamp
else:
raise Exception("Unknown filetype '%s' specified" % filetype)
dump_dir = get_dump_dir(context, directory)
file_path = glob.glob(os.path.join(dump_dir, context.backup_timestamp[0:8], '%s%s' % (context.dump_prefix, filename)))
if len(file_path) == 0 or not os.path.exists(file_path[0]):
raise Exception("File path %s does not exist for filetype '%s'" % (file_path, filetype))
@then('verify there are no "{tmp_file_prefix}" tempfiles')
def impl(context, tmp_file_prefix):
if tmp_file_prefix is not None and tmp_file_prefix:
if glob.glob('/tmp/%s*' % tmp_file_prefix):
raise Exception('Found temp %s files where they should not be present' % tmp_file_prefix)
else:
raise Exception('Invalid call to temp file removal %s' % tmp_file_prefix)
def compare_table_lists(table_names, stored_table_names, dbname):
if table_names != stored_table_names:
print "Table names after backup:"
print stored_table_names
print "Table names after restore:"
print table_names
raise Exception(
'Schema not restored correctly. List of tables are not equal before and after restore in database %s' % dbname)
@then('tables names should be identical to stored table names in "{dbname}" except "{fq_table_name}"')
def impl(context, dbname, fq_table_name):
table_names = sorted(get_table_names(dbname))
stored_table_names = sorted(context.table_names)
if fq_table_name != "":
stored_table_names.remove(fq_table_name.strip().split('.'))
compare_table_lists(table_names, stored_table_names, dbname)
@then('tables names should be identical to stored table names in "{dbname}"')
def impl(context, dbname):
table_names = sorted(get_table_names(dbname))
stored_table_names = sorted(context.table_names)
compare_table_lists(table_names, stored_table_names, dbname)
@then('tables names in database "{dbname}" should be identical to stored table names in file "{table_file_name}"')
def impl(context, dbname, table_file_name):
table_names = sorted(get_table_names(dbname))
stored_table_file_path = os.path.join('test/behave/mgmt_utils/steps/data', table_file_name)
stored_table_file = open(stored_table_file_path, 'r')
reader = csv.reader(stored_table_file)
stored_table_names = list(reader)
compare_table_lists(table_names, stored_table_names, dbname)
@then('tables in "{dbname}" should not contain any data')
def impl(context, dbname):
for table in context.table_names:
table_name = "%s.%s" % (table[0], table[1])
check_empty_table(table_name, dbname)
@then('verify that the data of "{expected_count}" tables in "{dbname}" is validated after restore')
def impl(context, dbname, expected_count):
validate_db_data(context, dbname, int(expected_count))
@then(
'verify that the data of "{expected_count}" tables in "{dbname}" is validated after restore from "{backedup_dbname}"')
def impl(context, dbname, expected_count, backedup_dbname):
validate_db_data(context, dbname, int(expected_count), backedup_dbname=backedup_dbname)
@then('all the data from the remote segments in "{dbname}" are stored in path "{dir}" for "{backup_type}"')
def impl(context, dbname, dir, backup_type):
segs = get_segment_hostnames(context, dbname)
if backup_type == 'inc':
timestamp = context.backup_timestamp[0:8]
elif backup_type == 'full':
timestamp = context.full_backup_timestamp[0:8]
from_path = '%s/db_dumps/%s' % (dir, timestamp)
to_path = '%s/db_dumps' % (dir)
for seg in segs:
print type(seg[0].strip())
cmdStr = "%s -o 'StrictHostKeyChecking no' -r %s:%s %s" % (
findCmdInPath('scp'), seg[0].strip(), from_path, to_path)
run_command(context, cmdStr)
@then('pg_stat_last_operation registers the truncate for tables "{table_list}" in "{dbname}" in schema "{schema}"')
def impl(context, table_list, dbname, schema):
if not table_list:
raise Exception('Empty table list')
tables = table_list.split(',')
for t in tables:
table_oid = get_table_oid(context, dbname, schema, t.strip())
verify_truncate_in_pg_stat_last_operation(context, dbname, table_oid)
@then(
'pg_stat_last_operation does not register the truncate for tables "{table_list}" in "{dbname}" in schema "{schema}"')
def impl(context, table_list, dbname, schema):
if not table_list:
raise Exception('Empty table list')
tables = table_list.split(',')
for t in tables:
table_oid = get_table_oid(context, dbname, schema, t.strip())
verify_truncate_not_in_pg_stat_last_operation(context, dbname, table_oid)
@given('the numbers "{lownum}" to "{highnum}" are inserted into "{tablename}" tables in "{dbname}"')
@when('the numbers "{lownum}" to "{highnum}" are inserted into "{tablename}" tables in "{dbname}"')
def impl(context, lownum, highnum, tablename, dbname):
insert_numbers(dbname, tablename, lownum, highnum)
@when('the user adds column "{cname}" with type "{ctype}" and default "{defval}" to "{tname}" table in "{dbname}"')
def impl(context, cname, ctype, defval, tname, dbname):
sql = "ALTER table %s ADD COLUMN %s %s DEFAULT %s" % (tname, cname, ctype, defval)
execute_sql(dbname, sql)
@given('there is a fake timestamp for "{ts}"')
def impl(context, ts):
dname = os.path.join(get_dump_dir(context, master_data_dir), ts[0:8])
os.makedirs(dname)
contents = """
Timestamp Key: %s
Backup Type: Full
gp_dump utility finished successfully.
""" % ts
fname = os.path.join(dname, 'gp_dump_%s.rpt' % ts)
with open(fname, 'w') as fd:
fd.write(contents)
@then('a timestamp in increments file in "{directory}" is modified to be newer')
def impl(context, directory):
if not hasattr(context, 'full_backup_timestamp'):
raise Exception('Full backup timestamp needs to be specified in the test')
if not directory.strip():
directory = master_data_dir
dump_dir = os.path.join(directory, 'db_dumps', context.full_backup_timestamp[0:8])
increments_filename = os.path.join(dump_dir, 'gp_dump_%s_increments' % context.full_backup_timestamp)
if not os.path.exists(increments_filename):
raise Exception('Increments file %s does not exist !' % increments_filename)
with open(increments_filename) as fd:
lines = fd.readlines()
lines[0] = str(int(lines[0].strip()) + 10000)
with open(increments_filename, 'w') as fd:
for line in lines:
fd.write(line + '\n')
@then('the "{table_type}" state file under "{backup_dir}" is saved for the "{backup_type}" timestamp')
def impl(context, table_type, backup_dir, backup_type):
timestamp_key = None
if backup_type == 'full':
timestamp_key = context.full_backup_timestamp
elif backup_type == 'inc':
timestamp_key = context.backup_timestamp
backup_dir = backup_dir if len(backup_dir.strip()) != 0 else master_data_dir
context.state_file = os.path.join(backup_dir, 'db_dumps', timestamp_key[0:8],
'gp_dump_%s_%s_state_file' % (timestamp_key, table_type))
@then('the saved state file is deleted')
def impl(context):
run_command(context, 'rm -f %s' % context.state_file)
if context.exception:
raise context.exception
@then('the saved state file is corrupted')
def impl(context):
write_lines = list()
with open(context.state_file, "r") as fr:
lines = fr.readlines()
for line in lines:
line = line.replace(",", "")
write_lines.append(line)
with open(context.state_file, "w") as fw:
for line in write_lines:
fw.write("%s\n" % line.rstrip())
@then('"{table_name}" is marked as dirty in dirty_list file')
def impl(context, table_name):
dirty_list = get_dirty_list_filename(context)
with open(dirty_list) as fp:
for line in fp:
if table_name.strip() in line.strip():
return
raise Exception('Expected table %s to be marked as dirty in %s' % (table_name, dirty_list))
@when('the "{table_name}" is recreated with same data in "{dbname}"')
def impl(context, table_name, dbname):
select_sql = 'select * into public.temp from %s' % table_name
execute_sql(dbname, select_sql)
drop_sql = 'drop table %s' % table_name
execute_sql(dbname, drop_sql)
recreate_sql = 'select * into %s from public.temp' % table_name
execute_sql(dbname, recreate_sql)
@then('verify that plan file has latest timestamp for "{table_name}"')
def impl(context, table_name):
plan_file = get_plan_filename(context)
with open(plan_file) as fp:
for line in fp:
if table_name in line.strip():
timestamp = line.split(':')[0].strip()
if timestamp != context.backup_timestamp:
raise Exception('Expected table %s with timestamp %s in plan file %s does not match timestamp %s' \
% (table_name, context.backup_timestamp, plan_file, timestamp))
@given('the row "{row_values}" is inserted into "{table}" in "{dbname}"')
def impl(context, row_values, table, dbname):
insert_row(context, row_values, table, dbname)
@when('the method get_partition_state is executed on table "{table}" in "{dbname}" for ao table "{ao_table}"')
def impl(context, table, dbname, ao_table):
(sch, tbl) = table.split('.')
ao_sch, ao_tbl = ao_table.split('.')
part_info = [(1, ao_sch, ao_tbl, tbl)]
try:
backup_utils = Context()
backup_utils.master_port = os.environ.get('PGPORT')
backup_utils.target_db = dbname
context.exception = None
context.partition_list_res = None
context.partition_list_res = get_partition_state(backup_utils, sch, part_info)
except Exception as e:
context.exception = e
@then('an exception should be raised with "{txt}"')
def impl(context, txt):
if not context.exception:
raise Exception("An exception was not raised")
output = context.exception.__str__()
if not txt in output:
raise Exception("Exception output is not matching: '%s'" % output)
@then('the get_partition_state result should contain "{elem}"')
def impl(context, elem):
if not context.partition_list_res:
raise Exception('get_partition_state did not return any results')
if len(context.partition_list_res) != 1:
raise Exception('get_partition_state returned more results than expected "%s"' % context.partition_list_res)
if elem not in context.partition_list_res:
raise Exception('Expected text "%s" not found in partition list returned by get_partition_state "%s"' % (
elem, context.partition_list_res))
@given('older backup directories "{dirlist}" exists')
@when('older backup directories "{dirlist}" exists')
@then('older backup directories "{dirlist}" exists')
def impl(context, dirlist):
dirs = [d.strip() for d in dirlist.split(',')]
for d in dirs:
if len(d) != 8 or not d.isdigit():
raise Exception('Invalid directory name provided %s' % d)
for d in dirs:
dump_dir = os.path.join(master_data_dir, 'db_dumps', d)
if os.path.exists(dump_dir):
continue
os.makedirs(dump_dir)
for i in range(10):
with open(os.path.join(dump_dir, '%s_%s' % (d, i)), 'w'):
pass
@then('the dump directories "{dirlist}" should not exist')
def impl(context, dirlist):
dirs = [d.strip() for d in dirlist.split(',')]
for d in dirs:
if len(d) != 8 or not d.isdigit():
raise Exception('Invalid directory name provided %s' % d)
for d in dirs:
dump_dir = os.path.join(master_data_dir, 'db_dumps', d)
if os.path.exists(dump_dir):
raise Exception('Unexpected directory exists %s' % dump_dir)
@then('the dump directory for the stored timestamp should exist')
def impl(context):
if not hasattr(context, 'full_backup_timestamp'):
raise Exception('Full backup timestamp needs to be stored')
dump_dir = os.path.join(master_data_dir, 'db_dumps', context.full_backup_timestamp[0:8])
if not os.path.exists(dump_dir):
raise Exception('Expected directory does not exist %s' % dump_dir)
def validate_master_config_backup_files(context, directory=master_data_dir):
if not hasattr(context, "dump_prefix"):
context.dump_prefix = ''
dump_dir = os.path.join(get_dump_dir(context, directory), context.backup_timestamp[0:8])
dump_files = os.listdir(dump_dir)
for df in dump_files:
if df.startswith('%sgp_master_config_files' % context.dump_prefix) and df.endswith('.tar'):
return
raise Exception('Config files not backed up on master "%s"' % dump_dir)
def validate_segment_config_backup_files(context, directory=None):
if not hasattr(context, "dump_prefix"):
context.dump_prefix = ''
gparray = GpArray.initFromCatalog(dbconn.DbURL())
primary_segs = [seg for seg in gparray.getDbList() if seg.isSegmentPrimary()]
for ps in primary_segs:
seg_data_dir = directory if directory is not None else ps.getSegmentDataDirectory()
dump_dir = os.path.join(get_dump_dir(context, seg_data_dir), context.backup_timestamp[0:8])
dump_files = ListRemoteFilesByPattern(dump_dir,
'%sgp_segment_config_files_*_%d_%s.tar' % (
context.dump_prefix, ps.getSegmentDbId(), context.backup_timestamp),
ps.getSegmentHostName()).run()
if len(dump_files) != 1:
raise Exception('Found too many config files for segment %s: %s' % (dump_files, seg_data_dir))
@then('config files should be backed up on all segments')
def impl(context):
if not hasattr(context, 'backup_timestamp'):
raise Exception('Backup timestamp needs to be stored')
validate_master_config_backup_files(context)
validate_segment_config_backup_files(context)
@then('config files should be backed up on all segments in directory "{directory}"')
def impl(context, directory):
if not hasattr(context, 'backup_timestamp'):
raise Exception('Backup timestamp needs to be stored')
validate_master_config_backup_files(context, directory=directory)
validate_segment_config_backup_files(context, directory=directory)
@then('verify that the table "{table_name}" in "{dbname}" has dump info for the stored timestamp')
def impl(context, table_name, dbname):
dump_history = {}
dump_history_sql = 'select dump_key,options from public.%s' % table_name
dump_history = getRows(dbname, dump_history_sql)
for (dump_key, options) in dump_history:
if context.backup_timestamp == dump_key.strip() and dbname in options:
return
raise Exception('Could not find dump info for timestamp %s in %s table' % (context.backup_timestamp, table_name))
@then('verify that database "{dbname}" does not exist')
def impl(context, dbname):
with dbconn.connect(dbconn.DbURL(dbname='template1')) as conn:
sql = """SELECT datname FROM pg_database"""
dbs = dbconn.execSQL(conn, sql)
if dbname in dbs:
raise Exception('Database exists when it shouldnt "%s"' % dbname)
@then('there are no saved data files')
def impl(context):
clear_all_saved_data_verify_files(context)
@then('the dump timestamp for "{db_list}" are different')
def impl(context, db_list):
if db_list is None:
raise Exception('Expected at least 1 database in the list, found none.')
if not hasattr(context, 'db_timestamps'):
raise Exception('The database timestamps need to be stored')
db_names = db_list.strip().split(',')
for db in db_names:
if db.strip() not in context.db_timestamps:
raise Exception('Could not find timestamp for database: %s' % context.db_timestamps)
timestamp_set = set([v for v in context.db_timestamps.values()])
if len(timestamp_set) != len(context.db_timestamps):
raise Exception('Some databases have same timestamp: "%s"' % context.db_timestamps)
@given('there is a "{table_type}" table "{table_name}" in "{db_name}" having large number of partitions')
def impl(context, table_type, table_name, db_name):
create_large_num_partitions(table_type, table_name, db_name)
@given('there is a "{table_type}" table "{table_name}" in "{db_name}" having "{num_partitions}" partitions')
def impl(context, table_type, table_name, db_name, num_partitions):
if not num_partitions.strip().isdigit():
raise Exception('Invalid number of partitions specified "%s"' % num_partitions)
num_partitions = int(num_partitions.strip()) + 1
create_large_num_partitions(table_type, table_name, db_name, num_partitions)
@given('the length of partition names of table "{table_name}" in "{db_name}" exceeds the command line maximum limit')
def impl(context, table_name, db_name):
partitions = get_partition_tablenames(table_name, db_name)
partition_list_string = ''
for part in partitions:
partition_list_string += (part[0] + ',')
if partition_list_string[-1] == ',':
parition_list_string = partition_list_string[:-1]
MAX_COMMAND_LINE_LEN = 100000
if len(partition_list_string) < MAX_COMMAND_LINE_LEN:
raise Exception('Expected the length of the string to be greater than %s, but got %s instead' % (
MAX_COMMAND_LINE_LEN, len(partition_list_string)))
@given('there is a table-file "{filename}" with tables "{table_list}"')
@then('there is a table-file "{filename}" with tables "{table_list}"')
def impl(context, filename, table_list):
tables = table_list.split(',')
with open(filename, 'w') as fd:
for table in tables:
fd.write(table.strip() + '\n')
if not os.path.exists(filename):
raise Exception('Unable to create file "%s"' % filename)
def create_ext_table_file(file_location):
with open(file_location, 'w') as fd:
for i in range(100):
fd.write('abc, 10, 10\n')
def get_host_and_port():
if 'PGPORT' not in os.environ:
raise Exception('PGPORT needs to be set in the environment')
port = os.environ['PGPORT']
gparray = GpArray.initFromCatalog(dbconn.DbURL())
master_host = None
for seg in gparray.getDbList():
if seg.isSegmentMaster():
master_host = seg.getSegmentAddress()
if master_host is None:
raise Exception('Unable to determine the master hostname')
return (master_host, port)
@given('there is an external table "{tablename}" in "{dbname}" with data for file "{file_location}"')
def impl(context, tablename, dbname, file_location):
create_ext_table_file(file_location)
host, port = get_host_and_port()
ext_table_sql = """CREATE EXTERNAL WEB TABLE %s(name text, column1 int, column2 int) EXECUTE 'cat %s 2> /dev/null || true'
ON MASTER FORMAT 'CSV' (DELIMITER ',')""" % (tablename, file_location)
execute_sql(dbname, ext_table_sql)
verify_ext_table_creation_sql = """SELECT count(*) FROM pg_class WHERE relname = '%s'""" % tablename
row_count = getRows(dbname, verify_ext_table_creation_sql)[0][0]
if row_count != 1:
raise Exception(
'Creation of external table failed for "%s:%s, row count = %s"' % (file_location, tablename, row_count))
@then('verify that there is no "{tablename}" in the "{file_type}" file in "{backup_dir}"')
def impl(context, tablename, file_type, backup_dir):
dump_dir = backup_dir if len(backup_dir.strip()) != 0 else master_data_dir
if not hasattr(context, "dump_prefix"):
context.dump_prefix = ''
filename = '%s/db_dumps/%s/%sgp_dump_%s_%s' % (
dump_dir, context.backup_timestamp[0:8], context.dump_prefix, context.backup_timestamp, file_type)
with open(filename) as fd:
for line in fd:
if tablename.strip() == line.strip():
raise Exception('Found an unwanted table in the file: "%s" in line: "%s"' % (filename, line))
@then('verify that exactly "{num_tables}" tables in "{dbname}" have been restored')
def impl(context, num_tables, dbname):
validate_num_restored_tables(context, num_tables, dbname)
@then('verify that exactly "{num_tables}" tables in "{dbname}" have been restored from "{backedup_dbname}"')
def impl(context, num_tables, dbname, backedup_dbname):
validate_num_restored_tables(context, num_tables, dbname, backedup_dbname=backedup_dbname)
@then('the user runs gpdbrestore on dump date directory with options "{options}"')
def impl(context, options):
command = 'gpdbrestore -e -b %s %s -a' % (context.backup_timestamp[0:8], options)
command = append_storage_config_to_restore_command(context, command)
run_gpcommand(context, command)
@then('the timestamps should be printed in sorted order')
def impl(context):
stdout_lines = context.stdout_message.split('\n')
process_ts = False
timestamps = []
for line in stdout_lines:
if '--------------------------' in line:
process_ts = True
elif process_ts:
if 'Enter timestamp number to restore' not in line:
timestamps.append(line.strip().split('......')[-1].strip())
else:
process_ts = False
break
timestamps = [ts.split()[0] + ts.split()[1] for ts in timestamps]
sorted_timestamps = sorted(timestamps, key=lambda x: int(x))
if sorted_timestamps != timestamps:
raise Exception('Timestamps are not in sorted order "%s"' % timestamps)
@given('there are "{table_count}" "{tabletype}" tables "{table_name}" with data in "{dbname}"')
def impl(context, table_count, tabletype, table_name, dbname):
table_count = int(table_count)
for i in range(1, table_count + 1):
tablename = "%s_%s" % (table_name, i)
create_database_if_not_exists(context, dbname)
drop_table_if_exists(context, table_name=tablename, dbname=dbname)
create_partition(context, tablename, tabletype, dbname, compression_type=None, partition=False)
@given('the tables "{table_list}" are in dirty hack file "{dirty_hack_file}"')
def impl(context, table_list, dirty_hack_file):
tables = [t.strip() for t in table_list.split(',')]
with open(dirty_hack_file, 'w') as fd:
for t in tables:
fd.write(t + '\n')
if not os.path.exists(dirty_hack_file):
raise Exception('Failed to create dirty hack file "%s"' % dirty_hack_file)
@given(
'partition "{part_num}" of partition tables "{table_list}" in "{dbname}" in schema "{schema}" are in dirty hack file "{dirty_hack_file}"')
def impl(context, part_num, table_list, dbname, schema, dirty_hack_file):
tables = table_list.split(',')
with open(dirty_hack_file, 'w') as fd:
part_num = int(part_num.strip())
for table in tables:
part_t = get_partition_names(schema, table.strip(), dbname, 1, part_num)
if len(part_t) < 1 or len(part_t[0]) < 1:
print part_t
partition_name = part_t[0][0].strip()
fd.write(partition_name + '\n')
if not os.path.exists(dirty_hack_file):
raise Exception('Failed to write to dirty hack file "%s"' % dirty_hack_file)
@then('verify that the config files are backed up with the stored timestamp')
def impl(context):
if not hasattr(context, 'backup_timestamp'):
raise Exception('Timestamp needs to be stored')
config_file = os.path.join(master_data_dir, 'db_dumps', context.backup_timestamp[0:8],
'gp_master_config_files_%s.tar' % context.backup_timestamp)
if not os.path.exists(config_file):
raise Exception('Failed to locate config file on master "%s"' % config_file)
gparray = GpArray.initFromCatalog(dbconn.DbURL())
primary_segs = [seg for seg in gparray.getDbList() if seg.isSegmentPrimary(current_role=True)]
for seg in primary_segs:
segment_config_file = os.path.join(seg.getSegmentDataDirectory(), 'db_dumps', context.backup_timestamp[0:8],
'gp_segment_config_files_0_%s_%s.tar' % (
seg.getSegmentDbId(), context.backup_timestamp))
if not CheckRemoteFile(segment_config_file, seg.getSegmentAddress()):
raise Exception('Failed to locate "%s" on "%s"' % segment_config_file, seg.getSegmentDataDirectory())
@then('verify that the list of stored timestamps is printed to stdout')
def impl(context):
found_ts = 0
stdout = context.stdout_message
for ts in context.inc_backup_timestamps:
for line in stdout.splitlines():
ts_str = 'Backup Timestamp: %s' % ts
if ts_str in line:
found_ts += 1
print 'context.inc_backup_timestamps = ', context.inc_backup_timestamps
if found_ts != len(context.inc_backup_timestamps):
raise Exception(
'Expected "%d" timestamps but found "%d" timestamps' % (len(context.inc_backup_timestamps), found_ts))
@given('there is a "{table_type}" table "{tablename}" with funny characters in "{dbname}"')
def impl(context, table_type, tablename, dbname):
funny_chars_table_name_sql = """create table "%s
new line in it" (a int)""" % tablename.strip()
table_type = table_type.strip()
if table_type == 'ao':
funny_chars_table_name_sql += ' with(appendonly=true)'
elif table_type == 'co':
funny_chars_table_name_sql += ' with(appendonly=true, orientation=column)'
elif table_type == 'heap':
pass
else:
raise Exception('Unknown table type specified "%s"' % table_type)
execute_sql(dbname.strip(), funny_chars_table_name_sql)
@then('verify that the tuple count of all appendonly tables are consistent in "{dbname}"')
def impl(context, dbname):
ao_partition_list = get_partition_list('ao', dbname)
verify_stats(dbname, ao_partition_list)
co_partition_list = get_partition_list('co', dbname)
verify_stats(dbname, co_partition_list)
@then('verify that there are no aoco stats in "{dbname}" for table "{tables}"')
def impl(context, dbname, tables):
tables = tables.split(',')
for t in tables:
validate_no_aoco_stats(context, dbname, t.strip())
@then('verify that there are "{tupcount}" tuples in "{dbname}" for table "{tables}"')
def impl(context, tupcount, dbname, tables):
tables = tables.split(',')
for t in tables:
validate_aoco_stats(context, dbname, t.strip(), tupcount)
@when('the performance timer is started')
def impl(context):
context.performance_timer = time.time()
@then('the performance timer should be less then "{num_seconds}" seconds')
def impl(context, num_seconds):
max_seconds = float(num_seconds)
current_time = time.time()
elapsed = current_time - context.performance_timer
if elapsed > max_seconds:
raise Exception(
"Performance timer ran for %.1f seconds but had a max limit of %.1f seconds" % (elapsed, max_seconds))
print "Elapsed time was %.1f seconds" % elapsed
@given('the file "{filename}" is removed from the system')
@when('the file "{filename}" is removed from the system')
@then('the file "{filename}" is removed from the system')
def impl(context, filename):
os.remove(filename)
@given('the client program "{program_name}" is present under {parent_dir} in "{sub_dir}"')
def impl(context, program_name, parent_dir, sub_dir):
if parent_dir == 'CWD':
parent_dir = os.getcwd()
program_path = '%s/%s/%s' % (parent_dir, sub_dir, program_name)
print program_path
if not os.path.isfile(program_path):
raise Exception('gpfdist client progream does not exist: %s' % (program_path))
@when('the user runs client program "{program_name}" from "{subdir}" under {parent_dir}')
def impl(context, program_name, subdir, parent_dir):
if parent_dir == 'CWD':
parent_dir = os.getcwd()
command_line = "python %s/%s/%s" % (parent_dir, subdir, program_name)
run_command(context, command_line)
@then('the gpfdist should print {msg} to "{filename}" under {parent_dir}')
def impl(context, msg, filename, parent_dir):
if parent_dir == 'CWD':
parent_dir = os.getcwd()
filepath = '%s/%s' % (parent_dir, filename)
with open(filepath, 'r') as fp:
for line in fp:
if msg in line:
return
raise Exception('Log file %s did not contain the message %s' % (filepath, msg))
@given('the "{process_name}" process is killed')
@then('the "{process_name}" process is killed')
@when('the "{process_name}" process is killed')
def impl(context, process_name):
run_command(context, 'pkill %s' % process_name)
@then('the client program should print "{msg}" to stdout with value in range {min_val} to {max_val}')
def impl(context, msg, min_val, max_val):
stdout = context.stdout_message
for line in stdout:
if msg in line:
val = re.finadall(r'\d+', line)
if not val:
raise Exception('Expected a numeric digit after message: %s' % msg)
if len(val) > 1:
raise Exception('Expected one numeric digit after message: %s' % msg)
if val[0] < min_val or val[0] > max_val:
raise Exception('Value not in acceptable range %s' % val[0])
@given('the directory "{dirname}" exists')
def impl(context, dirname):
if not os.path.isdir(dirname):
os.mkdir(dirname)
if not os.path.isdir(dirname):
raise Exception("directory '%s' not created" % dirname)
@then('the directory "{dirname}" does not exist')
def impl(context, dirname):
if os.path.isdir(dirname):
shutil.rmtree(dirname, ignore_errors=True)
if os.path.isdir(dirname):
raise Exception("directory '%s' not removed" % dirname)
@given('the directory "{dirname}" exists in current working directory')
def impl(context, dirname):
dirname = os.path.join(os.getcwd(), dirname)
if os.path.isdir(dirname):
shutil.rmtree(dirname, ignore_errors=True)
if os.path.isdir(dirname):
raise Exception("directory '%s' not removed" % dirname)
os.mkdir(dirname)
if not os.path.isdir(dirname):
raise Exception("directory '%s' not created" % dirname)
@given('the file "{filename}" exists under "{directory}" in current working directory')
def impl(context, filename, directory):
directory = os.path.join(os.getcwd(), directory)
if not os.path.isdir(directory):
raise Exception("directory '%s' not exists" % directory)
filepath = os.path.join(directory, filename)
open(filepath, 'a').close()
if not os.path.exists(filepath):
raise Exception("file '%s' not created" % filepath)
@given('the directory "{dirname}" does not exist in current working directory')
def impl(context, dirname):
dirname = os.path.join(os.getcwd(), dirname)
if os.path.isdir(dirname):
shutil.rmtree(dirname, ignore_errors=True)
if os.path.isdir(dirname):
raise Exception("directory '%s' not removed" % dirname)
@when('the data line "{dataline}" is appened to "{fname}" in cwd')
@then('the data line "{dataline}" is appened to "{fname}" in cwd')
def impl(context, dataline, fname):
fname = os.path.join(os.getcwd(), fname)
with open(fname, 'a') as fd:
fd.write("%s\n" % dataline)
@when('a "{readwrite}" external table "{tname}" is created on file "{fname}" in "{dbname}"')
def impl(context, readwrite, tname, fname, dbname):
hostname = socket.gethostname()
sql = """CREATE %s EXTERNAL TABLE
%s (name varchar(255), id int)
LOCATION ('gpfdist://%s:8088/%s')
FORMAT 'text'
(DELIMITER '|');
""" % (readwrite, tname, hostname, fname)
with dbconn.connect(dbconn.DbURL(dbname=dbname)) as conn:
dbconn.execSQL(conn, sql)
conn.commit()
@given('the external table "{tname}" does not exist in "{dbname}"')
def impl(context, tname, dbname):
drop_external_table_if_exists(context, table_name=tname, dbname=dbname)
@when('all rows from table "{tname}" db "{dbname}" are stored in the context')
def impl(context, tname, dbname):
context.stored_rows = []
with dbconn.connect(dbconn.DbURL(dbname=dbname)) as conn:
sql = "SELECT * FROM %s" % tname
curs = dbconn.execSQL(conn, sql)
context.stored_rows = curs.fetchall()
@given('results of the sql "{sql}" db "{dbname}" are stored in the context')
@when( 'results of the sql "{sql}" db "{dbname}" are stored in the context')
def impl(context, sql, dbname):
context.stored_sql_results = []
with dbconn.connect(dbconn.DbURL(dbname=dbname)) as conn:
curs = dbconn.execSQL(conn, sql)
context.stored_sql_results = curs.fetchall()
@then('validate that "{dataline}" "{formatter}" seperated by "{delim}" is in the stored rows')
def impl(context, dataline, formatter, delim):
lookfor = dataline.split(delim)
formatter = formatter.split(delim)
for i in range(len(formatter)):
if formatter[i] == 'int':
lookfor[i] = int(lookfor[i])
if lookfor not in context.stored_rows:
print context.stored_rows
print lookfor
raise Exception("'%s' not found in stored rows" % dataline)
@then('validate that following rows are in the stored rows')
def impl(context):
for row in context.table:
found_match = False
for stored_row in context.stored_rows:
match_this_row = True
for i in range(len(stored_row)):
value = row[i]
if isinstance(stored_row[i], bool):
value = str(True if row[i] == 't' else False)
if value != str(stored_row[i]):
match_this_row = False
break
if match_this_row:
found_match = True
break
if not found_match:
print context.stored_rows
raise Exception("'%s' not found in stored rows" % row)
@then('validate that stored rows has "{numlines}" lines of output')
def impl(context, numlines):
num_found = len(context.stored_rows)
numlines = int(numlines)
if num_found != numlines:
raise Exception("Found %d of stored query result but expected %d records" % (num_found, numlines))
@then('validate that first column of first stored row has "{numlines}" lines of raw output')
def impl(context, numlines):
raw_lines_count = len(context.stored_rows[0][0].splitlines())
numlines = int(numlines)
if raw_lines_count != numlines:
raise Exception("Found %d of stored query result but expected %d records" % (raw_lines_count, numlines))
def get_standby_host():
gparray = GpArray.initFromCatalog(dbconn.DbURL())
segments = gparray.getDbList()
standby_master = [seg.getSegmentHostName() for seg in segments if seg.isSegmentStandby()]
if len(standby_master) > 0:
return standby_master[0]
else:
return []
@given('user does not have ssh permissions')
def impl(context):
user_home = os.environ.get('HOME')
authorized_keys_file = '%s/.ssh/authorized_keys' % user_home
if os.path.exists(os.path.abspath(authorized_keys_file)):
shutil.move(authorized_keys_file, '%s.bk' % authorized_keys_file)
@then('user has ssh permissions')
def impl(context):
user_home = os.environ.get('HOME')
authorized_keys_backup_file = '%s/.ssh/authorized_keys.bk' % user_home
if os.path.exists(authorized_keys_backup_file):
shutil.move(authorized_keys_backup_file, authorized_keys_backup_file[:-3])
def delete_data_dir(host):
cmd = Command(name='remove data directories',
cmdStr='rm -rf %s' % master_data_dir,
ctxt=REMOTE,
remoteHost=host)
cmd.run(validateAfter=True)
@when('the user initializes a standby on the same host as master')
def impl(context):
hostname = get_master_hostname('template1')[0][0]
port_guaranteed_open = get_open_port()
temp_data_dir = tempfile.mkdtemp() + "/standby_datadir"
cmd = "gpinitstandby -a -s %s -P %d -F pg_system:%s" % (hostname, port_guaranteed_open, temp_data_dir)
run_gpcommand(context, cmd)
context.standby_data_dir = temp_data_dir
context.standby_was_initialized = True
# from https://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python/2838309#2838309
def get_open_port():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("",0))
s.listen(1)
port = s.getsockname()[1]
s.close()
return port
@given('"{path}" has its permissions set to "{perm}"')
def impl(context, path, perm):
path = os.path.expandvars(path)
if not os.path.exists(path):
raise Exception('Path does not exist! "%s"' % path)
old_permissions = os.stat(path).st_mode # keep it as a number that has a meaningful representation in octal
test_permissions = int(perm, 8) # accept string input with octal semantics and convert to a raw number
os.chmod(path, test_permissions)
context.path_for_which_to_restore_the_permissions = path
context.permissions_to_restore_path_to = old_permissions
@then('rely on environment.py to restore path permissions')
def impl(context):
print "go look in environment.py to see how it uses the path and permissions on context to make sure it's cleaned up"
@when('the user runs pg_controldata against the standby data directory')
def impl(context):
cmd = "pg_controldata " + context.standby_data_dir
run_gpcommand(context, cmd)
@when('the user initializes standby master on "{hostname}"')
def impl(context, hostname):
create_standby(context, hostname)
def create_standby(context, hostname):
port = os.environ.get('PGPORT')
if hostname.strip() == 'mdw':
if not hasattr(context, 'master') or not hasattr(context, 'standby_host'):
raise Exception('Expected master to be saved but was not found')
delete_data_dir(context.master)
cmd = Command(name='gpinitstandby',
cmdStr='PGPORT=%s MASTER_DATA_DIRECTORY=%s gpinitstandby -a -s %s' % (
port, master_data_dir, context.master),
ctxt=REMOTE,
remoteHost=context.standby_host)
cmd.run(validateAfter=True)
return
elif hostname.strip() == 'smdw':
context.master = get_master_hostname('template1')[0][0]
context.ret_code = 0
context.stdout_message = ''
context.error_message = ''
segment_hostlist = get_segment_hostlist()
segment_hosts = [seg for seg in segment_hostlist if seg != context.master]
context.standby_host = segment_hosts[0]
gparray = GpArray.initFromCatalog(dbconn.DbURL())
segdbs = gparray.getDbList()
for seg in segdbs:
if seg.getSegmentHostName() == context.standby_host:
context.standby_host_data_dir = seg.getSegmentDataDirectory()
context.standby_was_initialized = False
standby = get_standby_host()
if standby:
context.standby_was_initialized = True
context.standby_host = standby
return
delete_data_dir(context.standby_host)
cmd = "gpinitstandby -a -s %s" % context.standby_host
run_gpcommand(context, cmd)
else:
raise Exception('Invalid host type specified "%s"' % hostname)
@when('the user runs the query "{query}" on "{dbname}"')
def impl(context, query, dbname):
if query.lower().startswith('create') or query.lower().startswith('insert'):
thread.start_new_thread(execute_sql, (dbname, query))
else:
thread.start_new_thread(getRows, (dbname, query))
time.sleep(30)
@given('we have exchanged keys with the cluster')
def impl(context):
hostlist = get_all_hostnames_as_list(context, 'template1')
host_str = ' -h '.join(hostlist)
cmd_str = 'gpssh-exkeys %s' % host_str
run_gpcommand(context, cmd_str)
@then('the temp files "{filename_prefix}" are not created in the system')
def impl(context, filename_prefix):
hostlist = get_all_hostnames_as_list(context, 'template1')
print hostlist
file_pattern = 'ls /tmp/%s* | wc -l' % filename_prefix
print file_pattern
for host in hostlist:
cmd = Command(name='check for temp files',
cmdStr=file_pattern,
ctxt=REMOTE,
remoteHost=host)
cmd.run(validateAfter=True)
if int(cmd.get_stdout()) > 0:
raise Exception(
'Temp files with prefix %s are not cleaned up on host %s after gpcrondump' % (filename_prefix, host))
@when('the user activates standby on the standbyhost')
@then('the user activates standby on the standbyhost')
def impl(context):
port = os.environ.get('PGPORT')
cmd = 'PGPORT=%s MASTER_DATA_DIRECTORY=%s gpactivatestandby -d %s -fa' % (port, master_data_dir, master_data_dir)
cmd = Command('run remote command', cmd, ctxt=REMOTE, remoteHost=context.standby_host)
cmd.run(validateAfter=True)
@then('the user runs the command "{cmd}" from standby')
@when('the user runs the command "{cmd}" from standby')
def impl(context, cmd):
port = os.environ.get('PGPORT')
cmd = 'PGPORT=%s MASTER_DATA_DIRECTORY=%s %s' % (port, master_data_dir, cmd)
cmd = Command('run remote command', cmd, ctxt=REMOTE, remoteHost=context.standby_host)
cmd.run(validateAfter=True)
@given('user kills a primary postmaster process')
@when('user kills a primary postmaster process')
@then('user kills a primary postmaster process')
def impl(context):
if hasattr(context, 'pseg'):
seg_data_dir = context.pseg_data_dir
seg_host = context.pseg_hostname
seg_port = context.pseg.getSegmentPort()
else:
gparray = GpArray.initFromCatalog(dbconn.DbURL())
for seg in gparray.getDbList():
if seg.isSegmentPrimary():
seg_data_dir = seg.getSegmentDataDirectory()
seg_host = seg.getSegmentHostName()
seg_port = seg.getSegmentPort()
break
pid = get_pid_for_segment(seg_data_dir, seg_host)
if pid is None:
raise Exception('Unable to locate segment "%s" on host "%s"' % (seg_data_dir, seg_host))
kill_process(int(pid), seg_host, signal.SIGKILL)
has_process_eventually_stopped(pid, seg_host)
pid = get_pid_for_segment(seg_data_dir, seg_host)
if pid is not None:
raise Exception('Unable to kill postmaster with pid "%d" datadir "%s"' % (pid, seg_data_dir))
context.killed_seg_host = seg_host
context.killed_seg_port = seg_port
@when('the temp files "{filename_prefix}" are removed from the system')
@given('the temp files "{filename_prefix}" are removed from the system')
def impl(context, filename_prefix):
hostlist = get_all_hostnames_as_list(context, 'template1')
print hostlist
for host in hostlist:
cmd = Command(name='remove data directories',
cmdStr='rm -rf /tmp/%s*' % filename_prefix,
ctxt=REMOTE,
remoteHost=host)
cmd.run(validateAfter=True)
@given('user can start transactions')
@when('user can start transactions')
@then('user can start transactions')
def impl(context):
num_retries = 150
attempt = 0
while attempt < num_retries:
try:
with dbconn.connect(dbconn.DbURL()) as conn:
break
except Exception as e:
attempt += 1
pass
time.sleep(1)
if attempt == num_retries:
raise Exception('Unable to establish a connection to database !!!')
@when('user runs "{cmd}" with sudo access')
def impl(context, cmd):
gphome = os.environ.get('GPHOME')
python_path = os.environ.get('PYTHONPATH')
python_home = os.environ.get('PYTHONHOME')
ld_library_path = os.environ.get('LD_LIBRARY_PATH')
path = os.environ.get('PATH')
cmd_str = """sudo GPHOME=%s
PATH=%s
PYTHONHOME=%s
PYTHONPATH=%s
LD_LIBRARY_PATH=%s %s/bin/%s""" % (
gphome, path, python_home, python_path, ld_library_path, gphome, cmd)
run_command(context, cmd_str)
def verify_num_files(results, expected_num_files, timestamp):
num_files = results.stdout.strip()
if num_files != expected_num_files:
raise Exception(
'Expected "%s" files with timestamp key "%s" but found "%s"' % (expected_num_files, timestamp, num_files))
def verify_timestamps_on_master(timestamp, dump_type):
list_cmd = 'ls -l %s/db_dumps/%s/*%s* | wc -l' % (master_data_dir, timestamp[:8], timestamp)
cmd = Command('verify timestamps on master', list_cmd)
cmd.run(validateAfter=True)
expected_num_files = '10' if dump_type == 'incremental' else '8'
verify_num_files(cmd.get_results(), expected_num_files, timestamp)
def verify_timestamps_on_segments(timestamp):
gparray = GpArray.initFromCatalog(dbconn.DbURL())
primary_segs = [segdb for segdb in gparray.getDbList() if segdb.isSegmentPrimary()]
for seg in primary_segs:
db_dumps_dir = os.path.join(seg.getSegmentDataDirectory(),
'db_dumps',
timestamp[:8])
list_cmd = 'ls -l %s/*%s* | wc -l' % (db_dumps_dir, timestamp)
cmd = Command('get list of dump files', list_cmd, ctxt=REMOTE, remoteHost=seg.getSegmentHostName())
cmd.run(validateAfter=True)
verify_num_files(cmd.get_results(), '2', timestamp)
@then('verify that "{dump_type}" dump files have stored timestamp in their filename')
def impl(context, dump_type):
if dump_type.strip().lower() != 'full' and dump_type.strip().lower() != 'incremental':
raise Exception('Invalid dump type "%s"' % dump_type)
verify_timestamps_on_master(context.backup_timestamp, dump_type.strip().lower())
verify_timestamps_on_segments(context.backup_timestamp)
def validate_files(file_list, pattern_list, expected_file_count):
file_count = 0
for pattern in pattern_list:
pat = re.compile(pattern)
pat_found = False
for f in file_list:
m = pat.search(f.strip())
if m is not None:
pat_found = True
file_count += 1
if not pat_found:
raise Exception('Expected file not found for pattern: "%s" in file list "%s"' % (pattern, file_list))
if file_count != expected_file_count:
raise Exception('Expected count of %d does not match actual count %d in file list "%s"' % (
expected_file_count, file_count, file_list))
@then('the "{file_type}" file under "{directory}" with options "{options}" is validated after dump operation')
def impl(context, file_type, directory, options):
backup_dir = directory.strip() if directory.strip() != '' else master_data_dir
if len(options.split(',')) > 3:
raise Exception('Invalid options specified "%s"' % options)
option_list = options.split(',')
pipe_file_count = 1 + get_num_segments(primary=True, mirror=False, master=True, standby=False)
reg_file_count = 6
pipes_pattern_list = ['gp_dump_.*_%s.*(?:\.gz)?' % context.backup_timestamp]
regular_pattern_list = ['gp_cdatabase_.*_1_%s' % context.backup_timestamp,
'gp_dump_%s.*' % context.backup_timestamp,
'gp_dump_status_.*_1_%s' % context.backup_timestamp]
if '-G' in option_list:
pipe_file_count += 1
pipes_pattern_list += ['gp_global_.*_1_%s' % context.backup_timestamp]
if '-g' in option_list:
pipe_file_count += get_num_segments(primary=True, mirror=False, master=True, standby=False)
pipes_pattern_list += ['gp_master_config_files_%s.*' % context.backup_timestamp,
'gp_segment_config_files_.*_.*_%s.*' % context.backup_timestamp]
if '--incremental' in option_list:
regular_pattern_list += ['gp_dump_%s.*' % context.full_backup_timestamp]
reg_file_count += 1
if hasattr(context, "dump_prefix"):
if '-t' in option_list or '-T' in option_list:
reg_file_count += 1
for id, p in enumerate(pipes_pattern_list):
pipes_pattern_list[id] = '%s%s' % (context.dump_prefix, p)
for id, p in enumerate(regular_pattern_list):
regular_pattern_list[id] = '%s%s' % (context.dump_prefix, p)
filename = '%s/db_dumps/%s/%sgp_dump_%s_%s' % (
backup_dir, context.backup_timestamp[0:8], context.dump_prefix, context.backup_timestamp, file_type.strip())
with open(filename) as fp:
file_list = fp.readlines()
if file_type == 'pipes':
validate_files(file_list, pipes_pattern_list, pipe_file_count)
elif file_type == 'regular_files':
validate_files(file_list, regular_pattern_list, reg_file_count)
@then('the timestamp key "{timestamp_key}" for gpcrondump is stored')
def impl(context, timestamp_key):
context.backup_timestamp = timestamp_key
@given('the prefix "{prefix}" is stored')
def impl(context, prefix):
context.dump_prefix = prefix + '_'
def get_segment_dump_files(context, dir):
results = []
gparray = GpArray.initFromCatalog(dbconn.DbURL())
primary_segs = [seg for seg in gparray.getDbList() if seg.isSegmentPrimary()]
for seg in primary_segs:
segment_dump_dir = dir.strip() if len(dir.strip()) != 0 else seg.getSegmentDataDirectory()
cmd = Command('check dump files', 'ls %s/db_dumps/%s/*%s*' % (
segment_dump_dir, context.backup_timestamp[0:8], context.backup_timestamp), ctxt=REMOTE,
remoteHost=seg.getSegmentHostName())
cmd.run(validateAfter=False) # because we expect ls to fail
results.append((seg, [os.path.basename(r) for r in cmd.get_stdout().split()]))
return results
@then('the named pipes are created for the timestamp "{timestamp_key}" under "{dir}"')
def impl(context, timestamp_key, dir):
dump_dir = dir if len(dir.strip()) != 0 else master_data_dir
pipes_filename = '%s/db_dumps/%s/gp_dump_%s_pipes' % (dump_dir, timestamp_key[0:8], timestamp_key)
with open(pipes_filename, 'r') as fp:
for f in fp:
(host, filename) = [t.strip() for t in f.split(':')]
cmd_str = 'mkdir -p %s' % os.path.dirname(filename)
cmd = Command('create named pipes directory', cmd_str, ctxt=REMOTE, remoteHost=host)
cmd.run(validateAfter=True)
if int(cmd.get_return_code()) != 0:
raise Exception('Non zero return code during makedirs command')
cmd = Command('create named pipes', 'mkfifo %s' % filename, ctxt=REMOTE, remoteHost=host)
cmd.run(validateAfter=True)
if int(cmd.get_return_code()) != 0:
raise Exception('Non zero return code during mkfifo command')
@then('the named pipes are validated against the timestamp "{timestamp_key}" under "{dir}"')
def impl(context, timestamp_key, dir):
dump_dir = dir if len(dir.strip()) != 0 else master_data_dir
pipes_filename = '%s/db_dumps/%s/gp_dump_%s_pipes' % (dump_dir, timestamp_key[0:8], timestamp_key)
with open(pipes_filename, 'r') as fp:
for f in fp:
(host, filename) = [t.strip() for t in f.split(':')]
cmd = Command('create named pipes', 'file %s' % filename, ctxt=REMOTE, remoteHost=host)
cmd.run(validateAfter=True)
if int(cmd.get_return_code()) != 0:
raise Exception('Non zero return code during mkfifo command')
if not 'named pipe' in cmd.get_stdout():
raise Exception('Expected %s to be a named pipe' % filename)
@when('the named pipe script for the "{operation}" is run for the files under "{dump_directory}"')
@then('the named pipe script for the "{operation}" is run for the files under "{dump_directory}"')
def impl(context, operation, dump_directory):
dump_dir = dump_directory if len(dump_directory.strip()) != 0 else master_data_dir
if operation == 'restore' and hasattr(context, 'inc_backup_timestamps'):
if not hasattr(context, 'backup_timestamp'):
raise Exception('Backup timestamp not stored')
for ts in context.inc_backup_timestamps:
open_named_pipes(context, operation, ts, dump_dir)
else:
open_named_pipes(context, operation, context.backup_timestamp, dump_dir)
@then('close all opened pipes')
def impl(context):
hosts = set(get_all_hostnames_as_list(context, 'template1'))
for h in hosts:
find_cmd = Command('get list of pipe processes',
"ps -eaf | grep _pipe.py | grep -v grep | grep -v ssh",
ctxt=REMOTE,
remoteHost=h)
find_cmd.run()
results = find_cmd.get_stdout().split('\n')
for process in results:
if not process.strip():
continue
pid = process.split()[1].strip()
print 'pid = %s on host %s' % (pid, h)
cmd = Command('Kill pipe process',
"kill %s" % pid,
ctxt=REMOTE,
remoteHost=h)
cmd.run(validateAfter=True)
find_cmd.run() # We expect failure here
results = find_cmd.get_stdout()
if results:
raise Exception('Unexpected pipe processes found "%s"' % results)
def open_named_pipes(context, operation, timestamp, dump_dir):
sleeptime = 5
pipes_filename = '%s/db_dumps/%s/gp_dump_%s_pipes' % (dump_dir, timestamp[0:8], timestamp)
filename = os.path.join(os.getcwd(), './test/data/%s_pipe.py' % operation)
segs = get_all_hostnames_as_list(context, 'template1')
for seg in segs:
cmdStr = "%s -o 'StrictHostKeyChecking no' %s %s:%s" % (findCmdInPath('scp'), filename, seg, '/tmp')
run_command(context, cmdStr)
with open(pipes_filename, 'r') as fp:
for f in fp:
(host, filename) = [t.strip() for t in f.split(':')]
cmd = Command('run pipe script', 'sh -c "python /tmp/%s_pipe.py %s" &>/dev/null &' % (operation, filename),
ctxt=REMOTE, remoteHost=host)
cmd.run(validateAfter=True)
time.sleep(sleeptime)
@given('the core dump directory is stored')
def impl(context):
with open('/etc/sysctl.conf', 'r') as fp:
for line in fp:
if 'kernel.core_pattern' in line:
context.core_dir = os.path.dirname(line.strip().split('=')[1])
if not hasattr(context, 'core_dir') or not context.core_dir:
context.core_dir = os.getcwd()
@given('the number of core files "{stage}" running "{utility}" is stored')
@then('the number of core files "{stage}" running "{utility}" is stored')
def impl(context, stage, utility):
core_files_count = 0
files_list = os.listdir(context.core_dir)
for f in files_list:
if f.startswith('core'):
core_files_count += 1
if stage.strip() == 'before':
context.before_core_count = core_files_count
elif stage.strip() == 'after':
context.after_core_count = core_files_count
else:
raise Exception('Invalid stage entered: %s' % stage)
@then('the number of core files is the same')
def impl(context):
if not hasattr(context, 'before_core_count'):
raise Exception('Core file count not stored before operation')
if not hasattr(context, 'after_core_count'):
raise Exception('Core file count not stored after operation')
if context.before_core_count != context.after_core_count:
raise Exception('Core files count before %s does not match after %s' % (
context.before_core_count, context.after_core_count))
@given('the gpAdminLogs directory has been backed up')
def impl(context):
src = os.path.join(os.path.expanduser('~'), 'gpAdminLogs')
dest = os.path.join(os.path.expanduser('~'), 'gpAdminLogs.bk')
shutil.move(src, dest)
@given('the user does not have "{access}" permission on the home directory')
def impl(context, access):
home_dir = os.path.expanduser('~')
context.orig_write_permission = check_user_permissions(home_dir, 'write')
if access == 'write':
cmd = "sudo chmod u-w %s" % home_dir
run_command(context, cmd)
if check_user_permissions(home_dir, access):
raise Exception('Unable to change "%s" permissions for the directory "%s"' % (access, home_dir))
@then('the "{filetype}" path "{file_path}" should "{cond}" exist')
def impl(context, filetype, file_path, cond):
cond = cond.strip()
if file_path[0] == '~':
file_path = os.path.join(os.path.expanduser('~'), file_path[2:])
if filetype == 'file':
existence_check_fn = os.path.isfile
elif filetype == 'directory':
existence_check_fn = os.path.isdir
else:
raise Exception('File type should be either file or directory')
if cond == '' and not existence_check_fn(file_path):
raise Exception('The %s "%s" does not exist' % (filetype, file_path))
elif cond == 'not' and existence_check_fn(file_path):
raise Exception('The %s "%s" exist' % (filetype, file_path))
@then('the directory "{file_path}" is removed')
def impl(context, file_path):
if file_path[0] == '~':
file_path = os.path.join(os.path.expanduser('~'), file_path[2:])
backup_file_path = file_path + '.bk'
if not os.path.exists(backup_file_path):
raise Exception('Backup file "%s" must exist in order to delete the file "%s"' % (backup_file_path, file_path))
if '*' in file_path:
raise Exception('WildCard found in file path !!!!. Cannot delete')
run_command(context, 'rm -rf %s' % file_path)
@then('there should be dump files under "{directory}" with prefix "{prefix}"')
def impl(context, directory, prefix):
if not hasattr(context, "dump_prefix"):
context.dump_prefix = ''
dump_prefix = '%s_gp' % prefix.strip()
dump_dir = get_dump_dir(context, directory)
segment_dump_files = get_segment_dump_files(context, directory)
if not use_ddboost():
for seg, dump_files in segment_dump_files:
segment_dump_dir = directory if len(directory.strip()) != 0 else seg.getSegmentDataDirectory()
if len(dump_files) == 0:
raise Exception('Failed to find dump files on the segment %s under %s/db_dumps/%s' % (
seg.getSegmentDataDirectory(), segment_dump_dir, context.backup_timestamp[0:8]))
for dump_file in dump_files:
if not dump_file.startswith(dump_prefix):
raise Exception(
'Dump file %s on the segment %s under %s/db_dumps/%s does not start with required prefix %s' % (
dump_file, seg.getSegmentDataDirectory(), segment_dump_dir, context.backup_timestamp[0:8], prefix))
cmd = Command('check dump files',
'ls %s/%s/*%s*' % (dump_dir, context.backup_timestamp[0:8], context.backup_timestamp))
cmd.run(validateAfter=True)
results = cmd.get_stdout().split('\n')
if len(results) == 0:
raise Exception('Failed to find dump files %s on the master under %s' % (results, dump_dir))
for filename in results:
if not os.path.basename(filename).startswith(prefix.strip()):
raise Exception('Dump file %s on master under %s does not have required prefix %s' % (
filename, dump_dir, prefix))
@given('the environment variable "{var}" is not set')
def impl(context, var):
context.env_var = os.environ.get(var)
os.environ[var] = ''
@then('the environment variable "{var}" is reset')
def impl(context, var):
if hasattr(context, 'env_var'):
os.environ[var] = context.env_var
else:
raise Exception('Environment variable %s cannot be reset because its value was not saved.' % var)
@given('the environment variable "{var}" is set to "{val}"')
def impl(context, var, val):
context.env_var = os.environ.get(var)
os.environ[var] = val
@given('the path "{path}" exists')
def impl(context, path):
if not os.path.exists(path):
os.makedirs(path)
@then('the path "{path}" does not exist')
def impl(context, path):
if os.path.exists(path):
shutil.rmtree(path)
@when('the user runs the following query on "{dbname}" without fetching results')
def impl(context, dbname):
query = context.text.strip()
thread.start_new_thread(execute_sql, (dbname, query))
time.sleep(30)
@when('the user runs query from the file "{filename}" on "{dbname}" without fetching results')
def impl(context, filename, dbname):
with open(filename) as fr:
for line in fr:
query = line.strip()
thread.start_new_thread(execute_sql, (dbname, query))
time.sleep(30)
@then('the following text should be printed to stdout')
def impl(context):
check_stdout_msg(context, context.text.strip())
@then('the text in the file "{filename}" should be printed to stdout')
def impl(context, filename):
contents = ''
with open(filename) as fr:
for line in fr:
contents = line.strip()
print "contents: ", contents
check_stdout_msg(context, contents)
@when('the user runs command "{cmd}" on the "{seg_type}" segment')
def impl(context, cmd, seg_type):
if seg_type == 'Change Tracking':
port, host = get_change_tracking_segment_info()
elif seg_type == 'Original':
port, host = context.killed_seg_port, context.killed_seg_host
else:
raise Exception('Invalid segment type "%s" specified' % seg_type)
cmd += ' -p %s -h %s' % (port, host)
run_command(context, cmd)
@given('below sql is executed in "{dbname}" db')
@when('below sql is executed in "{dbname}" db')
def impl(context, dbname):
sql = context.text
execute_sql(dbname, sql)
@when('sql "{sql}" is executed in "{dbname}" db')
@then('sql "{sql}" is executed in "{dbname}" db')
def impl(context, sql, dbname):
execute_sql(dbname, sql)
@when('execute following sql in db "{dbname}" and store result in the context')
def impl(context, dbname):
context.stored_rows = []
with dbconn.connect(dbconn.DbURL(dbname=dbname)) as conn:
curs = dbconn.execSQL(conn, context.text)
context.stored_rows = curs.fetchall()
@when('execute sql "{sql}" in db "{dbname}" and store result in the context')
def impl(context, sql, dbname):
context.stored_rows = []
with dbconn.connect(dbconn.DbURL(dbname=dbname)) as conn:
curs = dbconn.execSQL(conn, sql)
context.stored_rows = curs.fetchall()
@then('validate that "{message}" is in the stored rows')
def impl(context, message):
for row in context.stored_rows:
for column in row:
if message in column:
return
print context.stored_rows
print message
raise Exception("'%s' not found in stored rows" % message)
@then('verify that file "{filename}" exists under "{path}"')
def impl(context, filename, path):
fullpath = "%s/%s" % (path, filename)
fullpath = os.path.expandvars(fullpath)
if not os.path.exists(fullpath):
raise Exception('file "%s" is not exist' % fullpath)
@given('waiting "{second}" seconds')
@when('waiting "{second}" seconds')
@then('waiting "{second}" seconds')
def impl(context, second):
time.sleep(float(second))
def get_opened_files(filename, pidfile):
cmd = "if [ `uname -s` = 'SunOS' ]; then CMD=pfiles; else CMD='lsof -p'; fi && PATH=$PATH:/usr/bin:/usr/sbin $CMD `cat %s` | grep %s | wc -l" % (
pidfile, filename)
return commands.getstatusoutput(cmd)
@then('the file "{filename}" by process "{pidfile}" is not closed')
def impl(context, filename, pidfile):
(ret, output) = get_opened_files(filename, pidfile)
if int(output) == 0:
raise Exception('file %s has been closed' % (filename))
@then('the file "{filename}" by process "{pidfile}" is closed')
def impl(context, filename, pidfile):
(ret, output) = get_opened_files(filename, pidfile)
if int(output) != 0:
raise Exception('file %s has not been closed' % (filename))
@then('the file "{filename}" by process "{pidfile}" opened number is "{num}"')
def impl(context, filename, pidfile, num):
(ret, output) = get_opened_files(filename, pidfile)
if int(output) != int(num):
raise Exception('file %s opened number %d is not %d' % (filename, int(output), int(num)))
@given('the directory {path} exists')
@then('the directory {path} exists')
def impl(context, path):
if not os.path.isdir(path):
raise Exception('Directory "%s" does not exist' % path)
@then('{file} should be found in tarball with prefix "{prefix}" within directory {path}')
def impl(context, file, prefix, path):
## look for subdirectory created during collection
collection_dirlist = os.listdir(path)
if len(collection_dirlist) > 1:
raise Exception('more then one data collection directory found.')
if len(collection_dirlist) == 0:
raise Exception('Collection directory was not found')
## get a listing of files in the subdirectory and make sure there is only one tarball found
tarpath = os.path.join(path, collection_dirlist[0])
collection_filelist = os.listdir(tarpath)
if len(collection_filelist) > 1:
raise Exception('Too many files found in "%s"' % tarpath)
if len(collection_filelist) == 0:
raise Exception('No files found in "%s"' % tarpath)
## Expand tarball with prefix "GP_LOG_COLLECTION_" and search for given file within collection
if prefix in collection_filelist[0]:
## extract the root tarball
tar = tarfile.open(os.path.join(tarpath, collection_filelist[0]), "r:")
tar.extractall(tarpath)
tar.close()
FOUND = False
for tfile in os.listdir(tarpath):
if prefix in tfile:
continue
## Find any tar file that contain given file
segtar = tarfile.open(os.path.join(tarpath, tfile), "r:gz")
for tarinfo in segtar:
if tarinfo.isreg() and file in tarinfo.name:
FOUND = True
segtar.close()
break ## break segtar loop
if FOUND:
return ## we found the file so pass the test case
else:
## the file should have been found in the first segment tarball
raise Exception('Unable to find "%s" in "%s" tar file' % (file, collection_filelist[0]))
else:
raise Exception('tarball with prefix "%s" was not found' % prefix)
@given('the directory {path} is removed or does not exist')
@when('the directory {path} is removed or does not exist')
@then('the directory {path} is removed or does not exist')
def impl(context, path):
if '*' in path:
raise Exception('Wildcard not supported')
if path[0] == '~':
path = os.path.join(os.path.expanduser('~'), path[2:])
run_command(context, 'rm -rf %s' % path)
@given('the user runs sbin command "{cmd}"')
@when('the user runs sbin command "{cmd}"')
@then('the user runs sbin command "{cmd}"')
def impl(context, cmd):
gpsbin = os.path.join(os.environ.get('GPHOME'), 'sbin')
if not os.path.isdir(gpsbin):
raise Exception('ERROR: GPHOME not set in environment')
cmd = gpsbin + "/" + cmd ## don't us os.path join because command might have arguments
run_command(context, cmd)
@given('the OS type is not "{os_type}"')
def impl(context, os_type):
assert platform.system() != os_type
@then('{file1} and {file2} should exist and have a new mtime')
def impl(context, file1, file2):
gphome = os.environ.get('GPHOME')
if not os.path.isfile(os.path.join(gphome, file1)) or not os.path.isfile(os.path.join(gphome, file2)):
raise Exception(
'installation of ' + context.utility + ' failed because one or more files do not exist in ' + os.path.join(
gphome, file1))
file1_mtime = os.path.getmtime(os.path.join(gphome, file1))
file2_mtime = os.path.getmtime(os.path.join(gphome, file2))
if file1_mtime < context.currenttime or file2_mtime < context.currenttime:
raise Exception('one or both file mtime was not updated')
os.chdir(context.cwd)
run_command(context, 'rm -rf %s' % context.path)
@given('you are about to run a database query')
@when('you are about to run a database query')
@then('you are about to run a database query')
def impl(context):
context.sessionID = []
@given('the user ran this query "{query}" against database "{dbname}" for table "{table}" and it hangs')
@when('the user ran this query "{query}" against database "{dbname}" for table "{table}" and it hangs')
def impl(context, query, dbname, table):
get_sessionID_query = "SELECT sess_id FROM pg_stat_activity WHERE current_query ~ '" + table + "' AND current_query !~ 'pg_stat_activity'"
if not check_db_exists(dbname):
raise Exception('The database ' + dbname + 'Does not exist')
thread.start_new_thread(getRows, (dbname, query))
time.sleep(15)
context.sessionIDRow = getRows(dbname, get_sessionID_query)
if len(context.sessionIDRow) == 0:
raise Exception('Was not able to determine the session ID')
context.sessionID.append(context.sessionIDRow[0][0])
@then('user runs "{command}" against the queries session ID')
def impl(context, command):
## build the session_list
session_list = None
for session in context.sessionID:
if not session_list:
session_list = str(session)
else:
session_list = session_list + ',' + str(session)
command += " " + session_list
run_gpcommand(context, command)
@then('{file} file with queries sessionIDs should be found within directory {path}')
def impl(context, file, path):
######################################################################################
## This function needs to be modified.. changes are pending hung_analyzer revisions ##
######################################################################################
## look for subdirectory created during collection
collection_dirlist = os.listdir(path)
if len(collection_dirlist) > 1:
raise Exception(
'more then one data collection directory found. Possibly left over from a previous run of hung analyzer')
if len(collection_dirlist) == 0:
raise Exception('Collection directory was not found')
## Make sure we have a core file for each session
sessions_found = 0
for rootdir, dirs, files in os.walk(os.path.join(path, collection_dirlist[0])):
for session in context.sessionID:
for f in files:
core_prefix = file + str(session) + '.'
if core_prefix in f:
sessions_found += 1
break
if sessions_found == 0:
raise Exception('No core files were found in collection')
if sessions_found != len(context.sessionID):
raise Exception('Only ' + str(sessions_found) + ' core files were found out of ' + str(len(context.sessionID)))
@then('{file} file should be found within directory {path}')
def impl(context, file, path):
## look for subdirectory created during collection
collection_dirlist = os.listdir(path)
if len(collection_dirlist) > 1:
raise Exception(
'more then one data collection directory found. Possibly left over from a previous run of hung analyzer')
if len(collection_dirlist) == 0:
raise Exception('Collection directory was not found')
## get a listing of files and dirs and prune until file is found
for rootdir, dirs, files in os.walk(os.path.join(path, collection_dirlist[0])):
for f in files:
if file in f:
return
raise Exception('File was not found in :' + path)
@then('database is restarted to kill the hung query')
def impl(context):
try:
stop_database_if_started(context)
except Exception as e:
context.exception = None
pass ## capture the thread dieing from our hung query
if check_database_is_running(context):
raise Exception('Failed to stop the database')
start_database_if_not_started(context)
if not check_database_is_running():
raise Exception('Failed to start the database')
@then('partition "{partitionnum}" is added to partition table "{tablename}" in "{dbname}"')
def impl(context, partitionnum, tablename, dbname):
add_partition(context, partitionnum, tablename, dbname)
@then('partition "{partitionnum}" is dropped from partition table "{tablename}" in "{dbname}"')
def impl(context, partitionnum, tablename, dbname):
drop_partition(context, partitionnum, tablename, dbname)
@when('table "{tablename}" is dropped in "{dbname}"')
@then('table "{tablename}" is dropped in "{dbname}"')
@given('table "{tablename}" is dropped in "{dbname}"')
def impl(context, tablename, dbname):
drop_table_if_exists(context, table_name=tablename, dbname=dbname)
def create_trigger_function(dbname, trigger_func_name, tablename):
trigger_func_sql = """
CREATE OR REPLACE FUNCTION %s() RETURNS TRIGGER AS $$
BEGIN
INSERT INTO %s VALUES(2001, 'backup', '2100-08-23');
END;
$$ LANGUAGE plpgsql
""" % (trigger_func_name, tablename)
execute_sql(dbname, trigger_func_sql)
def create_trigger(dbname, trigger_func_name, trigger_name, tablename):
SQL = """
CREATE TRIGGER %s AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH STATEMENT EXECUTE PROCEDURE %s();
""" % (trigger_name, tablename, trigger_func_name)
execute_sql(dbname, SQL)
@given(
'there is a trigger "{trigger_name}" on table "{tablename}" in "{dbname}" based on function "{trigger_func_name}"')
def impl(context, trigger_name, tablename, dbname, trigger_func_name):
create_trigger_function(dbname, trigger_func_name, tablename)
create_trigger(dbname, trigger_func_name, trigger_name, tablename)
@then('there is a trigger function "{trigger_func_name}" on table "{tablename}" in "{dbname}"')
def impl(context, trigger_func_name, tablename, dbname):
create_trigger_function(dbname, trigger_func_name, tablename)
@when('the index "{index_name}" in "{dbname}" is dropped')
def impl(context, index_name, dbname):
drop_index_sql = """DROP INDEX %s""" % index_name
execute_sql(dbname, drop_index_sql)
@when('the trigger "{trigger_name}" on table "{tablename}" in "{dbname}" is dropped')
def impl(context, trigger_name, tablename, dbname):
drop_trigger_sql = """DROP TRIGGER %s ON %s""" % (trigger_name, tablename)
execute_sql(dbname, drop_trigger_sql)
@given('all the segments are running')
@when('all the segments are running')
@then('all the segments are running')
def impl(context):
if not are_segments_running():
raise Exception("all segments are not currently running")
return
@given('the "{seg}" segment information is saved')
@when('the "{seg}" segment information is saved')
@then('the "{seg}" segment information is saved')
def impl(context, seg):
gparray = GpArray.initFromCatalog(dbconn.DbURL())
if seg == "primary":
primary_segs = [seg for seg in gparray.getDbList() if seg.isSegmentPrimary()]
context.pseg = primary_segs[0]
context.pseg_data_dir = context.pseg.getSegmentDataDirectory()
context.pseg_hostname = context.pseg.getSegmentHostName()
context.pseg_dbid = context.pseg.getSegmentDbId()
elif seg == "mirror":
mirror_segs = [seg for seg in gparray.getDbList() if seg.isSegmentMirror()]
context.mseg = mirror_segs[0]
context.mseg_hostname = context.mseg.getSegmentHostName()
context.mseg_dbid = context.mseg.getSegmentDbId()
context.mseg_data_dir = context.mseg.getSegmentDataDirectory()
@when('we run a sample background script to generate a pid on "{seg}" segment')
def impl(context, seg):
if seg == "primary":
if not hasattr(context, 'pseg_hostname'):
raise Exception("primary seg host is not saved in the context")
hostname = context.pseg_hostname
elif seg == "smdw":
if not hasattr(context, 'standby_host'):
raise Exception("Standby host is not saved in the context")
hostname = context.standby_host
filename = os.path.join(os.getcwd(), './test/behave/mgmt_utils/steps/data/pid_background_script.py')
cmd = Command(name="Remove background script on remote host", cmdStr='rm -f /tmp/pid_background_script.py',
remoteHost=hostname, ctxt=REMOTE)
cmd.run(validateAfter=True)
cmd = Command(name="Copy background script to remote host", cmdStr='scp %s %s:/tmp' % (filename, hostname))
cmd.run(validateAfter=True)
cmd = Command(name="Run Bg process to save pid",
cmdStr='sh -c "python /tmp/pid_background_script.py" &>/dev/null &', remoteHost=hostname, ctxt=REMOTE)
cmd.run(validateAfter=True)
cmd = Command(name="get bg pid", cmdStr="ps ux | grep pid_background_script.py | grep -v grep | awk '{print \$2}'",
remoteHost=hostname, ctxt=REMOTE)
cmd.run(validateAfter=True)
context.bg_pid = cmd.get_stdout()
if not context.bg_pid:
raise Exception("Unable to obtain the pid of the background script. Seg Host: %s, get_results: %s" %
(hostname, cmd.get_stdout()))
@when('the background pid is killed on "{seg}" segment')
@then('the background pid is killed on "{seg}" segment')
def impl(context, seg):
if seg == "primary":
if not hasattr(context, 'pseg_hostname'):
raise Exception("primary seg host is not saved in the context")
hostname = context.pseg_hostname
elif seg == "smdw":
if not hasattr(context, 'standby_host'):
raise Exception("Standby host is not saved in the context")
hostname = context.standby_host
cmd = Command(name="get bg pid", cmdStr="ps ux | grep pid_background_script.py | grep -v grep | awk '{print \$2}'",
remoteHost=hostname, ctxt=REMOTE)
cmd.run(validateAfter=True)
pids = cmd.get_stdout().splitlines()
for pid in pids:
cmd = Command(name="killbg pid", cmdStr='kill -9 %s' % pid, remoteHost=hostname, ctxt=REMOTE)
cmd.run(validateAfter=True)
@when('we generate the postmaster.pid file with the background pid on "{seg}" segment')
def impl(context, seg):
if seg == "primary":
if not hasattr(context, 'pseg_hostname'):
raise Exception("primary seg host is not saved in the context")
hostname = context.pseg_hostname
data_dir = context.pseg_data_dir
elif seg == "smdw":
if not hasattr(context, 'standby_host'):
raise Exception("Standby host is not saved in the context")
hostname = context.standby_host
data_dir = context.standby_host_data_dir
pid_file = os.path.join(data_dir, 'postmaster.pid')
pid_file_orig = pid_file + '.orig'
cmd = Command(name="Copy pid file", cmdStr='cp %s %s' % (pid_file_orig, pid_file), remoteHost=hostname, ctxt=REMOTE)
cmd.run(validateAfter=True)
cpCmd = Command(name='copy pid file to master for editing', cmdStr='scp %s:%s /tmp' % (hostname, pid_file))
cpCmd.run(validateAfter=True)
with open('/tmp/postmaster.pid', 'r') as fr:
lines = fr.readlines()
lines[0] = "%s\n" % context.bg_pid
with open('/tmp/postmaster.pid', 'w') as fw:
fw.writelines(lines)
cpCmd = Command(name='copy pid file to segment after editing',
cmdStr='scp /tmp/postmaster.pid %s:%s' % (hostname, pid_file))
cpCmd.run(validateAfter=True)
@when('we generate the postmaster.pid file with a non running pid on the same "{seg}" segment')
def impl(context, seg):
if seg == "primary":
data_dir = context.pseg_data_dir
hostname = context.pseg_hostname
elif seg == "mirror":
data_dir = context.mseg_data_dir
hostname = context.mseg_hostname
elif seg == "smdw":
if not hasattr(context, 'standby_host'):
raise Exception("Standby host is not saved in the context")
hostname = context.standby_host
data_dir = context.standby_host_data_dir
pid_file = os.path.join(data_dir, 'postmaster.pid')
pid_file_orig = pid_file + '.orig'
cmd = Command(name="Copy pid file", cmdStr='cp %s %s' % (pid_file_orig, pid_file), remoteHost=hostname, ctxt=REMOTE)
cmd.run(validateAfter=True)
cpCmd = Command(name='copy pid file to master for editing', cmdStr='scp %s:%s /tmp' % (hostname, pid_file))
cpCmd.run(validateAfter=True)
# Since Command creates a short-lived SSH session, we observe the PID given
# a throw-away remote process. Assume that the PID is unused and available on
# the remote in the near future.
# This pid is no longer associated with a
# running process and won't be recycled for long enough that tests
# have finished.
cmd = Command(name="get non-existing pid", cmdStr="echo \$\$", remoteHost=hostname, ctxt=REMOTE)
cmd.run(validateAfter=True)
pid = cmd.get_results().stdout.strip()
with open('/tmp/postmaster.pid', 'r') as fr:
lines = fr.readlines()
lines[0] = "%s\n" % pid
with open('/tmp/postmaster.pid', 'w') as fw:
fw.writelines(lines)
cpCmd = Command(name='copy pid file to segment after editing',
cmdStr='scp /tmp/postmaster.pid %s:%s' % (hostname, pid_file))
cpCmd.run(validateAfter=True)
@when('the user starts one "{seg}" segment')
def impl(context, seg):
if seg == "primary":
dbid = context.pseg_dbid
hostname = context.pseg_hostname
segment = context.pseg
elif seg == "mirror":
dbid = context.mseg_dbid
hostname = context.mseg_hostname
segment = context.mseg
segStartCmd = SegmentStart(name="Starting new segment dbid %s on host %s." % (str(dbid), hostname)
, gpdb=segment
, numContentsInCluster=0 # Starting seg on it's own.
, era=None
, mirrormode=MIRROR_MODE_MIRRORLESS
, utilityMode=False
, ctxt=REMOTE
, remoteHost=hostname
, noWait=False
, timeout=300)
segStartCmd.run(validateAfter=True)
@when('the postmaster.pid file on "{seg}" segment is saved')
def impl(context, seg):
if seg == "primary":
data_dir = context.pseg_data_dir
hostname = context.pseg_hostname
elif seg == "mirror":
data_dir = context.mseg_data_dir
hostname = context.mseg_hostname
elif seg == "smdw":
if not hasattr(context, 'standby_host'):
raise Exception("Standby host is not saved in the context")
hostname = context.standby_host
data_dir = context.standby_host_data_dir
pid_file = os.path.join(data_dir, 'postmaster.pid')
pid_file_orig = pid_file + '.orig'
cmd = Command(name="Copy pid file", cmdStr='cp %s %s' % (pid_file, pid_file_orig), remoteHost=hostname, ctxt=REMOTE)
cmd.run(validateAfter=True)
@then('the backup pid file is deleted on "{seg}" segment')
def impl(context, seg):
if seg == "primary":
data_dir = context.pseg_data_dir
hostname = context.pseg_hostname
elif seg == "mirror":
data_dir = context.mseg_data_dir
hostname = context.mseg_hostname
elif seg == "smdw":
data_dir = context.standby_host_data_dir
hostname = context.standby_host
cmd = Command(name="Remove pid file", cmdStr='rm -f %s' % (os.path.join(data_dir, 'postmaster.pid.orig')),
remoteHost=hostname, ctxt=REMOTE)
cmd.run(validateAfter=True)
@given('the user creates an init config file "{to_file}" without mirrors')
@when('the user creates an init config file "{to_file}" without mirrors')
@then('the user creates an init config file "{to_file}" without mirrors')
def impl(context, to_file):
write_lines = []
BLDWRAP_TOP = os.environ.get('BLDWRAP_TOP')
# this file is the output of the pulse system, where gpinit has been run
from_file = BLDWRAP_TOP + '/sys_mgmt_test/test/general/cluster_conf.out'
with open(from_file) as fr:
lines = fr.readlines()
for line in lines:
if not line.startswith('REPLICATION_PORT_BASE') and not line.startswith(
'MIRROR_REPLICATION_PORT_BASE') and not line.startswith('MIRROR_PORT_BASE') and not line.startswith(
'declare -a MIRROR_DATA_DIRECTORY'):
write_lines.append(line)
with open(to_file, 'w+') as fw:
fw.writelines(write_lines)
@given('the user creates mirrors config file "{to_file}"')
@when('the user creates mirrors config file "{to_file}"')
@then('the user creates mirrors config file "{to_file}"')
def impl(context, to_file):
data_dirs = []
BLDWRAP_TOP = os.environ.get('BLDWRAP_TOP')
from_file = BLDWRAP_TOP + '/sys_mgmt_test/test/general/cluster_conf.out'
with open(from_file) as fr:
lines = fr.readlines()
for line in lines:
if line.startswith('declare -a MIRROR_DATA_DIRECTORY'):
data_dirs = line.split('(')[-1].strip().strip(')').split()
break
if not data_dirs:
raise Exception("Could not find MIRROR_DATA_DIRECTORY in config file %s" % from_file)
with open(to_file, 'w+') as fw:
for dir in data_dirs:
fw.write(dir.strip(')') + '\n')
@given('the standby hostname is saved')
@when('the standby hostname is saved')
@then('the standby hostname is saved')
def impl(context):
gparray = GpArray.initFromCatalog(dbconn.DbURL())
primary_segs = [seg for seg in gparray.getDbList() if (seg.isSegmentPrimary() and not seg.isSegmentMaster())]
context.standby = primary_segs[0].getSegmentHostName()
@given('user runs the init command "{cmd}" with the saved standby host')
@when('user runs the init command "{cmd}" with the saved standby host')
@then('user runs the init command "{cmd}" with the saved standby host')
def impl(context, cmd):
run_cmd = cmd + '-s %s' % context.standby
run_cmd.run(validateAfter=True)
@given('there is a sequence "{seq_name}" in "{dbname}"')
def impl(context, seq_name, dbname):
sequence_sql = 'CREATE SEQUENCE %s' % seq_name
execute_sql(dbname, sequence_sql)
@when('the user removes the "{cmd}" command on standby')
@then('the user removes the "{cmd}" command on standby')
def impl(context, cmd):
cmdStr = 'chmod u+rw ~/.bashrc && cp ~/.bashrc ~/.bashrc.backup'
run_cmd = Command('run remote command', cmdStr, ctxt=REMOTE, remoteHost=context.standby_host)
run_cmd.run(validateAfter=True)
cmdStr = """echo >>~/.bashrc && echo "shopt -s expand_aliases" >>~/.bashrc && echo "alias %s='no_command'" >>~/.bashrc""" % cmd
run_cmd = Command('run remote command', cmdStr, ctxt=REMOTE, remoteHost=context.standby_host)
run_cmd.run(validateAfter=True)
@when('the user restores the "{cmd}" command on the standby')
@then('the user restores the "{cmd}" command on the standby')
def impl(context, cmd):
cmdStr = 'cp ~/.bashrc.backup ~/.bashrc'
run_cmd = Command('run remote command', cmdStr, ctxt=REMOTE, remoteHost=context.standby_host)
run_cmd.run(validateAfter=True)
@when('the user stops the syncmaster')
@then('the user stops the syncmaster')
def impl(context):
host = context.gparray.standbyMaster.hostname
# Cat is added because pgrep returns all the processes of the tree, while
# child processes are kill when the parent is kill, which produces an error
cmdStr = 'pgrep syncmaster | xargs -i kill {} | cat'
run_cmd = Command('kill syncmaster', cmdStr, ctxt=REMOTE, remoteHost=host)
run_cmd.run(validateAfter=True)
datadir = context.gparray.standbyMaster.datadir
@when('the user starts the syncmaster')
@then('the user starts the syncmaster')
def impl(context):
host = context.gparray.standbyMaster.hostname
datadir = context.gparray.standbyMaster.datadir
port = context.gparray.standbyMaster.port
dbid = context.gparray.standbyMaster.dbid
ncontents = context.gparray.getNumSegmentContents()
GpStandbyStart.remote('test start syncmaster', host, datadir, port, ncontents, dbid)
@when('save the cluster configuration')
@then('save the cluster configuration')
def impl(context):
context.gparray = GpArray.initFromCatalog(dbconn.DbURL())
@given(
'partition "{partition}" of partition table "{schema_parent}.{table_name}" is assumed to be in schema "{schema_child}" in database "{dbname}"')
@when(
'partition "{partition}" of partition table "{schema_parent}.{table_name}" is assumed to be in schema "{schema_child}" in database "{dbname}"')
@then(
'partition "{partition}" of partition table "{schema_parent}.{table_name}" is assumed to be in schema "{schema_child}" in database "{dbname}"')
def impl(context, partition, schema_parent, table_name, schema_child, dbname):
part_t = get_partition_names(schema_parent.strip(), table_name.strip(), dbname.strip(), 1, partition)
if len(part_t) < 1 or len(part_t[0]) < 1:
print part_t
a_partition_name = part_t[0][0].strip()
alter_sql = """ALTER TABLE %s SET SCHEMA %s""" % (a_partition_name, schema_child)
execute_sql(dbname, alter_sql)
@given('this test sleeps for "{secs}" seconds')
@when('this test sleeps for "{secs}" seconds')
@then('this test sleeps for "{secs}" seconds')
def impl(context, secs):
secs = float(secs)
time.sleep(secs)
@then('verify that there are no duplicates in column "{columnname}" of table "{tablename}" in "{dbname}"')
def impl(context, columnname, tablename, dbname):
duplicate_sql = 'SELECT %s, COUNT(*) FROM %s GROUP BY %s HAVING COUNT(*) > 1' % (columnname, tablename, columnname)
rows = getRows(dbname, duplicate_sql)
if rows:
raise Exception(
'Found duplicate rows in the column "%s" for table "%s" in database "%s"' % (columnname, tablename, dbname))
def execute_sql_for_sec(dbname, query, sec):
with dbconn.connect(dbconn.DbURL(dbname=dbname)) as conn:
dbconn.execSQL(conn, query)
conn.commit()
time.sleep(sec)
@given('the user runs the query "{query}" on "{dbname}" for "{sec}" seconds')
@when('the user runs the query "{query}" on "{dbname}" for "{sec}" seconds')
@then('the user runs the query "{query}" on "{dbname}" for "{sec}" seconds')
def impl(context, query, dbname, sec):
if query.lower().startswith('create') or query.lower().startswith('insert'):
thread.start_new_thread(execute_sql_for_sec, (dbname, query, float(sec)))
else:
thread.start_new_thread(getRows, (dbname, query))
time.sleep(30)
@given('verify that the contents of the files "{expected_filepath}" and "{result_filepath}" are identical')
@when('verify that the contents of the files "{expected_filepath}" and "{result_filepath}" are identical')
@then('verify that the contents of the files "{expected_filepath}" and "{result_filepath}" are identical')
def impl(context, expected_filepath, result_filepath):
diff_files(expected_filepath, result_filepath)
@given('the standby is not initialized')
@then('the standby is not initialized')
def impl(context):
standby = get_standby_host()
if standby:
context.cluster_had_standby = True
context.standby_host = standby
run_gpcommand(context, 'gpinitstandby -ra')
@when('user can "{can_ssh}" ssh locally on standby')
@then('user can "{can_ssh}" ssh locally on standby')
def impl(context, can_ssh):
if not hasattr(context, 'standby_host'):
raise Exception('Standby host not stored in context !')
if can_ssh.strip() == 'not':
cmdStr = 'mv ~/.ssh/authorized_keys ~/.ssh/authorized_keys.bk'
else:
cmdStr = 'mv ~/.ssh/authorized_keys.bk ~/.ssh/authorized_keys'
cmd = Command(name='disable ssh locally', cmdStr=cmdStr,
ctxt=REMOTE, remoteHost=context.standby_host)
cmd.run(validateAfter=True)
@given('all the compression data from "{dbname}" is saved for verification')
def impl(context, dbname):
partitions = get_partition_list('ao', dbname) + get_partition_list('co', dbname)
with open('test/data/compression_{db}_backup'.format(db=dbname), 'w') as fp:
with dbconn.connect(dbconn.DbURL(dbname=dbname)) as conn:
for p in partitions:
query = """SELECT get_ao_compression_ratio('{schema}.{table}')""".format(schema=p[1], table=p[2])
compression_rate = dbconn.execSQLForSingleton(conn, query)
fp.write('{schema}.{table}:{comp}\n'.format(schema=p[1], table=p[2], comp=compression_rate))
@then('verify that the compression ratio of "{table}" in "{dbname}" is good')
def impl(context, table, dbname):
with dbconn.connect(dbconn.DbURL(dbname=dbname)) as conn:
query = """SELECT get_ao_compression_ratio('{table}')""".format(table=table)
compression_rate = dbconn.execSQLForSingleton(conn, query)
found = False
with open('test/data/compression_{db}_backup'.format(db=dbname)) as fp:
for line in fp:
t, c = line.split(':')
if t == table:
if float(c) != compression_rate and float(c) - 0.1 * float(
c) > compression_rate: # 10% more than original compression rate
raise Exception('Expected compression ratio to be greater than or equal to %s but got %s' % (
c, compression_rate))
found = True
if not found:
raise Exception('Compression ratio for table %s was not stored' % table)
@then('verify that the data of tables in "{dbname}" is validated after reload')
def impl(context, dbname):
tbls = get_table_names(dbname)
backed_up_data = []
reloaded_data = []
for t in tbls:
with open('test/data/%s.%s_backup' % (t[0], t[1])) as fp:
for line in fp:
toks = line.split()
backed_up_data.append(
' '.join(toks[1:])) # Ignore the gp_segment_id value since it changes after reload
with dbconn.connect(dbconn.DbURL(dbname=dbname)) as conn:
res = dbconn.execSQL(conn, 'select * from %s.%s' % (t[0], t[1]))
for r in res:
reloaded_data.append(' '.join([str(x) for x in r]))
if sorted(reloaded_data) != sorted(backed_up_data):
raise Exception('Data does not match for table %s.%s' % (t[0], t[1]))
@given('the schemas "{schema_list}" do not exist in "{dbname}"')
@then('the schemas "{schema_list}" do not exist in "{dbname}"')
def impl(context, schema_list, dbname):
schemas = [s.strip() for s in schema_list.split(',')]
for s in schemas:
drop_schema_if_exists(context, s.strip(), dbname)
@then('verify that the schema "{schema_name}" exists in "{dbname}"')
def impl(context, schema_name, dbname):
schema_exists = check_schema_exists(context, schema_name, dbname)
if not schema_exists:
raise Exception("Schema '%s' does not exist in the database '%s'" % (schema_name, dbname))
def get_log_name(utilname, logdir):
today = datetime.now()
logname = "%s/%s_%s.log" % (logdir, utilname, today.strftime('%Y%m%d'))
return logname
@then('verify that a log was created by {utilname} in the user\'s "{dirname}" directory')
def impl(context, utilname, dirname):
absdirname = "%s/%s" % (os.path.expanduser("~"), dirname)
if not os.path.exists(absdirname):
raise Exception('No such directory: %s' % absdirname)
logname = get_log_name(utilname, absdirname)
if not os.path.exists(logname):
raise Exception('Log "%s" was not created' % logname)
@then('verify that a log was created by {utilname} in the "{dirname}" directory')
def impl(context, utilname, dirname):
if not os.path.exists(dirname):
raise Exception('No such directory: %s' % dirname)
logname = get_log_name(utilname, dirname)
if not os.path.exists(logname):
raise Exception('Log "%s" was not created' % logname)
@given('a table is created containing rows of length "{length}" with connection "{dbconn}"')
def impl(context, length, dbconn):
length = int(length)
wide_row_file = 'test/behave/mgmt_utils/steps/data/gptransfer/wide_row_%s.sql' % length
tablename = 'public.wide_row_%s' % length
entry = "x" * length
with open(wide_row_file, 'w') as sql_file:
sql_file.write("CREATE TABLE %s (a integer, b text);\n" % tablename)
for i in range(10):
sql_file.write("INSERT INTO %s VALUES (%d, \'%s\');\n" % (tablename, i, entry))
command = '%s -f %s' % (dbconn, wide_row_file)
run_gpcommand(context, command)
@then('drop the table "{tablename}" with connection "{dbconn}"')
def impl(context, tablename, dbconn):
command = "%s -c \'drop table if exists %s\'" % (dbconn, tablename)
run_gpcommand(context, command)
# gptransfer must be run in verbose mode (-v) with default log location when using this step
@then('verify that gptransfer has a sub batch size of "{num}"')
def impl(context, num):
num = int(num)
log_dir = _get_gpAdminLogs_directory()
if not os.path.exists(log_dir):
raise Exception('No such directory: %s' % log_dir)
log_name = get_log_name('gptransfer', log_dir)
full_path = os.path.join(log_dir, log_name)
if not os.path.isfile(full_path):
raise Exception("Can not find file: %s" % full_path)
# todo why open file if we don't care about contents?
with open(full_path) as fd:
fd.read()
for i in range(num):
worker = "\[DEBUG\]:-\[worker%d\]" % i
try:
check_stdout_msg(context, worker)
except:
raise Exception("gptransfer sub batch size should be %d, is %d" % (num, i))
worker = "\[DEBUG\]:-\[worker%d\]" % num
try:
check_string_not_present_stdout(context, worker)
except:
raise Exception("gptransfer sub batch size should be %d, is at least %d" % (num, num + 1))
def _get_gpAdminLogs_directory():
return "%s/gpAdminLogs" % os.path.expanduser("~")
# Read in a full map file, remove the first host, print it to a new file
@given('an incomplete map file is created')
def impl(context):
map_file = os.environ['GPTRANSFER_MAP_FILE']
contents = []
with open(map_file, 'r') as fd:
contents = fd.readlines()
with open('/tmp/incomplete_map_file', 'w') as fd:
for line in contents[1:]:
fd.write(line)
@given(
'there is a table "{table_name}" dependent on function "{func_name}" in database "{dbname}" on the source system')
def impl(context, table_name, func_name, dbname):
dbconn = 'psql -d %s -p $GPTRANSFER_SOURCE_PORT -U $GPTRANSFER_SOURCE_USER -h $GPTRANSFER_SOURCE_HOST' % dbname
SQL = """CREATE TABLE %s (num integer); CREATE FUNCTION %s (integer) RETURNS integer AS 'select abs(\$1);' LANGUAGE SQL IMMUTABLE; CREATE INDEX test_index ON %s (%s(num))""" % (
table_name, func_name, table_name, func_name)
command = '%s -c "%s"' % (dbconn, SQL)
run_command(context, command)
@then(
'the function-dependent table "{table_name}" and the function "{func_name}" in database "{dbname}" are dropped on the source system')
def impl(context, table_name, func_name, dbname):
dbconn = 'psql -d %s -p $GPTRANSFER_SOURCE_PORT -U $GPTRANSFER_SOURCE_USER -h $GPTRANSFER_SOURCE_HOST' % dbname
SQL = """DROP TABLE %s; DROP FUNCTION %s(integer);""" % (table_name, func_name)
command = '%s -c "%s"' % (dbconn, SQL)
run_command(context, command)
@then('verify that function "{func_name}" exists in database "{dbname}"')
def impl(context, func_name, dbname):
SQL = """SELECT proname FROM pg_proc WHERE proname = '%s';""" % func_name
row_count = getRows(dbname, SQL)[0][0]
if row_count != 'test_function':
raise Exception('Function %s does not exist in %s"' % (func_name, dbname))
@when('the user runs the query "{query}" in database "{dbname}" and sends the output to "{filename}"')
def impl(context, query, dbname, filename):
cmd = "psql -d %s -p $GPTRANSFER_DEST_PORT -U $GPTRANSFER_DEST_USER -c '\copy (%s) to %s'" % (
dbname, query, filename)
thread.start_new_thread(run_gpcommand, (context, cmd))
time.sleep(10)
@given('the user runs the command "{cmd}" in the background')
@when('the user runs the command "{cmd}" in the background')
def impl(context, cmd):
thread.start_new_thread(run_command, (context, cmd))
time.sleep(10)
@given('the user runs the command "{cmd}" in the background without sleep')
@when('the user runs the command "{cmd}" in the background without sleep')
def impl(context, cmd):
thread.start_new_thread(run_command, (context, cmd))
@then('verify that the file "{filename}" contains the string "{output}"')
def impl(context, filename, output):
contents = ''
with open(filename) as fr:
for line in fr:
contents = line.strip()
print contents
check_stdout_msg(context, output)
@then('verify that the last line of the file "{filename}" in the master data directory contains the string "{output}"')
def impl(context, filename, output):
contents = ''
file_path = os.path.join(master_data_dir, filename)
with open(file_path) as fr:
for line in fr:
contents = line.strip()
pat = re.compile(output)
if not pat.search(contents):
err_str = "Expected stdout string '%s' and found: '%s'" % (output, contents)
raise Exception(err_str)
@then('the user waits for "{process_name}" to finish running')
def impl(context, process_name):
run_command(context, "ps ux | grep `which %s` | grep -v grep | awk '{print $2}' | xargs" % process_name)
pids = context.stdout_message.split()
while len(pids) > 0:
for pid in pids:
try:
os.kill(int(pid), 0)
except OSError:
pids.remove(pid)
time.sleep(10)
@given('the gpfdists occupying port {port} on host "{hostfile}"')
def impl(context, port, hostfile):
remote_gphome = os.environ.get('GPHOME')
gp_source_file = os.path.join(remote_gphome, 'greenplum_path.sh')
source_map_file = os.environ.get(hostfile)
dir = '/tmp'
ctxt = 2
with open(source_map_file, 'r') as f:
for line in f:
host = line.strip().split(',')[0]
if host in ('localhost', '127.0.0.1', socket.gethostname()):
ctxt = 1
gpfdist = Gpfdist('gpfdist on host %s' % host, dir, port, os.path.join('/tmp', 'gpfdist.pid'),
ctxt, host, gp_source_file)
gpfdist.startGpfdist()
@then('the gpfdists running on port {port} get cleaned up from host "{hostfile}"')
def impl(context, port, hostfile):
remote_gphome = os.environ.get('GPHOME')
gp_source_file = os.path.join(remote_gphome, 'greenplum_path.sh')
source_map_file = os.environ.get(hostfile)
dir = '/tmp'
ctxt = 2
with open(source_map_file, 'r') as f:
for line in f:
host = line.strip().split(',')[0]
if host in ('localhost', '127.0.0.1', socket.gethostname()):
ctxt = 1
gpfdist = Gpfdist('gpfdist on host %s' % host, dir, port, os.path.join('/tmp', 'gpfdist.pid'),
ctxt, host, gp_source_file)
gpfdist.cleanupGpfdist()
@when('verify that db_dumps directory does not exist in master or segments')
@then('verify that db_dumps directory does not exist in master or segments')
def impl(context):
check_dump_dir_exists(context, 'template1')
@when('verify that the restored table "{table_name}" in database "{dbname}" is analyzed')
@then('verify that the restored table "{table_name}" in database "{dbname}" is analyzed')
def impl(context, table_name, dbname):
if verify_restored_table_is_analyzed(context, table_name, dbname) is not True:
raise Exception("The restored table \'%s\' of database \'%s\' is not analyzed" % (table_name, dbname))
@when('verify that the table "{table_name}" in database "{dbname}" is not analyzed')
@then('verify that the table "{table_name}" in database "{dbname}" is not analyzed')
def impl(context, table_name, dbname):
if (verify_restored_table_is_analyzed(context, table_name, dbname)):
raise Exception("The restored table \'%s\' of database \'%s\' is analyzed" % (table_name, dbname))
@given('the database "{dbname}" is analyzed')
def impl(context, dbname):
analyze_database(context, dbname)
@when('the user deletes rows from the table "{table_name}" of database "{dbname}" where "{column_name}" is "{info}"')
@then('the user deletes rows from the table "{table_name}" of database "{dbname}" where "{column_name}" is "{info}"')
def impl(context, dbname, table_name, column_name, info):
delete_rows_from_table(context, dbname, table_name, column_name, info)
@then('verify that the query "{query}" in database "{dbname}" returns "{nrows}"')
def impl(context, dbname, query, nrows):
check_count_for_specific_query(dbname, query, int(nrows))
@then('verify that the file "{filepath}" contains "{line}"')
def impl(context, filepath, line):
filepath = glob.glob(filepath)[0]
if line not in open(filepath).read():
raise Exception("The file '%s' does not contain '%s'" % (filepath, line))
@then('verify that the file "{filepath}" does not contain "{line}"')
def impl(context, filepath, line):
filepath = glob.glob(filepath)[0]
if line in open(filepath).read():
raise Exception("The file '%s' does contain '%s'" % (filepath, line))
@then('verify that gptransfer is in order of "{filepath}" when partition transfer is "{is_partition_transfer}"')
def impl(context, filepath, is_partition_transfer):
with open(filepath) as f:
table = f.read().splitlines()
if is_partition_transfer != "None":
table = [x.split(',')[0] for x in table]
split_message = re.findall("Starting transfer of.*\n", context.stdout_message)
if len(split_message) == 0 and len(table) != 0:
raise Exception("There were no tables transfered")
counter_table = 0
counter_split = 0
found = 0
while counter_table < len(table) and counter_split < len(split_message):
for i in range(counter_split, len(split_message)):
pat = table[counter_table] + " to"
prog = re.compile(pat)
res = prog.search(split_message[i])
if not res:
counter_table += 1
break
else:
found += 1
counter_split += 1
if found != len(split_message):
raise Exception("expected to find %s tables in order and only found %s in order" % (len(split_message), found))
@given('database "{dbname}" is dropped and recreated')
@when('database "{dbname}" is dropped and recreated')
@then('database "{dbname}" is dropped and recreated')
def impl(context, dbname):
drop_database_if_exists(context, dbname)
create_database(context, dbname)
@given('the user runs the query "{query}" on "{dbname}" in the background until stopped')
@when('the user runs the query "{query}" on "{dbname}" in the background until stopped')
@then('the user runs the query "{query}" on "{dbname}" in the background until stopped')
def impl(context, query, dbname):
thread.start_new_thread(execute_sql_until_stopped, (context, dbname, query))
def execute_sql_until_stopped(context, dbname, query):
with dbconn.connect(dbconn.DbURL(dbname=dbname)) as conn:
dbconn.execSQL(conn, query)
conn.commit()
while True:
if hasattr(context, 'background_query_lock'):
break
time.sleep(1)
@when('the user stops all background queries')
@then('the user stops all background queries')
def impl(context):
context.background_query_lock = True
@given('the backup test is initialized with no backup files')
def impl(context):
context.execute_steps(u'''
Given the database is running
And database "bkdb" is dropped and recreated
And there are no backup files
And the backup files in "/tmp" are deleted
And the DDBoost dump directory is deleted for the "local" storage unit
And the DDBoost dump directory is deleted for the "remote" storage unit
''')
@given('the backup test is initialized with database "{dbname}"')
def impl(context, dbname):
context.execute_steps(u'''
Given the database is running
And database "%s" is dropped and recreated
''' % dbname)
@given('the backup test is initialized for special characters')
def impl(context):
os.environ["SP_CHAR_DB"] = """ DB`~@#$%^&*()_-+[{]}|\;: \\'/?><;1 """
os.environ["SP_CHAR_SCHEMA"] = """ S`~@#$%^&*()-+[{]}|\;: \\'"/?><1 """
os.environ["SP_CHAR_SCHEMA2"] = """ S`~@#$%^&*()_-+[{]}|\;: \\'"/?><2 """
os.environ["SP_CHAR_HEAP"] = """ heap_T`~@#$%^&*()-+[{]}|\;: \\'"/?><1 """
os.environ["SP_CHAR_AO"] = """ ao_T`~@#$%^&*()-+[{]}|\;: \\'"/?><1 """
os.environ["SP_CHAR_CO"] = """ co_T`~@#$%^&*()-+[{]}|\;: \\'"/?><1 """
context.execute_steps(u'''
Given the database is running
And the user runs "psql -f test/behave/mgmt_utils/steps/data/special_chars/create_special_database.sql template1"
And the user runs "psql -f test/behave/mgmt_utils/steps/data/special_chars/create_special_schema.sql template1"
And the user runs "psql -f test/behave/mgmt_utils/steps/data/special_chars/create_special_table.sql template1"
And the user runs "psql -f test/behave/mgmt_utils/steps/data/special_chars/insert_into_special_table.sql template1"
''')
@then('validate and run gpcheckcat repair')
def impl(context):
context.execute_steps(u'''
Then gpcheckcat should print "repair script\(s\) generated in dir gpcheckcat.repair.*" to stdout
Then the path "gpcheckcat.repair.*" is found in cwd "1" times
Then run all the repair scripts in the dir "gpcheckcat.repair.*"
And the path "gpcheckcat.repair.*" is removed from current working directory
''')
@given('there is a "{tabletype}" table "{tablename}" in "{dbname}" with data')
@then('there is a "{tabletype}" table "{tablename}" in "{dbname}" with data')
@when('there is a "{tabletype}" table "{tablename}" in "{dbname}" with data')
def impl(context, tabletype, tablename, dbname):
populate_regular_table_data(context, tabletype, tablename, 'None', dbname, with_data=True)
@given(
'there is a "{tabletype}" table "{table_name}" with compression "{compression_type}" in "{dbname}" with data and {rowcount} rows')
@when(
'there is a "{tabletype}" table "{table_name}" with compression "{compression_type}" in "{dbname}" with data and {rowcount} rows')
@then(
'there is a "{tabletype}" table "{table_name}" with compression "{compression_type}" in "{dbname}" with data and {rowcount} rows')
def impl(context, tabletype, table_name, compression_type, dbname, rowcount):
populate_regular_table_data(context, tabletype, table_name, compression_type, dbname, int(rowcount))
@given('there is a "{tabletype}" partition table "{table_name}" in "{dbname}" with data')
@then('there is a "{tabletype}" partition table "{table_name}" in "{dbname}" with data')
@when('there is a "{tabletype}" partition table "{table_name}" in "{dbname}" with data')
def impl(context, tabletype, table_name, dbname):
create_partition(context, tablename=table_name, storage_type=tabletype, dbname=dbname, with_data=True)
@then('read pid from file "{filename}" and kill the process')
@when('read pid from file "{filename}" and kill the process')
@given('read pid from file "{filename}" and kill the process')
def impl(context, filename):
with open(filename) as fr:
pid = fr.readline().strip()
if not pid:
raise Exception("process id '%s' not found in the file '%s'" % (pid, filename))
cmd = Command(name="killing pid", cmdStr='kill -9 %s' % pid)
cmd.run(validateAfter=True)
@then('an attribute of table "{table}" in database "{dbname}" is deleted on segment with content id "{segid}"')
def impl(context, table, dbname, segid):
local_cmd = 'psql %s -t -c "SELECT port,hostname FROM gp_segment_configuration WHERE content=%s and role=\'p\';"' % (
dbname, segid)
run_command(context, local_cmd)
port, host = context.stdout_message.split("|")
port = port.strip()
host = host.strip()
user = os.environ.get('USER')
source_file = os.path.join(os.environ.get('GPHOME'), 'greenplum_path.sh')
# Yes, the below line is ugly. It looks much uglier when done with separate strings, given the multiple levels of escaping required.
remote_cmd = """
ssh %s "source %s; export PGUSER=%s; export PGPORT=%s; export PGOPTIONS=\\\"-c gp_session_role=utility\\\"; psql -d %s -c \\\"SET allow_system_table_mods=\'dml\'; DELETE FROM pg_attribute where attrelid=\'%s\'::regclass::oid;\\\""
""" % (host, source_file, user, port, dbname, table)
run_command(context, remote_cmd.strip())
@then('The user runs sql "{query}" in "{dbname}" on first primary segment')
@when('The user runs sql "{query}" in "{dbname}" on first primary segment')
@given('The user runs sql "{query}" in "{dbname}" on first primary segment')
def impl(context, query, dbname):
host, port = get_primary_segment_host_port()
psql_cmd = "PGDATABASE=\'%s\' PGOPTIONS=\'-c gp_session_role=utility\' psql -h %s -p %s -c \"%s\"; " % (
dbname, host, port, query)
Command(name='Running Remote command: %s' % psql_cmd, cmdStr=psql_cmd).run(validateAfter=True)
@then('The user runs sql file "{file}" in "{dbname}" on all the segments')
@when('The user runs sql file "{file}" in "{dbname}" on all the segments')
@given('The user runs sql file "{file}" in "{dbname}" on all the segments')
def impl(context, file, dbname):
with open(file) as fd:
query = fd.read().strip()
gparray = GpArray.initFromCatalog(dbconn.DbURL())
segments = gparray.getDbList()
for seg in segments:
host = seg.getSegmentHostName()
if seg.isSegmentPrimary() or seg.isSegmentMaster():
port = seg.getSegmentPort()
psql_cmd = "PGDATABASE=\'%s\' PGOPTIONS=\'-c gp_session_role=utility\' psql -h %s -p %s -c \"%s\"; " % (
dbname, host, port, query)
Command(name='Running Remote command: %s' % psql_cmd, cmdStr=psql_cmd).run(validateAfter=True)
@then('The path "{path}" is removed from current working directory')
@when('The path "{path}" is removed from current working directory')
@given('The path "{path}" is removed from current working directory')
def impl(context, path):
remove_local_path(path)
@given('the path "{path}" is found in cwd "{num}" times')
@then('the path "{path}" is found in cwd "{num}" times')
@when('the path "{path}" is found in cwd "{num}" times')
def impl(context, path, num):
result = validate_local_path(path)
if result != int(num):
raise Exception("expected %s items but found %s items in path %s" % (num, result, path))
@then('run all the repair scripts in the dir "{dir}"')
def impl(context, dir):
command = "cd {0} ; for i in *.sh ; do bash $i; done".format(dir)
run_command(context, command)
@when(
'the entry for the table "{user_table}" is removed from "{catalog_table}" with key "{primary_key}" in the database "{db_name}"')
def impl(context, user_table, catalog_table, primary_key, db_name):
delete_qry = "delete from %s where %s='%s'::regclass::oid;" % (catalog_table, primary_key, user_table)
with dbconn.connect(dbconn.DbURL(dbname=db_name)) as conn:
for qry in ["set allow_system_table_mods='dml';", "set allow_segment_dml=true;", delete_qry]:
dbconn.execSQL(conn, qry)
conn.commit()
@when('the entry for the table "{user_table}" is removed from "{catalog_table}" with key "{primary_key}" in the database "{db_name}" on the first primary segment')
@given('the entry for the table "{user_table}" is removed from "{catalog_table}" with key "{primary_key}" in the database "{db_name}" on the first primary segment')
def impl(context, user_table, catalog_table, primary_key, db_name):
host, port = get_primary_segment_host_port()
delete_qry = "delete from %s where %s='%s'::regclass::oid;" % (catalog_table, primary_key, user_table)
with dbconn.connect(dbconn.DbURL(dbname=db_name, port=port, hostname=host), utility=True,
allowSystemTableMods='dml') as conn:
for qry in [delete_qry]:
dbconn.execSQL(conn, qry)
conn.commit()
@given('the timestamps in the repair dir are consistent')
@when('the timestamps in the repair dir are consistent')
@then('the timestamps in the repair dir are consistent')
def impl(_):
repair_regex = "gpcheckcat.repair.*"
timestamp = ""
repair_dir = ""
for file in os.listdir('.'):
if fnmatch.fnmatch(file, repair_regex):
repair_dir = file
timestamp = repair_dir.split('.')[2]
if not timestamp:
raise Exception("Timestamp was not found")
for file in os.listdir(repair_dir):
if not timestamp in file:
raise Exception("file found containing inconsistent timestamp")
@when('user kills a mirror process with the saved information')
def impl(context):
cmdStr = "ps ux | grep '[m]irror process' | grep %s | awk '{print $2}'" % context.mirror_port
cmd = Command(name='get mirror pid: %s' % cmdStr, cmdStr=cmdStr)
cmd.run()
pid = cmd.get_stdout_lines()[0]
kill_process(int(pid), context.mirror_segdbname, sig=signal.SIGABRT)
@when('user temporarily moves the data directory of the killed mirror')
@then('user temporarily moves the data directory of the killed mirror')
def impl(context):
rmStr = "mv %s{,.bk}" % context.mirror_datadir
cmd = Command(name='Move mirror data directory', cmdStr=rmStr)
cmd.run(validateAfter=True)
@when('user returns the data directory to the default location of the killed mirror')
@then('user returns the data directory to the default location of the killed mirror')
def impl(context):
rmStr = "mv %s{.bk,}" % context.mirror_datadir
cmd = Command(name='Move mirror data directory', cmdStr=rmStr)
cmd.run(validateAfter=True)
@when('wait until the mirror is down')
@then('wait until the mirror is down')
@given('wait until the mirror is down')
def impl(context):
qry = "select status from gp_segment_configuration where dbid='%s' and status='d' " % context.mirror_segdbId
start_time = current_time = datetime.now()
while (current_time - start_time).seconds < 120:
row_count = len(getRows('template1', qry))
if row_count == 1:
break
time.sleep(5)
current_time = datetime.now()
@when('wait until the process "{proc}" goes down')
@then('wait until the process "{proc}" goes down')
@given('wait until the process "{proc}" goes down')
def impl(context, proc):
is_stopped = has_process_eventually_stopped(proc)
context.ret_code = 0 if is_stopped else 1
if not is_stopped:
context.error_message = 'The process %s is still running after waiting' % proc
check_return_code(context, 0)
@when('wait until the process "{proc}" is up')
@then('wait until the process "{proc}" is up')
@given('wait until the process "{proc}" is up')
def impl(context, proc):
cmd = Command(name='pgrep for %s' % proc, cmdStr="pgrep %s" % proc)
start_time = current_time = datetime.now()
while (current_time - start_time).seconds < 120:
cmd.run()
if cmd.get_return_code() > 1:
raise Exception("unexpected problem with gprep, return code: %s" % cmd.get_return_code())
if cmd.get_return_code() != 1: # 0 means match
break
time.sleep(2)
current_time = datetime.now()
context.ret_code = cmd.get_return_code()
context.error_message = ''
if context.ret_code > 1:
context.error_message = 'pgrep internal error'
check_return_code(context, 0) # 0 means one or more processes were matched
@when('wait until the results from boolean sql "{sql}" is "{boolean}"')
@then('wait until the results from boolean sql "{sql}" is "{boolean}"')
@given('wait until the results from boolean sql "{sql}" is "{boolean}"')
def impl(context, sql, boolean):
cmd = Command(name='psql', cmdStr='psql --tuples-only -d gpperfmon -c "%s"' % sql)
start_time = current_time = datetime.now()
result = None
while (current_time - start_time).seconds < 120:
cmd.run()
if cmd.get_return_code() != 0:
break
result = cmd.get_stdout()
if _str2bool(result) == _str2bool(boolean):
break
time.sleep(2)
current_time = datetime.now()
if cmd.get_return_code() != 0:
context.ret_code = cmd.get_return_code()
context.error_message = 'psql internal error: %s' % cmd.get_stderr()
check_return_code(context, 0)
else:
if _str2bool(result) != _str2bool(boolean):
raise Exception("sql output '%s' is not same as '%s'" % (result, boolean))
def _str2bool(string):
return string.lower().strip() in ['t', 'true', '1', 'yes', 'y']
@when('run gppersistent_rebuild with the saved content id')
@then('run gppersistent_rebuild with the saved content id')
def impl(context):
cmdStr = "echo -e 'y\ny\n' | $GPHOME/sbin/gppersistentrebuild -c %s" % context.saved_segcid
cmd = Command(name='Run gppersistentrebuild', cmdStr=cmdStr)
cmd.run(validateAfter=True)
context.ret_code = cmd.get_return_code()
@given('the information of a "{seg}" segment on any host is saved')
@when('the information of a "{seg}" segment on any host is saved')
@then('the information of a "{seg}" segment on any host is saved')
def impl(context, seg):
gparray = GpArray.initFromCatalog(dbconn.DbURL())
if seg == "mirror":
to_save_segs = [seg for seg in gparray.getDbList() if seg.isSegmentMirror()]
context.mirror_segdbId = to_save_segs[0].getSegmentDbId()
context.mirror_segcid = to_save_segs[0].getSegmentContentId()
context.mirror_segdbname = to_save_segs[0].getSegmentHostName()
context.mirror_datadir = to_save_segs[0].getSegmentDataDirectory()
context.mirror_port = to_save_segs[0].getSegmentPort()
elif seg == "primary":
to_save_segs = [seg for seg in gparray.getDbList() if seg.isSegmentPrimary()]
elif seg == "master":
to_save_segs = [seg for seg in gparray.getDbList() if seg.isSegmentMaster()]
context.saved_segcid = to_save_segs[0].getSegmentContentId()
@given('the user creates an index for table "{table_name}" in database "{db_name}"')
@when('the user creates an index for table "{table_name}" in database "{db_name}"')
@then('the user creates an index for table "{table_name}" in database "{db_name}"')
def impl(context, table_name, db_name):
index_qry = "create table {0}(i int primary key, j varchar); create index test_index on index_table using bitmap(j)".format(
table_name)
with dbconn.connect(dbconn.DbURL(dbname=db_name)) as conn:
dbconn.execSQL(conn, index_qry)
conn.commit()
@given('verify that mirror_existence_state of segment "{segc_id}" is "{mirror_existence_state}"')
@when('verify that mirror_existence_state of segment "{segc_id}" is "{mirror_existence_state}"')
@then('verify that mirror_existence_state of segment "{segc_id}" is "{mirror_existence_state}"')
def impl(context, segc_id, mirror_existence_state):
with dbconn.connect(dbconn.DbURL(dbname='template1')) as conn:
sql = """SELECT mirror_existence_state from gp_dist_random('gp_persistent_relation_node') where gp_segment_id=%s group by 1;""" % segc_id
cluster_state = dbconn.execSQL(conn, sql).fetchone()
if cluster_state[0] != int(mirror_existence_state):
raise Exception("mirror_existence_state of segment %s is %s. Expected %s." % (
segc_id, cluster_state[0], mirror_existence_state))
@given('a role "{role_name}" is created')
@when('a role "{role_name}" is created')
@then('a role "{role_name}" is created')
def impl(context, role_name):
with dbconn.connect(dbconn.DbURL(dbname='template1')) as conn:
pghba = PgHba()
new_entry = Entry(entry_type='local',
database='all',
user=role_name,
authmethod="password")
pghba.add_entry(new_entry)
pghba.write()
dbconn.execSQL(conn, "Drop role if exists dsp_role")
dbconn.execSQL(conn, "Create role %s with login password 'dsprolepwd'" % role_name)
dbconn.execSQL(conn, "select pg_reload_conf()")
conn.commit()
@given('the backup files for the stored timestamp are in the old format in dir "{directory}"')
@when('the backup files for the stored timestamp are in the old format in dir "{directory}"')
@then('the backup files for the stored timestamp are in the old format in dir "{directory}"')
def impl(context, directory):
store_timestamp_in_old_format(context, directory=directory)
@given('the backup files for the stored timestamp are in the old format')
@when('the backup files for the stored timestamp are in the old format')
@then('the backup files for the stored timestamp are in the old format')
def impl(context):
store_timestamp_in_old_format(context)
@given('the backup files for the stored timestamp are in the old format with prefix "{prefix}"')
@when('the backup files for the stored timestamp are in the old format with prefix "{prefix}"')
@then('the backup files for the stored timestamp are in the old format with prefix "{prefix}"')
def impl(context, prefix):
store_timestamp_in_old_format(context, prefix=prefix)
def store_timestamp_in_old_format(context, directory=None, prefix=""):
gparray = GpArray.initFromCatalog(dbconn.DbURL())
primary_segs = [seg for seg in gparray.getDbList() if seg.isSegmentPrimary() or seg.isSegmentMaster()]
try:
context.backup_timestamp
except:
context.backup_timestamp = None
if context.backup_timestamp is not None:
timestamp = context.backup_timestamp
else:
timestamp = context.full_backup_timestamp
if directory is None:
master_dump_dir = gparray.master.getSegmentDataDirectory()
else:
master_dump_dir = directory
if prefix is not "":
prefix = prefix + "_"
for ps in primary_segs:
if directory is None:
seg_dir = ps.getSegmentDataDirectory()
else:
seg_dir = directory
dump_dir = os.path.join(seg_dir, 'db_dumps', timestamp[0:8])
segdbId = ps.getSegmentDbId()
segcid = ps.getSegmentContentId()
segdbname = ps.getSegmentHostName()
new_format = "%s_%s" % (segcid, segdbId)
old_format = "%s_%s" % (1 if ps.isSegmentMaster() else 0, segdbId)
rename_files_to_older_format = """ ssh {segdbname} 'if [ -d "{dump_dir}" ]; then for i in `ls {dump_dir}/*{new_format}_{timestamp}* | xargs`; do
old_format=${{i/{new_format}/{old_format}}}
if [ ! -f $old_format ]; then mv $i $old_format; fi ;
done; fi;'
""".format(segdbname=segdbname,
dump_dir=dump_dir,
new_format=new_format,
old_format=old_format,
timestamp=timestamp)
run_command(context, rename_files_to_older_format)
if context.exception:
raise context.exception
# replace new format with old format on master directory report file
master_report_file = os.path.join(master_dump_dir, 'db_dumps', timestamp[0:8],
'%sgp_dump_%s.rpt' % (prefix, timestamp))
change_report_file_content = "sed -i 's|%s|%s|' %s" % (new_format, old_format, master_report_file)
run_command(context, change_report_file_content)
# todo this seems like it can only be a given or a when, not a "then"
@then('the timestamp will be stored in json format')
@given('the timestamp will be stored in json format')
@when('the timestamp will be stored in json format')
def impl(context):
context.is_timestamp_stored_as_json = True
@given('the gptransfer test is initialized')
def impl(context):
context.execute_steps(u'''
Given the database is running
And the database "gptest" does not exist
And the database "gptransfer_destdb" does not exist
And the database "gptransfer_testdb1" does not exist
And the database "gptransfer_testdb3" does not exist
And the database "gptransfer_testdb4" does not exist
And the database "gptransfer_testdb5" does not exist
''')
@given('gpperfmon is configured and running in qamode')
@then('gpperfmon is configured and running in qamode')
def impl(context):
target_line = 'qamode = 1'
gpperfmon_config_file = "%s/gpperfmon/conf/gpperfmon.conf" % os.getenv("MASTER_DATA_DIRECTORY")
if not check_db_exists("gpperfmon", "localhost"):
context.execute_steps(u'''
When the user runs "gpperfmon_install --port 15432 --enable --password foo"
Then gpperfmon_install should return a return code of 0
''')
if not file_contains_line(gpperfmon_config_file, target_line):
context.execute_steps(u'''
When the user runs command "echo 'qamode = 1' >> $MASTER_DATA_DIRECTORY/gpperfmon/conf/gpperfmon.conf"
Then echo should return a return code of 0
When the user runs command "echo 'verbose = 1' >> $MASTER_DATA_DIRECTORY/gpperfmon/conf/gpperfmon.conf"
Then echo should return a return code of 0
When the user runs command "echo 'min_query_time = 0' >> $MASTER_DATA_DIRECTORY/gpperfmon/conf/gpperfmon.conf"
Then echo should return a return code of 0
When the user runs command "echo 'quantum = 10' >> $MASTER_DATA_DIRECTORY/gpperfmon/conf/gpperfmon.conf"
Then echo should return a return code of 0
When the user runs command "echo 'harvest_interval = 5' >> $MASTER_DATA_DIRECTORY/gpperfmon/conf/gpperfmon.conf"
Then echo should return a return code of 0
''')
if not is_process_running("gpsmon"):
context.execute_steps(u'''
When the database is not running
Then wait until the process "postgres" goes down
When the user runs "gpstart -a"
Then gpstart should return a return code of 0
And verify that a role "gpmon" exists in database "gpperfmon"
And verify that the last line of the file "postgresql.conf" in the master data directory contains the string "gpperfmon_log_alert_level='warning'"
And verify that there is a "heap" table "database_history" in "gpperfmon"
Then wait until the process "gpmmon" is up
And wait until the process "gpsmon" is up
''')
@given('the setting "{variable_name}" is NOT set in the configuration file "{path_to_file}"')
@when('the setting "{variable_name}" is NOT set in the configuration file "{path_to_file}"')
def impl(context, variable_name, path_to_file):
path = os.path.join(os.getenv("MASTER_DATA_DIRECTORY"), path_to_file)
output_file = "/tmp/gpperfmon_temp_config"
cmd = Command("sed to remove line", "sed '/^%s/,+1 d' < %s > %s" % (variable_name, path, output_file))
cmd.run(validateAfter=True)
shutil.move(output_file, path)
@given('the setting "{setting_string}" is placed in the configuration file "{path_to_file}"')
@when('the setting "{setting_string}" is placed in the configuration file "{path_to_file}"')
def impl(context, setting_string, path_to_file):
path = os.path.join(os.getenv("MASTER_DATA_DIRECTORY"), path_to_file)
with open(path, 'a') as f:
f.write(setting_string)
f.write("\n")
@given('the latest gpperfmon gpdb-alert log is copied to a file with a fake (earlier) timestamp')
@when('the latest gpperfmon gpdb-alert log is copied to a file with a fake (earlier) timestamp')
def impl(context):
gpdb_alert_file_path_src = sorted(glob.glob(os.path.join(os.getenv("MASTER_DATA_DIRECTORY"),
"gpperfmon",
"logs",
"gpdb-alert*")))[-1]
# typical filename would be gpdb-alert-2017-04-26_155335.csv
# setting the timestamp to a string that starts with `-` (em-dash)
# will be sorted (based on ascii) before numeric timestamps
# without colliding with a real timestamp
dest = re.sub(r"_\d{6}\.csv$", "_-takeme.csv", gpdb_alert_file_path_src)
# Let's wait until there's actually something in the file before actually
# doing a copy of the log...
for _ in range(60):
if os.stat(gpdb_alert_file_path_src).st_size != 0:
shutil.copy(gpdb_alert_file_path_src, dest)
context.fake_timestamp_file = dest
return
sleep(1)
raise Exception("File: %s is empty" % gpdb_alert_file_path_src)
@then('the file with the fake timestamp no longer exists')
def impl(context):
if os.path.exists(context.fake_timestamp_file):
raise Exception("expected no file at: %s" % context.fake_timestamp_file)
def use_netbackup():
if os.getenv('NETBACKUP'):
return True
else:
return False
def use_ddboost():
if os.getenv('DDBOOST'):
return True
else:
return False
def append_storage_config_to_backup_command(context, command):
if use_netbackup():
command += " --netbackup-service-host " + context._root['netbackup_service_host'] + " --netbackup-policy " + context._root['netbackup_policy'] + " --netbackup-schedule " + context._root['netbackup_schedule']
elif use_ddboost():
command += " --ddboost"
return command
def append_storage_config_to_restore_command(context, command):
if use_netbackup():
command += " --netbackup-service-host " + context._root['netbackup_service_host']
elif use_ddboost():
command += " --ddboost"
return command
def parse_config_params():
if use_netbackup():
current_path = os.path.realpath(__file__)
current_dir = os.path.dirname(current_path)
netbackup_yaml_file_path = os.path.join(current_dir, 'data/netbackup_behave_config.yaml')
config_yaml = read_config_yaml(netbackup_yaml_file_path)
elif use_ddboost():
mdd = os.getenv('MASTER_DATA_DIRECTORY')
ddboost_yaml_file_path = os.path.join(mdd,'ddboost_config.yml')
config_yaml = read_config_yaml(ddboost_yaml_file_path)
return config_yaml
def ddboost_config_setup(context, storage_unit=None):
cmd_remove_config = "gpcrondump --ddboost-config-remove"
print "context is %s" % context
print "cmd is %s" % cmd_remove_config
run_command(context, cmd_remove_config)
cmd_config = "gpcrondump --ddboost-host %s --ddboost-user %s --ddboost-backupdir %s" % \
(context._root['local_ddboost_host'], \
context._root['local_ddboost_user'], \
context._root['ddboost_backupdir'])
if storage_unit:
cmd_config += " --ddboost-storage-unit %s" % storage_unit
cmd_config
local = pexpect.spawn(cmd_config)
local.expect('Password: ')
local.sendline(context._root['local_ddboost_password'])
local.expect(pexpect.EOF)
local.close()
cmd_config = "gpcrondump --ddboost-host %s --ddboost-user %s --ddboost-backupdir %s --ddboost-remote" % \
(context._root['remote_ddboost_host'], \
context._root['remote_ddboost_user'], \
context._root['ddboost_backupdir'])
if storage_unit:
cmd_config += " --ddboost-storage-unit %s" % storage_unit
cmd_config
local = pexpect.spawn(cmd_config)
local.expect('Password: ')
local.sendline(context._root['remote_ddboost_password'])
local.expect(pexpect.EOF)
local.close()
def _copy_nbu_lib_files(context, ver, gphome):
ver = ver.replace('.', '')
hosts = set(get_all_hostnames_as_list(context, 'template1'))
cpCmd = 'cp -f {gphome}/lib/nbu{ver}/lib/* {gphome}/lib/'.format(gphome=gphome,
ver=ver)
for host in hosts:
cmd = Command(name='Copy NBU lib files',
cmdStr=cpCmd,
ctxt=REMOTE,
remoteHost=host)
cmd.run(validateAfter=True)
def read_config_yaml(yaml_file):
""" Reads in a yaml file. """
try:
cfgfile = open(yaml_file, 'r')
except IOError as e:
raise Exception("Unable to open file %s: %s" % (yaml_file, e))
try:
cfgyamldata = yaml.load(cfgfile.read())
except yaml.YAMLError, exc:
raise Exception("Error reading file %s: %s" % (yaml_file, exc))
finally:
cfgfile.close()
if len(cfgyamldata) == 0:
raise Exception("The load of the config file %s failed.\
No configuration information to continue testing operation." % yaml_file)
else:
return cfgyamldata
@given('the test suite is initialized for Netbackup "{ver}"')
def impl(context, ver):
gphome = os.environ.get('GPHOME')
_copy_nbu_lib_files(context=context, ver=ver, gphome=gphome)
os.environ["NETBACKUP"] = "TRUE"
NETBACKUPDICT = defaultdict(dict)
NETBACKUPDICT['NETBACKUPINFO'] = parse_config_params()
context._root['netbackup_service_host'] = NETBACKUPDICT['NETBACKUPINFO']['NETBACKUP_PARAMS']['NETBACKUP_SERVICE_HOST']
context._root['netbackup_policy'] = NETBACKUPDICT['NETBACKUPINFO']['NETBACKUP_PARAMS']['NETBACKUP_POLICY']
context._root['netbackup_schedule'] = NETBACKUPDICT['NETBACKUPINFO']['NETBACKUP_PARAMS']['NETBACKUP_SCHEDULE']
@given('the test suite is initialized for DDBoost')
def impl(context):
os.environ["DDBOOST"] = "TRUE"
DDBOOSTDICT = defaultdict(dict)
DDBOOSTDICT['DDBOOSTINFO'] = parse_config_params()
context._root['local_ddboost_host'] = DDBOOSTDICT['DDBOOSTINFO']['DDBOOST_HOST_1']
context._root['local_ddboost_user'] = DDBOOSTDICT['DDBOOSTINFO']['DDBOOST_USER_1']
context._root['local_ddboost_password'] = DDBOOSTDICT['DDBOOSTINFO']['DDBOOST_PASSWORD_1']
context._root['remote_ddboost_host'] = DDBOOSTDICT['DDBOOSTINFO']['DDBOOST_HOST_2']
context._root['remote_ddboost_user'] = DDBOOSTDICT['DDBOOSTINFO']['DDBOOST_USER_2']
context._root['remote_ddboost_password'] = DDBOOSTDICT['DDBOOSTINFO']['DDBOOST_PASSWORD_2']
if 'ddboost_backupdir' not in context._root:
directory = os.getenv('PULSE_PROJECT', default='GPDB') + os.getenv('PULSE_BUILD_VERSION', default='') + os.getenv('PULSE_STAGE', default='') + '_DIR'
context._root['ddboost_backupdir'] = directory
ddboost_config_setup(context, storage_unit="GPDB")
@given('the DDBoost dump directory is deleted for the "{which}" storage unit')
@then('the DDBoost dump directory is deleted for the "{which}" storage unit')
@when('the DDBoost dump directory is deleted for the "{which}" storage unit')
def impl(context, which):
if use_ddboost():
if which == "local":
cmd_del_dir = "gpddboost --del-dir=%s" % context._root['ddboost_backupdir']
elif which == "remote":
cmd_del_dir = "gpddboost --del-dir=%s --remote" % context._root['ddboost_backupdir']
else:
raise Exception('Invalid storage unit specified. Options are "local" and "remote".')
run_command(context, cmd_del_dir)
@then('gpcrondump should print the correct disk space check message')
def impl(context):
if use_ddboost():
check_stdout_msg(context, "Bypassing disk space checks due to DDBoost parameters")
else:
check_stdout_msg(context, "Validating disk space")
@then('store the vacuum timestamp for verification in database "{dbname}"')
def impl(context, dbname):
sleep(2)
res = execute_sql_singleton(dbname, 'select last_vacuum from pg_stat_all_tables where last_vacuum is not null order by last_vacuum desc limit 1')
context.vacuum_timestamp = res
@then('verify that vacuum has been run in database "{dbname}"')
def impl(context, dbname):
sleep(2)
res = execute_sql_singleton(dbname, 'select last_vacuum from pg_stat_all_tables where last_vacuum is not null order by last_vacuum desc limit 1')
if res == context.vacuum_timestamp:
raise Exception ("Vacuum did not occur as expected. The last_vacuum timestamp %s has not changed" % context.vacuum_timestamp)
@then('the "{utility}" log file should exist under "{directory}"')
def impl(context, utility, directory):
filepath = glob.glob(os.path.join(directory, utility+"*"))
if not os.path.isfile(filepath[0]):
err_str = "The output file '%s' does not exist.\n" % filepath
raise Exception(err_str)
@then('no dump files should be present on the data domain server')
def impl(context):
command = 'gpddboost --listDirectory --dir=%s' % (os.path.join(context._root['ddboost_backupdir'], context.full_backup_timestamp[0:8]))
run_gpcommand(context, command)
if not context.exception:
raise Exception("Directory for date %s still exists" % context.full_backup_timestamp[0:8])
@then('"{gppkg_name}" gppkg files exist on all hosts')
def impl(context, gppkg_name):
remote_gphome = os.environ.get('GPHOME')
gparray = GpArray.initFromCatalog(dbconn.DbURL())
hostlist = get_all_hostnames_as_list(context, 'template1')
# We can assume the GPDB is installed at the same location for all hosts
rpm_command_list_all = 'rpm -qa --dbpath %s/share/packages/database' % remote_gphome
for hostname in set(hostlist):
cmd = Command(name='check if internal rpm gppkg is installed',
cmdStr=rpm_command_list_all,
ctxt=REMOTE,
remoteHost=hostname)
cmd.run(validateAfter=True)
if not gppkg_name in cmd.get_stdout():
raise Exception( '"%s" gppkg is not installed on host: %s. \nInstalled packages: %s' % (gppkg_name, hostname, cmd.get_stdout()))
@given('"{gppkg_name}" gppkg files do not exist on any hosts')
@when('"{gppkg_name}" gppkg files do not exist on any hosts')
@then('"{gppkg_name}" gppkg files do not exist on any hosts')
def impl(context, gppkg_name):
remote_gphome = os.environ.get('GPHOME')
hostlist = get_all_hostnames_as_list(context, 'template1')
# We can assume the GPDB is installed at the same location for all hosts
rpm_command_list_all = 'rpm -qa --dbpath %s/share/packages/database' % remote_gphome
for hostname in set(hostlist):
cmd = Command(name='check if internal rpm gppkg is installed',
cmdStr=rpm_command_list_all,
ctxt=REMOTE,
remoteHost=hostname)
cmd.run(validateAfter=True)
if gppkg_name in cmd.get_stdout():
raise Exception( '"%s" gppkg is installed on host: %s. \nInstalled packages: %s' % (gppkg_name, hostname, cmd.get_stdout()))
def _remove_gppkg_from_host(context, gppkg_name, is_master_host):
remote_gphome = os.environ.get('GPHOME')
if is_master_host:
hostname = get_master_hostname()[0][0] # returns a list of list
else:
hostlist = get_segment_hostlist()
if not hostlist:
raise Exception("Current GPDB setup is not a multi-host cluster.")
# Let's just pick whatever is the first host in the list, it shouldn't
# matter which one we remove from
hostname = hostlist[0]
rpm_command_list_all = 'rpm -qa --dbpath %s/share/packages/database' % remote_gphome
cmd = Command(name='get all rpm from the host',
cmdStr=rpm_command_list_all,
ctxt=REMOTE,
remoteHost=hostname)
cmd.run(validateAfter=True)
installed_gppkgs = cmd.get_stdout_lines()
if not installed_gppkgs:
raise Exception("Found no packages installed")
full_gppkg_name = next((gppkg for gppkg in installed_gppkgs if gppkg_name in gppkg), None)
if not full_gppkg_name:
raise Exception("Found no matches for gppkg '%s'\n"
"gppkgs installed:\n%s" % (gppkg_name, installed_gppkgs))
rpm_remove_command = 'rpm -e %s --dbpath %s/share/packages/database' % (full_gppkg_name, remote_gphome)
cmd = Command(name='Cleanly remove from the remove host',
cmdStr=rpm_remove_command,
ctxt=REMOTE,
remoteHost=hostname)
cmd.run(validateAfter=True)
remove_archive_gppgk = 'rm -f %s/share/packages/archive/%s.gppkg' % (remote_gphome, gppkg_name)
cmd = Command(name='Remove archive gppkg',
cmdStr=remove_archive_gppgk,
ctxt=REMOTE,
remoteHost=hostname)
cmd.run(validateAfter=True)
@when('gppkg "{gppkg_name}" is removed from a segment host')
def impl(context, gppkg_name):
_remove_gppkg_from_host(context, gppkg_name, is_master_host=False)
@when('gppkg "{gppkg_name}" is removed from master host')
def impl(context, gppkg_name):
_remove_gppkg_from_host(context, gppkg_name, is_master_host=True)
@given('gpAdminLogs directory has no "{prefix}" files')
def impl(context, prefix):
log_dir = _get_gpAdminLogs_directory()
items = glob.glob('%s/%s_*.log' % (log_dir, prefix))
for item in items:
os.remove(item)
@given('"{filepath}" is copied to the install directory')
def impl(context, filepath):
gphome = os.getenv("GPHOME")
if not gphome:
raise Exception("GPHOME must be set")
shutil.copy(filepath, os.path.join(gphome, "bin"))
@then('{command} should print "{target}" to logfile')
def impl(context, command, target):
log_dir = _get_gpAdminLogs_directory()
filename = glob.glob('%s/%s_*.log' % (log_dir, command))[0]
contents = ''
with open(filename) as fr:
for line in fr:
contents += line
if target not in contents:
raise Exception("cannot find %s in %s" % (target, filename))
| apache-2.0 |
bendraaisma/gnuob-soap | src/main/java/br/com/netbrasoft/gnuob/generic/content/ContentWebServiceImpl.java | 7684 | /*
* Copyright 2016 Netbrasoft
*
* 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 br.com.netbrasoft.gnuob.generic.content;
import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.CONTENT_PARAM_NAME;
import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.CONTENT_WEB_SERVICE_IMPL_NAME;
import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.COUNT_CONTENT_OPERATION_NAME;
import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.FIND_CONTENT_BY_ID_OPERATION_NAME;
import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.FIND_CONTENT_OPERATION_NAME;
import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.GNUOB_WEB_SERVICE_TARGET_NAMESPACE;
import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.MERGE_CONTENT_OPERATION_NAME;
import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.META_DATA_PARAM_NAME;
import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.ORDER_BY_PARAM_NAME;
import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.PAGING_PARAM_NAME;
import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.PERSIST_CONTENT_OPERATION_NAME;
import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.REFRESH_CONTENT_OPERATION_NAME;
import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.REMOVE_CONTENT_OPERATION_NAME;
import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.SECURED_GENERIC_TYPE_SERVICE_IMPL_NAME;
import static br.com.netbrasoft.gnuob.generic.factory.MessageCreaterFactory.createMessage;
import static org.slf4j.LoggerFactory.getLogger;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import org.slf4j.Logger;
import br.com.netbrasoft.gnuob.exception.GNUOpenBusinessServiceException;
import br.com.netbrasoft.gnuob.generic.IGenericTypeWebService;
import br.com.netbrasoft.gnuob.generic.OrderByEnum;
import br.com.netbrasoft.gnuob.generic.Paging;
import br.com.netbrasoft.gnuob.generic.security.ISecuredGenericTypeService;
import br.com.netbrasoft.gnuob.generic.security.MetaData;
import br.com.netbrasoft.gnuob.monitor.AppSimonInterceptor;
@WebService(targetNamespace = GNUOB_WEB_SERVICE_TARGET_NAMESPACE)
@Stateless(name = CONTENT_WEB_SERVICE_IMPL_NAME)
@Interceptors(value = {AppSimonInterceptor.class})
public class ContentWebServiceImpl<T extends Content> implements IGenericTypeWebService<T> {
private static final Logger LOGGER = getLogger(ContentWebServiceImpl.class);
@EJB(beanName = SECURED_GENERIC_TYPE_SERVICE_IMPL_NAME)
private ISecuredGenericTypeService<T> securedGenericContentService;
public ContentWebServiceImpl() {
// This constructor will be used by the EJB container.
}
ContentWebServiceImpl(final ISecuredGenericTypeService<T> securedGenericContentService) {
this.securedGenericContentService = securedGenericContentService;
}
@Override
@WebMethod(operationName = COUNT_CONTENT_OPERATION_NAME)
public long count(@WebParam(name = META_DATA_PARAM_NAME, header = true) final MetaData credentials,
@WebParam(name = CONTENT_PARAM_NAME) final T type) {
try {
return securedGenericContentService.count(credentials, type);
} catch (final Exception e) {
throw new GNUOpenBusinessServiceException(e.getMessage(), e);
} finally {
LOGGER.debug(createMessage(COUNT_CONTENT_OPERATION_NAME, credentials, type));
}
}
@Override
@WebMethod(operationName = FIND_CONTENT_BY_ID_OPERATION_NAME)
public T find(@WebParam(name = META_DATA_PARAM_NAME, header = true) final MetaData credentials,
@WebParam(name = CONTENT_PARAM_NAME) final T type) {
try {
return securedGenericContentService.find(credentials, type, type.getId());
} catch (final Exception e) {
throw new GNUOpenBusinessServiceException(e.getMessage(), e);
} finally {
LOGGER.debug(createMessage(FIND_CONTENT_BY_ID_OPERATION_NAME, credentials, type));
}
}
@Override
@WebMethod(operationName = FIND_CONTENT_OPERATION_NAME)
public List<T> find(@WebParam(name = META_DATA_PARAM_NAME, header = true) final MetaData credentials,
@WebParam(name = CONTENT_PARAM_NAME) final T type, @WebParam(name = PAGING_PARAM_NAME) final Paging paging,
@WebParam(name = ORDER_BY_PARAM_NAME) final OrderByEnum orderingProperty) {
try {
return securedGenericContentService.find(credentials, type, paging, orderingProperty);
} catch (final Exception e) {
throw new GNUOpenBusinessServiceException(e.getMessage(), e);
} finally {
LOGGER.debug(createMessage(FIND_CONTENT_OPERATION_NAME, credentials, type, paging, orderingProperty));
}
}
@Override
@WebMethod(operationName = MERGE_CONTENT_OPERATION_NAME)
public T merge(@WebParam(name = META_DATA_PARAM_NAME, header = true) final MetaData credentials,
@WebParam(name = CONTENT_PARAM_NAME) final T type) {
try {
return securedGenericContentService.merge(credentials, type);
} catch (final Exception e) {
throw new GNUOpenBusinessServiceException(e.getMessage(), e);
} finally {
LOGGER.debug(createMessage(MERGE_CONTENT_OPERATION_NAME, credentials, type));
}
}
@Override
@WebMethod(operationName = PERSIST_CONTENT_OPERATION_NAME)
public T persist(@WebParam(name = META_DATA_PARAM_NAME, header = true) final MetaData credentials,
@WebParam(name = CONTENT_PARAM_NAME) final T type) {
try {
return persitMergeContent(credentials, type);
} catch (final Exception e) {
throw new GNUOpenBusinessServiceException(e.getMessage(), e);
} finally {
LOGGER.debug(createMessage(PERSIST_CONTENT_OPERATION_NAME, credentials, type));
}
}
private T persitMergeContent(final MetaData credentials, final T type) {
if (type.isDetached()) {
return securedGenericContentService.merge(credentials, type);
}
securedGenericContentService.persist(credentials, type);
return type;
}
@Override
@WebMethod(operationName = REFRESH_CONTENT_OPERATION_NAME)
public T refresh(@WebParam(name = META_DATA_PARAM_NAME, header = true) final MetaData credentials,
@WebParam(name = CONTENT_PARAM_NAME) final T type) {
try {
return securedGenericContentService.refresh(credentials, type, type.getId());
} catch (final Exception e) {
throw new GNUOpenBusinessServiceException(e.getMessage(), e);
} finally {
LOGGER.debug(createMessage(REFRESH_CONTENT_OPERATION_NAME, credentials, type));
}
}
@Override
@WebMethod(operationName = REMOVE_CONTENT_OPERATION_NAME)
public void remove(@WebParam(name = META_DATA_PARAM_NAME, header = true) final MetaData credentials,
@WebParam(name = CONTENT_PARAM_NAME) final T type) {
try {
securedGenericContentService.remove(credentials, type);
} catch (final Exception e) {
throw new GNUOpenBusinessServiceException(e.getMessage(), e);
} finally {
LOGGER.debug(createMessage(REMOVE_CONTENT_OPERATION_NAME, credentials, type));
}
}
}
| apache-2.0 |
Alfredux79/softbills | src/main/webapp/app/entities/work-day/work-day.route.ts | 1980 | import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes, CanActivate } from '@angular/router';
import { UserRouteAccessService } from '../../shared';
import { JhiPaginationUtil } from 'ng-jhipster';
import { WorkDayComponent } from './work-day.component';
import { WorkDayDetailComponent } from './work-day-detail.component';
import { WorkDayPopupComponent } from './work-day-dialog.component';
import { WorkDayDeletePopupComponent } from './work-day-delete-dialog.component';
export const workDayRoute: Routes = [
{
path: 'work-day',
component: WorkDayComponent,
data: {
authorities: ['ROLE_USER'],
pageTitle: 'softbillsApp.workDay.home.title'
},
canActivate: [UserRouteAccessService]
}, {
path: 'work-day/:id',
component: WorkDayDetailComponent,
data: {
authorities: ['ROLE_USER'],
pageTitle: 'softbillsApp.workDay.home.title'
},
canActivate: [UserRouteAccessService]
}
];
export const workDayPopupRoute: Routes = [
{
path: 'work-day-new',
component: WorkDayPopupComponent,
data: {
authorities: ['ROLE_USER'],
pageTitle: 'softbillsApp.workDay.home.title'
},
canActivate: [UserRouteAccessService],
outlet: 'popup'
},
{
path: 'work-day/:id/edit',
component: WorkDayPopupComponent,
data: {
authorities: ['ROLE_USER'],
pageTitle: 'softbillsApp.workDay.home.title'
},
canActivate: [UserRouteAccessService],
outlet: 'popup'
},
{
path: 'work-day/:id/delete',
component: WorkDayDeletePopupComponent,
data: {
authorities: ['ROLE_USER'],
pageTitle: 'softbillsApp.workDay.home.title'
},
canActivate: [UserRouteAccessService],
outlet: 'popup'
}
];
| apache-2.0 |
zouzias/spark-lucenerdd-examples | src/main/scala/org/zouzias/spark/lucenerdd/examples/linkage/LinkageScholarvsDBLP.scala | 3643 | package org.zouzias.spark.lucenerdd.examples.linkage
import org.apache.spark.SparkConf
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{DataFrame, Row, SparkSession}
import org.zouzias.spark.lucenerdd.LuceneRDD
import org.zouzias.spark.lucenerdd._
import org.zouzias.spark.lucenerdd.logging.Logging
/**
* Record linkage example between Google scholar and DBLP using [[LuceneRDD]]
*
* You can run this locally with, ./spark-linkage-dblp-vs-scholar-articles.sh
*/
object LinkageScholarvsDBLP extends Logging {
def get_ids(df: RDD[(Row, Array[Row])], leftIdName: String, rightIdName: String)(sparkSession: SparkSession)
: DataFrame = {
sparkSession.createDataFrame(df.map{ case (schl, topDocs) =>
val rightId = topDocs.head.getString(topDocs.head.fieldIndex("id"))
val leftId = schl.getString(schl.fieldIndex("id"))
(leftId, rightId)
}).toDF(leftIdName, rightIdName)
}
def main(args: Array[String]) {
// initialise spark context
val conf = new SparkConf().setAppName(LinkageScholarvsDBLP.getClass.getName)
implicit val spark: SparkSession = SparkSession.builder.config(conf).getOrCreate()
import spark.implicits._
// Load input datasets
val start = System.currentTimeMillis()
val scholarDF = spark.read.parquet("data/linkage-papers1/linkage-papers-scholar.parquet")
logInfo(s"Loaded ${scholarDF.count} ACM records")
val dblpDF = spark.read.parquet("data/linkage-papers1/linkage-papers-dblp.parquet")
logInfo(s"Loaded ${scholarDF.count} DBLP records")
val groundTruthDF = spark.read.parquet("data/linkage-papers1/linkage-papers-scholar-vs-dblp.parquet")
val scholar = scholarDF.select("id", "title", "authors", "venue")
// Index DBLP dataset
val dblp = LuceneRDD(dblpDF)
// Define a custom linker (defines your linkage logic)
val linker: Row => String = { row =>
val title = row.getString(row.fieldIndex("title"))
val authors = row.getString(row.fieldIndex("authors"))
val titleTokens = title.split(" ")
.map(_.replaceAll("[^a-zA-Z0-9]", ""))
.filter(_.length > 3)
.mkString(" OR ")
val authorsTerms = authors.split(" ")
.map(_.replaceAll("[^a-zA-Z0-9]", ""))
.filter(_.compareToIgnoreCase("OR") != 0)
.filter(_.length > 2)
.mkString(" OR ")
if (titleTokens.nonEmpty && authorsTerms.nonEmpty) {
s"(title:($titleTokens) OR authors:($authorsTerms))"
}
else if (titleTokens.nonEmpty){
s"title:($titleTokens)"
}
else if (authorsTerms.nonEmpty){
s"authors:($authorsTerms)"
}
else {
"*:*"
}
}
// Perform linkage and return top-3 results
val linkedResults = dblp.linkDataFrame(scholar, linker, 3).filter(_._2.nonEmpty)
// Compute the performance of linkage (accuracy)
val linkageResults = get_ids(linkedResults, "idScholar", "idDBLP")(spark)
val correctHits: Double = linkageResults.join(groundTruthDF, groundTruthDF.col("idDBLP")
.equalTo(linkageResults("idDBLP")) && groundTruthDF.col("idScholar").equalTo(linkageResults("idScholar"))).count
val total: Double = groundTruthDF.count
val accuracy = correctHits / total.toDouble
val end = System.currentTimeMillis()
logInfo("=" * 40)
logInfo(s"Elapsed time: ${(end - start) / 1000.0} seconds")
logInfo("=" * 40)
logInfo("********************************")
logInfo(s"Accuracy of linkage is $accuracy")
logInfo("********************************")
// terminate spark context
spark.stop()
}
}
| apache-2.0 |
WolfgangFahl/Mediawiki-Japi | jaxbgenerator/src/com/bitplan/mediawiki/japi/api/ObjectFactory.java | 1954 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.01.09 at 03:50:42 PM CET
//
package com.bitplan.mediawiki.japi.api;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the com.bitplan.mediawiki.japi.api package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.bitplan.mediawiki.japi.api
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link Api }
*
*/
public Api createApi() {
return new Api();
}
/**
* Create an instance of {@link Continue }
*
*/
public Continue createContinue() {
return new Continue();
}
/**
* Create an instance of {@link Query }
*
*/
public Query createQuery() {
return new Query();
}
/**
* Create an instance of {@link Recentchanges }
*
*/
public Recentchanges createRecentchanges() {
return new Recentchanges();
}
/**
* Create an instance of {@link Rc }
*
*/
public Rc createRc() {
return new Rc();
}
}
| apache-2.0 |
avadev/AvaTax-REST-V2-DotNet-SDK | src/enums/FilingRequestStatus.cs | 1221 | using System;
/*
* AvaTax API Client Library
*
* (c) 2004-2019 Avalara, Inc.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Genevieve Conty
* @author Greg Hester
* Swagger name: AvaTaxClient
*/
namespace Avalara.AvaTax.RestClient
{
/// <summary>
///
/// </summary>
public enum FilingRequestStatus
{
/// <summary>
///
/// </summary>
New = 1,
/// <summary>
///
/// </summary>
Validated = 2,
/// <summary>
///
/// </summary>
Pending = 3,
/// <summary>
///
/// </summary>
Active = 4,
/// <summary>
///
/// </summary>
PendingStop = 5,
/// <summary>
///
/// </summary>
Inactive = 6,
/// <summary>
///
/// </summary>
ChangeRequest = 7,
/// <summary>
///
/// </summary>
RequestApproved = 8,
/// <summary>
///
/// </summary>
RequestDenied = 9,
}
}
| apache-2.0 |
google-ar/sceneform-android-sdk | sceneformsrc/sceneform/src/main/java/com/google/ar/sceneform/utilities/ChangeId.java | 929 | package com.google.ar.sceneform.utilities;
/**
* Used to identify when the state of an object has changed by incrementing an integer id. Other
* classes can determine when this object has changed by polling to see if the id has changed.
*
* <p>This is useful as an alternative to an event listener subscription model when there is no safe
* point in the lifecycle of an object to unsubscribe from the event listeners. Unlike event
* listeners, this cannot cause memory leaks.
*
* @hide
*/
public class ChangeId {
public static final int EMPTY_ID = 0;
private int id = EMPTY_ID;
public int get() {
return id;
}
public boolean isEmpty() {
return id == EMPTY_ID;
}
public boolean checkChanged(int id) {
return this.id != id && !isEmpty();
}
public void update() {
id++;
// Skip EMPTY_ID if the id has cycled all the way around.
if (id == EMPTY_ID) {
id++;
}
}
}
| apache-2.0 |
google-research/google-research | learning_parameter_allocation/utils.py | 22798 | # coding=utf-8
# Copyright 2022 The Google Research 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.
"""Utility functions for building models with learned parameter allocations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
from learning_parameter_allocation.pathnet import components as pn_components
from learning_parameter_allocation.pathnet import pathnet_lib as pn
from learning_parameter_allocation.pathnet.utils import \
create_wrapped_routed_layer
import numpy as np
import tensorflow.compat.v1 as tf
from tqdm import tqdm
def run_pathnet_training_step(
session, p_inputs, p_labels, p_task_id, train_step_op, train_data):
"""Trains a PathNet multitask image classification model for a single step.
Args:
session: (tf.Session) session to use.
p_inputs: (tf.placeholder) placeholder for the input image.
p_labels: (tf.placeholder) placeholder for the target labels.
p_task_id: (tf.placeholder) placeholder for the task id.
train_step_op: (tf.Operation) training op.
train_data: (list of tf.data.Datasets) training data for each of the tasks.
"""
for task_id, dataset in train_data:
data = session.run(dataset)
inputs, labels = data['image'], data['label']
feed_dict = {
p_inputs: inputs,
p_labels: labels,
p_task_id: np.array(task_id)
}
summary_ops = tf.contrib.summary.all_summary_ops()
summary_ops = [op for op in summary_ops if not op.name.startswith('final')]
fetch = [train_step_op, summary_ops]
session.run(fetch, feed_dict=feed_dict)
def run_pathnet_evaluation(
session, p_inputs, p_task_id, out_logits, task_names, eval_data):
"""Evaluates a PathNet multitask image classification model.
Args:
session: (tf.Session) session to use.
p_inputs: (tf.placeholder) placeholder for the input image.
p_task_id: (tf.placeholder) placeholder for the task id.
out_logits: (tf.Operation) PathNet output (classification logits).
task_names: (list of strings) names of tasks.
eval_data: (list of tf.data.Datasets) eval data for each task, should have
the same length as `task_names`. The evaluation will go through each
dataset in `eval_data` until it stops returning new batches.
Returns:
A list of floats, containing evaluation accuracy for each of the tasks.
"""
task_accuracies = []
for task_id in range(len(task_names)):
# Number of correctly classified eval samples.
count_correct = 0
# Total number of eval samples.
count_all = 0
data_iterator, num_batches = eval_data[task_id]
for _ in range(num_batches):
data = session.run(data_iterator)
inputs, labels = data['image'], data['label']
feed_dict = {p_inputs: inputs, p_task_id: np.array(task_id)}
logits = session.run([out_logits], feed_dict=feed_dict)
answers = np.argmax(logits, axis=-1)
count_correct += np.sum(answers == labels)
count_all += labels.shape[0]
accuracy = count_correct / count_all
print(task_names[task_id], accuracy, '(%d/%d)' % (count_correct, count_all))
task_accuracies.append(accuracy)
return task_accuracies
def create_accuracy_summary_ops(task_names, summary_name_prefix):
"""Creates ops for writing accuracy summaries.
Args:
task_names: (list of strings) names of tasks.
summary_name_prefix: (string) prefix to prepend to summary names.
Returns:
A pair of (`p_task_accuracies`, `summary_op`), where `p_task_accuracies`
is a list of tf.placeholder's for all tasks' accuracies, and `summary_op`
is a tf.Operation that writes these summaries.
"""
p_task_accuracies = []
summary_ops = []
with tf.contrib.summary.always_record_summaries():
for task_id in range(len(task_names)):
task_name = task_names[task_id]
p_task_accuracy = tf.placeholder(tf.float32, shape=())
summary_ops.append(tf.contrib.summary.scalar(
'%s/%s' % (summary_name_prefix, task_name), p_task_accuracy))
p_task_accuracies.append(p_task_accuracy)
average_task_accuracy = tf.reduce_mean(p_task_accuracies)
summary_ops.append(tf.contrib.summary.scalar(
'%s/Average' % summary_name_prefix, average_task_accuracy))
return p_task_accuracies, tf.group(*summary_ops)
def run_accuracy_summary_ops(
session,
p_task_accuracies,
task_accuracies,
accuracy_summary_op):
"""Runs ops that write accuracy summaries.
Args:
session: (tf.Session) session to use.
p_task_accuracies: (list of tf.placeholder's) placeholders for all tasks'
accuracies, as returned from `create_accuracy_summary_ops`.
task_accuracies: (list of floats) all tasks' accuracies, they will be fed
into `p_task_accuracies`.
accuracy_summary_op: (tf.Operation) an op that writes accuracy summaries,
as returned from `create_accuracy_summary_ops`.
"""
feed_dict = {
p_task_accuracy: task_accuracy
for (p_task_accuracy, task_accuracy) in zip(
p_task_accuracies, task_accuracies)
}
session.run(accuracy_summary_op, feed_dict=feed_dict)
def build_pathnet_graph(p_inputs, p_labels, p_task_id, pathnet, training):
"""Builds a PathNet graph, returns input placeholders and output tensors.
Args:
p_inputs: (tf.placeholder) placeholder for the input image.
p_labels: (tf.placeholder) placeholder for the target labels.
p_task_id: (tf.placeholder) placeholder for the task id.
pathnet: (pn.PathNet) PathNet model to use.
training: (bool) whether the graph is being created for training.
Returns:
A pair of (`train_step_op`, `out_logits`), where `train_step_op` is
the training op, and `out_logits` is the final network output
(classification logits).
"""
end_state = pathnet({
'in_tensor': p_inputs,
'labels': p_labels,
'task_id': p_task_id,
'training': training
})
# The train op is the same for all tasks. Note that the last layer in
# PathNet models contains heads that compute the task losses, with one head
# per task. The head is chosen depending on `task_id`, so the loss for
# the current task is always under `task_loss` key in `end_state`.
train_step_op = end_state['train_op']
out_logits = end_state['in_tensor']
return train_step_op, out_logits
def count_batches(session, dataset):
"""Count the number of batches in a dataset."""
num_batches = 0
try:
while True:
session.run(dataset)
num_batches += 1
except tf.errors.OutOfRangeError:
pass
return num_batches
# pylint: disable=dangerous-default-value
def run_pathnet_training_and_evaluation(
task_names,
task_data,
input_data_shape,
training_hparams,
components_layers,
evaluate_on,
summary_dir,
resume_checkpoint_dir=None,
save_checkpoint_every_n_steps=250,
intermediate_eval_steps=[]):
"""Trains and evaluates a PathNet multitask image classification model.
Args:
task_names: (list of strings) names of tasks.
task_data: (list of dicts) list of dictionaries, one per task.
Each dictionary should map strings into `tf.data.Dataset`s.
The `i`-th dictionary should contain all dataset splits (such as 'train',
'test', 'eval', etc) for the `i`-th task. The splits can be arbitrary,
but to run the training, every dataset should contain a 'train' split.
input_data_shape: (sequence of ints) expected shape of input images
(excluding batch dimension). For example, for the MNIST dataset
`input_data_shape=[28, 28, 1]`.
training_hparams: (tf.contrib.training.HParams) training hyperparameters.
components_layers: (list of `pn.ComponentsLayer`s) layers that make up
the PathNet model.
evaluate_on: (list of strings) dataset splits on which the trained PathNet
should be evaluated. These keys should be present in every dictionary
in `task_data`.
summary_dir: (string) directory for the summary writer.
resume_checkpoint_dir: (string or None) directory for the checkpoint
to reload, or None if should start from scratch.
save_checkpoint_every_n_steps: (int) frequency for saving model checkpoints.
intermediate_eval_steps: (list of ints) training step numbers at which
accuracy should be evaluated. An evaluation after the last step is
always performed.
"""
session = tf.Session(graph=tf.get_default_graph())
summary_writer = tf.contrib.summary.create_file_writer(summary_dir)
summary_writer.set_as_default()
num_tasks = len(task_names)
# Every `num_tasks` subsequent steps contain exactly one step for each task,
# and always in the order as they appear in `task_data`. Setting the logging
# frequency to `num_tasks + 1` (or any other number coprime with `num_tasks`)
# guarantees that each task will get to record summaries with the same
# frequency.
with tf.contrib.summary.record_summaries_every_n_global_steps(num_tasks + 1):
pathnet = pn.PathNet(components_layers, training_hparams)
num_steps = training_hparams.num_steps
eval_steps = intermediate_eval_steps + [num_steps]
# Loop each training dataset forever.
train_data = [
dataset['train'].repeat().make_one_shot_iterator().get_next()
for dataset in task_data
]
# Attach the task id to each dataset.
train_data = list(enumerate(train_data))
p_inputs = tf.placeholder(tf.float32, shape=[None] + input_data_shape)
p_labels = tf.placeholder(tf.int64, shape=[None])
p_task_id = tf.placeholder(tf.int32, shape=[], name='task_id')
train_step_op, _ = build_pathnet_graph(
p_inputs, p_labels, p_task_id, pathnet, training=True)
with tf.variable_scope(tf.get_variable_scope(), reuse=True):
_, out_logits_eval = build_pathnet_graph(
p_inputs, p_labels, p_task_id, pathnet, training=False)
session.run(tf.global_variables_initializer())
tf.contrib.summary.initialize(session=session)
saver = tf.train.Saver(tf.global_variables())
start_step = 0
p_task_accuracies = {}
accuracy_summary_op = {}
for data_split in evaluate_on:
p_task_accuracies[data_split], accuracy_summary_op[data_split] = \
create_accuracy_summary_ops(
task_names, summary_name_prefix='final_eval_%s' % data_split)
if resume_checkpoint_dir is not None:
print('Resuming from checkpoint: %s' % resume_checkpoint_dir)
last_global_step = int(resume_checkpoint_dir.split('-')[-1])
assert last_global_step % num_tasks == 0
start_step = last_global_step // num_tasks
saver.restore(session, resume_checkpoint_dir)
for dataset in task_data:
for data_split in evaluate_on:
num_batches = count_batches(
session, dataset[data_split].make_one_shot_iterator().get_next())
dataset[data_split] = dataset[data_split].repeat()
dataset[data_split] = (
dataset[data_split].make_one_shot_iterator().get_next())
dataset[data_split] = (dataset[data_split], num_batches)
for step in tqdm(range(start_step, num_steps)):
random.shuffle(train_data)
run_pathnet_training_step(
session, p_inputs, p_labels, p_task_id, train_step_op, train_data)
if step + 1 in eval_steps:
for data_split in evaluate_on:
eval_data = [dataset[data_split] for dataset in task_data]
print('Running evaluation on: %s' % data_split)
task_accuracies = run_pathnet_evaluation(
session=session,
p_inputs=p_inputs,
p_task_id=p_task_id,
out_logits=out_logits_eval,
task_names=task_names,
eval_data=eval_data)
run_accuracy_summary_ops(
session,
p_task_accuracies[data_split],
task_accuracies,
accuracy_summary_op[data_split])
if (step + 1) % save_checkpoint_every_n_steps == 0:
path = summary_dir + '/chkpt'
saver.save(
session, path, global_step=tf.train.get_or_create_global_step())
def compute_output_shape_and_create_routed_layer(
keras_components, in_shape, router_fn, router_out):
"""A utility to wrap a list of keras layers into a routed layer.
Args:
keras_components: (list of keras.layers.Layer) components to wrap.
in_shape: (sequence of ints) expected input shape to this layer (excluding
batch dimension).
router_fn: function that, given a single argument `num_components`, returns
a router (see routers in `pathnet/pathnet_lib.py`) for a layer containing
`num_components` components.
router_out: a router (see routers in `pathnet/pathnet_lib.py`) to use to
route into the next layer.
Raises:
Exception: if components in `keras_components` would produce different
output shapes for the given input shape `in_shape`.
Returns:
A pair of (`layers`, `out_shape`), where `layers` is a list of PathNet
layers (returned from `create_wrapped_routed_layer`) and `out_shape` is
the output shape (excluding batch dimension), computed based on
`keras_components` and `in_shape`.
"""
num_components = len(keras_components)
assert num_components >= 1
# Compute output shapes by using `compute_output_shape`. Note that we
# temporarily add the batch dimension of 1, and then remove it.
out_shapes = [
component.compute_output_shape([1] + in_shape)[1:]
for component in keras_components
]
out_shape = out_shapes[0]
# Check if all outputs are the same.
for shape in out_shapes:
if shape != out_shape:
raise Exception(
'Output shapes for keras components do not match:'
' got %s and %s' % (str(out_shape), str(shape)))
components = [pn_components.KerasComponent(
'KerasComponent', component, out_shape) for component in keras_components]
return create_wrapped_routed_layer(
components=components,
router=router_fn(num_components),
router_out=router_out,
combiner=pn.WeightedSumCombiner(),
in_shape=in_shape,
out_shape=out_shape,
sparse=False
), out_shape
def get_router_fn_by_name(num_tasks, routing_method_name, **kwargs):
"""Returns a `router_fn` based on its name.
Args:
num_tasks: (int) number of tasks.
routing_method_name: (string) name of the allocation pattern, one of:
'no_sharing' - the `i`-th task is routed only to the `i`-th component.
This method can be only used for layer with `num_tasks` components.
'shared_bottom' - every task is routed to all components.
'gumbel_matrix' - uses a `pathnet_lib.GumbelMatrixRouter`.
**kwargs: additional keyword arguments that will be passed as constructor
arguments when creating the router.
Raises:
Exception: if `routing_method_name` is outside of the allowed set.
Returns:
A `router_fn` function for the given name. This function, when given
a single argument `num_components`, returns a router (see routers in
`pathnet/pathnet_lib.py`) for a layer containing `num_components`
components. The returned router assumes the number of tasks is `num_tasks`.
"""
def no_sharing_router_fn(num_components):
if num_components != num_tasks:
raise Exception(
'Got %d components, and %d tasks. The `no_sharing` routing method '
'was used, which expects these numbers to match.' % (
num_components, num_tasks))
return pn.IndependentTaskBasedRouter(
num_tasks=num_tasks,
record_summaries=True,
**kwargs)
def shared_bottom_router_fn(num_components):
return pn.FixedRouter(
tf.ones((num_tasks, num_components)),
record_summaries=True,
**kwargs)
def gumbel_router_fn(num_components):
return pn.GumbelMatrixRouter(
num_tasks=num_tasks,
num_out_paths=num_components,
record_summaries=True,
**kwargs)
if routing_method_name == 'no_sharing':
return no_sharing_router_fn
elif routing_method_name == 'shared_bottom':
return shared_bottom_router_fn
elif routing_method_name == 'gumbel_matrix':
return gumbel_router_fn
else:
raise Exception('Unrecognized method: %s' % routing_method_name)
def create_layer_with_task_specific_linear_heads(num_classes_for_tasks):
"""Returns a `pathnet_lib.ComponentsLayer` with linear task specific layers.
This is a small helper function to create a layer of fully connected
components for multiple classification tasks (with possibly different
numbers of classses). The constructed layer assumes that the next layer
contains task heads to compute the task loss, and uses a
`pathnet_lib.TaskBasedRouter` to route into the next layer.
Args:
num_classes_for_tasks: (list of ints) number of classes for each task.
Returns:
A `pathnet_lib.ComponentsLayer` containing one FC layer per task.
"""
num_tasks = len(num_classes_for_tasks)
components = []
for num_classes in num_classes_for_tasks:
components.append(pn.RoutedComponent(
pn_components.FCLComponent(numbers_of_units=[num_classes]),
pn.IndependentTaskBasedRouter(num_tasks=num_tasks)))
return pn.ComponentsLayer(components=components, combiner=pn.SelectCombiner())
def create_auxiliary_loss_function(routers, **kwargs):
"""Returns an auxiliary loss function that can be used with PathNet.
This function can take any subset of the following arguments, which correspond
to adding various auxiliary losses. All kinds of losses are listed below,
along with parameters that have to be supplied to enable them.
Disconnect penalty:
- `disconnect_penalty`: a coefficient to multiply by the probability, that
some task selects zero components in some layer.
Connection penalty:
- `connection_penalty`: a penalty per every active component.
Budget exceeded penalty:
- `budget`: a value in the [0.0, 1.0] range, denoting the target fraction
of the network that we want each task to use. The network will
be penalized only if `budget` is exceeded.
- `num_total_components`: total number of components in the network (only in
routed layers).
- `budget_penalty`: if `budget` is exceeded, the value by which
it is exceeded is multiplied by this coefficient.
Entropy penalty:
- `num_total_steps`: number of steps the traning will take (i.e. the maximum
value that will ever be attained by `global_step`).
- `entropy_penalty`: a target value for entropy penalty applied at the end
of training.
- `entropy_penalty_alpha`: a hyperparameter to control the speed at which
the entropy penalty increases from 0 to `entropy_penalty`. The actual
entropy penalty at time `t` will be:
`entropy_penalty * (t / num_total_steps)^entropy_penalty_alpha`
Args:
routers: routers in all routed layers which should be taken into account
for the auxiliary losses.
**kwargs: parameters for selected auxiliary losses.
Returns:
A function that computes the total auxiliary loss from the current state.
The returned function can be directly passed into `ModelHeadComponent`
under the `auxiliary_loss_fn` argument.
"""
def auxiliary_loss_fn(state):
"""Computes an auxiliary loss.
Args:
state: (dict) PathNet state as a dict containing a 'task_id' entry with
scalar task id.
Raises:
Exception: if some parameter names are not recognized.
Returns:
The total auxiliary loss for the given task and at the given timestep.
"""
task_id = state['task_id']
loss = tf.constant(0.0)
for key, value in kwargs.items():
if key == 'disconnect_penalty':
disconnect_penalty = value
if disconnect_penalty > 0.0:
loss += disconnect_penalty * tf.reduce_sum([
router.get_probability_of_having_no_connections(task_id)
for router in routers
])
elif key == 'connection_penalty':
connection_penalty = value
if connection_penalty > 0.0:
loss += connection_penalty * tf.reduce_sum([
router.get_expected_number_of_connections_for_task(task_id)
for router in routers
])
elif key == 'budget_penalty':
budget_penalty = value
if budget_penalty > 0.0:
budget = kwargs['budget']
num_total_components = kwargs['num_total_components']
expected_number_of_connections = tf.reduce_sum([
router.get_expected_number_of_connections_for_task(task_id)
for router in routers
])
expected_fraction_of_connections = (
expected_number_of_connections / num_total_components)
loss += budget_penalty * tf.math.maximum(
tf.constant(0.0), expected_fraction_of_connections - budget)
elif key in ['budget', 'num_total_components']:
pass
elif key == 'entropy_penalty':
entropy_penalty = value
if entropy_penalty > 0.0:
entropy_penalty_alpha = kwargs['entropy_penalty_alpha']
num_total_steps = kwargs['num_total_steps']
global_step = tf.train.get_or_create_global_step()
current_entropy_penalty = entropy_penalty * tf.math.pow(
global_step / num_total_steps, entropy_penalty_alpha)
current_entropy_penalty = tf.dtypes.cast(
current_entropy_penalty, dtype=tf.float32)
loss += current_entropy_penalty * tf.reduce_sum([
router.get_entropy(task_id) for router in routers
])
elif key in ['entropy_penalty_alpha', 'num_total_steps']:
pass
elif key == 'l2_penalty':
l2_penalty = value
if l2_penalty > 0.0:
# Penalize all trainable variables apart from biases and
# allocation logits.
l2_penalty_vars = [
var for var in tf.trainable_variables()
if 'bias' not in var.name and 'router_dist' not in var.name
]
loss += tf.add_n([
tf.nn.l2_loss(var) for var in l2_penalty_vars
]) * l2_penalty
else:
raise Exception('Unrecognized parameter for auxiliary losses: %s' % key)
return loss
return auxiliary_loss_fn
| apache-2.0 |
vjanmey/EpicMudfia | com/planet_ink/coffee_mud/Locales/EndlessSky.java | 6191 | package com.planet_ink.coffee_mud.Locales;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2014 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class EndlessSky extends StdGrid
{
@Override public String ID(){return "EndlessSky";}
protected boolean crossLinked=false;
public EndlessSky()
{
super();
basePhyStats.setWeight(1);
recoverPhyStats();
setDisplayText("Up in the sky");
setDescription("");
xsize=CMProps.getIntVar(CMProps.Int.SKYSIZE);
ysize=CMProps.getIntVar(CMProps.Int.SKYSIZE);
if(xsize<0) xsize=xsize*-1;
if(ysize<0) ysize=ysize*-1;
if((xsize==0)||(ysize==0))
{
xsize=3;
ysize=3;
}
}
@Override public int domainType(){return Room.DOMAIN_OUTDOORS_AIR;}
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost,msg))
return false;
return InTheAir.isOkAirAffect(this,msg);
}
@Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
super.executeMsg(myHost,msg);
InTheAir.airAffects(this,msg);
}
@Override public String getGridChildLocaleID(){return "InTheAir";}
@Override
protected Room findCenterRoom(int dirCode)
{
if(dirCode!=Directions.DOWN)
return super.findCenterRoom(dirCode);
return subMap[subMap.length-1][subMap[0].length-1];
}
@Override
protected void buildFinalLinks()
{
final Exit ox=CMClass.getExit("Open");
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
if(d==Directions.GATE) continue;
final Room dirRoom=rawDoors()[d];
Exit dirExit=getRawExit(d);
if((dirExit==null)||(dirExit.hasADoor()))
dirExit=ox;
if(dirRoom!=null)
{
Exit altExit=dirRoom.getRawExit(Directions.getOpDirectionCode(d));
if(altExit==null) altExit=ox;
switch(d)
{
case Directions.NORTH:
for (final Room[] element : subMap)
linkRoom(element[0],dirRoom,d,dirExit,altExit);
break;
case Directions.SOUTH:
for (final Room[] element : subMap)
linkRoom(element[subMap[0].length-1],dirRoom,d,dirExit,altExit);
break;
case Directions.EAST:
for(int y=0;y<subMap[0].length;y++)
linkRoom(subMap[subMap.length-1][y],dirRoom,d,dirExit,altExit);
break;
case Directions.WEST:
for(int y=0;y<subMap[0].length;y++)
linkRoom(subMap[0][y],dirRoom,d,dirExit,altExit);
break;
case Directions.UP:
linkRoom(subMap[0][0],dirRoom,d,dirExit,altExit);
break;
case Directions.DOWN:
linkRoom(subMap[subMap.length-1][subMap[0].length-1],dirRoom,d,dirExit,altExit);
break;
case Directions.NORTHEAST:
linkRoom(subMap[subMap.length-1][0],dirRoom,d,dirExit,altExit);
break;
case Directions.NORTHWEST:
linkRoom(subMap[0][0],dirRoom,d,dirExit,altExit);
break;
case Directions.SOUTHEAST:
linkRoom(subMap[subMap.length-1][subMap[0].length-1],dirRoom,d,dirExit,altExit);
break;
case Directions.SOUTHWEST:
linkRoom(subMap[0][subMap[0].length-1],dirRoom,d,dirExit,altExit);
break;
}
}
}
}
@Override
public void buildGrid()
{
clearGrid(null);
try
{
final Exit ox=CMClass.getExit("Open");
subMap=new Room[xsize][ysize];
for(int x=0;x<subMap.length;x++)
for(int y=0;y<subMap[x].length;y++)
{
final Room newRoom=getGridRoom(x,y);
if(newRoom!=null)
{
subMap[x][y]=newRoom;
if((y>0)&&(subMap[x][y-1]!=null))
{
linkRoom(newRoom,subMap[x][y-1],Directions.NORTH,ox,ox);
linkRoom(newRoom,subMap[x][y-1],Directions.UP,ox,ox);
}
if((x>0)&&(subMap[x-1][y]!=null))
linkRoom(newRoom,subMap[x-1][y],Directions.WEST,ox,ox);
if((y>0)&&(x>0)&&(subMap[x-1][y-1]!=null)&&(Directions.NORTHWEST<Directions.NUM_DIRECTIONS()))
linkRoom(newRoom,subMap[x-1][y-1],Directions.NORTHWEST,ox,ox);
if((y>0)&&(x<subMap.length-1)&&(subMap[x+1][y-1]!=null)&&(Directions.NORTHEAST<Directions.NUM_DIRECTIONS()))
linkRoom(newRoom,subMap[x+1][y-1],Directions.NORTHEAST,ox,ox);
}
}
buildFinalLinks();
if((subMap[0][0]!=null)
&&(subMap[0][0].rawDoors()[Directions.UP]==null)
&&(xsize>1))
linkRoom(subMap[0][0],subMap[1][0],Directions.UP,ox,ox);
for(int y=0;y<subMap[0].length;y++)
linkRoom(subMap[0][y],subMap[subMap.length-1][y],Directions.WEST,ox,ox);
for (final Room[] element : subMap)
linkRoom(element[0],element[element.length-1],Directions.NORTH,ox,ox);
for(int x=1;x<subMap.length;x++)
linkRoom(subMap[x][0],subMap[x-1][subMap[x-1].length-1],Directions.UP,ox,ox);
if(Directions.NORTHWEST<Directions.NUM_DIRECTIONS())
linkRoom(subMap[0][0],subMap[subMap.length-1][subMap[0].length-1],Directions.NORTHWEST,ox,ox);
if(Directions.NORTHEAST<Directions.NUM_DIRECTIONS())
linkRoom(subMap[subMap.length-1][0],subMap[0][subMap[0].length-1],Directions.NORTHEAST,ox,ox);
}
catch(final Exception e)
{
clearGrid(null);
}
}
}
| apache-2.0 |
w9jds/azure-activedirectory-library-for-android | tests/Functional/src/com/microsoft/aad/adal/test/HashMapExtensionTests.java | 4289 | // Copyright © Microsoft Open Technologies, Inc.
//
// All Rights Reserved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
// ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
// PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache License, Version 2.0 for the specific language
// governing permissions and limitations under the License.
package com.microsoft.aad.adal.test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
public class HashMapExtensionTests extends AndroidTestHelper {
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
@SuppressWarnings("unchecked")
public void testURLFormDecodeNegative() throws IllegalArgumentException,
ClassNotFoundException, NoSuchMethodException, InstantiationException,
IllegalAccessException, InvocationTargetException {
final String methodName = "URLFormDecode";
Object foo = ReflectionUtils.getNonPublicInstance("com.microsoft.aad.adal.HashMapExtensions");
Method m = ReflectionUtils.getTestMethod(foo, methodName, String.class);
HashMap<String, String> result = (HashMap<String, String>)m.invoke(foo, "nokeyvalue");
assertNotNull(result);
assertTrue(result.isEmpty());
result = (HashMap<String, String>)m.invoke(foo, "&&&");
assertNotNull(result);
assertTrue(result.isEmpty());
result = (HashMap<String, String>)m.invoke(foo, "=&=");
assertNotNull(result);
assertTrue(result.isEmpty());
result = (HashMap<String, String>)m.invoke(foo, "=&");
assertNotNull(result);
assertTrue(result.isEmpty());
result = (HashMap<String, String>)m.invoke(foo, "&=");
assertNotNull(result);
assertTrue(result.isEmpty());
result = (HashMap<String, String>)m.invoke(foo, "&a=");
assertNotNull(result);
assertTrue(result.isEmpty());
result = (HashMap<String, String>)m.invoke(foo, "&=b");
assertNotNull(result);
assertTrue(result.isEmpty());
}
@SuppressWarnings("unchecked")
public void testURLFormDecodePositive() throws IllegalArgumentException,
ClassNotFoundException, NoSuchMethodException, InstantiationException,
IllegalAccessException, InvocationTargetException {
final String methodName = "URLFormDecode";
Object foo = ReflectionUtils.getNonPublicInstance("com.microsoft.aad.adal.HashMapExtensions");
Method m = ReflectionUtils.getTestMethod(foo, methodName, String.class);
HashMap<String, String> result = (HashMap<String, String>)m.invoke(foo, "a=b&c=2");
assertNotNull(result);
assertFalse(result.isEmpty());
assertTrue(result.containsKey("a"));
assertTrue(result.containsKey("c"));
assertTrue(result.containsValue("b"));
assertTrue(result.containsValue("2"));
assertTrue(result.containsKey("a"));
assertTrue(result.containsKey("c"));
assertTrue(result.containsValue("b"));
assertTrue(result.containsValue("2"));
result = (HashMap<String, String>)m.invoke(foo, "a=v");
assertNotNull(result);
assertFalse(result.isEmpty());
assertTrue(result.containsKey("a"));
assertTrue(result.containsValue("v"));
result = (HashMap<String, String>)m.invoke(foo, "d=f&");
assertNotNull(result);
assertFalse(result.isEmpty());
assertTrue(result.containsKey("d"));
assertTrue(result.containsValue("f"));
assertTrue(result.size() == 1);
}
private HashMap<String, String> getTestKeyValue(String key, String value) {
HashMap<String, String> result = new HashMap<String, String>();
result.put(key, value);
return result;
}
}
| apache-2.0 |
saghm/mongo-ruby-driver | spec/lite_spec_helper.rb | 4400 | COVERAGE_MIN = 90
CURRENT_PATH = File.expand_path(File.dirname(__FILE__))
SERVER_DISCOVERY_TESTS = Dir.glob("#{CURRENT_PATH}/spec_tests/data/sdam/**/*.yml")
SDAM_MONITORING_TESTS = Dir.glob("#{CURRENT_PATH}/spec_tests/data/sdam_monitoring/*.yml")
SERVER_SELECTION_RTT_TESTS = Dir.glob("#{CURRENT_PATH}/spec_tests/data/server_selection_rtt/*.yml")
SERVER_SELECTION_TESTS = Dir.glob("#{CURRENT_PATH}/spec_tests/data/server_selection/**/*.yml")
MAX_STALENESS_TESTS = Dir.glob("#{CURRENT_PATH}/spec_tests/data/max_staleness/**/*.yml")
CRUD_TESTS = Dir.glob("#{CURRENT_PATH}/spec_tests/data/crud/**/*.yml")
RETRYABLE_WRITES_TESTS = Dir.glob("#{CURRENT_PATH}/spec_tests/data/retryable_writes/**/*.yml")
COMMAND_MONITORING_TESTS = Dir.glob("#{CURRENT_PATH}/spec_tests/data/command_monitoring/**/*.yml")
CONNECTION_STRING_TESTS = Dir.glob("#{CURRENT_PATH}/spec_tests/data/connection_string/*.yml")
URI_OPTIONS_TESTS = Dir.glob("#{CURRENT_PATH}/spec_tests/data/uri_options/*.yml")
DNS_SEEDLIST_DISCOVERY_TESTS = Dir.glob("#{CURRENT_PATH}/spec_tests/data/dns_seedlist_discovery/*.yml")
GRIDFS_TESTS = Dir.glob("#{CURRENT_PATH}/spec_tests/data/gridfs/*.yml")
TRANSACTIONS_TESTS = Dir.glob("#{CURRENT_PATH}/spec_tests/data/transactions/*.yml")
TRANSACTIONS_API_TESTS = Dir.glob("#{CURRENT_PATH}/spec_tests/data/transactions_api/*.yml")
CHANGE_STREAMS_TESTS = Dir.glob("#{CURRENT_PATH}/spec_tests/data/change_streams/*.yml")
if ENV['DRIVERS_TOOLS']
CLIENT_CERT_PEM = ENV['DRIVER_TOOLS_CLIENT_CERT_PEM']
CLIENT_KEY_PEM = ENV['DRIVER_TOOLS_CLIENT_KEY_PEM']
CA_PEM = ENV['DRIVER_TOOLS_CA_PEM']
CLIENT_KEY_ENCRYPTED_PEM = ENV['DRIVER_TOOLS_CLIENT_KEY_ENCRYPTED_PEM']
else
SSL_CERTS_DIR = "#{CURRENT_PATH}/support/certificates"
CLIENT_PEM = "#{SSL_CERTS_DIR}/client.pem"
CLIENT_PASSWORD_PEM = "#{SSL_CERTS_DIR}/password_protected.pem"
CA_PEM = "#{SSL_CERTS_DIR}/ca.pem"
CRL_PEM = "#{SSL_CERTS_DIR}/crl.pem"
CLIENT_KEY_PEM = "#{SSL_CERTS_DIR}/client_key.pem"
CLIENT_CERT_PEM = "#{SSL_CERTS_DIR}/client_cert.pem"
CLIENT_KEY_ENCRYPTED_PEM = "#{SSL_CERTS_DIR}/client_key_encrypted.pem"
CLIENT_KEY_PASSPHRASE = "passphrase"
end
require 'mongo'
unless ENV['CI']
begin
require 'byebug'
rescue LoadError
# jruby - try pry
begin
require 'pry'
# jruby likes to raise random error classes, in this case
# NameError in addition to LoadError
rescue Exception
end
end
end
require 'support/spec_config'
Mongo::Logger.logger = Logger.new($stdout)
unless SpecConfig.instance.client_debug?
Mongo::Logger.logger.level = Logger::INFO
end
Encoding.default_external = Encoding::UTF_8
autoload :Timecop, 'timecop'
require 'ice_nine'
require 'support/matchers'
require 'support/lite_constraints'
require 'support/event_subscriber'
require 'support/server_discovery_and_monitoring'
require 'support/server_selection_rtt'
require 'support/server_selection'
require 'support/sdam_monitoring'
require 'support/crud'
require 'support/command_monitoring'
require 'support/connection_string'
require 'support/gridfs'
require 'support/transactions'
require 'support/change_streams'
require 'support/common_shortcuts'
require 'support/client_registry'
require 'support/client_registry_macros'
require 'support/json_ext_formatter'
require 'support/sdam_formatter_integration'
if SpecConfig.instance.mri?
require 'timeout_interrupt'
else
require 'timeout'
TimeoutInterrupt = Timeout
end
RSpec.configure do |config|
config.extend(CommonShortcuts)
config.extend(LiteConstraints)
config.include(ClientRegistryMacros)
if SpecConfig.instance.ci?
SdamFormatterIntegration.subscribe
config.add_formatter(JsonExtFormatter, File.join(File.dirname(__FILE__), '../tmp/rspec.json'))
config.around(:each) do |example|
SdamFormatterIntegration.assign_log_entries(nil)
begin
example.run
ensure
SdamFormatterIntegration.assign_log_entries(example.id)
end
end
end
if SpecConfig.instance.ci?
# Allow a max of 30 seconds per test.
# Tests should take under 10 seconds ideally but it seems
# we have some that run for more than 10 seconds in CI.
config.around(:each) do |example|
TimeoutInterrupt.timeout(45) do
example.run
end
end
end
end
EventSubscriber.initialize
if SpecConfig.instance.active_support?
require "active_support/time"
require 'mongo/active_support'
end
| apache-2.0 |
Artyou/killbill-ingenico-plugin | src/main/java/org/killbill/billing/plugin/ingenico/client/model/UserData.java | 6875 | /*
* Copyright 2014-2016 Groupon, Inc
* Copyright 2014-2016 The Billing Project, LLC
*
* The Billing Project 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.killbill.billing.plugin.ingenico.client.model;
import org.joda.time.DateTime;
import org.joda.time.chrono.StrictChronology;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class UserData {
private String shopperEmail;
private String shopperReference;
private Locale shopperLocale;
private String firstName;
private String lastName;
private String gender;
private String telephoneNumber;
private String vatNumber;
private DateTime dateOfBirth;
private String shopperIP;
private String companyName;
public String getShopperEmail() {
return shopperEmail;
}
public void setShopperEmail(final String shopperEmail) {
this.shopperEmail = shopperEmail;
}
public String getShopperReference() {
return shopperReference;
}
public void setShopperReference(final String shopperReference) {
this.shopperReference = shopperReference;
}
public Locale getShopperLocale() {
return shopperLocale;
}
public void setShopperLocale(final Locale shopperLocale) {
this.shopperLocale = shopperLocale;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(final String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(final String gender) {
this.gender = gender;
}
public String getTelephoneNumber() {
return telephoneNumber;
}
public void setTelephoneNumber(final String telephoneNumber) {
this.telephoneNumber = telephoneNumber;
}
public String getVatNumber() {
return vatNumber;
}
public void setVatNumber(final String socialSecurityNumber) {
this.vatNumber = socialSecurityNumber;
}
public DateTime getDateOfBirth() {
return dateOfBirth;
}
public String getFormattedDateOfBirth(String format) {
if(null == getDateOfBirth()) return null;
SimpleDateFormat ft = new SimpleDateFormat(format);
return ft.format(getDateOfBirth());
}
public void setDateOfBirth(final DateTime dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getShopperIP() {
return shopperIP;
}
public void setShopperIP(final String shopperIP) {
this.shopperIP = shopperIP;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(final String companyName) {
this.companyName = companyName;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("UserData{");
sb.append("shopperEmail='").append(shopperEmail).append('\'');
sb.append(", shopperReference='").append(shopperReference).append('\'');
sb.append(", shopperLocale=").append(shopperLocale);
sb.append(", firstName='").append(firstName).append('\'');
sb.append(", lastName='").append(lastName).append('\'');
sb.append(", gender='").append(gender).append('\'');
sb.append(", telephoneNumber='").append(telephoneNumber).append('\'');
sb.append(", vatNumber='").append(vatNumber).append('\'');
sb.append(", dateOfBirth=").append(dateOfBirth);
sb.append(", shopperIP='").append(shopperIP).append('\'');
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final UserData userData = (UserData) o;
if (shopperEmail != null ? !shopperEmail.equals(userData.shopperEmail) : userData.shopperEmail != null) {
return false;
}
if (shopperReference != null ? !shopperReference.equals(userData.shopperReference) : userData.shopperReference != null) {
return false;
}
if (shopperLocale != null ? !shopperLocale.equals(userData.shopperLocale) : userData.shopperLocale != null) {
return false;
}
if (firstName != null ? !firstName.equals(userData.firstName) : userData.firstName != null) {
return false;
}
if (lastName != null ? !lastName.equals(userData.lastName) : userData.lastName != null) {
return false;
}
if (gender != null ? !gender.equals(userData.gender) : userData.gender != null) {
return false;
}
if (telephoneNumber != null ? !telephoneNumber.equals(userData.telephoneNumber) : userData.telephoneNumber != null) {
return false;
}
if (vatNumber != null ? !vatNumber.equals(userData.vatNumber) : userData.vatNumber != null) {
return false;
}
if (dateOfBirth != null ? !dateOfBirth.equals(userData.dateOfBirth) : userData.dateOfBirth != null) {
return false;
}
return shopperIP != null ? shopperIP.equals(userData.shopperIP) : userData.shopperIP == null;
}
@Override
public int hashCode() {
int result = shopperEmail != null ? shopperEmail.hashCode() : 0;
result = 31 * result + (shopperReference != null ? shopperReference.hashCode() : 0);
result = 31 * result + (shopperLocale != null ? shopperLocale.hashCode() : 0);
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
result = 31 * result + (gender != null ? gender.hashCode() : 0);
result = 31 * result + (telephoneNumber != null ? telephoneNumber.hashCode() : 0);
result = 31 * result + (vatNumber != null ? vatNumber.hashCode() : 0);
result = 31 * result + (dateOfBirth != null ? dateOfBirth.hashCode() : 0);
result = 31 * result + (shopperIP != null ? shopperIP.hashCode() : 0);
return result;
}
}
| apache-2.0 |
elzzup/annict | app/helpers/markdown_helper.rb | 361 | # frozen_string_literal: true
require "github/markup"
module MarkdownHelper
def render_markdown(text)
html = GitHub::Markup.render_s(GitHub::Markups::MARKUP_MARKDOWN, text)
doc = Nokogiri::HTML::DocumentFragment.parse(html)
doc.search("img").each do |img|
img["class"] = "img-fluid img-thumbnail rounded"
end
doc.to_html
end
end
| apache-2.0 |
xschildw/Synapse-Repository-Services | lib/lib-table-cluster/src/main/java/org/sagebionetworks/table/cluster/ColumnTypeInfo.java | 7508 | package org.sagebionetworks.table.cluster;
import static org.sagebionetworks.repo.model.table.ColumnConstants.*;
import org.apache.commons.lang3.StringUtils;
import org.sagebionetworks.repo.model.table.ColumnType;
import org.sagebionetworks.repo.model.table.ValueParser;
import org.sagebionetworks.repo.model.table.parser.BooleanParser;
import org.sagebionetworks.repo.model.table.parser.DateToLongParser;
import org.sagebionetworks.repo.model.table.parser.DoubleParser;
import org.sagebionetworks.repo.model.table.parser.EntityIdParser;
import org.sagebionetworks.repo.model.table.parser.ListStringParser;
import org.sagebionetworks.repo.model.table.parser.LongParser;
import org.sagebionetworks.repo.model.table.parser.StringParser;
/**
* Mapping of ColumnType to database information.
*
*/
public enum ColumnTypeInfo {
INTEGER (ColumnType.INTEGER, MySqlColumnType.BIGINT, new LongParser(), 20L),
FILEHANDLEID(ColumnType.FILEHANDLEID, MySqlColumnType.BIGINT, new LongParser(), 20L),
DATE (ColumnType.DATE, MySqlColumnType.BIGINT, new DateToLongParser(), 20L),
ENTITYID (ColumnType.ENTITYID, MySqlColumnType.BIGINT, new EntityIdParser(), 20L),
SUBMISSIONID(ColumnType.SUBMISSIONID, MySqlColumnType.BIGINT, new LongParser(), 20L),
EVALUATIONID(ColumnType.EVALUATIONID, MySqlColumnType.BIGINT, new LongParser(), 20L),
LINK (ColumnType.LINK, MySqlColumnType.VARCHAR, new StringParser(), null),
STRING (ColumnType.STRING, MySqlColumnType.VARCHAR, new StringParser(), null),
DOUBLE (ColumnType.DOUBLE, MySqlColumnType.DOUBLE, new DoubleParser(), null),
BOOLEAN (ColumnType.BOOLEAN, MySqlColumnType.BOOLEAN, new BooleanParser(), null),
LARGETEXT (ColumnType.LARGETEXT, MySqlColumnType.MEDIUMTEXT, new StringParser(), null),
USERID (ColumnType.USERID, MySqlColumnType.BIGINT, new LongParser(), 20L),
STRING_LIST (ColumnType.STRING_LIST, MySqlColumnType.JSON, new ListStringParser(new StringParser(),false), null),
INTEGER_LIST(ColumnType.INTEGER_LIST, MySqlColumnType.JSON, new ListStringParser(new LongParser(),false), null),
BOOLEAN_LIST(ColumnType.BOOLEAN_LIST, MySqlColumnType.JSON, new ListStringParser(new BooleanParser(),false), null),
DATE_LIST (ColumnType.DATE_LIST, MySqlColumnType.JSON, new ListStringParser(new DateToLongParser(),false), null),
// Entity id lists need to be re-parsed to prepend "syn" to its elements
ENTITYID_LIST(ColumnType.ENTITYID_LIST, MySqlColumnType.JSON, new ListStringParser(new EntityIdParser(),true), null),
USERID_LIST (ColumnType.USERID_LIST, MySqlColumnType.JSON, new ListStringParser(new LongParser(),false), null)
;
private ColumnType type;
private MySqlColumnType mySqlType;
private Long maxSize;
private ValueParser parser;
private ColumnTypeInfo(ColumnType type, MySqlColumnType mySqlType, ValueParser parser, Long maxSize){
this.type = type;
this.mySqlType = mySqlType;
this.maxSize = maxSize;
this.parser = parser;
}
/**
* Get the SQL to define a column of this type in MySQL.
* @param inputSize
* @param defaultValue
* @param useDepricatedUtf8ThreeBytes Should only be set to true for the few old
* @return
*/
public String toSql(Long inputSize, String defaultValue, boolean useDepricatedUtf8ThreeBytes){
StringBuilder builder = new StringBuilder();
builder.append(mySqlType.name());
Long size = maxSize;
if(inputSize == null && requiresInputMaxSize()){
throw new IllegalArgumentException("Size must be provided for type: "+type);
}
// use the input size if given
if(inputSize != null){
size = inputSize;
}
if(size != null && mySqlType.hasSize()){
builder.append("(");
builder.append(size);
builder.append(")");
}
if(isStringType()){
builder.append(" ");
if(useDepricatedUtf8ThreeBytes) {
// This is a special case to support old large tables with UTF-8 3 bytes.
builder.append(DEPREICATED_THREE_BYTE_UTF8);
}else {
builder.append(CHARACTER_SET_UTF8_COLLATE_UTF8_GENERAL_CI);
}
}
// default
builder.append(" ");
appendDefaultValue(builder, defaultValue);
// Add the column type as a comment
builder.append(" COMMENT '").append(this.type.name()).append("'");
return builder.toString();
}
/**
* Is the type a string type?
*
* @return
*/
public boolean isStringType(){
return (MySqlColumnType.VARCHAR.equals(mySqlType) || MySqlColumnType.MEDIUMTEXT.equals(mySqlType));
}
/**
* Does this type require an input maximum size?
*
* @return
*/
public boolean requiresInputMaxSize(){
return (ColumnType.STRING.equals(type) || ColumnType.LINK.equals(type));
}
/**
* Lookup the ColumnTypeInfo for a given type.
* @param type
* @return
*/
public static ColumnTypeInfo getInfoForType(ColumnType type){
for(ColumnTypeInfo info: ColumnTypeInfo.values()){
if(info.type.equals(type)){
return info;
}
}
throw new IllegalArgumentException("Unknown ColumnType: "+type);
}
/**
* Parse the given value into an object that can be inserted into the database.
*
* @param value
* @return
*/
public Object parseValueForDatabaseWrite(String value){
if(value == null) {
return null;
}
return parser.parseValueForDatabaseWrite(value);
}
/**
* Parser the value for a database read.
*
* @param value
* @return
*/
public String parseValueForDatabaseRead(String value) {
if(value == null){
return null;
}
return parser.parseValueForDatabaseRead(value);
}
/**
* Append the a default value for this type to the passed builder.
*
* @param builder
* @param defaultValue
*/
public void appendDefaultValue(StringBuilder builder, String defaultValue){
builder.append("DEFAULT ");
if(defaultValue == null){
builder.append("NULL");
}else{
// escape single quotes
// NOTE: This originally used StringEscapeUtils.escapeSql() which only ever escaped single quotes and has been removed in later versions.
// https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html#escapeSql(java.lang.String)
// https://stackoverflow.com/questions/32096614/migrating-stringescapeutils-escapesql-from-commons-lang
defaultValue = StringUtils.replace(defaultValue, "'", "''");
// Validate the default can be applied.
Object objectValue = parseValueForDatabaseWrite(defaultValue);
if(mySqlType == MySqlColumnType.JSON){
builder.append("(");
}
if(isStringType() || mySqlType == MySqlColumnType.JSON){
builder.append("'");
}
builder.append(objectValue.toString());
if(isStringType() || mySqlType == MySqlColumnType.JSON){
builder.append("'");
}
if(mySqlType == MySqlColumnType.JSON){
builder.append(")");
}
}
}
/**
* The ColumnType for this info.
* @return
*/
public ColumnType getType() {
return type;
}
/**
* The MySqlColumnType for this info.
* @return
*/
public MySqlColumnType getMySqlType() {
return mySqlType;
}
/**
* Get default maximum size for this info.
* @return
*/
public Long getMaxSize() {
return maxSize;
}
/**
* The value parser used by this info.
* @return
*/
public ValueParser getParser() {
return parser;
}
}
| apache-2.0 |
lslewis901/SqlSchemaTool | SQL Schema Tool GUI/Forms/Main.Designer.cs | 80568 | namespace Lewis.SST.Gui
{
partial class Main
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Main));
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.BottomToolStripPanel = new System.Windows.Forms.ToolStripPanel();
this.statusBar = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabel2 = new System.Windows.Forms.ToolStripStatusLabel();
this.progressIndicator = new System.Windows.Forms.ToolStripProgressBar();
this.TopToolStripPanel = new System.Windows.Forms.ToolStripPanel();
this.mainToolbar = new System.Windows.Forms.ToolStrip();
this.btnOpenFile = new System.Windows.Forms.ToolStripSplitButton();
this.sqlToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.xMLFilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.btnSaveFile = new System.Windows.Forms.ToolStripButton();
this.btnSaveAll = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.btnCut = new System.Windows.Forms.ToolStripButton();
this.btnCopy = new System.Windows.Forms.ToolStripButton();
this.btnPaste = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.btnUndo = new System.Windows.Forms.ToolStripButton();
this.btnRedo = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.btnServerExplorer = new System.Windows.Forms.ToolStripButton();
this.btnXmlExplorer = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.btnAbout = new System.Windows.Forms.ToolStripButton();
this.mainMenu = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.fileToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.xMLFileToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.closeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.closeAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator();
this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator();
this.findToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.findAndReplaceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.findAndReplaceAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.actionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.compareSchemasToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.compareXMLSpanshotsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.selectedDatabasesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.xMLSnapshotAndDatabaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.generateSchemaToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.chooseXMLSnapshotToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.selectedDatabaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.createServerDTSPackageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.xMLFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.compareDataFromToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.selectedTablesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem8 = new System.Windows.Forms.ToolStripSeparator();
this.setSecurityToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addServerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripSeparator();
this.getDTSPackageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.generateXMLOutputToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dTSPackageSnapshotToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.databaseSnapshotToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.serverExplorerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.xmlExplorerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem9 = new System.Windows.Forms.ToolStripSeparator();
this.iconsAndTextToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.windowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.RightToolStripPanel = new System.Windows.Forms.ToolStripPanel();
this.LeftToolStripPanel = new System.Windows.Forms.ToolStripPanel();
this.ContentPanel = new System.Windows.Forms.ToolStripContentPanel();
this.dockPanel = new WeifenLuo.WinFormsUI.Docking.DockPanel();
this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
this.ActionToolbar = new System.Windows.Forms.ToolStrip();
this.btnSetSecurity = new System.Windows.Forms.ToolStripButton();
this.btnAddServer = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.btnCompareSelected = new System.Windows.Forms.ToolStripSplitButton();
this.createCommandlineBatchFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.btnGenerateSchema = new System.Windows.Forms.ToolStripSplitButton();
this.createCommandToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.btnCreateDTSPackage = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.btnGetDTSPackages = new System.Windows.Forms.ToolStripButton();
this.btnGenXml = new System.Windows.Forms.ToolStripButton();
this.btnGenDatabase = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.btnSyncXml = new System.Windows.Forms.ToolStripButton();
this.btnSelect = new System.Windows.Forms.ToolStripButton();
this.btnRefreshServers = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.btnHTML = new System.Windows.Forms.ToolStripSplitButton();
this.standardViewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.statusBar.SuspendLayout();
this.mainToolbar.SuspendLayout();
this.mainMenu.SuspendLayout();
this.toolStripContainer1.BottomToolStripPanel.SuspendLayout();
this.toolStripContainer1.ContentPanel.SuspendLayout();
this.toolStripContainer1.TopToolStripPanel.SuspendLayout();
this.toolStripContainer1.SuspendLayout();
this.ActionToolbar.SuspendLayout();
this.SuspendLayout();
//
// imageList1
//
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
this.imageList1.Images.SetKeyName(0, "Web_XML.ico");
this.imageList1.Images.SetKeyName(1, "Utility_VBScript.ico");
this.imageList1.Images.SetKeyName(2, "Web_GlobalAppClass.ico");
this.imageList1.Images.SetKeyName(3, "helpdoc.ico");
this.imageList1.Images.SetKeyName(4, "propertiesORoptions.ico");
this.imageList1.Images.SetKeyName(5, "textdoc.ico");
this.imageList1.Images.SetKeyName(6, "document.ico");
this.imageList1.Images.SetKeyName(7, "inifile.ico");
this.imageList1.Images.SetKeyName(8, "rc_html.ico");
this.imageList1.Images.SetKeyName(9, "idr_dll.ico");
this.imageList1.Images.SetKeyName(10, "UtilityText.ico");
this.imageList1.Images.SetKeyName(11, "Web_WebConfig.ico");
this.imageList1.Images.SetKeyName(12, "eventlog.ico");
this.imageList1.Images.SetKeyName(13, "xml.gif");
//
// BottomToolStripPanel
//
this.BottomToolStripPanel.Location = new System.Drawing.Point(0, 0);
this.BottomToolStripPanel.Name = "BottomToolStripPanel";
this.BottomToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.BottomToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0);
this.BottomToolStripPanel.Size = new System.Drawing.Size(0, 0);
//
// statusBar
//
this.statusBar.Dock = System.Windows.Forms.DockStyle.None;
this.statusBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel1,
this.toolStripStatusLabel2,
this.progressIndicator});
this.statusBar.Location = new System.Drawing.Point(0, 0);
this.statusBar.Name = "statusBar";
this.statusBar.Size = new System.Drawing.Size(839, 22);
this.statusBar.TabIndex = 3;
this.statusBar.Text = "statusStrip1";
//
// toolStripStatusLabel1
//
this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
this.toolStripStatusLabel1.Size = new System.Drawing.Size(0, 17);
this.toolStripStatusLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// toolStripStatusLabel2
//
this.toolStripStatusLabel2.MergeAction = System.Windows.Forms.MergeAction.Insert;
this.toolStripStatusLabel2.Name = "toolStripStatusLabel2";
this.toolStripStatusLabel2.Size = new System.Drawing.Size(0, 17);
this.toolStripStatusLabel2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// progressIndicator
//
this.progressIndicator.Name = "progressIndicator";
this.progressIndicator.Size = new System.Drawing.Size(100, 16);
//
// TopToolStripPanel
//
this.TopToolStripPanel.Location = new System.Drawing.Point(0, 0);
this.TopToolStripPanel.Name = "TopToolStripPanel";
this.TopToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.TopToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0);
this.TopToolStripPanel.Size = new System.Drawing.Size(0, 0);
//
// mainToolbar
//
this.mainToolbar.AllowItemReorder = true;
this.mainToolbar.Dock = System.Windows.Forms.DockStyle.None;
this.mainToolbar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btnOpenFile,
this.btnSaveFile,
this.btnSaveAll,
this.toolStripSeparator1,
this.btnCut,
this.btnCopy,
this.btnPaste,
this.toolStripSeparator2,
this.btnUndo,
this.btnRedo,
this.toolStripSeparator3,
this.btnServerExplorer,
this.btnXmlExplorer,
this.toolStripSeparator4,
this.btnAbout});
this.mainToolbar.Location = new System.Drawing.Point(3, 24);
this.mainToolbar.Name = "mainToolbar";
this.mainToolbar.Size = new System.Drawing.Size(298, 25);
this.mainToolbar.TabIndex = 2;
this.mainToolbar.Text = "Toolbar Buttons";
//
// btnOpenFile
//
this.btnOpenFile.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnOpenFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.sqlToolStripMenuItem,
this.xMLFilesToolStripMenuItem});
this.btnOpenFile.Image = ((System.Drawing.Image)(resources.GetObject("btnOpenFile.Image")));
this.btnOpenFile.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnOpenFile.Name = "btnOpenFile";
this.btnOpenFile.Size = new System.Drawing.Size(32, 22);
this.btnOpenFile.Text = "Open Files...";
this.btnOpenFile.ButtonClick += new System.EventHandler(this.btnOpenFile_ButtonClick);
//
// sqlToolStripMenuItem
//
this.sqlToolStripMenuItem.Name = "sqlToolStripMenuItem";
this.sqlToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.sqlToolStripMenuItem.Text = "SQL File...";
this.sqlToolStripMenuItem.Click += new System.EventHandler(this.sqlToolStripMenuItem_Click);
//
// xMLFilesToolStripMenuItem
//
this.xMLFilesToolStripMenuItem.Name = "xMLFilesToolStripMenuItem";
this.xMLFilesToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.xMLFilesToolStripMenuItem.Text = "XML File...";
this.xMLFilesToolStripMenuItem.Click += new System.EventHandler(this.xMLFilesToolStripMenuItem_Click);
//
// btnSaveFile
//
this.btnSaveFile.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnSaveFile.Image = ((System.Drawing.Image)(resources.GetObject("btnSaveFile.Image")));
this.btnSaveFile.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnSaveFile.Name = "btnSaveFile";
this.btnSaveFile.Size = new System.Drawing.Size(23, 22);
this.btnSaveFile.Text = "Save Current Open Document";
this.btnSaveFile.Click += new System.EventHandler(this.btnSaveFile_Click);
//
// btnSaveAll
//
this.btnSaveAll.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnSaveAll.Image = ((System.Drawing.Image)(resources.GetObject("btnSaveAll.Image")));
this.btnSaveAll.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnSaveAll.Name = "btnSaveAll";
this.btnSaveAll.Size = new System.Drawing.Size(23, 22);
this.btnSaveAll.Text = "Save All Open Documents";
this.btnSaveAll.Click += new System.EventHandler(this.btnSaveAll_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// btnCut
//
this.btnCut.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnCut.Image = ((System.Drawing.Image)(resources.GetObject("btnCut.Image")));
this.btnCut.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnCut.Name = "btnCut";
this.btnCut.Size = new System.Drawing.Size(23, 22);
this.btnCut.Text = "Cut selected text";
this.btnCut.Click += new System.EventHandler(this.btnCut_Click);
//
// btnCopy
//
this.btnCopy.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnCopy.Image = ((System.Drawing.Image)(resources.GetObject("btnCopy.Image")));
this.btnCopy.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnCopy.Name = "btnCopy";
this.btnCopy.Size = new System.Drawing.Size(23, 22);
this.btnCopy.Text = "Copy selected text";
this.btnCopy.Click += new System.EventHandler(this.btnCopy_Click);
//
// btnPaste
//
this.btnPaste.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnPaste.Enabled = false;
this.btnPaste.Image = ((System.Drawing.Image)(resources.GetObject("btnPaste.Image")));
this.btnPaste.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnPaste.Name = "btnPaste";
this.btnPaste.Size = new System.Drawing.Size(23, 22);
this.btnPaste.Text = "Paste saved text";
this.btnPaste.Click += new System.EventHandler(this.btnPaste_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25);
//
// btnUndo
//
this.btnUndo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnUndo.Image = ((System.Drawing.Image)(resources.GetObject("btnUndo.Image")));
this.btnUndo.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnUndo.Name = "btnUndo";
this.btnUndo.Size = new System.Drawing.Size(23, 22);
this.btnUndo.Text = "Undo edit";
this.btnUndo.Click += new System.EventHandler(this.btnUndo_Click);
//
// btnRedo
//
this.btnRedo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnRedo.Enabled = false;
this.btnRedo.Image = ((System.Drawing.Image)(resources.GetObject("btnRedo.Image")));
this.btnRedo.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnRedo.Name = "btnRedo";
this.btnRedo.Size = new System.Drawing.Size(23, 22);
this.btnRedo.Text = "Redo edit";
this.btnRedo.Click += new System.EventHandler(this.btnRedo_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(6, 25);
//
// btnServerExplorer
//
this.btnServerExplorer.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnServerExplorer.Image = ((System.Drawing.Image)(resources.GetObject("btnServerExplorer.Image")));
this.btnServerExplorer.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnServerExplorer.Name = "btnServerExplorer";
this.btnServerExplorer.Size = new System.Drawing.Size(23, 22);
this.btnServerExplorer.Text = "Display Server Explorer";
this.btnServerExplorer.Click += new System.EventHandler(this.btnServerExplorer_Click);
//
// btnXmlExplorer
//
this.btnXmlExplorer.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnXmlExplorer.Image = ((System.Drawing.Image)(resources.GetObject("btnXmlExplorer.Image")));
this.btnXmlExplorer.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnXmlExplorer.Name = "btnXmlExplorer";
this.btnXmlExplorer.Size = new System.Drawing.Size(23, 22);
this.btnXmlExplorer.Text = "Display XML Explorer";
this.btnXmlExplorer.Click += new System.EventHandler(this.btnXmlExplorer_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(6, 25);
//
// btnAbout
//
this.btnAbout.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnAbout.Image = ((System.Drawing.Image)(resources.GetObject("btnAbout.Image")));
this.btnAbout.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnAbout.Name = "btnAbout";
this.btnAbout.Size = new System.Drawing.Size(23, 22);
this.btnAbout.Text = "Show About Window";
this.btnAbout.Click += new System.EventHandler(this.btnAbout_Click);
//
// mainMenu
//
this.mainMenu.Dock = System.Windows.Forms.DockStyle.None;
this.mainMenu.GripStyle = System.Windows.Forms.ToolStripGripStyle.Visible;
this.mainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.actionToolStripMenuItem,
this.viewToolStripMenuItem,
this.windowToolStripMenuItem,
this.helpToolStripMenuItem});
this.mainMenu.Location = new System.Drawing.Point(0, 0);
this.mainMenu.Name = "mainMenu";
this.mainMenu.Size = new System.Drawing.Size(839, 24);
this.mainMenu.TabIndex = 4;
this.mainMenu.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openToolStripMenuItem,
this.saveToolStripMenuItem,
this.saveAsToolStripMenuItem,
this.saveAllToolStripMenuItem,
this.toolStripMenuItem1,
this.closeToolStripMenuItem,
this.closeAllToolStripMenuItem,
this.toolStripMenuItem3,
this.printToolStripMenuItem,
this.toolStripMenuItem6,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem1,
this.xMLFileToolStripMenuItem1});
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
this.openToolStripMenuItem.Text = "&Open";
//
// fileToolStripMenuItem1
//
this.fileToolStripMenuItem1.Image = ((System.Drawing.Image)(resources.GetObject("fileToolStripMenuItem1.Image")));
this.fileToolStripMenuItem1.Name = "fileToolStripMenuItem1";
this.fileToolStripMenuItem1.Size = new System.Drawing.Size(135, 22);
this.fileToolStripMenuItem1.Text = "&SQL File...";
this.fileToolStripMenuItem1.Click += new System.EventHandler(this.fileToolStripMenuItem1_Click);
//
// xMLFileToolStripMenuItem1
//
this.xMLFileToolStripMenuItem1.Image = ((System.Drawing.Image)(resources.GetObject("xMLFileToolStripMenuItem1.Image")));
this.xMLFileToolStripMenuItem1.Name = "xMLFileToolStripMenuItem1";
this.xMLFileToolStripMenuItem1.Size = new System.Drawing.Size(135, 22);
this.xMLFileToolStripMenuItem1.Text = "&XML File...";
this.xMLFileToolStripMenuItem1.Click += new System.EventHandler(this.xMLFileToolStripMenuItem1_Click);
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripMenuItem.Image")));
this.saveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black;
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
this.saveToolStripMenuItem.Text = "&Save";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// saveAsToolStripMenuItem
//
this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem";
this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
this.saveAsToolStripMenuItem.Text = "Save &As...";
this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.saveAsToolStripMenuItem_Click);
//
// saveAllToolStripMenuItem
//
this.saveAllToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveAllToolStripMenuItem.Image")));
this.saveAllToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black;
this.saveAllToolStripMenuItem.Name = "saveAllToolStripMenuItem";
this.saveAllToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
this.saveAllToolStripMenuItem.Text = "Save A&ll";
this.saveAllToolStripMenuItem.Click += new System.EventHandler(this.saveAllToolStripMenuItem_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(133, 6);
//
// closeToolStripMenuItem
//
this.closeToolStripMenuItem.Name = "closeToolStripMenuItem";
this.closeToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
this.closeToolStripMenuItem.Text = "&Close";
this.closeToolStripMenuItem.Click += new System.EventHandler(this.closeToolStripMenuItem_Click);
//
// closeAllToolStripMenuItem
//
this.closeAllToolStripMenuItem.Name = "closeAllToolStripMenuItem";
this.closeAllToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
this.closeAllToolStripMenuItem.Text = "Clos&e All";
this.closeAllToolStripMenuItem.Click += new System.EventHandler(this.closeAllToolStripMenuItem_Click);
//
// toolStripMenuItem3
//
this.toolStripMenuItem3.Name = "toolStripMenuItem3";
this.toolStripMenuItem3.Size = new System.Drawing.Size(133, 6);
//
// printToolStripMenuItem
//
this.printToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printToolStripMenuItem.Image")));
this.printToolStripMenuItem.Name = "printToolStripMenuItem";
this.printToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
this.printToolStripMenuItem.Text = "&Print";
this.printToolStripMenuItem.Visible = false;
this.printToolStripMenuItem.Click += new System.EventHandler(this.printToolStripMenuItem_Click);
//
// toolStripMenuItem6
//
this.toolStripMenuItem6.Name = "toolStripMenuItem6";
this.toolStripMenuItem6.Size = new System.Drawing.Size(133, 6);
this.toolStripMenuItem6.Visible = false;
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoToolStripMenuItem,
this.redoToolStripMenuItem,
this.toolStripMenuItem5,
this.cutToolStripMenuItem,
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.toolStripMenuItem4,
this.findToolStripMenuItem,
this.findAndReplaceToolStripMenuItem,
this.findAndReplaceAllToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.editToolStripMenuItem.Text = "&Edit";
//
// undoToolStripMenuItem
//
this.undoToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("undoToolStripMenuItem.Image")));
this.undoToolStripMenuItem.Name = "undoToolStripMenuItem";
this.undoToolStripMenuItem.Size = new System.Drawing.Size(181, 22);
this.undoToolStripMenuItem.Text = "Un&do";
this.undoToolStripMenuItem.Click += new System.EventHandler(this.undoToolStripMenuItem_Click);
//
// redoToolStripMenuItem
//
this.redoToolStripMenuItem.Enabled = false;
this.redoToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("redoToolStripMenuItem.Image")));
this.redoToolStripMenuItem.Name = "redoToolStripMenuItem";
this.redoToolStripMenuItem.Size = new System.Drawing.Size(181, 22);
this.redoToolStripMenuItem.Text = "R&edo";
this.redoToolStripMenuItem.Click += new System.EventHandler(this.redoToolStripMenuItem_Click);
//
// toolStripMenuItem5
//
this.toolStripMenuItem5.Name = "toolStripMenuItem5";
this.toolStripMenuItem5.Size = new System.Drawing.Size(178, 6);
//
// cutToolStripMenuItem
//
this.cutToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("cutToolStripMenuItem.Image")));
this.cutToolStripMenuItem.Name = "cutToolStripMenuItem";
this.cutToolStripMenuItem.Size = new System.Drawing.Size(181, 22);
this.cutToolStripMenuItem.Text = "C&ut";
this.cutToolStripMenuItem.Click += new System.EventHandler(this.cutToolStripMenuItem_Click);
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("copyToolStripMenuItem.Image")));
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.Size = new System.Drawing.Size(181, 22);
this.copyToolStripMenuItem.Text = "&Copy";
this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click);
//
// pasteToolStripMenuItem
//
this.pasteToolStripMenuItem.Enabled = false;
this.pasteToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("pasteToolStripMenuItem.Image")));
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.Size = new System.Drawing.Size(181, 22);
this.pasteToolStripMenuItem.Text = "&Paste";
this.pasteToolStripMenuItem.Click += new System.EventHandler(this.pasteToolStripMenuItem_Click);
//
// toolStripMenuItem4
//
this.toolStripMenuItem4.Name = "toolStripMenuItem4";
this.toolStripMenuItem4.Size = new System.Drawing.Size(178, 6);
//
// findToolStripMenuItem
//
this.findToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("findToolStripMenuItem.Image")));
this.findToolStripMenuItem.Name = "findToolStripMenuItem";
this.findToolStripMenuItem.Size = new System.Drawing.Size(181, 22);
this.findToolStripMenuItem.Text = "&Find";
this.findToolStripMenuItem.Click += new System.EventHandler(this.findToolStripMenuItem_Click);
//
// findAndReplaceToolStripMenuItem
//
this.findAndReplaceToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("findAndReplaceToolStripMenuItem.Image")));
this.findAndReplaceToolStripMenuItem.Name = "findAndReplaceToolStripMenuItem";
this.findAndReplaceToolStripMenuItem.Size = new System.Drawing.Size(181, 22);
this.findAndReplaceToolStripMenuItem.Text = "Find and &Replace";
this.findAndReplaceToolStripMenuItem.Click += new System.EventHandler(this.findAndReplaceToolStripMenuItem_Click);
//
// findAndReplaceAllToolStripMenuItem
//
this.findAndReplaceAllToolStripMenuItem.Name = "findAndReplaceAllToolStripMenuItem";
this.findAndReplaceAllToolStripMenuItem.Size = new System.Drawing.Size(181, 22);
this.findAndReplaceAllToolStripMenuItem.Text = "Find and Replace &All";
this.findAndReplaceAllToolStripMenuItem.Click += new System.EventHandler(this.findAndReplaceAllToolStripMenuItem_Click);
//
// actionToolStripMenuItem
//
this.actionToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.compareSchemasToolStripMenuItem,
this.generateSchemaToolStripMenuItem,
this.createServerDTSPackageToolStripMenuItem,
this.toolStripMenuItem2,
this.compareDataFromToolStripMenuItem,
this.toolStripMenuItem8,
this.setSecurityToolStripMenuItem,
this.addServerToolStripMenuItem,
this.toolStripMenuItem7,
this.getDTSPackageToolStripMenuItem,
this.generateXMLOutputToolStripMenuItem});
this.actionToolStripMenuItem.Name = "actionToolStripMenuItem";
this.actionToolStripMenuItem.Size = new System.Drawing.Size(49, 20);
this.actionToolStripMenuItem.Text = "&Action";
//
// compareSchemasToolStripMenuItem
//
this.compareSchemasToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.compareXMLSpanshotsToolStripMenuItem,
this.selectedDatabasesToolStripMenuItem,
this.xMLSnapshotAndDatabaseToolStripMenuItem});
this.compareSchemasToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("compareSchemasToolStripMenuItem.Image")));
this.compareSchemasToolStripMenuItem.Name = "compareSchemasToolStripMenuItem";
this.compareSchemasToolStripMenuItem.Size = new System.Drawing.Size(233, 22);
this.compareSchemasToolStripMenuItem.Text = "&Compare Schemas From...";
//
// compareXMLSpanshotsToolStripMenuItem
//
this.compareXMLSpanshotsToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.compareXMLSpanshotsToolStripMenuItem.Name = "compareXMLSpanshotsToolStripMenuItem";
this.compareXMLSpanshotsToolStripMenuItem.Size = new System.Drawing.Size(222, 22);
this.compareXMLSpanshotsToolStripMenuItem.Text = "&XML Snapshots";
this.compareXMLSpanshotsToolStripMenuItem.Click += new System.EventHandler(this.compareXMLSpanshotsToolStripMenuItem_Click);
//
// selectedDatabasesToolStripMenuItem
//
this.selectedDatabasesToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.selectedDatabasesToolStripMenuItem.Enabled = false;
this.selectedDatabasesToolStripMenuItem.Name = "selectedDatabasesToolStripMenuItem";
this.selectedDatabasesToolStripMenuItem.Size = new System.Drawing.Size(222, 22);
this.selectedDatabasesToolStripMenuItem.Text = "Selected &Databases";
this.selectedDatabasesToolStripMenuItem.Click += new System.EventHandler(this.selectedDatabasesToolStripMenuItem_Click);
//
// xMLSnapshotAndDatabaseToolStripMenuItem
//
this.xMLSnapshotAndDatabaseToolStripMenuItem.Enabled = false;
this.xMLSnapshotAndDatabaseToolStripMenuItem.Name = "xMLSnapshotAndDatabaseToolStripMenuItem";
this.xMLSnapshotAndDatabaseToolStripMenuItem.Size = new System.Drawing.Size(222, 22);
this.xMLSnapshotAndDatabaseToolStripMenuItem.Text = "XML &Snapshot and Database";
this.xMLSnapshotAndDatabaseToolStripMenuItem.Click += new System.EventHandler(this.xMLSnapshotAndDatabaseToolStripMenuItem_Click);
//
// generateSchemaToolStripMenuItem
//
this.generateSchemaToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.chooseXMLSnapshotToolStripMenuItem,
this.selectedDatabaseToolStripMenuItem});
this.generateSchemaToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("generateSchemaToolStripMenuItem.Image")));
this.generateSchemaToolStripMenuItem.Name = "generateSchemaToolStripMenuItem";
this.generateSchemaToolStripMenuItem.Size = new System.Drawing.Size(233, 22);
this.generateSchemaToolStripMenuItem.Text = "&Generate SQL Schema From...";
//
// chooseXMLSnapshotToolStripMenuItem
//
this.chooseXMLSnapshotToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.chooseXMLSnapshotToolStripMenuItem.Name = "chooseXMLSnapshotToolStripMenuItem";
this.chooseXMLSnapshotToolStripMenuItem.Size = new System.Drawing.Size(175, 22);
this.chooseXMLSnapshotToolStripMenuItem.Text = "&XML Snapshot";
this.chooseXMLSnapshotToolStripMenuItem.Click += new System.EventHandler(this.chooseXMLSnapshotToolStripMenuItem_Click);
//
// selectedDatabaseToolStripMenuItem
//
this.selectedDatabaseToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.selectedDatabaseToolStripMenuItem.Enabled = false;
this.selectedDatabaseToolStripMenuItem.Name = "selectedDatabaseToolStripMenuItem";
this.selectedDatabaseToolStripMenuItem.Size = new System.Drawing.Size(175, 22);
this.selectedDatabaseToolStripMenuItem.Text = "Selected &Database";
this.selectedDatabaseToolStripMenuItem.Click += new System.EventHandler(this.selectedDatabaseToolStripMenuItem_Click);
//
// createServerDTSPackageToolStripMenuItem
//
this.createServerDTSPackageToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.xMLFileToolStripMenuItem});
this.createServerDTSPackageToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("createServerDTSPackageToolStripMenuItem.Image")));
this.createServerDTSPackageToolStripMenuItem.Name = "createServerDTSPackageToolStripMenuItem";
this.createServerDTSPackageToolStripMenuItem.Size = new System.Drawing.Size(233, 22);
this.createServerDTSPackageToolStripMenuItem.Text = "&Recreate DTS Package From...";
//
// xMLFileToolStripMenuItem
//
this.xMLFileToolStripMenuItem.Name = "xMLFileToolStripMenuItem";
this.xMLFileToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
this.xMLFileToolStripMenuItem.Text = "XML &Package";
this.xMLFileToolStripMenuItem.Click += new System.EventHandler(this.xMLFileToolStripMenuItem_Click);
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(230, 6);
//
// compareDataFromToolStripMenuItem
//
this.compareDataFromToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.selectedTablesMenuItem});
this.compareDataFromToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("compareDataFromToolStripMenuItem.Image")));
this.compareDataFromToolStripMenuItem.Name = "compareDataFromToolStripMenuItem";
this.compareDataFromToolStripMenuItem.Size = new System.Drawing.Size(233, 22);
this.compareDataFromToolStripMenuItem.Text = "Compare Data &From...";
//
// selectedTablesMenuItem
//
this.selectedTablesMenuItem.Enabled = false;
this.selectedTablesMenuItem.Name = "selectedTablesMenuItem";
this.selectedTablesMenuItem.Size = new System.Drawing.Size(160, 22);
this.selectedTablesMenuItem.Text = "&Selected Tables";
this.selectedTablesMenuItem.Click += new System.EventHandler(this.selectedTablesToolStripMenuItem_Click);
//
// toolStripMenuItem8
//
this.toolStripMenuItem8.Name = "toolStripMenuItem8";
this.toolStripMenuItem8.Size = new System.Drawing.Size(230, 6);
//
// setSecurityToolStripMenuItem
//
this.setSecurityToolStripMenuItem.Enabled = false;
this.setSecurityToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("setSecurityToolStripMenuItem.Image")));
this.setSecurityToolStripMenuItem.Name = "setSecurityToolStripMenuItem";
this.setSecurityToolStripMenuItem.Size = new System.Drawing.Size(233, 22);
this.setSecurityToolStripMenuItem.Text = "&Set Server Security";
this.setSecurityToolStripMenuItem.Click += new System.EventHandler(this.setSecurityToolStripMenuItem_Click);
//
// addServerToolStripMenuItem
//
this.addServerToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("addServerToolStripMenuItem.Image")));
this.addServerToolStripMenuItem.Name = "addServerToolStripMenuItem";
this.addServerToolStripMenuItem.Size = new System.Drawing.Size(233, 22);
this.addServerToolStripMenuItem.Text = "&Add SQL Server Login";
this.addServerToolStripMenuItem.Click += new System.EventHandler(this.addServerToolStripMenuItem_Click);
//
// toolStripMenuItem7
//
this.toolStripMenuItem7.Name = "toolStripMenuItem7";
this.toolStripMenuItem7.Size = new System.Drawing.Size(230, 6);
//
// getDTSPackageToolStripMenuItem
//
this.getDTSPackageToolStripMenuItem.Enabled = false;
this.getDTSPackageToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("getDTSPackageToolStripMenuItem.Image")));
this.getDTSPackageToolStripMenuItem.Name = "getDTSPackageToolStripMenuItem";
this.getDTSPackageToolStripMenuItem.Size = new System.Drawing.Size(233, 22);
this.getDTSPackageToolStripMenuItem.Text = "Get Server &DTS Packages";
this.getDTSPackageToolStripMenuItem.Click += new System.EventHandler(this.getDTSPackageToolStripMenuItem_Click);
//
// generateXMLOutputToolStripMenuItem
//
this.generateXMLOutputToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.dTSPackageSnapshotToolStripMenuItem,
this.databaseSnapshotToolStripMenuItem});
this.generateXMLOutputToolStripMenuItem.Enabled = false;
this.generateXMLOutputToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("generateXMLOutputToolStripMenuItem.Image")));
this.generateXMLOutputToolStripMenuItem.Name = "generateXMLOutputToolStripMenuItem";
this.generateXMLOutputToolStripMenuItem.Size = new System.Drawing.Size(233, 22);
this.generateXMLOutputToolStripMenuItem.Text = "Generate &XML From...";
//
// dTSPackageSnapshotToolStripMenuItem
//
this.dTSPackageSnapshotToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.dTSPackageSnapshotToolStripMenuItem.Enabled = false;
this.dTSPackageSnapshotToolStripMenuItem.Name = "dTSPackageSnapshotToolStripMenuItem";
this.dTSPackageSnapshotToolStripMenuItem.Size = new System.Drawing.Size(191, 22);
this.dTSPackageSnapshotToolStripMenuItem.Text = "&Selected DTS Package";
this.dTSPackageSnapshotToolStripMenuItem.Click += new System.EventHandler(this.dTSPackageSnapshotToolStripMenuItem_Click);
//
// databaseSnapshotToolStripMenuItem
//
this.databaseSnapshotToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.databaseSnapshotToolStripMenuItem.Enabled = false;
this.databaseSnapshotToolStripMenuItem.Name = "databaseSnapshotToolStripMenuItem";
this.databaseSnapshotToolStripMenuItem.Size = new System.Drawing.Size(191, 22);
this.databaseSnapshotToolStripMenuItem.Text = "Selected &Database";
this.databaseSnapshotToolStripMenuItem.Click += new System.EventHandler(this.databaseSnapshotToolStripMenuItem_Click);
//
// viewToolStripMenuItem
//
this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.serverExplorerToolStripMenuItem,
this.xmlExplorerToolStripMenuItem,
this.toolStripMenuItem9,
this.iconsAndTextToolStripMenuItem});
this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
this.viewToolStripMenuItem.Size = new System.Drawing.Size(41, 20);
this.viewToolStripMenuItem.Text = "&View";
//
// serverExplorerToolStripMenuItem
//
this.serverExplorerToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("serverExplorerToolStripMenuItem.Image")));
this.serverExplorerToolStripMenuItem.Name = "serverExplorerToolStripMenuItem";
this.serverExplorerToolStripMenuItem.Size = new System.Drawing.Size(192, 22);
this.serverExplorerToolStripMenuItem.Text = "&Server Explorer";
this.serverExplorerToolStripMenuItem.Click += new System.EventHandler(this.serverExplorerToolStripMenuItem_Click);
//
// xmlExplorerToolStripMenuItem
//
this.xmlExplorerToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("xmlExplorerToolStripMenuItem.Image")));
this.xmlExplorerToolStripMenuItem.Name = "xmlExplorerToolStripMenuItem";
this.xmlExplorerToolStripMenuItem.Size = new System.Drawing.Size(192, 22);
this.xmlExplorerToolStripMenuItem.Text = "&XML Explorer";
this.xmlExplorerToolStripMenuItem.Click += new System.EventHandler(this.xmlExplorerToolStripMenuItem_Click);
//
// toolStripMenuItem9
//
this.toolStripMenuItem9.Name = "toolStripMenuItem9";
this.toolStripMenuItem9.Size = new System.Drawing.Size(189, 6);
//
// iconsAndTextToolStripMenuItem
//
this.iconsAndTextToolStripMenuItem.CheckOnClick = true;
this.iconsAndTextToolStripMenuItem.Name = "iconsAndTextToolStripMenuItem";
this.iconsAndTextToolStripMenuItem.Size = new System.Drawing.Size(192, 22);
this.iconsAndTextToolStripMenuItem.Text = "Button Icons and Text";
this.iconsAndTextToolStripMenuItem.Click += new System.EventHandler(this.iconsAndTextToolStripMenuItem_Click);
//
// windowToolStripMenuItem
//
this.windowToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.optionsToolStripMenuItem});
this.windowToolStripMenuItem.Name = "windowToolStripMenuItem";
this.windowToolStripMenuItem.Size = new System.Drawing.Size(57, 20);
this.windowToolStripMenuItem.Text = "&Window";
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
this.optionsToolStripMenuItem.Size = new System.Drawing.Size(122, 22);
this.optionsToolStripMenuItem.Text = "&Options";
this.optionsToolStripMenuItem.Click += new System.EventHandler(this.optionsToolStripMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 20);
this.helpToolStripMenuItem.Text = "&Help";
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("aboutToolStripMenuItem.Image")));
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
this.aboutToolStripMenuItem.Text = "&About SQL Schema Tool";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// RightToolStripPanel
//
this.RightToolStripPanel.Location = new System.Drawing.Point(0, 0);
this.RightToolStripPanel.Name = "RightToolStripPanel";
this.RightToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.RightToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0);
this.RightToolStripPanel.Size = new System.Drawing.Size(0, 0);
//
// LeftToolStripPanel
//
this.LeftToolStripPanel.Location = new System.Drawing.Point(0, 0);
this.LeftToolStripPanel.Name = "LeftToolStripPanel";
this.LeftToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.LeftToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0);
this.LeftToolStripPanel.Size = new System.Drawing.Size(0, 0);
//
// ContentPanel
//
this.ContentPanel.AutoScroll = true;
this.ContentPanel.Size = new System.Drawing.Size(551, 378);
//
// dockPanel
//
this.dockPanel.ActiveAutoHideContent = null;
this.dockPanel.AllowEndUserNestedDocking = false;
this.dockPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.dockPanel.DocumentStyle = WeifenLuo.WinFormsUI.Docking.DocumentStyle.DockingWindow;
this.dockPanel.Font = new System.Drawing.Font("Tahoma", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
this.dockPanel.Location = new System.Drawing.Point(0, 0);
this.dockPanel.Name = "dockPanel";
this.dockPanel.Size = new System.Drawing.Size(839, 378);
this.dockPanel.TabIndex = 8;
//
// toolStripContainer1
//
//
// toolStripContainer1.BottomToolStripPanel
//
this.toolStripContainer1.BottomToolStripPanel.Controls.Add(this.statusBar);
//
// toolStripContainer1.ContentPanel
//
this.toolStripContainer1.ContentPanel.AutoScroll = true;
this.toolStripContainer1.ContentPanel.Controls.Add(this.dockPanel);
this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(839, 378);
this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.toolStripContainer1.Location = new System.Drawing.Point(0, 0);
this.toolStripContainer1.Name = "toolStripContainer1";
this.toolStripContainer1.Size = new System.Drawing.Size(839, 449);
this.toolStripContainer1.TabIndex = 9;
this.toolStripContainer1.Text = "toolStripContainer1";
//
// toolStripContainer1.TopToolStripPanel
//
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.mainMenu);
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.mainToolbar);
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.ActionToolbar);
//
// ActionToolbar
//
this.ActionToolbar.Dock = System.Windows.Forms.DockStyle.None;
this.ActionToolbar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btnSetSecurity,
this.btnAddServer,
this.toolStripSeparator5,
this.btnCompareSelected,
this.btnGenerateSchema,
this.btnCreateDTSPackage,
this.toolStripSeparator6,
this.btnGetDTSPackages,
this.btnGenXml,
this.btnGenDatabase,
this.toolStripSeparator7,
this.btnSyncXml,
this.btnSelect,
this.btnRefreshServers,
this.toolStripSeparator8,
this.btnHTML});
this.ActionToolbar.Location = new System.Drawing.Point(301, 24);
this.ActionToolbar.Name = "ActionToolbar";
this.ActionToolbar.Size = new System.Drawing.Size(339, 25);
this.ActionToolbar.TabIndex = 5;
//
// btnSetSecurity
//
this.btnSetSecurity.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnSetSecurity.Enabled = false;
this.btnSetSecurity.Image = ((System.Drawing.Image)(resources.GetObject("btnSetSecurity.Image")));
this.btnSetSecurity.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnSetSecurity.Name = "btnSetSecurity";
this.btnSetSecurity.Size = new System.Drawing.Size(23, 22);
this.btnSetSecurity.Text = "Server Security Settings";
this.btnSetSecurity.Click += new System.EventHandler(this.btnSetSecurity_Click);
//
// btnAddServer
//
this.btnAddServer.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnAddServer.Image = ((System.Drawing.Image)(resources.GetObject("btnAddServer.Image")));
this.btnAddServer.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnAddServer.Name = "btnAddServer";
this.btnAddServer.Size = new System.Drawing.Size(23, 22);
this.btnAddServer.Text = "Add SQL Server Login";
this.btnAddServer.Click += new System.EventHandler(this.btnAddServer_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(6, 25);
//
// btnCompareSelected
//
this.btnCompareSelected.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnCompareSelected.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.createCommandlineBatchFileToolStripMenuItem});
this.btnCompareSelected.Image = ((System.Drawing.Image)(resources.GetObject("btnCompareSelected.Image")));
this.btnCompareSelected.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnCompareSelected.Name = "btnCompareSelected";
this.btnCompareSelected.Size = new System.Drawing.Size(32, 22);
this.btnCompareSelected.Text = "Compare Selected Objects...";
this.btnCompareSelected.ToolTipText = "Compare Selected...";
this.btnCompareSelected.ButtonClick += new System.EventHandler(this.btnCompareSelected_Click);
//
// createCommandlineBatchFileToolStripMenuItem
//
this.createCommandlineBatchFileToolStripMenuItem.Name = "createCommandlineBatchFileToolStripMenuItem";
this.createCommandlineBatchFileToolStripMenuItem.Size = new System.Drawing.Size(233, 22);
this.createCommandlineBatchFileToolStripMenuItem.Text = "Create Commandline Batch File";
this.createCommandlineBatchFileToolStripMenuItem.Click += new System.EventHandler(this.createCommandlineBatchFileToolStripMenuItem_Click);
//
// btnGenerateSchema
//
this.btnGenerateSchema.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnGenerateSchema.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.createCommandToolStripMenuItem});
this.btnGenerateSchema.Image = ((System.Drawing.Image)(resources.GetObject("btnGenerateSchema.Image")));
this.btnGenerateSchema.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnGenerateSchema.Name = "btnGenerateSchema";
this.btnGenerateSchema.Size = new System.Drawing.Size(32, 22);
this.btnGenerateSchema.Text = "Generate SQL Schema From...";
this.btnGenerateSchema.ToolTipText = "Generate SQL Schema From Selected...";
this.btnGenerateSchema.ButtonClick += new System.EventHandler(this.btnGenerateSchema_Click);
//
// createCommandToolStripMenuItem
//
this.createCommandToolStripMenuItem.Name = "createCommandToolStripMenuItem";
this.createCommandToolStripMenuItem.Size = new System.Drawing.Size(233, 22);
this.createCommandToolStripMenuItem.Text = "Create Commandline Batch File";
this.createCommandToolStripMenuItem.Click += new System.EventHandler(this.createCommandToolStripMenuItem_Click);
//
// btnCreateDTSPackage
//
this.btnCreateDTSPackage.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnCreateDTSPackage.Image = ((System.Drawing.Image)(resources.GetObject("btnCreateDTSPackage.Image")));
this.btnCreateDTSPackage.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnCreateDTSPackage.Name = "btnCreateDTSPackage";
this.btnCreateDTSPackage.Size = new System.Drawing.Size(23, 22);
this.btnCreateDTSPackage.Text = "Recreate DTS Package From...";
this.btnCreateDTSPackage.ToolTipText = "Recreate DTS Package From Selected...";
this.btnCreateDTSPackage.Click += new System.EventHandler(this.btnCreateDTSPackage_Click);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(6, 25);
//
// btnGetDTSPackages
//
this.btnGetDTSPackages.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnGetDTSPackages.Enabled = false;
this.btnGetDTSPackages.Image = ((System.Drawing.Image)(resources.GetObject("btnGetDTSPackages.Image")));
this.btnGetDTSPackages.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnGetDTSPackages.Name = "btnGetDTSPackages";
this.btnGetDTSPackages.Size = new System.Drawing.Size(23, 22);
this.btnGetDTSPackages.Text = "Get Server DTS Packages";
this.btnGetDTSPackages.Click += new System.EventHandler(this.getDTSPackages_Click);
//
// btnGenXml
//
this.btnGenXml.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnGenXml.Enabled = false;
this.btnGenXml.Image = ((System.Drawing.Image)(resources.GetObject("btnGenXml.Image")));
this.btnGenXml.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnGenXml.Name = "btnGenXml";
this.btnGenXml.Size = new System.Drawing.Size(23, 22);
this.btnGenXml.Text = "Generate XML From...";
this.btnGenXml.ToolTipText = "Generate XML From Selected...";
this.btnGenXml.Click += new System.EventHandler(this.btnGenXml_Click);
//
// btnGenDatabase
//
this.btnGenDatabase.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnGenDatabase.Enabled = false;
this.btnGenDatabase.Image = ((System.Drawing.Image)(resources.GetObject("btnGenDatabase.Image")));
this.btnGenDatabase.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnGenDatabase.Name = "btnGenDatabase";
this.btnGenDatabase.Size = new System.Drawing.Size(23, 22);
this.btnGenDatabase.Text = "Execute SQL Doc";
this.btnGenDatabase.ToolTipText = "Execute SQL Doc as a command on a server database";
this.btnGenDatabase.Click += new System.EventHandler(this.btnGenDatabase_Click);
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
this.toolStripSeparator7.Size = new System.Drawing.Size(6, 25);
//
// btnSyncXml
//
this.btnSyncXml.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnSyncXml.Enabled = false;
this.btnSyncXml.Image = ((System.Drawing.Image)(resources.GetObject("btnSyncXml.Image")));
this.btnSyncXml.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnSyncXml.Name = "btnSyncXml";
this.btnSyncXml.Size = new System.Drawing.Size(23, 22);
this.btnSyncXml.Text = "Sync with XML Node Explorer";
this.btnSyncXml.Click += new System.EventHandler(this.btnSyncXml_Click);
//
// btnSelect
//
this.btnSelect.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnSelect.Enabled = false;
this.btnSelect.Image = ((System.Drawing.Image)(resources.GetObject("btnSelect.Image")));
this.btnSelect.ImageTransparentColor = System.Drawing.Color.Transparent;
this.btnSelect.Name = "btnSelect";
this.btnSelect.Size = new System.Drawing.Size(23, 22);
this.btnSelect.Text = "Select For Compare";
this.btnSelect.Click += new System.EventHandler(this.btnSelect_Click);
//
// btnRefreshServers
//
this.btnRefreshServers.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnRefreshServers.Enabled = false;
this.btnRefreshServers.Image = ((System.Drawing.Image)(resources.GetObject("btnRefreshServers.Image")));
this.btnRefreshServers.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnRefreshServers.Name = "btnRefreshServers";
this.btnRefreshServers.Size = new System.Drawing.Size(23, 22);
this.btnRefreshServers.Text = "Refresh Servers";
this.btnRefreshServers.ToolTipText = "Refresh SQL server list from the available local and networked SQL servers";
this.btnRefreshServers.Click += new System.EventHandler(this.btnRefreshServers_Click);
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
this.toolStripSeparator8.Size = new System.Drawing.Size(6, 25);
//
// btnHTML
//
this.btnHTML.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnHTML.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.standardViewToolStripMenuItem});
this.btnHTML.Enabled = false;
this.btnHTML.Image = ((System.Drawing.Image)(resources.GetObject("btnHTML.Image")));
this.btnHTML.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnHTML.Name = "btnHTML";
this.btnHTML.Size = new System.Drawing.Size(32, 22);
this.btnHTML.Text = "Display HTML Report";
this.btnHTML.ButtonClick += new System.EventHandler(this.btnHTML_Click);
//
// standardViewToolStripMenuItem
//
this.standardViewToolStripMenuItem.Name = "standardViewToolStripMenuItem";
this.standardViewToolStripMenuItem.Size = new System.Drawing.Size(190, 22);
this.standardViewToolStripMenuItem.Text = "Standard Report View";
this.standardViewToolStripMenuItem.ToolTipText = "Standard Browser XML View";
this.standardViewToolStripMenuItem.Click += new System.EventHandler(this.standardViewToolStripMenuItem_Click);
//
// timer1
//
this.timer1.Interval = 1000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// Main
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(839, 449);
this.Controls.Add(this.toolStripContainer1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.IsMdiContainer = true;
this.MainMenuStrip = this.mainMenu;
this.Name = "Main";
this.Text = "SQL Schema Tool";
this.Load += new System.EventHandler(this.Main_Load);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Main_FormClosing);
this.statusBar.ResumeLayout(false);
this.statusBar.PerformLayout();
this.mainToolbar.ResumeLayout(false);
this.mainToolbar.PerformLayout();
this.mainMenu.ResumeLayout(false);
this.mainMenu.PerformLayout();
this.toolStripContainer1.BottomToolStripPanel.ResumeLayout(false);
this.toolStripContainer1.BottomToolStripPanel.PerformLayout();
this.toolStripContainer1.ContentPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.PerformLayout();
this.toolStripContainer1.ResumeLayout(false);
this.toolStripContainer1.PerformLayout();
this.ActionToolbar.ResumeLayout(false);
this.ActionToolbar.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.StatusStrip statusBar;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2;
private System.Windows.Forms.ToolStrip mainToolbar;
private System.Windows.Forms.ToolStripSplitButton btnOpenFile;
private System.Windows.Forms.ToolStripMenuItem sqlToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem xMLFilesToolStripMenuItem;
private System.Windows.Forms.ToolStripButton btnSaveFile;
private System.Windows.Forms.ToolStripButton btnSaveAll;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripButton btnCut;
private System.Windows.Forms.ToolStripButton btnCopy;
private System.Windows.Forms.ToolStripButton btnPaste;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripButton btnUndo;
private System.Windows.Forms.ToolStripButton btnRedo;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripButton btnServerExplorer;
private System.Windows.Forms.ToolStripButton btnXmlExplorer;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripButton btnAbout;
private System.Windows.Forms.MenuStrip mainMenu;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem xMLFileToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveAllToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem closeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem closeAllToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3;
private System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem6;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem5;
private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4;
private System.Windows.Forms.ToolStripMenuItem findToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem findAndReplaceToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem findAndReplaceAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem actionToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem compareSchemasToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem compareXMLSpanshotsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem selectedDatabasesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem xMLSnapshotAndDatabaseToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem generateSchemaToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem chooseXMLSnapshotToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem selectedDatabaseToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem createServerDTSPackageToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem xMLFileToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem setSecurityToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem addServerToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem7;
private System.Windows.Forms.ToolStripMenuItem getDTSPackageToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem generateXMLOutputToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem dTSPackageSnapshotToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem databaseSnapshotToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem serverExplorerToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem xmlExplorerToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem windowToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.ToolStripContainer toolStripContainer1;
private System.Windows.Forms.ToolStrip ActionToolbar;
private System.Windows.Forms.ToolStripButton btnSetSecurity;
private System.Windows.Forms.ToolStripButton btnAddServer;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripButton btnGetDTSPackages;
private System.Windows.Forms.ToolStripButton btnGenXml;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripButton btnSyncXml;
private System.Windows.Forms.ToolStripButton btnSelect;
private System.Windows.Forms.ToolStripButton btnRefreshServers;
private System.Windows.Forms.ToolStripButton btnGenDatabase;
private WeifenLuo.WinFormsUI.Docking.DockPanel dockPanel;
private System.Windows.Forms.ToolStripProgressBar progressIndicator;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
private System.Windows.Forms.ToolStripSplitButton btnHTML;
private System.Windows.Forms.ToolStripMenuItem standardViewToolStripMenuItem;
private System.Windows.Forms.ToolStripSplitButton btnCompareSelected;
private System.Windows.Forms.ToolStripMenuItem createCommandlineBatchFileToolStripMenuItem;
private System.Windows.Forms.ToolStripSplitButton btnGenerateSchema;
private System.Windows.Forms.ToolStripMenuItem createCommandToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem compareDataFromToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem selectedTablesMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem8;
private System.Windows.Forms.ToolStripButton btnCreateDTSPackage;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem9;
private System.Windows.Forms.ToolStripMenuItem iconsAndTextToolStripMenuItem;
private System.Windows.Forms.ToolStripPanel BottomToolStripPanel;
private System.Windows.Forms.ToolStripPanel TopToolStripPanel;
private System.Windows.Forms.ToolStripPanel RightToolStripPanel;
private System.Windows.Forms.ToolStripPanel LeftToolStripPanel;
private System.Windows.Forms.ToolStripContentPanel ContentPanel;
}
}
| apache-2.0 |
olivier-voutat/BlackStar.Localization | BlackStar.Localization/SqlDataManager.cs | 6945 | /*
Copyright 2017 Oliver Voutat
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
namespace BlackStar.Localization
{
public class SqlDataManager : IDataManager
{
private readonly string _baseName;
private readonly Dictionary<string, string> _dbArgs;
private readonly ILogger _logger;
private readonly List<CustomStringData> _stringData;
/// <summary>
/// Creates a new <see cref="SqlDataManager"/>.
/// </summary>
/// <param name="baseName">The base name used to search the strings.</param>
/// <param name="dbArgs">Database information where to get the data.</param>
/// <param name="logger">The <see cref="ILogger"/>.</param>
internal SqlDataManager(string baseName, Dictionary<string, string> dbArgs, ILogger logger)
{
if (!dbArgs.ContainsKey("ConnectionString"))
{
throw new KeyNotFoundException("ConnectionString information missing in source arguments.");
}
if (!dbArgs.ContainsKey("Table"))
{
throw new KeyNotFoundException("Table information missing in source arguments.");
}
if (!dbArgs.ContainsKey("Column"))
{
throw new KeyNotFoundException("Column information missing in source arguments.");
}
_baseName = baseName;
_dbArgs = dbArgs;
_logger = logger;
_stringData = new List<CustomStringData>();
}
/// <summary>
/// Returns the value of the specified string from the database.
/// </summary>
/// <param name="name">The name of the resource to retrieve.</param>
/// <returns>The resource string, or <c>null</c> if none was found.</returns>
public string GetString(string name)
{
return GetString(name, CultureInfo.CurrentUICulture);
}
/// <summary>
/// Returns the value of the specified string from the database localized for the specified culture.
/// </summary>
/// <param name="name">The name of the resource to retrieve.</param>
/// <param name="culture">The <see cref="CultureInfo"/> to get the string for.</param>
/// <returns>The resource string, or <c>null</c> if none was found.</returns>
public string GetString(string name, CultureInfo culture)
{
if (culture == null) throw new ArgumentNullException(nameof(culture));
InitializeData();
CustomStringData result = _stringData.FirstOrDefault(x => x.CultureName == culture.Name && x.Name == name);
if (result != null) return result.Value;
return _stringData.FirstOrDefault(x => string.IsNullOrEmpty(x.CultureName) && x.Name == name)?.Value;
}
/// <summary>
/// Returns all names in the current culture.
/// </summary>
/// <param name="includeParentCultures">Include parent cultures.</param>
/// <returns>The strings.</returns>
public IEnumerable<string> GetAllNames(bool includeParentCultures)
{
return GetAllNames(includeParentCultures, CultureInfo.CurrentUICulture);
}
/// <summary>
/// Returns all names in the specified culture.
/// </summary>
/// <param name="includeParentCultures">Include parent cultures.</param>
/// <param name="culture">The <see cref="CultureInfo"/> to get strings for.</param>
/// <returns>The strings.</returns>
public IEnumerable<string> GetAllNames(bool includeParentCultures, CultureInfo culture)
{
if (culture == null) throw new ArgumentNullException(nameof(culture));
InitializeData();
if (includeParentCultures)
{
foreach (var s in _stringData.Where(x => new CultureInfo(x.CultureName).Parent == new CultureInfo(culture.Name).Parent))
{
yield return s.Name;
}
}
else
{
foreach (var s in _stringData.Where(x => x.CultureName == culture.Name))
{
yield return s.Name;
}
}
}
private void InitializeData()
{
if (_stringData.Any()) return;
using (SqlConnection con = new SqlConnection(_dbArgs["ConnectionString"]))
{
using (SqlCommand cmd = new SqlCommand($"SELECT CultureName, ResourceKey, {_dbArgs["Column"]} FROM {_dbArgs["Table"]} WHERE Path LIKE @path", con))
{
try
{
var indexes = Regex.Matches(_baseName, "\\.").Cast<Match>().Select(m => m.Index).ToArray();
cmd.Parameters.AddWithValue("@path", _baseName.Substring(indexes[indexes.Length - 2] + 1));
cmd.Connection.Open();
var r = cmd.ExecuteReader();
while (r.Read())
{
_stringData.Add(new CustomStringData()
{
CultureName = r["CultureName"].ToString(),
Name = r["ResourceKey"].ToString(),
Value = r[_dbArgs["Column"]].ToString()
});
}
}
catch (Exception ex)
{
_logger.LogCritical("Connection string: {0}; Datatable: {1}; Column: {2}; Exception Message: {3}; Exception StackTrace: {4}",
_dbArgs["ConnectionString"],
_dbArgs["Table"],
_dbArgs["Column"],
ex.Message,
ex.StackTrace);
throw;
}
}
}
}
private class CustomStringData
{
public string CultureName { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-applicationinsights/src/main/java/com/amazonaws/services/applicationinsights/model/Problem.java | 18886 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.applicationinsights.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Describes a problem that is detected by correlating observations.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/application-insights-2018-11-25/Problem" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Problem implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The ID of the problem.
* </p>
*/
private String id;
/**
* <p>
* The name of the problem.
* </p>
*/
private String title;
/**
* <p>
* A detailed analysis of the problem using machine learning.
* </p>
*/
private String insights;
/**
* <p>
* The status of the problem.
* </p>
*/
private String status;
/**
* <p>
* The resource affected by the problem.
* </p>
*/
private String affectedResource;
/**
* <p>
* The time when the problem started, in epoch seconds.
* </p>
*/
private java.util.Date startTime;
/**
* <p>
* The time when the problem ended, in epoch seconds.
* </p>
*/
private java.util.Date endTime;
/**
* <p>
* A measure of the level of impact of the problem.
* </p>
*/
private String severityLevel;
/**
* <p>
* The name of the resource group affected by the problem.
* </p>
*/
private String resourceGroupName;
/**
* <p>
* Feedback provided by the user about the problem.
* </p>
*/
private java.util.Map<String, String> feedback;
/**
* <p>
* The ID of the problem.
* </p>
*
* @param id
* The ID of the problem.
*/
public void setId(String id) {
this.id = id;
}
/**
* <p>
* The ID of the problem.
* </p>
*
* @return The ID of the problem.
*/
public String getId() {
return this.id;
}
/**
* <p>
* The ID of the problem.
* </p>
*
* @param id
* The ID of the problem.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withId(String id) {
setId(id);
return this;
}
/**
* <p>
* The name of the problem.
* </p>
*
* @param title
* The name of the problem.
*/
public void setTitle(String title) {
this.title = title;
}
/**
* <p>
* The name of the problem.
* </p>
*
* @return The name of the problem.
*/
public String getTitle() {
return this.title;
}
/**
* <p>
* The name of the problem.
* </p>
*
* @param title
* The name of the problem.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withTitle(String title) {
setTitle(title);
return this;
}
/**
* <p>
* A detailed analysis of the problem using machine learning.
* </p>
*
* @param insights
* A detailed analysis of the problem using machine learning.
*/
public void setInsights(String insights) {
this.insights = insights;
}
/**
* <p>
* A detailed analysis of the problem using machine learning.
* </p>
*
* @return A detailed analysis of the problem using machine learning.
*/
public String getInsights() {
return this.insights;
}
/**
* <p>
* A detailed analysis of the problem using machine learning.
* </p>
*
* @param insights
* A detailed analysis of the problem using machine learning.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withInsights(String insights) {
setInsights(insights);
return this;
}
/**
* <p>
* The status of the problem.
* </p>
*
* @param status
* The status of the problem.
* @see Status
*/
public void setStatus(String status) {
this.status = status;
}
/**
* <p>
* The status of the problem.
* </p>
*
* @return The status of the problem.
* @see Status
*/
public String getStatus() {
return this.status;
}
/**
* <p>
* The status of the problem.
* </p>
*
* @param status
* The status of the problem.
* @return Returns a reference to this object so that method calls can be chained together.
* @see Status
*/
public Problem withStatus(String status) {
setStatus(status);
return this;
}
/**
* <p>
* The status of the problem.
* </p>
*
* @param status
* The status of the problem.
* @return Returns a reference to this object so that method calls can be chained together.
* @see Status
*/
public Problem withStatus(Status status) {
this.status = status.toString();
return this;
}
/**
* <p>
* The resource affected by the problem.
* </p>
*
* @param affectedResource
* The resource affected by the problem.
*/
public void setAffectedResource(String affectedResource) {
this.affectedResource = affectedResource;
}
/**
* <p>
* The resource affected by the problem.
* </p>
*
* @return The resource affected by the problem.
*/
public String getAffectedResource() {
return this.affectedResource;
}
/**
* <p>
* The resource affected by the problem.
* </p>
*
* @param affectedResource
* The resource affected by the problem.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withAffectedResource(String affectedResource) {
setAffectedResource(affectedResource);
return this;
}
/**
* <p>
* The time when the problem started, in epoch seconds.
* </p>
*
* @param startTime
* The time when the problem started, in epoch seconds.
*/
public void setStartTime(java.util.Date startTime) {
this.startTime = startTime;
}
/**
* <p>
* The time when the problem started, in epoch seconds.
* </p>
*
* @return The time when the problem started, in epoch seconds.
*/
public java.util.Date getStartTime() {
return this.startTime;
}
/**
* <p>
* The time when the problem started, in epoch seconds.
* </p>
*
* @param startTime
* The time when the problem started, in epoch seconds.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withStartTime(java.util.Date startTime) {
setStartTime(startTime);
return this;
}
/**
* <p>
* The time when the problem ended, in epoch seconds.
* </p>
*
* @param endTime
* The time when the problem ended, in epoch seconds.
*/
public void setEndTime(java.util.Date endTime) {
this.endTime = endTime;
}
/**
* <p>
* The time when the problem ended, in epoch seconds.
* </p>
*
* @return The time when the problem ended, in epoch seconds.
*/
public java.util.Date getEndTime() {
return this.endTime;
}
/**
* <p>
* The time when the problem ended, in epoch seconds.
* </p>
*
* @param endTime
* The time when the problem ended, in epoch seconds.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withEndTime(java.util.Date endTime) {
setEndTime(endTime);
return this;
}
/**
* <p>
* A measure of the level of impact of the problem.
* </p>
*
* @param severityLevel
* A measure of the level of impact of the problem.
* @see SeverityLevel
*/
public void setSeverityLevel(String severityLevel) {
this.severityLevel = severityLevel;
}
/**
* <p>
* A measure of the level of impact of the problem.
* </p>
*
* @return A measure of the level of impact of the problem.
* @see SeverityLevel
*/
public String getSeverityLevel() {
return this.severityLevel;
}
/**
* <p>
* A measure of the level of impact of the problem.
* </p>
*
* @param severityLevel
* A measure of the level of impact of the problem.
* @return Returns a reference to this object so that method calls can be chained together.
* @see SeverityLevel
*/
public Problem withSeverityLevel(String severityLevel) {
setSeverityLevel(severityLevel);
return this;
}
/**
* <p>
* A measure of the level of impact of the problem.
* </p>
*
* @param severityLevel
* A measure of the level of impact of the problem.
* @return Returns a reference to this object so that method calls can be chained together.
* @see SeverityLevel
*/
public Problem withSeverityLevel(SeverityLevel severityLevel) {
this.severityLevel = severityLevel.toString();
return this;
}
/**
* <p>
* The name of the resource group affected by the problem.
* </p>
*
* @param resourceGroupName
* The name of the resource group affected by the problem.
*/
public void setResourceGroupName(String resourceGroupName) {
this.resourceGroupName = resourceGroupName;
}
/**
* <p>
* The name of the resource group affected by the problem.
* </p>
*
* @return The name of the resource group affected by the problem.
*/
public String getResourceGroupName() {
return this.resourceGroupName;
}
/**
* <p>
* The name of the resource group affected by the problem.
* </p>
*
* @param resourceGroupName
* The name of the resource group affected by the problem.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withResourceGroupName(String resourceGroupName) {
setResourceGroupName(resourceGroupName);
return this;
}
/**
* <p>
* Feedback provided by the user about the problem.
* </p>
*
* @return Feedback provided by the user about the problem.
*/
public java.util.Map<String, String> getFeedback() {
return feedback;
}
/**
* <p>
* Feedback provided by the user about the problem.
* </p>
*
* @param feedback
* Feedback provided by the user about the problem.
*/
public void setFeedback(java.util.Map<String, String> feedback) {
this.feedback = feedback;
}
/**
* <p>
* Feedback provided by the user about the problem.
* </p>
*
* @param feedback
* Feedback provided by the user about the problem.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withFeedback(java.util.Map<String, String> feedback) {
setFeedback(feedback);
return this;
}
public Problem addFeedbackEntry(String key, String value) {
if (null == this.feedback) {
this.feedback = new java.util.HashMap<String, String>();
}
if (this.feedback.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.feedback.put(key, value);
return this;
}
/**
* Removes all the entries added into Feedback.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem clearFeedbackEntries() {
this.feedback = null;
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getId() != null)
sb.append("Id: ").append(getId()).append(",");
if (getTitle() != null)
sb.append("Title: ").append(getTitle()).append(",");
if (getInsights() != null)
sb.append("Insights: ").append(getInsights()).append(",");
if (getStatus() != null)
sb.append("Status: ").append(getStatus()).append(",");
if (getAffectedResource() != null)
sb.append("AffectedResource: ").append(getAffectedResource()).append(",");
if (getStartTime() != null)
sb.append("StartTime: ").append(getStartTime()).append(",");
if (getEndTime() != null)
sb.append("EndTime: ").append(getEndTime()).append(",");
if (getSeverityLevel() != null)
sb.append("SeverityLevel: ").append(getSeverityLevel()).append(",");
if (getResourceGroupName() != null)
sb.append("ResourceGroupName: ").append(getResourceGroupName()).append(",");
if (getFeedback() != null)
sb.append("Feedback: ").append(getFeedback());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Problem == false)
return false;
Problem other = (Problem) obj;
if (other.getId() == null ^ this.getId() == null)
return false;
if (other.getId() != null && other.getId().equals(this.getId()) == false)
return false;
if (other.getTitle() == null ^ this.getTitle() == null)
return false;
if (other.getTitle() != null && other.getTitle().equals(this.getTitle()) == false)
return false;
if (other.getInsights() == null ^ this.getInsights() == null)
return false;
if (other.getInsights() != null && other.getInsights().equals(this.getInsights()) == false)
return false;
if (other.getStatus() == null ^ this.getStatus() == null)
return false;
if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
return false;
if (other.getAffectedResource() == null ^ this.getAffectedResource() == null)
return false;
if (other.getAffectedResource() != null && other.getAffectedResource().equals(this.getAffectedResource()) == false)
return false;
if (other.getStartTime() == null ^ this.getStartTime() == null)
return false;
if (other.getStartTime() != null && other.getStartTime().equals(this.getStartTime()) == false)
return false;
if (other.getEndTime() == null ^ this.getEndTime() == null)
return false;
if (other.getEndTime() != null && other.getEndTime().equals(this.getEndTime()) == false)
return false;
if (other.getSeverityLevel() == null ^ this.getSeverityLevel() == null)
return false;
if (other.getSeverityLevel() != null && other.getSeverityLevel().equals(this.getSeverityLevel()) == false)
return false;
if (other.getResourceGroupName() == null ^ this.getResourceGroupName() == null)
return false;
if (other.getResourceGroupName() != null && other.getResourceGroupName().equals(this.getResourceGroupName()) == false)
return false;
if (other.getFeedback() == null ^ this.getFeedback() == null)
return false;
if (other.getFeedback() != null && other.getFeedback().equals(this.getFeedback()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode());
hashCode = prime * hashCode + ((getTitle() == null) ? 0 : getTitle().hashCode());
hashCode = prime * hashCode + ((getInsights() == null) ? 0 : getInsights().hashCode());
hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
hashCode = prime * hashCode + ((getAffectedResource() == null) ? 0 : getAffectedResource().hashCode());
hashCode = prime * hashCode + ((getStartTime() == null) ? 0 : getStartTime().hashCode());
hashCode = prime * hashCode + ((getEndTime() == null) ? 0 : getEndTime().hashCode());
hashCode = prime * hashCode + ((getSeverityLevel() == null) ? 0 : getSeverityLevel().hashCode());
hashCode = prime * hashCode + ((getResourceGroupName() == null) ? 0 : getResourceGroupName().hashCode());
hashCode = prime * hashCode + ((getFeedback() == null) ? 0 : getFeedback().hashCode());
return hashCode;
}
@Override
public Problem clone() {
try {
return (Problem) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.applicationinsights.model.transform.ProblemMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| apache-2.0 |
devent/globalpom-utils | globalpomutils-fileresources/src/main/java/com/anrisoftware/globalpom/fileresourcemanager/ResourceSaver.java | 5016 | /**
* Copyright © 2013 Erwin Müller (erwin.mueller@anrisoftware.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.anrisoftware.globalpom.fileresourcemanager;
import static org.apache.commons.transaction.file.ResourceManager.SHUTDOWN_MODE_NORMAL;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import javax.inject.Inject;
import org.apache.commons.transaction.file.FileResourceManager;
import org.apache.commons.transaction.file.ResourceManagerException;
import org.apache.commons.transaction.file.ResourceManagerSystemException;
import com.google.inject.assistedinject.Assisted;
/**
* Saves resources in a transaction.
*
* @author Erwin Mueller, erwin.mueller@deventm.org
* @since 1.8
*/
public class ResourceSaver {
private final File storeDir;
private FileResourceManager manager;
/**
* @see ResourceSaverFactory#create(File)
*/
@Inject
ResourceSaver(@Assisted File storeDir) {
this.storeDir = storeDir;
}
@Inject
void FileResourceManagerProvider(FileResourceManagerProvider manager) {
manager.setStoreDir(storeDir);
this.manager = manager.get();
}
/**
* Save the specified resources in the store directory.
*
* @param resources the {@link Resource} resources.
*
* @throws FileResourceException if there was an error create the file manager;
* error saving the resources.
*/
public void saveResource(Resource... resources) throws FileResourceException {
startManager();
String id = startTransaction();
try {
saveResources(id, resources);
manager.commitTransaction(id);
} catch (Throwable e) {
rollbackTransaction(manager, id);
try {
termManager();
} catch (IOException e1) {
throw new SaveResourceException(e, resources, storeDir);
}
throw new SaveResourceException(e, resources, storeDir);
}
try {
termManager();
} catch (IOException e) {
throw new FileResourceException("", e);
}
}
private void termManager() throws FileResourceException, IOException {
stopManager(manager);
Files.delete(new File(manager.getWorkDir()).toPath());
}
private void startManager() throws FileResourceException {
try {
manager.start();
} catch (ResourceManagerSystemException e) {
throw new StartManagerException(e, storeDir);
}
}
private String startTransaction() throws FileResourceException {
try {
String id = manager.generatedUniqueTxId();
manager.startTransaction(id);
return id;
} catch (ResourceManagerSystemException e) {
throw new StartTransactionException(e, storeDir);
} catch (ResourceManagerException e) {
throw new StartTransactionException(e, storeDir);
}
}
private void saveResources(String id, Resource[] resources) throws ResourceManagerException, FileResourceException {
for (Resource resource : resources) {
saveResource(manager, id, resource);
}
}
private void saveResource(FileResourceManager manager, String id, Resource resource)
throws ResourceManagerException, FileResourceException {
String projectId = resource.getName();
OutputStream projectStream = manager.writeResource(id, projectId);
saveResource(projectStream, resource);
}
private void saveResource(OutputStream stream, Resource resource) throws FileResourceException {
try {
resource.save(stream);
} catch (Exception e) {
throw new SaveResourceException(e, resource, storeDir);
}
}
private void rollbackTransaction(FileResourceManager manager, String id) throws FileResourceException {
try {
manager.rollbackTransaction(id);
} catch (ResourceManagerException e) {
throw new RollbackTransactionException(e, id);
}
}
private void stopManager(FileResourceManager manager) throws FileResourceException {
try {
manager.stop(SHUTDOWN_MODE_NORMAL);
} catch (ResourceManagerSystemException e) {
throw new StopManagerException(e, manager.getStoreDir());
}
}
}
| apache-2.0 |
google/assetMG | app/asset_browser/frontend/src/app/shared/loader/loader.component.spec.ts | 1225 | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { LoaderComponent } from './loader.component';
describe('LoaderComponent', () => {
let component: LoaderComponent;
let fixture: ComponentFixture<LoaderComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoaderComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoaderComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| apache-2.0 |
trevor/calendarserver | txweb2/client/interfaces.py | 2530 | # -*- test-case-name: txweb2.test.test_client -*-
##
# Copyright (c) 2007 Twisted Matrix Laboratories.
# Copyright (c) 2010-2014 Apple Inc. All rights reserved.
#
# 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.
#
##
from zope.interface import Interface
class IHTTPClientManager(Interface):
"""I coordinate between multiple L{HTTPClientProtocol} objects connected to a
single server to facilite request queuing and pipelining.
"""
def clientBusy(proto):
"""Called when the L{HTTPClientProtocol} doesn't want to accept anymore
requests.
@param proto: The L{HTTPClientProtocol} that is changing state.
@type proto: L{HTTPClientProtocol}
"""
pass
def clientIdle(proto):
"""Called when an L{HTTPClientProtocol} is able to accept more requests.
@param proto: The L{HTTPClientProtocol} that is changing state.
@type proto: L{HTTPClientProtocol}
"""
pass
def clientPipelining(proto):
"""Called when the L{HTTPClientProtocol} determines that it is able to
support request pipelining.
@param proto: The L{HTTPClientProtocol} that is changing state.
@type proto: L{HTTPClientProtocol}
"""
pass
def clientGone(proto):
"""Called when the L{HTTPClientProtocol} disconnects from the server.
@param proto: The L{HTTPClientProtocol} that is changing state.
@type proto: L{HTTPClientProtocol}
"""
pass
| apache-2.0 |
ontop/ontop | client/protege/src/main/java/org/protege/osgi/jdbc/impl/OSGiJdbcDriver.java | 1797 | package org.protege.osgi.jdbc.impl;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
import org.protege.osgi.jdbc.JdbcRegistry;
import java.sql.*;
import java.util.Properties;
import java.util.logging.Logger;
public class OSGiJdbcDriver implements Driver {
private final Version version;
private final JdbcRegistry registry;
public OSGiJdbcDriver(BundleContext context, JdbcRegistry registry) {
this.registry = registry;
String versionString = context.getBundle().getHeaders().get(Constants.BUNDLE_VERSION);
this.version = new Version(versionString);
}
@Override
public boolean acceptsURL(String url) throws SQLException {
return getDelegate(url) != null;
}
@Override
public Connection connect(String url, Properties info) throws SQLException {
Driver delegate = getDelegate(url);
return (delegate == null) ? null : delegate.connect(url, info);
}
@Override
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
Driver delegate = getDelegate(url);
return (delegate == null) ? null : delegate.getPropertyInfo(url, info);
}
private Driver getDelegate(String url) throws SQLException {
for (Driver delegate : registry.getJdbcDrivers())
if (delegate.acceptsURL(url))
return delegate;
return null;
}
@Override
public boolean jdbcCompliant() {
return registry.getJdbcDrivers().stream().allMatch(Driver::jdbcCompliant);
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
throw new SQLFeatureNotSupportedException();
}
@Override
public int getMajorVersion() {
return version.getMajor();
}
@Override
public int getMinorVersion() {
return version.getMinor();
}
}
| apache-2.0 |
Communote/communote-server | communote/persistence/src/main/java/com/communote/server/core/client/ClientInitializationException.java | 915 | package com.communote.server.core.client;
/**
* Exception thrown by the {@link ClientInitializer} to indicate that the initialization failed.
*
* @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a>
*/
public class ClientInitializationException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Create a new exception with detail message
*
* @param message
* detail message
*/
public ClientInitializationException(String message) {
super(message);
}
/**
* Create a new exception with detail message and cause
*
* @param message
* detail message
* @param cause
* the cause
*/
public ClientInitializationException(String message, Throwable cause) {
super(message, cause);
}
}
| apache-2.0 |
clementparizot/ET_Redux | src/main/java/org/earthtime/Tripoli/sessions/TripoliSessionFractionationCalculatorInterface.java | 1317 | /*
* TripoliSessionFractionationCalculatorInterface.java
*
* Created Jul 1, 2011
*
* Copyright 2006-2015 James F. Bowring and www.Earth-Time.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.earthtime.Tripoli.sessions;
/**
*
* @author James F. Bowring
*/
public interface TripoliSessionFractionationCalculatorInterface {
/**
*
*/
public void calculateDownholeFitSummariesForPrimaryStandard ();
// public void calculateAllInterceptAlphaFitSummariesForPrimaryStandard ();
/**
*
*/
public void calculateSessionFitFunctionsForPrimaryStandard ();
/**
*
*/
public void applyCorrections ();
/**
*
* @return
*/
public boolean isCalculatedInitialFitFunctions();
}
| apache-2.0 |
jokeog/ProjectCalendae | library/src/main/java/com/mikephil/charting/formatter/DefaultYAxisValueFormatter.java | 1110 | package com.mikephil.charting.formatter;
import com.mikephil.charting.components.YAxis;
import java.text.DecimalFormat;
/**
* Created by Philipp Jahoda on 20/09/15.
* Default formatter used for formatting labels of the YAxis. Uses a DecimalFormat with
* pre-calculated number of digits (depending on max and min value).
*/
public class DefaultYAxisValueFormatter implements YAxisValueFormatter {
/** decimalformat for formatting */
private DecimalFormat mFormat;
/**
* Constructor that specifies to how many digits the value should be
* formatted.
*
* @param digits
*/
public DefaultYAxisValueFormatter(int digits) {
StringBuffer b = new StringBuffer();
for (int i = 0; i < digits; i++) {
if (i == 0)
b.append(".");
b.append("0");
}
mFormat = new DecimalFormat("###,###,###,##0" + b.toString());
}
@Override
public String getFormattedValue(float value, YAxis yAxis) {
// avoid memory allocations here (for performance)
return mFormat.format(value);
}
}
| apache-2.0 |
RBMHTechnology/vind | api/src/main/java/com/rbmhtechnology/vind/parser/queryparser/Literal.java | 245 | package com.rbmhtechnology.vind.parser.queryparser;
import com.rbmhtechnology.vind.api.query.filter.Filter;
import com.rbmhtechnology.vind.model.FieldDescriptor;
public interface Literal{
Filter toVindFilter(FieldDescriptor descriptor);
}
| apache-2.0 |
ssm/ssm-munin | spec/defines/munin_plugin_spec.rb | 4217 | require 'spec_helper'
t_conf_dir = {}
t_conf_dir.default = '/etc/munin'
t_conf_dir['Solaris'] = '/opt/local/etc/munin'
t_conf_dir['FreeBSD'] = '/usr/local/etc/munin'
t_share_dir = {}
t_share_dir.default = '/usr/share/munin'
t_share_dir['Solaris'] = '/opt/local/share/munin'
t_share_dir['FreeBSD'] = '/usr/local/share/munin'
t_share_dir['Archlinux'] = '/usr/lib/munin'
describe 'munin::plugin', type: 'define' do
let(:title) { 'testplugin' }
on_supported_os.each do |os, facts|
# Avoid testing on distributions similar to RedHat and Debian
next if %r{^(ubuntu|centos|scientific|oraclelinux)-}.match?(os)
context "on #{os}" do
let(:facts) do
facts
end
conf_dir = t_conf_dir[facts[:osfamily]]
plugin_share_dir = "#{t_share_dir[facts[:osfamily]]}/plugins"
context 'with no parameters' do
it { is_expected.not_to contain_file("#{conf_dir}/plugins/testplugin") }
it do
is_expected.to contain_file("#{conf_dir}/plugin-conf.d/testplugin.conf")
.with_ensure('absent')
end
end
context 'with ensure=link parameter' do
let(:params) { { ensure: 'link' } }
it do
is_expected.to contain_file("#{conf_dir}/plugins/testplugin")
.with_ensure('link')
.with_target("#{plugin_share_dir}/testplugin")
end
it do
is_expected.to contain_file("#{conf_dir}/plugin-conf.d/testplugin.conf")
.with_ensure('absent')
end
end
context 'with ensure=link and target parameters' do
let(:title) { 'test_foo' }
let(:params) do
{ ensure: 'link',
target: 'test_' }
end
it do
is_expected.to contain_file("#{conf_dir}/plugins/test_foo")
.with_ensure('link')
.with_target("#{plugin_share_dir}/test_")
end
it do
is_expected.to contain_file("#{conf_dir}/plugin-conf.d/test_foo.conf")
.with_ensure('absent')
end
end
context 'with ensure=present and source parameters' do
let(:params) do
{ ensure: 'present',
source: 'puppet:///modules/munin/plugins/testplugin' }
end
it do
is_expected.to contain_file("#{conf_dir}/plugins/testplugin")
.with_ensure('present')
.with_source('puppet:///modules/munin/plugins/testplugin')
end
it do
is_expected.to contain_file("#{conf_dir}/plugin-conf.d/testplugin.conf")
.with_ensure('absent')
end
end
context 'with ensure=present, source and config parameters' do
let(:params) do
{ ensure: 'present',
source: 'puppet:///modules/munin/plugins/testplugin',
config: ['something wonderful'] }
end
it do
is_expected.to contain_file("#{conf_dir}/plugins/testplugin")
.with_ensure('present')
.with_source('puppet:///modules/munin/plugins/testplugin')
end
it do
is_expected.to contain_file("#{conf_dir}/plugin-conf.d/testplugin.conf")
.with_ensure('present')
.with_content(%r{something wonderful})
end
end
context 'only configuration' do
let(:params) do
{ config: ['env.rootdn cn=admin,dc=example,dc=org'],
config_label: 'slapd_*' }
end
it do
is_expected.to contain_file("#{conf_dir}/plugin-conf.d/testplugin.conf")
.with_ensure('present')
.with_content(%r{env.rootdn})
end
it do
expect { is_expected.to contain_file("#{conf_dir}/plugins/testplugin") }
.to raise_error("expected that the catalogue would contain File[#{conf_dir}/plugins/testplugin]")
end
end
context 'with absolute target' do
let(:params) do
{ ensure: 'link',
target: '/full/path/to/testplugin' }
end
it do
is_expected.to contain_file("#{conf_dir}/plugins/testplugin")
.with_ensure('link')
.with_target('/full/path/to/testplugin')
end
end
end
end
end
| apache-2.0 |
pebble2015/cpoi | src/org/apache/poi/ss/formula/ptg/OperationPtg.cpp | 1108 | // Generated from /POI/java/org/apache/poi/ss/formula/ptg/OperationPtg.java
#include <org/apache/poi/ss/formula/ptg/OperationPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/Ptg.hpp>
poi::ss::formula::ptg::OperationPtg::OperationPtg(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
poi::ss::formula::ptg::OperationPtg::OperationPtg()
: OperationPtg(*static_cast< ::default_init_tag* >(0))
{
ctor();
}
constexpr int32_t poi::ss::formula::ptg::OperationPtg::TYPE_UNARY;
constexpr int32_t poi::ss::formula::ptg::OperationPtg::TYPE_BINARY;
constexpr int32_t poi::ss::formula::ptg::OperationPtg::TYPE_FUNCTION;
int8_t poi::ss::formula::ptg::OperationPtg::getDefaultOperandClass()
{
return Ptg::CLASS_VALUE;
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* poi::ss::formula::ptg::OperationPtg::class_()
{
static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.formula.ptg.OperationPtg", 42);
return c;
}
java::lang::Class* poi::ss::formula::ptg::OperationPtg::getClass0()
{
return class_();
}
| apache-2.0 |
fgdorais/lean | src/library/messages.cpp | 393 | /*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Gabriel Ebner
*/
#include <string>
#include "library/messages.h"
namespace lean {
message::message(parser_exception const & ex) :
message(ex.get_file_name(), pos_info(ex.get_line(), ex.get_pos()),
ERROR, ex.get_msg()) {}
}
| apache-2.0 |
tengqm/senlin-container | senlin/engine/parser.py | 2624 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
from oslo_serialization import jsonutils
import six
from six.moves import urllib
import yaml
from senlin.common.i18n import _
# Try LibYAML if available
if hasattr(yaml, 'CSafeLoader'):
Loader = yaml.CSafeLoader
else:
Loader = yaml.SafeLoader
if hasattr(yaml, 'CSafeDumper'):
Dumper = yaml.CSafeDumper
else:
Dumper = yaml.SafeDumper
class YamlLoader(Loader):
def normalise_file_path_to_url(self, path):
if urllib.parse.urlparse(path).scheme:
return path
path = os.path.abspath(path)
return urllib.parse.urljoin('file:',
urllib.request.pathname2url(path))
def include(self, node):
try:
url = self.normalise_file_path_to_url(self.construct_scalar(node))
tmpl = urllib.request.urlopen(url).read()
return yaml.load(tmpl, Loader)
except urllib.error.URLError as ex:
raise IOError('Failed retrieving file %s: %s' %
(url, six.text_type(ex)))
def process_unicode(self, node):
# Override the default string handling function to always return
# unicode objects
return self.construct_scalar(node)
YamlLoader.add_constructor('!include', YamlLoader.include)
YamlLoader.add_constructor(u'tag:yaml.org,2002:str',
YamlLoader.process_unicode)
YamlLoader.add_constructor(u'tag:yaml.org,2002:timestamp',
YamlLoader.process_unicode)
def simple_parse(in_str):
try:
out_dict = jsonutils.loads(in_str)
except ValueError:
try:
out_dict = yaml.load(in_str, Loader=YamlLoader)
except yaml.YAMLError as yea:
yea = six.text_type(yea)
msg = _('Error parsing input: %s') % yea
raise ValueError(msg)
else:
if out_dict is None:
out_dict = {}
if not isinstance(out_dict, dict):
msg = _('The input is not a JSON object or YAML mapping.')
raise ValueError(msg)
return out_dict
| apache-2.0 |
kohii/smoothcsv | smoothcsv-app-modules/smoothcsv-core/src/main/java/com/smoothcsv/core/sql/engine/SqlTaskWorker.java | 2672 | package com.smoothcsv.core.sql.engine;
import java.awt.Dialog;
import java.sql.ResultSet;
import java.util.function.Consumer;
import javax.swing.SwingUtilities;
import com.smoothcsv.core.component.AsyncTaskDialog;
import com.smoothcsv.core.sql.engine.core.Csvsql;
import com.smoothcsv.framework.error.ErrorHandlerFactory;
import com.smoothcsv.framework.util.SCBundle;
import org.apache.commons.lang3.mutable.MutableObject;
public class SqlTaskWorker {
private AsyncTaskDialog.Monitor monitor;
private String sql;
private ResultSet resultSet;
public SqlTaskWorker(Dialog owner, String sql) {
this.sql = sql;
monitor = new AsyncTaskDialog.Monitor(owner, SCBundle.get("key.sql.runningQuery"), true);
monitor.setDialogSize(200, 150);
monitor.setText1(SCBundle.get("key.sql.runningQuery"));
}
public boolean executeQuery() {
Throwable throwable = null;
try {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
monitor.begin();
}
});
final MutableObject<Integer> status = new MutableObject<>(0);
final MutableObject<Throwable> error = new MutableObject<>();
new Thread(new Runnable() {
@Override
public void run() {
try {
resultSet = Csvsql.executeQuery(sql);
status.setValue(1);
} catch (Exception e) {
status.setValue(2);
error.setValue(e);
}
}
}).start();
while (status.getValue() == 0) {
if (monitor.isCanceled()) {
Csvsql.close();
status.setValue(2);
break;
}
Thread.sleep(500);
}
if (status.getValue() == 2) {
if (error.getValue() != null) {
if (!monitor.isCanceled()) {
throw error.getValue();
}
} else {
throw new InterruptedException();
}
}
return status.getValue() == 1;
} catch (InterruptedException e) {
return false;
} catch (Throwable t) {
throwable = t;
return false;
} finally {
Throwable _throwable = throwable;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (monitor.isDialogVisible()) {
monitor.end();
}
if (_throwable != null) {
ErrorHandlerFactory.getErrorHandler().handle(_throwable);
}
}
});
}
}
public void handleResult(Consumer<ResultSet> handler) {
handler.accept(resultSet);
}
/**
* @return resultSet
*/
public ResultSet getResultSet() {
return resultSet;
}
} | apache-2.0 |
jlz27/gs-collections | unit-tests/src/test/java/com/gs/collections/impl/set/mutable/UnmodifiableMutableSetTest.java | 6945 | /*
* Copyright 2011 Goldman Sachs.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gs.collections.impl.set.mutable;
import java.util.NoSuchElementException;
import com.gs.collections.api.collection.MutableCollection;
import com.gs.collections.api.set.MutableSet;
import com.gs.collections.impl.collection.mutable.AbstractCollectionTestCase;
import com.gs.collections.impl.list.mutable.FastList;
import com.gs.collections.impl.test.Verify;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* JUnit test for {@link UnmodifiableMutableSet}.
*/
public class UnmodifiableMutableSetTest extends AbstractCollectionTestCase
{
private static final String LED_ZEPPELIN = "Led Zeppelin";
private static final String METALLICA = "Metallica";
private MutableSet<String> mutableSet;
private MutableSet<String> unmodifiableSet;
@Before
public void setUp()
{
this.mutableSet = UnifiedSet.newSetWith(METALLICA, "Bon Jovi", "Europe", "Scorpions");
this.unmodifiableSet = this.mutableSet.asUnmodifiable();
}
@Override
protected <T> MutableSet<T> classUnderTest()
{
return UnifiedSet.<T>newSet().asUnmodifiable();
}
@Override
protected <T> MutableSet<T> newWith(T one)
{
return UnifiedSet.newSetWith(one).asUnmodifiable();
}
@Override
protected <T> MutableSet<T> newWith(T one, T two)
{
return UnifiedSet.newSetWith(one, two).asUnmodifiable();
}
@Override
protected <T> MutableSet<T> newWith(T one, T two, T three)
{
return UnifiedSet.newSetWith(one, two, three).asUnmodifiable();
}
@Override
protected <T> MutableSet<T> newWith(T... elements)
{
return UnifiedSet.newSetWith(elements).asUnmodifiable();
}
@Override
@Test(expected = UnsupportedOperationException.class)
public void removeObject()
{
super.removeObject();
}
@Override
@Test(expected = UnsupportedOperationException.class)
public void removeIfWith()
{
super.removeIfWith();
}
@Override
@Test(expected = UnsupportedOperationException.class)
public void clear()
{
super.clear();
}
@Override
@Test(expected = UnsupportedOperationException.class)
public void addAll()
{
super.addAll();
}
@Override
@Test(expected = UnsupportedOperationException.class)
public void addAllIterable()
{
super.addAllIterable();
}
@Override
@Test(expected = UnsupportedOperationException.class)
public void remove()
{
super.remove();
}
@Override
@Test(expected = UnsupportedOperationException.class)
public void removeAll()
{
super.removeAll();
}
@Override
@Test(expected = UnsupportedOperationException.class)
public void removeAllIterable()
{
super.removeAllIterable();
}
@Override
@Test(expected = UnsupportedOperationException.class)
public void retainAll()
{
super.retainAll();
}
@Override
@Test(expected = UnsupportedOperationException.class)
public void retainAllIterable()
{
super.retainAllIterable();
}
@Override
@Test
public void testToString()
{
MutableCollection<Object> collection = this.<Object>newWith(1, 2);
String simpleName = collection.getClass().getSimpleName();
String string = collection.toString();
Assert.assertTrue("[1, 2]".equals(string) || "[2, 1]".equals(string));
}
@Override
@Test
public void makeString()
{
MutableCollection<Object> collection = this.<Object>newWith(1, 2, 3);
Assert.assertEquals(collection.toString(), '[' + collection.makeString() + ']');
}
@Override
@Test
public void appendString()
{
MutableCollection<Object> collection = this.<Object>newWith(1, 2, 3);
Appendable builder = new StringBuilder();
collection.appendString(builder);
Assert.assertEquals(collection.toString(), '[' + builder.toString() + ']');
}
@Override
@Test
public void getFirst()
{
Assert.assertNotNull(this.newWith(1, 2, 3).getFirst());
Assert.assertNull(this.classUnderTest().getFirst());
}
@Override
@Test
public void getLast()
{
Assert.assertNotNull(this.newWith(1, 2, 3).getLast());
Assert.assertNull(this.classUnderTest().getLast());
}
@Override
@Test
public void asSynchronized()
{
Verify.assertInstanceOf(SynchronizedMutableSet.class, this.classUnderTest().asSynchronized());
}
@Override
@Test
public void asUnmodifiable()
{
Verify.assertInstanceOf(UnmodifiableMutableSet.class, this.classUnderTest().asUnmodifiable());
}
@Test
public void testEqualsAndHashCode()
{
Verify.assertEqualsAndHashCode(this.mutableSet, this.unmodifiableSet);
Verify.assertPostSerializedEqualsAndHashCode(this.unmodifiableSet);
}
@Test
public void testNewEmpty()
{
MutableSet<String> set = this.unmodifiableSet.newEmpty();
set.add(LED_ZEPPELIN);
Verify.assertContains(LED_ZEPPELIN, set);
}
@Test
public void testClone()
{
MutableSet<String> set = this.classUnderTest();
MutableSet<String> clone = set.clone();
Assert.assertSame(clone, set);
}
@Test(expected = NoSuchElementException.class)
public void min_empty_throws_without_comparator()
{
this.newWith().min();
}
@Test(expected = NoSuchElementException.class)
public void max_empty_throws_without_comparator()
{
this.newWith().max();
}
@Override
@Test(expected = UnsupportedOperationException.class)
public void with()
{
this.newWith(1, 2, 3).with(4);
}
@Override
@Test(expected = UnsupportedOperationException.class)
public void withAll()
{
this.newWith(1, 2, 3).withAll(FastList.newListWith(4, 5));
}
@Override
@Test(expected = UnsupportedOperationException.class)
public void without()
{
this.newWith(1, 2, 3).without(2);
}
@Override
@Test(expected = UnsupportedOperationException.class)
public void withoutAll()
{
this.newWith(1, 2, 3, 4, 5).withoutAll(FastList.newListWith(2, 4));
}
}
| apache-2.0 |
shanti/olio | tags/0.1-final/webapp/rails/trunk/config/environment.rb | 3871 | #
# 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.
#
# Be sure to restart your web server when you modify this file.
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
# RAILS_GEM_VERSION = '2.1.2' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
require 'hodel_3000_compliant_logger'
IMAGE_STORE_PATH = 'public/uploaded_files'
DOCUMENT_STORE_PATH = 'public/uploaded_files'
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here
# Skip frameworks you're not going to use (only works if using vendor/rails)
# config.frameworks -= [ :action_web_service, :action_mailer ]
# Only load the plugins named here, by default all plugins in vendor/plugins are loaded
# config.plugins = %W( exception_notification ssl_requirement )
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
# config.log_level = :debug
# config.logger = Hodel3000CompliantLogger.new(config.log_path)
# Use the database for sessions instead of the file system
# (create the session table with 'rake db:sessions:create')
# config.action_controller.session_store = :active_record_store
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
# Make Active Record use UTC-base instead of local time
# config.active_record.default_timezone = :utc
config.action_controller.session = {
:session_key => '_perf_session',
:secret => 'dab95a8389324e5fa99cf6b178d4377d320b3c94ac2af58946b59118b92d2149a3091bbada03862361ee401e594279022b15fdaeee0df45ee17de07caa912576'
}
# Add new inflection rules using the following format
# (all these examples are active by default):
# Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# See Rails::Configuration for more options
end
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register "application/x-mobile", :mobile
# Include your application configuration below
require 'uploadable'
require 'will_paginate'
#require RAILS_ROOT + '/test/selenium_helper' if defined? SeleniumOnRails::FixtureLoader
require 'geolocation'
Geolocation.url = 'http://localhost:8080/geocoder/geocode?appid=gsd5f'
| apache-2.0 |
williammartin/guardian | rundmc/runrunc/runruncfakes/fake_bundle_loader.go | 2690 | // Code generated by counterfeiter. DO NOT EDIT.
package runruncfakes
import (
"sync"
"code.cloudfoundry.org/guardian/rundmc/goci"
"code.cloudfoundry.org/guardian/rundmc/runrunc"
)
type FakeBundleLoader struct {
LoadStub func(path string) (goci.Bndl, error)
loadMutex sync.RWMutex
loadArgsForCall []struct {
path string
}
loadReturns struct {
result1 goci.Bndl
result2 error
}
loadReturnsOnCall map[int]struct {
result1 goci.Bndl
result2 error
}
invocations map[string][][]interface{}
invocationsMutex sync.RWMutex
}
func (fake *FakeBundleLoader) Load(path string) (goci.Bndl, error) {
fake.loadMutex.Lock()
ret, specificReturn := fake.loadReturnsOnCall[len(fake.loadArgsForCall)]
fake.loadArgsForCall = append(fake.loadArgsForCall, struct {
path string
}{path})
fake.recordInvocation("Load", []interface{}{path})
fake.loadMutex.Unlock()
if fake.LoadStub != nil {
return fake.LoadStub(path)
}
if specificReturn {
return ret.result1, ret.result2
}
return fake.loadReturns.result1, fake.loadReturns.result2
}
func (fake *FakeBundleLoader) LoadCallCount() int {
fake.loadMutex.RLock()
defer fake.loadMutex.RUnlock()
return len(fake.loadArgsForCall)
}
func (fake *FakeBundleLoader) LoadArgsForCall(i int) string {
fake.loadMutex.RLock()
defer fake.loadMutex.RUnlock()
return fake.loadArgsForCall[i].path
}
func (fake *FakeBundleLoader) LoadReturns(result1 goci.Bndl, result2 error) {
fake.LoadStub = nil
fake.loadReturns = struct {
result1 goci.Bndl
result2 error
}{result1, result2}
}
func (fake *FakeBundleLoader) LoadReturnsOnCall(i int, result1 goci.Bndl, result2 error) {
fake.LoadStub = nil
if fake.loadReturnsOnCall == nil {
fake.loadReturnsOnCall = make(map[int]struct {
result1 goci.Bndl
result2 error
})
}
fake.loadReturnsOnCall[i] = struct {
result1 goci.Bndl
result2 error
}{result1, result2}
}
func (fake *FakeBundleLoader) Invocations() map[string][][]interface{} {
fake.invocationsMutex.RLock()
defer fake.invocationsMutex.RUnlock()
fake.loadMutex.RLock()
defer fake.loadMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
for key, value := range fake.invocations {
copiedInvocations[key] = value
}
return copiedInvocations
}
func (fake *FakeBundleLoader) recordInvocation(key string, args []interface{}) {
fake.invocationsMutex.Lock()
defer fake.invocationsMutex.Unlock()
if fake.invocations == nil {
fake.invocations = map[string][][]interface{}{}
}
if fake.invocations[key] == nil {
fake.invocations[key] = [][]interface{}{}
}
fake.invocations[key] = append(fake.invocations[key], args)
}
var _ runrunc.BundleLoader = new(FakeBundleLoader)
| apache-2.0 |
dlemstra/Magick.NET | tests/Magick.NET.Tests/Colors/MagickColorTests/TheToStringMethod.cs | 1315 | // Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.
using ImageMagick;
using Xunit;
namespace Magick.NET.Tests
{
public partial class MagickColorTests
{
public class TheToStringMethod
{
[Fact]
public void ShouldReturnTheCorrectString()
{
var color = new MagickColor(MagickColors.Red);
#if Q8
Assert.Equal("#FF0000FF", color.ToString());
#else
Assert.Equal("#FFFF00000000FFFF", color.ToString());
#endif
}
[Fact]
public void ShouldReturnTheCorrectStringForCmykColor()
{
#if Q8
var color = new MagickColor(0, Quantum.Max, 0, 0, (System.Byte)(Quantum.Max / 3));
#elif Q16
var color = new MagickColor(0, Quantum.Max, 0, 0, (System.UInt16)(Quantum.Max / 3));
#else
var color = new MagickColor(0, Quantum.Max, 0, 0, (System.Single)(Quantum.Max / 3));
#endif
Assert.Equal("cmyka(0," + Quantum.Max + ",0,0,0.3333)", color.ToString());
color = new MagickColor(0, Quantum.Max, 0, 0, Quantum.Max);
Assert.Equal("cmyka(0," + Quantum.Max + ",0,0,1.0)", color.ToString());
}
}
}
}
| apache-2.0 |
cronn-de/jira-sync | src/main/java/de/cronn/jira/sync/mapping/DefaultPriorityMapper.java | 2278 | package de.cronn.jira.sync.mapping;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import de.cronn.jira.sync.config.JiraSyncConfig;
import de.cronn.jira.sync.domain.JiraIssue;
import de.cronn.jira.sync.domain.JiraPriority;
import de.cronn.jira.sync.service.JiraService;
@Component
public class DefaultPriorityMapper implements PriorityMapper {
private static final Logger log = LoggerFactory.getLogger(DefaultPriorityMapper.class);
private JiraSyncConfig syncConfig;
@Autowired
public void setSyncConfig(JiraSyncConfig syncConfig) {
this.syncConfig = syncConfig;
}
@Override
public JiraPriority mapPriority(JiraService jiraTarget, JiraIssue sourceIssue) {
String sourcePriorityName = getSourcePriorityName(sourceIssue);
if (sourcePriorityName == null) {
return null;
}
JiraPriority targetPriority = getTargetPriorityName(jiraTarget, syncConfig, sourcePriorityName);
if (targetPriority == null) {
return null;
}
log.trace("priority: {} --> {}", sourcePriorityName, targetPriority);
return targetPriority;
}
private static JiraPriority getTargetPriorityName(JiraService jiraTarget, JiraSyncConfig syncConfig, String sourcePriorityName) {
String targetPriorityName = syncConfig.getPriorityMapping().get(sourcePriorityName);
if (targetPriorityName == null) {
log.warn("no mapping defined for {}", sourcePriorityName);
return null;
}
JiraPriority targetPriority = jiraTarget.getPriorities().stream()
.filter(priority -> Objects.equals(priority.getName(), targetPriorityName))
.findFirst()
.orElse(null);
if (targetPriority == null) {
log.warn("target priority '{}' not found", targetPriorityName);
return null;
}
return targetPriority;
}
private static String getSourcePriorityName(JiraIssue sourceIssue) {
JiraPriority sourcePriority = sourceIssue.getFields().getPriority();
if (sourcePriority == null) {
return null;
}
String sourcePriorityName = sourcePriority.getName();
Assert.notNull(sourcePriorityName, "sourcePriorityName not set for: " + sourceIssue);
return sourcePriorityName;
}
}
| apache-2.0 |
soundcloud/zipkin | zipkin-server/src/test/java/zipkin/server/internal/ITZipkinServerQueryDisabled.java | 2196 | /**
* Copyright 2015-2018 The OpenZipkin 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 zipkin.server.internal;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import zipkin.server.ZipkinServer;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Collector-only builds should be able to disable the query (and indirectly the UI), so that
* associated assets 404 vs throw exceptions.
*/
@SpringBootTest(
classes = ZipkinServer.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {
"spring.config.name=zipkin-server",
"zipkin.query.enabled=false",
"zipkin.ui.enabled=false"
}
)
@RunWith(SpringRunner.class)
public class ITZipkinServerQueryDisabled {
@Value("${local.server.port}") int zipkinPort;
OkHttpClient client = new OkHttpClient.Builder().followRedirects(false).build();
@Test public void queryRelatedEndpoints404() throws Exception {
assertThat(get("/api/v1/traces").code()).isEqualTo(404);
assertThat(get("/api/v2/traces").code()).isEqualTo(404);
assertThat(get("/index.html").code()).isEqualTo(404);
// but other endpoints are ok
assertThat(get("/health").isSuccessful()).isTrue();
}
private Response get(String path) throws IOException {
return client.newCall(new Request.Builder()
.url("http://localhost:" + zipkinPort + path)
.build()).execute();
}
}
| apache-2.0 |
xiaopeng163/gocode | int.go | 276 | package main
import "fmt"
var (
a = 1
b = 2
c = 3
)
var d int
var e int = 5
func main() {
f := 6
fmt.Printf("a is %d\n", a)
fmt.Printf("b is %d\n", b)
fmt.Printf("c is %d\n", c)
fmt.Printf("d is %d\n", d)
fmt.Printf("e is %d\n", e)
fmt.Printf("f is %d\n", f)
}
| apache-2.0 |
pacozaa/BoofCV | main/recognition/src/boofcv/factory/tracker/FactoryTrackerObjectQuad.java | 7119 | /*
* Copyright (c) 2011-2015, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.factory.tracker;
import boofcv.abst.filter.derivative.ImageGradient;
import boofcv.abst.tracker.*;
import boofcv.alg.filter.derivative.GImageDerivativeOps;
import boofcv.alg.interpolate.InterpolatePixelS;
import boofcv.alg.tracker.circulant.CirculantTracker;
import boofcv.alg.tracker.meanshift.PixelLikelihood;
import boofcv.alg.tracker.meanshift.TrackerMeanShiftComaniciu2003;
import boofcv.alg.tracker.meanshift.TrackerMeanShiftLikelihood;
import boofcv.alg.tracker.sfot.SfotConfig;
import boofcv.alg.tracker.sfot.SparseFlowObjectTracker;
import boofcv.alg.tracker.tld.TldTracker;
import boofcv.core.image.border.BorderType;
import boofcv.factory.filter.derivative.FactoryDerivative;
import boofcv.factory.interpolate.FactoryInterpolation;
import boofcv.struct.image.ImageBase;
import boofcv.struct.image.ImageSingleBand;
import boofcv.struct.image.ImageType;
/**
* Factory for implementations of {@link TrackerObjectQuad}, a high level interface for tracking user specified
* objects inside video sequences. As usual, the high level interface makes it easier to use these algorithms
* at the expensive of algorithm specific features.
*
* @author Peter Abeles
*/
public class FactoryTrackerObjectQuad {
/**
* Create an instance of {@link TldTracker Tracking-Learning-Detection (TLD)} tracker for the
* {@link TrackerObjectQuad} interface.
* @param config Configuration for the tracker
* @param <T> Image input type
* @param <D> Image derivative type
* @return TrackerObjectQuad
*/
public static <T extends ImageSingleBand,D extends ImageSingleBand>
TrackerObjectQuad<T> tld(ConfigTld config , Class<T> imageType ) {
if( config == null )
config = new ConfigTld();
Class<D> derivType = GImageDerivativeOps.getDerivativeType(imageType);
InterpolatePixelS<T> interpolate = FactoryInterpolation.bilinearPixelS(imageType, BorderType.EXTENDED);
ImageGradient<T,D> gradient = FactoryDerivative.sobel(imageType, derivType);
TldTracker<T,D> tracker = new TldTracker<T,D>(config.parameters,interpolate,gradient,imageType,derivType);
return new Tld_to_TrackerObjectQuad<T,D>(tracker,imageType);
}
/**
* Create an instance of {@link SparseFlowObjectTracker Sparse Flow Object Tracker} for the
* {@link TrackerObjectQuad} interface.
* @param config Configuration for the tracker, Null for default.
* @param <T> Image input type
* @param <D> Image derivative type. Null for default.
* @return TrackerObjectQuad
*/
public static <T extends ImageSingleBand,D extends ImageSingleBand>
TrackerObjectQuad<T> sparseFlow(SfotConfig config, Class<T> imageType , Class<D> derivType ) {
if( derivType == null )
derivType = GImageDerivativeOps.getDerivativeType(imageType);
if( config == null )
config = new SfotConfig();
ImageGradient<T, D> gradient = FactoryDerivative.sobel(imageType,derivType);
SparseFlowObjectTracker<T,D> tracker = new SparseFlowObjectTracker<T,D>(config,imageType,derivType,gradient);
return new Sfot_to_TrackObjectQuad<T,D>(tracker,imageType);
}
/**
* Very basic and very fast implementation of mean-shift which uses a fixed sized rectangle for its region.
* Works best when the target is composed of a single color.
*
* @see TrackerMeanShiftLikelihood
*
* @param maxIterations Maximum number of mean-shift iterations. Try 30.
* @param numBins Number of bins in the histogram color model. Try 5.
* @param maxPixelValue Maximum number of pixel values. For 8-bit images this will be 256
* @param modelType Type of color model used.
* @param imageType Type of image
* @return TrackerObjectQuad based on {@link TrackerMeanShiftLikelihood}.
*/
public static <T extends ImageBase>
TrackerObjectQuad<T> meanShiftLikelihood(int maxIterations,
int numBins,
double maxPixelValue,
MeanShiftLikelihoodType modelType,
ImageType<T> imageType) {
PixelLikelihood<T> likelihood;
switch( modelType ) {
case HISTOGRAM:
likelihood = FactoryTrackerObjectAlgs.likelihoodHistogramCoupled(maxPixelValue,numBins,imageType);
break;
case HISTOGRAM_INDEPENDENT_RGB_to_HSV:
if( imageType.getNumBands() != 3 )
throw new IllegalArgumentException("Expected RGB image as input with 3-bands");
likelihood = FactoryTrackerObjectAlgs.
likelihoodHueSatHistIndependent(maxPixelValue, numBins, (ImageType) imageType);
break;
case HISTOGRAM_RGB_to_HSV:
if( imageType.getNumBands() != 3 )
throw new IllegalArgumentException("Expected RGB image as input with 3-bands");
likelihood = FactoryTrackerObjectAlgs.likelihoodHueSatHistCoupled(maxPixelValue,numBins,(ImageType)imageType);
break;
default:
throw new IllegalArgumentException("Unknown likelihood model "+modelType);
}
TrackerMeanShiftLikelihood<T> alg =
new TrackerMeanShiftLikelihood<T>(likelihood,maxIterations,0.1f);
return new Msl_to_TrackerObjectQuad<T>(alg,likelihood,imageType);
}
/**
* Implementation of mean-shift which matches the histogram and can handle targets composed of multiple colors.
* The tracker can also be configured to estimate gradual changes in scale. The track region is
* composed of a rotated rectangle.
*
* @see TrackerMeanShiftComaniciu2003
*
* @param config Tracker configuration
* @param <T> Image type
* @return TrackerObjectQuad based on Comaniciu2003
*/
public static <T extends ImageBase>
TrackerObjectQuad<T> meanShiftComaniciu2003(ConfigComaniciu2003 config, ImageType<T> imageType ) {
TrackerMeanShiftComaniciu2003<T> alg = FactoryTrackerObjectAlgs.meanShiftComaniciu2003(config,imageType);
return new Comaniciu2003_to_TrackerObjectQuad<T>(alg,imageType);
}
/**
* Creates the Circulant feature tracker. Texture based tracker which uses the theory of circulant matrices,
* Discrete Fourier Transform (DCF), and linear classifiers to track a target. Fixed sized rectangular target
* and only estimates translation. Can't detect when it loses track or re-aquire track.
*
* @see CirculantTracker
*
* @param config Configuration
* @return CirculantTracker
*/
public static <T extends ImageSingleBand>
TrackerObjectQuad<T> circulant( ConfigCirculantTracker config , Class<T> imageType ) {
CirculantTracker<T> alg = FactoryTrackerObjectAlgs.circulant(config,imageType);
return new Circulant_to_TrackerObjectQuad<T>(alg,ImageType.single(imageType));
}
}
| apache-2.0 |
tberg12/murphy | src/tberg/murphy/sequence/HMM.java | 6849 | package tberg.murphy.sequence;
import tberg.murphy.sequence.ForwardBackward.StationaryLattice;
import tberg.murphy.sequence.ForwardBackward.StationaryStateProjector;
public class HMM {
public interface StationaryTransitionModel {
public int numSequences();
public int sequenceLength(int d);
public int numStates(int d);
public double startLogProb(int d, int ts);
public double endLogProb(int d, int ts);
public double startProb(int d, int ts);
public double endProb(int d, int ts);
public int[] allowedForwardTransitions(int d, int ts);
public double[] allowedForwardTransitionsLogProbs(int d, int ts);
public double[] allowedForwardTransitionsProbs(int d, int ts);
public int[] allowedBackwardTransitions(int d, int ts);
public double[] allowedBackwardTransitionsLogProbs(int d, int ts);
public double[] allowedBackwardTransitionsProbs(int d, int ts);
}
public interface TransitionModel {
public int numSequences();
public int sequenceLength(int d);
public int numStates(int d, int t);
public double startLogProb(int d, int ts);
public double endLogProb(int d, int ts);
public double startProb(int d, int ts);
public double endProb(int d, int ts);
public int[] allowedForwardTransitions(int d, int t, int ts);
public double[] allowedForwardTransitionsLogProbs(int d, int t, int ts);
public double[] allowedForwardTransitionsProbs(int d, int t, int ts);
public int[] allowedBackwardTransitions(int d, int t, int ts);
public double[] allowedBackwardTransitionsLogProbs(int d, int t, int ts);
public double[] allowedBackwardTransitionsProbs(int d, int t, int ts);
}
public interface StationaryEmissionModel<A> {
public int numSequences();
public int sequenceLength(int d);
public int numStates();
public double emissionLogProb(int d, int t, int es);
public double emissionProb(int d, int t, int es);
}
public static class StationaryHMMLattice<A> implements StationaryLattice {
private StationaryTransitionModel transitionModel;
private StationaryEmissionModel<A> emissionModel;
private StationaryStateProjector transitionToEmissionState;
private A[][] observations;
public StationaryHMMLattice(StationaryTransitionModel transitionModel, StationaryEmissionModel<A> emissionModel, StationaryStateProjector transitionToEmissionState, A[][] observations) {
this.transitionModel = transitionModel;
this.emissionModel = emissionModel;
this.transitionToEmissionState = transitionToEmissionState;
this.observations = observations;
}
public int numSequences() {
return observations.length;
}
public int sequenceLength(int d) {
return observations[d].length;
}
public int numStates(int d) {
return transitionModel.numStates(d);
}
public double nodeLogPotential(int d, int t, int ts) {
int es = transitionToEmissionState.project(d, t, ts);
if (t == 0) {
return transitionModel.startLogProb(d, ts) + emissionModel.emissionLogProb(d, t, es);
} else if (t == observations[d].length-1) {
return transitionModel.endLogProb(d, ts) + emissionModel.emissionLogProb(d, t, es);
} else {
return emissionModel.emissionLogProb(d, t, es);
}
}
public double nodePotential(int d, int t, int ts) {
int es = transitionToEmissionState.project(d, t, ts);
if (t == 0) {
return transitionModel.startProb(d, ts) * emissionModel.emissionProb(d, t, es);
} else if (t == observations[d].length-1) {
return transitionModel.endProb(d, ts) * emissionModel.emissionProb(d, t, es);
} else {
return emissionModel.emissionProb(d, t, es);
}
}
public double[] allowedEdgesLogPotentials(int d, int ts, boolean backward) {
if (backward) {
return transitionModel.allowedBackwardTransitionsLogProbs(d, ts);
} else {
return transitionModel.allowedForwardTransitionsLogProbs(d, ts);
}
}
public double[] allowedEdgesPotentials(int d, int ts, boolean backward) {
if (backward) {
return transitionModel.allowedBackwardTransitionsProbs(d, ts);
} else {
return transitionModel.allowedForwardTransitionsProbs(d, ts);
}
}
public int[] allowedEdges(int d, int ts, boolean backward) {
if (backward) {
return transitionModel.allowedBackwardTransitions(d, ts);
} else {
return transitionModel.allowedForwardTransitions(d, ts);
}
}
}
public static class NonStationaryHMMLattice<A> implements ForwardBackward.Lattice {
private TransitionModel transitionModel;
private StationaryEmissionModel<A> emissionModel;
private StationaryStateProjector transitionToEmissionState;
private A[][] observations;
public NonStationaryHMMLattice(TransitionModel transitionModel, StationaryEmissionModel<A> emissionModel, StationaryStateProjector transitionToEmissionState, A[][] observations) {
this.transitionModel = transitionModel;
this.emissionModel = emissionModel;
this.transitionToEmissionState = transitionToEmissionState;
this.observations = observations;
}
public int numSequences() {
return observations.length;
}
public int sequenceLength(int d) {
return observations[d].length;
}
public int numStates(int d, int t) {
return transitionModel.numStates(d, t);
}
public double nodeLogPotential(int d, int t, int ts) {
int es = transitionToEmissionState.project(d, t, ts);
if (t == 0) {
return transitionModel.startLogProb(d, ts) + emissionModel.emissionLogProb(d, t, es);
} else if (t == observations[d].length-1) {
return transitionModel.endLogProb(d, ts) + emissionModel.emissionLogProb(d, t, es);
} else {
return emissionModel.emissionLogProb(d, t, es);
}
}
public double nodePotential(int d, int t, int ts) {
int es = transitionToEmissionState.project(d, t, ts);
if (t == 0) {
return transitionModel.startProb(d, ts) * emissionModel.emissionProb(d, t, es);
} else if (t == observations[d].length-1) {
return transitionModel.endProb(d, ts) * emissionModel.emissionProb(d, t, es);
} else {
return emissionModel.emissionProb(d, t, es);
}
}
public double[] allowedEdgesLogPotentials(int d, int t, int ts, boolean backward) {
if (backward) {
return transitionModel.allowedBackwardTransitionsLogProbs(d, t, ts);
} else {
return transitionModel.allowedForwardTransitionsLogProbs(d, t, ts);
}
}
public double[] allowedEdgesPotentials(int d, int t, int ts, boolean backward) {
if (backward) {
return transitionModel.allowedBackwardTransitionsProbs(d, t, ts);
} else {
return transitionModel.allowedForwardTransitionsProbs(d, t, ts);
}
}
public int[] allowedEdges(int d, int t, int ts, boolean backward) {
if (backward) {
return transitionModel.allowedBackwardTransitions(d, t, ts);
} else {
return transitionModel.allowedForwardTransitions(d, t, ts);
}
}
}
}
| apache-2.0 |
teffy/okhttp | okhttp/src/main/java/okhttp3/ConnectionSpec.java | 12159 | /*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.SSLSocket;
import static okhttp3.internal.Util.concat;
import static okhttp3.internal.Util.contains;
import static okhttp3.internal.Util.immutableList;
import static okhttp3.internal.Util.intersect;
/**
* Specifies configuration for the socket connection that HTTP traffic travels through. For {@code
* https:} URLs, this includes the TLS version and cipher suites to use when negotiating a secure
* connection.
*
* <p>The TLS versions configured in a connection spec are only be used if they are also enabled in
* the SSL socket. For example, if an SSL socket does not have TLS 1.2 enabled, it will not be used
* even if it is present on the connection spec. The same policy also applies to cipher suites.
*
* <p>Use {@link Builder#allEnabledTlsVersions()} and {@link Builder#allEnabledCipherSuites} to
* defer all feature selection to the underlying SSL socket.
*/
public final class ConnectionSpec {
// This is a subset of the cipher suites supported in Chrome 46, current as of 2015-11-05.
// All of these suites are available on Android 5.0; earlier releases support a subset of
// these suites. https://github.com/square/okhttp/issues/330
private static final CipherSuite[] APPROVED_CIPHER_SUITES = new CipherSuite[] {
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
// Note that the following cipher suites are all on HTTP/2's bad cipher suites list. We'll
// continue to include them until better suites are commonly available. For example, none
// of the better cipher suites listed above shipped with Android 4.4 or Java 7.
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA,
CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
};
/** A modern TLS connection with extensions like SNI and ALPN available. */
public static final ConnectionSpec MODERN_TLS = new Builder(true)
.cipherSuites(APPROVED_CIPHER_SUITES)
.tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0)
.supportsTlsExtensions(true)
.build();
/** A backwards-compatible fallback connection for interop with obsolete servers. */
public static final ConnectionSpec COMPATIBLE_TLS = new Builder(MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_0)
.supportsTlsExtensions(true)
.build();
/** Unencrypted, unauthenticated connections for {@code http:} URLs. */
public static final ConnectionSpec CLEARTEXT = new Builder(false).build();
private final boolean tls;
private final boolean supportsTlsExtensions;
private final String[] cipherSuites;
private final String[] tlsVersions;
private ConnectionSpec(Builder builder) {
this.tls = builder.tls;
this.cipherSuites = builder.cipherSuites;
this.tlsVersions = builder.tlsVersions;
this.supportsTlsExtensions = builder.supportsTlsExtensions;
}
public boolean isTls() {
return tls;
}
/**
* Returns the cipher suites to use for a connection. Returns {@code null} if all of the SSL
* socket's enabled cipher suites should be used.
*/
public List<CipherSuite> cipherSuites() {
if (cipherSuites == null) return null;
CipherSuite[] result = new CipherSuite[cipherSuites.length];
for (int i = 0; i < cipherSuites.length; i++) {
result[i] = CipherSuite.forJavaName(cipherSuites[i]);
}
return immutableList(result);
}
/**
* Returns the TLS versions to use when negotiating a connection. Returns {@code null} if all of
* the SSL socket's enabled TLS versions should be used.
*/
public List<TlsVersion> tlsVersions() {
if (tlsVersions == null) return null;
TlsVersion[] result = new TlsVersion[tlsVersions.length];
for (int i = 0; i < tlsVersions.length; i++) {
result[i] = TlsVersion.forJavaName(tlsVersions[i]);
}
return immutableList(result);
}
public boolean supportsTlsExtensions() {
return supportsTlsExtensions;
}
/** Applies this spec to {@code sslSocket}. */
void apply(SSLSocket sslSocket, boolean isFallback) {
ConnectionSpec specToApply = supportedSpec(sslSocket, isFallback);
if (specToApply.tlsVersions != null) {
sslSocket.setEnabledProtocols(specToApply.tlsVersions);
}
if (specToApply.cipherSuites != null) {
sslSocket.setEnabledCipherSuites(specToApply.cipherSuites);
}
}
/**
* Returns a copy of this that omits cipher suites and TLS versions not enabled by {@code
* sslSocket}.
*/
private ConnectionSpec supportedSpec(SSLSocket sslSocket, boolean isFallback) {
String[] cipherSuitesIntersection = cipherSuites != null
? intersect(String.class, cipherSuites, sslSocket.getEnabledCipherSuites())
: sslSocket.getEnabledCipherSuites();
String[] tlsVersionsIntersection = tlsVersions != null
? intersect(String.class, tlsVersions, sslSocket.getEnabledProtocols())
: sslSocket.getEnabledProtocols();
// In accordance with https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00
// the SCSV cipher is added to signal that a protocol fallback has taken place.
if (isFallback && contains(sslSocket.getSupportedCipherSuites(), "TLS_FALLBACK_SCSV")) {
cipherSuitesIntersection = concat(cipherSuitesIntersection, "TLS_FALLBACK_SCSV");
}
return new Builder(this)
.cipherSuites(cipherSuitesIntersection)
.tlsVersions(tlsVersionsIntersection)
.build();
}
/**
* Returns {@code true} if the socket, as currently configured, supports this connection spec.
* In order for a socket to be compatible the enabled cipher suites and protocols must intersect.
*
* <p>For cipher suites, at least one of the {@link #cipherSuites() required cipher suites} must
* match the socket's enabled cipher suites. If there are no required cipher suites the socket
* must have at least one cipher suite enabled.
*
* <p>For protocols, at least one of the {@link #tlsVersions() required protocols} must match the
* socket's enabled protocols.
*/
public boolean isCompatible(SSLSocket socket) {
if (!tls) {
return false;
}
if (tlsVersions != null
&& !nonEmptyIntersection(tlsVersions, socket.getEnabledProtocols())) {
return false;
}
if (cipherSuites != null
&& !nonEmptyIntersection(cipherSuites, socket.getEnabledCipherSuites())) {
return false;
}
return true;
}
/**
* An N*M intersection that terminates if any intersection is found. The sizes of both
* arguments are assumed to be so small, and the likelihood of an intersection so great, that it
* is not worth the CPU cost of sorting or the memory cost of hashing.
*/
private static boolean nonEmptyIntersection(String[] a, String[] b) {
if (a == null || b == null || a.length == 0 || b.length == 0) {
return false;
}
for (String toFind : a) {
if (contains(b, toFind)) {
return true;
}
}
return false;
}
@Override public boolean equals(Object other) {
if (!(other instanceof ConnectionSpec)) return false;
if (other == this) return true;
ConnectionSpec that = (ConnectionSpec) other;
if (this.tls != that.tls) return false;
if (tls) {
if (!Arrays.equals(this.cipherSuites, that.cipherSuites)) return false;
if (!Arrays.equals(this.tlsVersions, that.tlsVersions)) return false;
if (this.supportsTlsExtensions != that.supportsTlsExtensions) return false;
}
return true;
}
@Override public int hashCode() {
int result = 17;
if (tls) {
result = 31 * result + Arrays.hashCode(cipherSuites);
result = 31 * result + Arrays.hashCode(tlsVersions);
result = 31 * result + (supportsTlsExtensions ? 0 : 1);
}
return result;
}
@Override public String toString() {
if (!tls) {
return "ConnectionSpec()";
}
String cipherSuitesString = cipherSuites != null ? cipherSuites().toString() : "[all enabled]";
String tlsVersionsString = tlsVersions != null ? tlsVersions().toString() : "[all enabled]";
return "ConnectionSpec("
+ "cipherSuites=" + cipherSuitesString
+ ", tlsVersions=" + tlsVersionsString
+ ", supportsTlsExtensions=" + supportsTlsExtensions
+ ")";
}
public static final class Builder {
private boolean tls;
private String[] cipherSuites;
private String[] tlsVersions;
private boolean supportsTlsExtensions;
Builder(boolean tls) {
this.tls = tls;
}
public Builder(ConnectionSpec connectionSpec) {
this.tls = connectionSpec.tls;
this.cipherSuites = connectionSpec.cipherSuites;
this.tlsVersions = connectionSpec.tlsVersions;
this.supportsTlsExtensions = connectionSpec.supportsTlsExtensions;
}
public Builder allEnabledCipherSuites() {
if (!tls) throw new IllegalStateException("no cipher suites for cleartext connections");
this.cipherSuites = null;
return this;
}
public Builder cipherSuites(CipherSuite... cipherSuites) {
if (!tls) throw new IllegalStateException("no cipher suites for cleartext connections");
String[] strings = new String[cipherSuites.length];
for (int i = 0; i < cipherSuites.length; i++) {
strings[i] = cipherSuites[i].javaName;
}
return cipherSuites(strings);
}
public Builder cipherSuites(String... cipherSuites) {
if (!tls) throw new IllegalStateException("no cipher suites for cleartext connections");
if (cipherSuites.length == 0) {
throw new IllegalArgumentException("At least one cipher suite is required");
}
this.cipherSuites = cipherSuites.clone(); // Defensive copy.
return this;
}
public Builder allEnabledTlsVersions() {
if (!tls) throw new IllegalStateException("no TLS versions for cleartext connections");
this.tlsVersions = null;
return this;
}
public Builder tlsVersions(TlsVersion... tlsVersions) {
if (!tls) throw new IllegalStateException("no TLS versions for cleartext connections");
String[] strings = new String[tlsVersions.length];
for (int i = 0; i < tlsVersions.length; i++) {
strings[i] = tlsVersions[i].javaName;
}
return tlsVersions(strings);
}
public Builder tlsVersions(String... tlsVersions) {
if (!tls) throw new IllegalStateException("no TLS versions for cleartext connections");
if (tlsVersions.length == 0) {
throw new IllegalArgumentException("At least one TLS version is required");
}
this.tlsVersions = tlsVersions.clone(); // Defensive copy.
return this;
}
public Builder supportsTlsExtensions(boolean supportsTlsExtensions) {
if (!tls) throw new IllegalStateException("no TLS extensions for cleartext connections");
this.supportsTlsExtensions = supportsTlsExtensions;
return this;
}
public ConnectionSpec build() {
return new ConnectionSpec(this);
}
}
}
| apache-2.0 |
querytalk/library | extensions/Extensions_Select.cs | 3299 | #region License
// Copyright (c) Amos Voron. All rights reserved.
// Licensed under the Apache 2.0 License. See LICENSE in the project root for license information.
#endregion
using QueryTalk.Wall;
namespace QueryTalk
{
public static partial class Extensions
{
#region Select
/// <summary>
/// Retrieves rows from the database with all columns from the base tables.
/// </summary>
/// <param name="prev">A predecessor object.</param>
public static SelectChainer Select(this ISelect prev)
{
return new SelectChainer((Chainer)prev, new Column[] { }, false);
}
/// <summary>
/// Retrieves rows from the database with columns from the specified list of columns.
/// </summary>
/// <param name="prev">A predecessor object.</param>
/// <param name="columns">
/// Is a specified list of columns.
/// </param>
public static SelectChainer Select(this ISelect prev, params Column[] columns)
{
return new SelectChainer((Chainer)prev, columns, false);
}
/// <summary>
/// <para>Retrieves the number of rows returned by the query.</para>
/// </summary>
/// <param name="prev">A predecessor object.</param>
public static SelectChainer SelectCount(this ISelect prev)
{
return new SelectChainer((Chainer)prev, new Column[] { Designer.Count().As(Text.Count) }, false);
}
/// <summary>
/// <para>Retrieves rows from the database with all columns from the base tables.</para>
/// </summary>
/// <param name="prev">A predecessor object.</param>
public static SelectChainer SelectDistinct(this ISelect prev)
{
return new SelectChainer((Chainer)prev, new Column[] { }, true);
}
/// <summary>
/// <para>Retrieves unique rows from the database with columns from the specified list of columns.</para>
/// </summary>
/// <param name="prev">A predecessor object.</param>
/// <param name="columns">
/// Is a specified list of columns.
/// </param>
public static SelectChainer SelectDistinct(this ISelect prev, params Column[] columns)
{
return new SelectChainer((Chainer)prev, columns, true);
}
#endregion
#region FromSelect
/// <summary>
/// Retrieves rows from the database with all columns from the specified table.
/// </summary>
/// <param name="prev">A predecessor object.</param>
/// <param name="table">Is a table argument.</param>
public static SelectChainer FromSelect(this IFrom prev, Table table)
{
return new FromChainer((Chainer)prev, table).Select();
}
/// <summary>
/// Retrieves rows from the database with all columns from the specified table.
/// </summary>
/// <param name="prev">A predecessor object.</param>
/// <param name="table">Is a subquery.</param>
public static SelectChainer FromSelect(this IFrom prev, IOpenView table)
{
return new FromChainer((Chainer)prev, table).Select();
}
#endregion
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-glacier/src/main/java/com/amazonaws/services/glacier/model/ServiceUnavailableException.java | 3024 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.glacier.model;
import javax.annotation.Generated;
/**
* <p>
* Returned if the service cannot complete the request.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ServiceUnavailableException extends com.amazonaws.services.glacier.model.AmazonGlacierException {
private static final long serialVersionUID = 1L;
/**
* <p>
* Server
* </p>
*/
private String type;
/**
* <p>
* 500 Internal Server Error
* </p>
*/
private String code;
/**
* Constructs a new ServiceUnavailableException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public ServiceUnavailableException(String message) {
super(message);
}
/**
* <p>
* Server
* </p>
*
* @param type
* Server
*/
@com.fasterxml.jackson.annotation.JsonProperty("type")
public void setType(String type) {
this.type = type;
}
/**
* <p>
* Server
* </p>
*
* @return Server
*/
@com.fasterxml.jackson.annotation.JsonProperty("type")
public String getType() {
return this.type;
}
/**
* <p>
* Server
* </p>
*
* @param type
* Server
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ServiceUnavailableException withType(String type) {
setType(type);
return this;
}
/**
* <p>
* 500 Internal Server Error
* </p>
*
* @param code
* 500 Internal Server Error
*/
@com.fasterxml.jackson.annotation.JsonProperty("code")
public void setCode(String code) {
this.code = code;
}
/**
* <p>
* 500 Internal Server Error
* </p>
*
* @return 500 Internal Server Error
*/
@com.fasterxml.jackson.annotation.JsonProperty("code")
public String getCode() {
return this.code;
}
/**
* <p>
* 500 Internal Server Error
* </p>
*
* @param code
* 500 Internal Server Error
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ServiceUnavailableException withCode(String code) {
setCode(code);
return this;
}
}
| apache-2.0 |
david-romero/tfg-vaadin | appEducacionalVaadin/src/main/java/com/app/ui/user/tutores/view/TutorView.java | 1922 | /**
* LoginView.java
* appEducacionalVaadin
* 29/11/2014 14:05:37
* Copyright David
* com.app.ui
*/
package com.app.ui.user.tutores.view;
import ru.xpoft.vaadin.DiscoveryNavigator;
import com.app.infrastructure.security.Authority;
import com.app.ui.NavigatorUI;
import com.app.ui.user.MenuComponent;
import com.app.ui.user.UserAbstractView;
import com.app.ui.user.calendario.view.CalendarioView;
import com.app.ui.user.panelControl.view.PanelControlView;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.ui.ComponentContainer;
import com.vaadin.ui.CssLayout;
/**
* @author David
*
*/
public class TutorView extends UserAbstractView {
/**
*
*/
private static final long serialVersionUID = -4830300048826230639L;
private DiscoveryNavigator navigator;
public void enter(ViewChangeListener.ViewChangeEvent event) {
generateRol();
super.enter(event);
removeAllComponents();
generateView();
}
/**
* @author David
*/
private void generateView() {
setSizeFull();
addStyleName("mainview");
addComponent(new MenuComponent());
ComponentContainer content = new CssLayout();
content.addStyleName("view-content");
content.setSizeFull();
addComponent(content);
setExpandRatio(content, 1.0f);
this.navigator = new NavigatorUI(getUI(), content);
this.navigator.addView("calendario", CalendarioView.class);
this.navigator.addView("panelControl", PanelControlView.class);
}
/* (non-Javadoc)
* @see com.app.ui.user.UserAbstractView#generateRol()
*/
@Override
public void generateRol() {
this.rol = new Authority();
this.rol.setAuthority(Authority.TUTOR);
}
/* (non-Javadoc)
* @see com.app.ui.user.UserAbstractView#getRol()
*/
@Override
public Authority getRol() {
if (this.rol==null){
generateRol();
return rol;
}else{
return super.getRol();
}
}
}
| apache-2.0 |
open-telemetry/opentelemetry-collector-contrib | receiver/redisreceiver/metric_functions_test.go | 1817 | // Copyright 2020, OpenTelemetry 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 redisreceiver
import (
"reflect"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
"go.opentelemetry.io/collector/component/componenttest"
"go.opentelemetry.io/collector/model/pdata"
"go.uber.org/zap"
"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/redisreceiver/internal/metadata"
)
func TestDataPointRecorders(t *testing.T) {
logger, _ := zap.NewDevelopment()
settings := componenttest.NewNopReceiverCreateSettings()
settings.Logger = logger
rs := &redisScraper{
redisSvc: newRedisSvc(newFakeClient()),
settings: settings,
mb: metadata.NewMetricsBuilder(Config{}.Metrics),
}
metricByRecorder := map[string]string{}
for metric, recorder := range rs.dataPointRecorders() {
switch recorder.(type) {
case func(pdata.Timestamp, int64), func(pdata.Timestamp, float64):
recorderName := runtime.FuncForPC(reflect.ValueOf(recorder).Pointer()).Name()
if m, ok := metricByRecorder[recorderName]; ok {
assert.Failf(t, "shared-recorder", "Metrics %q and %q share the same recorder", metric, m)
}
metricByRecorder[recorderName] = metric
default:
assert.Failf(t, "invalid-recorder", "Metric %q has invalid recorder type", metric)
}
}
}
| apache-2.0 |
wpride/commcare | backend/src/org/commcare/util/SessionFrame.java | 2996 | /**
*
*/
package org.commcare.util;
import java.util.Vector;
/**
* @author ctsims
*
*/
public class SessionFrame {
/** CommCare needs a Command (an entry, view, etc) to proceed. Generally sitting on a menu screen. */
public static final String STATE_COMMAND_ID = "COMMAND_ID";
/** CommCare needs the ID of a Case to proceed **/
public static final String STATE_DATUM_VAL = "CASE_ID";
/** Computed Value **/
public static final String STATE_DATUM_COMPUTED = "COMPTUED_DATUM";
/** CommCare needs the XMLNS of the form to be entered to proceed **/
public static final String STATE_FORM_XMLNS = "FORM_XMLNS";
public static final String ENTITY_NONE = "NONE";
private String frameId;
protected Vector<String[]> steps = new Vector<String[]>();
protected Vector<String[]> snapshot;
/**
* Create a new, un-id'd session frame
*/
public SessionFrame() {
}
public SessionFrame(String frameId) {
this.frameId = frameId;
}
public Vector<String[]> getSteps() {
return steps;
}
public String[] popStep() {
String[] recentPop = null;
if(steps.size() > 0) {
recentPop = steps.elementAt(steps.size() -1);
steps.removeElementAt(steps.size() - 1);
}
return recentPop;
}
public void pushStep(String[] step) {
steps.addElement(step);
}
public String getFrameId() {
return frameId;
}
/**
* Requests that the frame capture an original snapshot of its state.
* This snapshot can be referenced later to compare the eventual state
* of the frame to an earlier point
*/
public void captureSnapshot() {
synchronized(steps) {
snapshot = new Vector<String[]>();
for(String[] s : steps) {
snapshot.addElement(s);
}
}
}
/**
* Determines whether the current frame state is incompatible with
* a previously snapshotted frame state, if one exists. If no snapshot
* exists, this method will return false.
*
* Compatibility is determined by checking that each step in the previous
* snapshot is matched by an identical step in the current snapshot.
*
* @return
*/
public boolean isSnapshotIncompatible() {
synchronized(steps) {
//No snapshot, can't be incompatible.
if(snapshot == null) { return false; }
if(snapshot.size() > steps.size()) { return true; }
//Go through each step in the snapshot
for(int i = 0 ; i < snapshot.size() ; ++i ) {
String[] snapStep = snapshot.elementAt(i);
String[] curStep = steps.elementAt(i);
//Make sure they're the same length, otherwise they can't be equal
if(snapStep.length != curStep.length) { return true; }
//Make sure it's the same step, otherwise the snapshot is incompatible
for(int j = 0 ; j < snapStep.length ; ++j) {
if(!snapStep[j].equals(curStep[j])) { return true; }
}
}
//Id we didn't find anything wrong, we're good to go!
return false;
}
}
public void clearSnapshot() {
synchronized(steps) {
this.snapshot = null;
}
}
}
| apache-2.0 |
gamerson/bnd | biz.aQute.bndlib/src/aQute/bnd/maven/package-info.java | 100 | /**
*/
@Version("1.10.0")
package aQute.bnd.maven;
import org.osgi.annotation.versioning.Version;
| apache-2.0 |
CE-KMITL-CLOUD-2014/Automatic-CMS-Installation | dns/templates_c/96642fa89977ab56fbdfc6496ab4dd78e18d788c.file.pages.tpl.php | 4329 | <?php /* Smarty version Smarty-3.1.18, created on 2014-10-04 13:54:53
compiled from "../templates/pages.tpl" */ ?>
<?php /*%%SmartyHeaderCode:1599438714542ffc2d7141b9-38499056%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'96642fa89977ab56fbdfc6496ab4dd78e18d788c' =>
array (
0 => '../templates/pages.tpl',
1 => 1168782220,
2 => 'file',
),
),
'nocache_hash' => '1599438714542ffc2d7141b9-38499056',
'function' =>
array (
),
'variables' =>
array (
'pages' => 0,
'current_page' => 0,
'page' => 0,
'page_root' => 0,
),
'has_nocache_code' => false,
'version' => 'Smarty-3.1.18',
'unifunc' => 'content_542ffc2d7b2459_03811119',
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_542ffc2d7b2459_03811119')) {function content_542ffc2d7b2459_03811119($_smarty_tpl) {?><?php if (!is_callable('smarty_function_math')) include '/usr/share/smarty/plugins/function.math.php';
?><?php if ($_smarty_tpl->tpl_vars['pages']->value) {?><center><font size="-1" face="Arial,Helvetica"><?php }?>
<?php $_smarty_tpl->tpl_vars['page'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['page']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['pages']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
$_smarty_tpl->tpl_vars['page']->total= $_smarty_tpl->_count($_from);
$_smarty_tpl->tpl_vars['page']->iteration=0;
$_smarty_tpl->tpl_vars['page']->index=-1;
foreach ($_from as $_smarty_tpl->tpl_vars['page']->key => $_smarty_tpl->tpl_vars['page']->value) {
$_smarty_tpl->tpl_vars['page']->_loop = true;
$_smarty_tpl->tpl_vars['page']->iteration++;
$_smarty_tpl->tpl_vars['page']->index++;
$_smarty_tpl->tpl_vars['page']->first = $_smarty_tpl->tpl_vars['page']->index === 0;
$_smarty_tpl->tpl_vars['page']->last = $_smarty_tpl->tpl_vars['page']->iteration === $_smarty_tpl->tpl_vars['page']->total;
$_smarty_tpl->tpl_vars['smarty']->value['foreach']['pages']['first'] = $_smarty_tpl->tpl_vars['page']->first;
$_smarty_tpl->tpl_vars['smarty']->value['foreach']['pages']['last'] = $_smarty_tpl->tpl_vars['page']->last;
?>
<?php if ($_smarty_tpl->getVariable('smarty')->value['foreach']['pages']['first']) {?>
<?php if ($_smarty_tpl->tpl_vars['current_page']->value==$_smarty_tpl->tpl_vars['page']->value) {?>
<<First <Previous
<?php } else { ?>
<a class="class" href="<?php echo $_smarty_tpl->tpl_vars['page_root']->value;?>
page=<?php echo $_smarty_tpl->tpl_vars['page']->value;?>
"><<First</a>
<a class="class" href="<?php echo $_smarty_tpl->tpl_vars['page_root']->value;?>
page=<?php echo smarty_function_math(array('equation'=>((string)$_smarty_tpl->tpl_vars['current_page']->value)." - 1"),$_smarty_tpl);?>
"><Previous</a>
<?php }?>
<?php }?>
<?php if ($_smarty_tpl->tpl_vars['current_page']->value==$_smarty_tpl->tpl_vars['page']->value) {?>
<?php echo $_smarty_tpl->tpl_vars['page']->value;?>
<?php } else { ?>
<a class="class" href="<?php echo $_smarty_tpl->tpl_vars['page_root']->value;?>
page=<?php echo $_smarty_tpl->tpl_vars['page']->value;?>
"><?php echo $_smarty_tpl->tpl_vars['page']->value;?>
</a>
<?php }?>
<?php if ($_smarty_tpl->getVariable('smarty')->value['foreach']['pages']['last']) {?>
<?php if ($_smarty_tpl->tpl_vars['current_page']->value==$_smarty_tpl->tpl_vars['page']->value) {?>
Next> Last>>
<?php } else { ?>
<a class="class" href="<?php echo $_smarty_tpl->tpl_vars['page_root']->value;?>
page=<?php echo smarty_function_math(array('equation'=>((string)$_smarty_tpl->tpl_vars['current_page']->value)." + 1"),$_smarty_tpl);?>
">Next></a>
<a class="class" href="<?php echo $_smarty_tpl->tpl_vars['page_root']->value;?>
page=<?php echo $_smarty_tpl->tpl_vars['page']->value;?>
">Last>></a>
<?php }?>
<?php }?>
<?php } ?>
<?php if ($_smarty_tpl->tpl_vars['pages']->value) {?></font></center><?php }?>
<?php }} ?>
| apache-2.0 |