code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// // Copyright 2019 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. // #include "zetasql/public/input_argument_type.h" #include <algorithm> #include <memory> #include "zetasql/base/testing/status_matchers.h" #include "zetasql/public/type.h" #include "zetasql/testdata/test_schema.pb.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/cord.h" #include "absl/strings/str_join.h" namespace zetasql { static std::string ArgumentDebugStrings( const std::vector<InputArgumentType>& arguments) { std::vector<std::string> argument_strings; for (const InputArgumentType& argument : arguments) { argument_strings.push_back(argument.DebugString(true /* verbose */)); } return absl::StrJoin(argument_strings, ", "); } static void TestExpectedArgumentTypeLessPair(const InputArgumentType& type1, const InputArgumentType& type2) { const std::vector<InputArgumentType> expected_arguments = {type1, type2}; std::vector<InputArgumentType> arguments = {type1, type2}; std::sort(arguments.begin(), arguments.end(), InputArgumentTypeLess()); EXPECT_EQ(expected_arguments, arguments) << "expected: " << ArgumentDebugStrings(expected_arguments) << "\nactual: " << ArgumentDebugStrings(arguments); arguments = {type2, type1}; std::sort(arguments.begin(), arguments.end(), InputArgumentTypeLess()); EXPECT_EQ(expected_arguments, arguments) << "expected: " << ArgumentDebugStrings(expected_arguments) << "\nactual: " << ArgumentDebugStrings(arguments); } TEST(InputArgumentTypeTests, TestInputArgumentTypeLess) { Value null_int64_value = Value::NullInt64(); Value null_bool_value = Value::NullBool(); Value literal_int64_value_1 = Value::Int64(1); Value literal_int64_value_2 = Value::Int64(2); Value literal_bool_value = Value::Bool(true); InputArgumentType untyped_null; InputArgumentType null_int64(null_int64_value); InputArgumentType literal_int64_1(literal_int64_value_1); InputArgumentType literal_int64_2(literal_int64_value_2); InputArgumentType parameter_int64( types::Int64Type(), true /* is_parameter */); InputArgumentType non_literal_int64(types::Int64Type()); InputArgumentType literal_bool(literal_bool_value); // Different type kinds order the same regardless of non-literal, literal, // null, etc. TestExpectedArgumentTypeLessPair(non_literal_int64, literal_bool); TestExpectedArgumentTypeLessPair(parameter_int64, literal_bool); TestExpectedArgumentTypeLessPair(literal_int64_1, literal_bool); TestExpectedArgumentTypeLessPair(null_int64, literal_bool); TestExpectedArgumentTypeLessPair(untyped_null, literal_bool); // For a single type kind, non-literals order before literals and nulls. TestExpectedArgumentTypeLessPair(non_literal_int64, literal_int64_1); TestExpectedArgumentTypeLessPair(parameter_int64, literal_int64_1); TestExpectedArgumentTypeLessPair(non_literal_int64, null_int64); TestExpectedArgumentTypeLessPair(parameter_int64, null_int64); TestExpectedArgumentTypeLessPair(non_literal_int64, untyped_null); TestExpectedArgumentTypeLessPair(parameter_int64, untyped_null); // Literals before nulls. TestExpectedArgumentTypeLessPair(literal_int64_1, null_int64); TestExpectedArgumentTypeLessPair(literal_int64_1, untyped_null); // Non-literals order together (both parameters and non-parameters). // Neither is less than the other. EXPECT_FALSE( InputArgumentTypeLess()(parameter_int64, non_literal_int64)); EXPECT_FALSE( InputArgumentTypeLess()(non_literal_int64, parameter_int64)); // Literals with different values order together. EXPECT_FALSE( InputArgumentTypeLess()(literal_int64_1, literal_int64_2)); EXPECT_FALSE( InputArgumentTypeLess()(literal_int64_2, literal_int64_1)); // Nulls order together (both typed and untyped). EXPECT_FALSE( InputArgumentTypeLess()(null_int64, untyped_null)); EXPECT_FALSE( InputArgumentTypeLess()(untyped_null, null_int64)); // InputArgumentTypes are not less than themselves. EXPECT_FALSE( InputArgumentTypeLess()(non_literal_int64, non_literal_int64)); EXPECT_FALSE( InputArgumentTypeLess()(parameter_int64, parameter_int64)); EXPECT_FALSE( InputArgumentTypeLess()(literal_int64_1, literal_int64_1)); EXPECT_FALSE( InputArgumentTypeLess()(null_int64, null_int64)); EXPECT_FALSE( InputArgumentTypeLess()(untyped_null, untyped_null)); // Two complex types with the same kind and in the same equivalence // class sort via DebugString(). TypeFactory type_factory; const EnumType* enum_type; ZETASQL_ASSERT_OK(type_factory.MakeEnumType( zetasql_test__::TestEnum_descriptor(), &enum_type)); const Value enum_value(values::Enum(enum_type, 1)); const EnumType* another_enum_type; ZETASQL_ASSERT_OK(type_factory.MakeEnumType( zetasql_test__::AnotherTestEnum_descriptor(), &another_enum_type)); const Value another_enum_value(values::Enum(another_enum_type, 1)); TestExpectedArgumentTypeLessPair(InputArgumentType(enum_type), InputArgumentType(enum_value)); TestExpectedArgumentTypeLessPair(InputArgumentType(another_enum_type), InputArgumentType(enum_type)); TestExpectedArgumentTypeLessPair(InputArgumentType(another_enum_value), InputArgumentType(enum_value)); const StructType* struct_type; ZETASQL_ASSERT_OK(type_factory.MakeStructType( {{"a", type_factory.get_string()}, {"b", type_factory.get_int32()}}, &struct_type)); const Value struct_value( values::Struct(struct_type, {values::String("x"), values::Int32(1)})); const StructType* another_struct_type; ZETASQL_ASSERT_OK(type_factory.MakeStructType( {{"c", type_factory.get_int32()}, {"d", type_factory.get_string()}}, &another_struct_type)); const Value another_struct_value( values::Struct(another_struct_type, {values::Int32(1), values::String("x")})); TestExpectedArgumentTypeLessPair(InputArgumentType(struct_type), InputArgumentType(struct_value)); TestExpectedArgumentTypeLessPair(InputArgumentType(struct_type), InputArgumentType(another_struct_type)); TestExpectedArgumentTypeLessPair(InputArgumentType(struct_value), InputArgumentType(another_struct_value)); const ArrayType* array_type; ZETASQL_ASSERT_OK(type_factory.MakeArrayType(type_factory.get_int64(), &array_type)); const Value array_value(values::Array(array_type, {values::Int64(1)})); const ArrayType* another_array_type; ZETASQL_ASSERT_OK(type_factory.MakeArrayType(type_factory.get_int32(), &another_array_type)); const Value another_array_value(values::Array(another_array_type, {values::Int32(1)})); TestExpectedArgumentTypeLessPair(InputArgumentType(array_type), InputArgumentType(array_value)); TestExpectedArgumentTypeLessPair(InputArgumentType(another_array_type), InputArgumentType(array_type)); TestExpectedArgumentTypeLessPair(InputArgumentType(another_array_value), InputArgumentType(array_value)); const ProtoType* proto_type; ZETASQL_ASSERT_OK( type_factory.MakeProtoType(zetasql_test__::KitchenSinkPB::descriptor(), &proto_type)); const Value proto_value(values::Proto(proto_type, absl::Cord("a"))); const ProtoType* another_proto_type; ZETASQL_ASSERT_OK( type_factory.MakeProtoType(zetasql_test__::TestExtraPB::descriptor(), &another_proto_type)); const Value another_proto_value( values::Proto(another_proto_type, absl::Cord("a"))); TestExpectedArgumentTypeLessPair(InputArgumentType(proto_type), InputArgumentType(proto_value)); TestExpectedArgumentTypeLessPair(InputArgumentType(proto_type), InputArgumentType(another_proto_type)); TestExpectedArgumentTypeLessPair(InputArgumentType(proto_value), InputArgumentType(another_proto_value)); } TEST(InputArgumentTypeTest, TypeNameAndDebugString) { TypeFactory type_factory; const Value int64_value = values::Int64(5); const zetasql::StructType* struct_type = nullptr; ZETASQL_ASSERT_OK(type_factory.MakeStructType({{"x", types::Int64Type()}, {"y", types::StringType()}, {"z", types::DoubleType()}}, &struct_type)); struct TypeAndOutputs { InputArgumentType argument_type; std::string expected_external_type_name; std::string expected_debug_string; }; const std::vector<TypeAndOutputs> test_cases = { {InputArgumentType::UntypedNull(), "NULL", "NULL"}, {InputArgumentType(int64_value), "INT64", "literal INT64"}, {InputArgumentType(types::DoubleType()), "FLOAT64", "DOUBLE"}, {InputArgumentType(types::DoubleType(), true /* is_query_parameter */), "FLOAT64", "DOUBLE"}, {InputArgumentType::LambdaInputArgumentType(), "LAMBDA", "LAMBDA"}, }; for (const auto& test_case : test_cases) { const InputArgumentType& argument_type = test_case.argument_type; SCOPED_TRACE(argument_type.DebugString()); EXPECT_EQ(test_case.expected_external_type_name, argument_type.UserFacingName(PRODUCT_EXTERNAL)); EXPECT_EQ(test_case.expected_debug_string, argument_type.DebugString()); } } TEST(InputArgumentTypeTest, LambdaIsLambda) { EXPECT_TRUE(InputArgumentType::LambdaInputArgumentType().is_lambda()); } TEST(InputArgumentTypeTest, LongArgumentsString) { TypeFactory type_factory; const zetasql::StructType* struct_type = nullptr; ZETASQL_ASSERT_OK(type_factory.MakeStructType({{"x", types::Int64Type()}, {"y", types::StringType()}, {"z", types::DoubleType()}}, &struct_type)); std::vector<InputArgumentType> argument_types; for (int i = 0; i < 500; ++i) { argument_types.push_back(InputArgumentType(struct_type)); } const std::string argument_type_string = InputArgumentType::ArgumentsToString(argument_types); EXPECT_LT(argument_type_string.size(), argument_types.size() * 10); EXPECT_THAT(argument_type_string, testing::EndsWith("...")); } } // namespace zetasql
google/zetasql
zetasql/public/input_argument_type_test.cc
C++
apache-2.0
11,262
# # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from .horovod_ray_runner import HorovodRayRunner
intel-analytics/analytics-zoo
pyzoo/zoo/orca/learn/horovod/__init__.py
Python
apache-2.0
640
package com.xtrordinary.phantomspace; import com.badlogic.gdx.graphics.Texture; public class Player { int X; int Y; int Speed,SpeedMultiplier; Texture texture; Texture animatedTextures[] = new Texture[5]; int numberOfTextures; int CurrentWalk = 1; int DrawableTexture; public int WALK_1 = 1,WALK_2=2,WALK_3=3,JUMP_1=4; public void nullSpeed() { this.Speed = 0; } public void addSpeed(int speed) { if (this.Speed < 0) this.Speed = 0; this.Speed += speed; this.SpeedMultiplier = 0; } public void setX(int x) { X = x; } public void setY(int y) { Y = y; } public void addTexture(Texture texture,int x) { this.animatedTextures[x] = texture; if (numberOfTextures < 5){ numberOfTextures ++; } } public void setDrawableTexture(int texture){ //this.texture = animatedTextures[texture]; this.DrawableTexture = texture; CurrentWalk = texture; } public int getWidth() { return animatedTextures[DrawableTexture].getWidth(); } public int getHeight() { return animatedTextures[DrawableTexture].getHeight(); } public void nextWalkAnimation() { this.CurrentWalk++; if (this.CurrentWalk > 2) this.CurrentWalk = 1; } }
Junkmen/PhantomSpace
core/src/com/xtrordinary/phantomspace/Player.java
Java
apache-2.0
1,169
import pika auth = 'bunny:bunny' mq_credentials = pika.credentials.PlainCredentials(*auth.split(':')) params = pika.ConnectionParameters( host='bunny-vayu.sbgenomics.com', credentials=mq_credentials, virtual_host='bunny') fp = open('sample/app.json', 'r') sample_json = fp.read() connection = pika.BlockingConnection(params) channel = connection.channel() channel.exchange_declare(exchange='backend_exchange_d1abee3f-af71-4f5f-bd00-942ea4a50036', type='direct') channel.basic_publish(exchange='backend_exchange_d1abee3f-af71-4f5f-bd00-942ea4a50036', routing_key='receive_routing_key', body=sample_json) connection.close() print 'no errors, sent'
rabix/bunny
rabix-integration-testing/backends/mock_backend/mq_send.py
Python
apache-2.0
700
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.config.provision; import com.yahoo.cloud.config.ApplicationIdConfig; /** * A complete, immutable identification of an application instance. * * @author Ulf Lilleengen * @author vegard * @author bratseth */ public final class ApplicationId implements Comparable<ApplicationId> { private final TenantName tenant; private final ApplicationName application; private final InstanceName instance; private final String stringValue; private final String serializedForm; public ApplicationId(ApplicationIdConfig config) { this(TenantName.from(config.tenant()), ApplicationName.from(config.application()), InstanceName.from(config.instance())); } private ApplicationId(TenantName tenant, ApplicationName applicationName, InstanceName instanceName) { this.tenant = tenant; this.application = applicationName; this.instance = instanceName; this.stringValue = toStringValue(); this.serializedForm = toSerializedForm(); } public static ApplicationId from(TenantName tenant, ApplicationName application, InstanceName instance) { return new ApplicationId(tenant, application, instance); } public static ApplicationId from(String tenant, String application, String instance) { return new ApplicationId(TenantName.from(tenant), ApplicationName.from(application), InstanceName.from(instance)); } public static ApplicationId fromSerializedForm(String idString) { String[] parts = idString.split(":"); if (parts.length < 3) throw new IllegalArgumentException("Application ids must be on the form tenant:application:instance, but was " + idString); return new Builder().tenant(parts[0]).applicationName(parts[1]).instanceName(parts[2]).build(); } public static ApplicationId fromFullString(String idString) { String[] parts = idString.split("\\."); if (parts.length < 3) throw new IllegalArgumentException("Application ids must be on the form tenant.application.instance, but was " + idString); return new Builder().tenant(parts[0]).applicationName(parts[1]).instanceName(parts[2]).build(); } @Override public int hashCode() { return stringValue.hashCode(); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; ApplicationId rhs = (ApplicationId) other; return tenant.equals(rhs.tenant) && application.equals(rhs.application) && instance.equals(rhs.instance); } /** Returns a serialized form of the content of this: tenant:application:instance */ public String serializedForm() { return serializedForm; } private String toStringValue() { return "tenant '" + tenant + "', application '" + application + "', instance '" + instance + "'"; } /** Returns "dotted" string (tenant.application.instance) with instance name omitted if it is "default" */ public String toShortString() { return tenant().value() + "." + application().value() + ( instance().isDefault() ? "" : "." + instance().value() ); } /** Returns "dotted" string (tenant.application.instance) with instance name always included */ public String toFullString() { return tenant().value() + "." + application().value() + "." + instance().value(); } private String toSerializedForm() { return tenant + ":" + application + ":" + instance; } @Override public String toString() { return toShortString(); } public TenantName tenant() { return tenant; } public ApplicationName application() { return application; } public InstanceName instance() { return instance; } @Override public int compareTo(ApplicationId other) { int diff; diff = tenant.compareTo(other.tenant); if (diff != 0) { return diff; } diff = application.compareTo(other.application); if (diff != 0) { return diff; } diff = instance.compareTo(other.instance); if (diff != 0) { return diff; } return 0; } /** Returns an application id where all fields are "default" */ public static ApplicationId defaultId() { return new ApplicationId(TenantName.defaultName(), ApplicationName.defaultName(), InstanceName.defaultName()); } /** Returns an application id where all fields are "*" */ public static ApplicationId global() { return new Builder().tenant("*") .applicationName("*") .instanceName("*") .build(); } public static class Builder { private TenantName tenant; private ApplicationName application; private InstanceName instance; public Builder() { this.tenant = TenantName.defaultName(); this.application = null; this.instance = InstanceName.defaultName(); } public Builder tenant(TenantName ten) { this.tenant = ten; return this; } public Builder tenant(String ten) { return tenant(TenantName.from(ten)); } public Builder applicationName(ApplicationName nam) { this.application = nam; return this; } public Builder applicationName(String nam) { return applicationName(ApplicationName.from(nam)); } public Builder instanceName(InstanceName ins) { this.instance = ins; return this; } public Builder instanceName(String ins) { return instanceName(InstanceName.from(ins)); } public ApplicationId build() { if (application == null) { throw new IllegalArgumentException("must set application name in builder"); } return ApplicationId.from(tenant, application, instance); } } }
vespa-engine/vespa
config-provisioning/src/main/java/com/yahoo/config/provision/ApplicationId.java
Java
apache-2.0
6,033
package mb.nabl2.relations.terms; import static mb.nabl2.terms.matching.TermMatch.M; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Optional; import org.metaborg.util.functions.PartialFunction1; import org.metaborg.util.tuple.Tuple2; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import mb.nabl2.terms.ITerm; import mb.nabl2.terms.matching.Pattern; import mb.nabl2.terms.matching.TermMatch.IMatcher; import mb.nabl2.terms.matching.TermPattern; import mb.nabl2.terms.substitution.ISubstitution; public class FunctionTerms { public static IMatcher<Map<String, PartialFunction1<ITerm, ITerm>>> functions() { return M.listElems(function(), (l, funDefs) -> { ImmutableMap.Builder<String, PartialFunction1<ITerm, ITerm>> functions = ImmutableMap.builder(); for(Tuple2<String, Eval> funDef : funDefs) { functions.put(funDef._1(), funDef._2()); } return functions.build(); }); } private static IMatcher<Tuple2<String, Eval>> function() { return M.tuple2(NamedFunction.matcher(), M.listElems(functionCase()), (t, name, cases) -> { return Tuple2.of(name.getName(), new Eval(cases)); }); } private static IMatcher<Tuple2<Pattern, ITerm>> functionCase() { return M.tuple2(M.term(), M.term(), (t, pattern, term) -> { if(!pattern.getVars().containsAll(term.getVars())) { throw new IllegalStateException("Function case is not closed."); } return Tuple2.of(TermPattern.P.fromTerm(pattern), term); }); } public static class Eval implements PartialFunction1<ITerm, ITerm>, Serializable { private static final long serialVersionUID = 42L; private final List<Tuple2<Pattern, ITerm>> cases; private Eval(List<Tuple2<Pattern, ITerm>> cases) { this.cases = ImmutableList.copyOf(cases); } @Override public Optional<ITerm> apply(ITerm term) { if(!term.isGround()) { throw new IllegalStateException("Term argument must be ground."); } for(Tuple2<Pattern, ITerm> c : cases) { final Pattern pattern = c._1(); final ISubstitution.Immutable matchResult; if((matchResult = pattern.match(term).orElse(null)) != null) { final ITerm result = matchResult.apply(c._2()); return Optional.of(result); } } return Optional.empty(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + cases.hashCode(); return result; } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(getClass() != obj.getClass()) return false; final Eval other = (Eval) obj; if(!cases.equals(other.cases)) return false; return true; } } }
metaborg/nabl
nabl2.solver/src/main/java/mb/nabl2/relations/terms/FunctionTerms.java
Java
apache-2.0
3,247
package org.commcare.graph.view; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import android.webkit.JavascriptInterface; import java.util.TimerTask; /** * Created by jenniferschweers on 5/20/16. * * Interface between Android's GraphView and the JavaScript graphing code. * Its responsibility is to hide a spinner that displays while the graph loads. */ public class GraphLoader extends TimerTask { private final AppCompatActivity activity; private final View spinner; public GraphLoader(AppCompatActivity a, View v) { activity = a; spinner = v; } @JavascriptInterface @Override public void run() { activity.runOnUiThread(() -> spinner.setVisibility(View.GONE)); } }
dimagi/commcare-android
app/src/org/commcare/graph/view/GraphLoader.java
Java
apache-2.0
762
package pl.jalokim.propertiestojson.resolvers.primitives.delegator; import static pl.jalokim.utils.reflection.InvokableReflectionUtils.setValueForField; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; import java.util.Optional; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver; import pl.jalokim.propertiestojson.resolvers.primitives.PrimitiveJsonTypeResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.AbstractObjectToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToConcreteObjectResolver; @SuppressWarnings("unchecked") @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { private final TextToConcreteObjectResolver toObjectResolver; private final AbstractObjectToJsonTypeConverter toJsonResolver; @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, AbstractObjectToJsonTypeConverter toJsonResolver) { this.toObjectResolver = toObjectResolver; this.toJsonResolver = toJsonResolver; setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); } @Override public Class<?> resolveTypeOfResolver() { if (toJsonResolver != null) { return toJsonResolver.resolveTypeOfResolver(); } return null; } @Override public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, T convertedValue, String propertyKey) { Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, convertedValue, propertyKey); return optional.get(); } @Override protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, propertyValue, propertyKey); return optionalObject.map(o -> (T) o); } @Override public List<Class<?>> getClassesWhichCanResolve() { return toJsonResolver.getClassesWhichCanResolve(); } }
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java
Java
apache-2.0
2,516
//This module creates a window to show all the pictures in a gallery Ti.include('helper.js'); var Gallery = (function(){ function Gallery(a_navigation_group){ this.gallery_path = Ti.Filesystem.applicationDataDirectory + "/Gallery/"; this.nav_group = a_navigation_group; this.colons_num = 0; this.rows_num = 0; this.gallery_window = Ti.UI.createWindow({ title:'Gallery' }); this.gallery_view = Ti.UI.createView({ layout:'vertical', height:Ti.UI.FILL, width:Ti.UI.FILL }); if (isAndroid()) { this.gallery_window.addEventListener('open', eventHandler = function(e){ var the_window = e.source; var action_bar = the_window.getActivity().getActionBar(); if (action_bar) { action_bar.setDisplayHomeAsUp(true); action_bar.onHomeIconItemSelected = function(){ the_window.close(); the_window.removeEventListener('open', eventHandler); Gallery.prototype.dealloc(); the_window = null; action_bar = null; } } }); } this.gallery_window.add(this.gallery_view); //this.gallery_window.open(); } Gallery.prototype.getWindow = function(){ return this.gallery_window; }; Gallery.prototype.buildGallery = function(){ var dir = Ti.Filesystem.getFile(this.gallery_path); var pictures = dir.getDirectoryListing(); var pic_num = pictures.length; var image_container; var file; var vertical_view, horizontal_view; var row = []; horizontal_view = Ti.UI.createScrollView({ width:Ti.UI.FILL, height:'100', layout:'horizontal' }); this.rows_num = 1; for (var i = 0; i < pic_num; i++) { if ((i%3) != 0) { file = Ti.Filesystem.getFile(this.gallery_path + pictures[i]); image_container = Ti.UI.createImageView({ height:'100', width:'100', image:file.nativePath }); horizontal_view.add(image_container); this.colons_num++; } else if (i == 0) { file = Ti.Filesystem.getFile(this.gallery_path + pictures[i]); Ti.API.info('Entro qui! ' + pictures[i]); image_container = Ti.UI.createImageView({ height:'100', width:'100', image:file.nativePath }); horizontal_view.add(image_container); this.colons_num++; } else { //va aggiunta quella in posizione i per il quale i%3 == 0 //this.gallery_view.add(vertical_view); row.push(horizontal_view); horizontal_view = Ti.UI.createScrollView({ width:Ti.UI.FILL, height:'100', layout:'horizontal' }); file = Ti.Filesystem.getFile(this.gallery_path + pictures[i]); Ti.API.info('Entro qui! ' + pictures[i]); image_container = Ti.UI.createImageView({ height:'100', width:'100', image:file.nativePath }); horizontal_view.add(image_container); this.rows_num++; } } for (var i = 0; i < row.length; i++) { this.gallery_view.add(row[i]); } //this.gallery_view.add(horizontal_view); Ti.API.info('Allah! ' + horizontal_view.children + " window: " + this.gallery_window); //this.gallery_window.add(this.gallery_view); Ti.API.info('mah: ' + this.gallery_window.children); }; Gallery.prototype.dealloc = function(){ this.gallery_path = null; this.nav_group = null; }; return Gallery; })(); module.exports = Gallery;
AlessandroSangiuliano/myDiary
Resources/gallery.js
JavaScript
apache-2.0
3,581
/* * Copyright 2018-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ package example.springdata.cassandra.events; import org.springframework.data.cassandra.core.mapping.PrimaryKey; import org.springframework.data.cassandra.core.mapping.Table; /** * Sample user class. * * @author Mark Paluch */ @Table(value = "users") public record User(@PrimaryKey long id, String firstname, String lastname) { }
spring-projects/spring-data-examples
cassandra/example/src/main/java/example/springdata/cassandra/events/User.java
Java
apache-2.0
958
/** * */ package org.vocefiscal.models; import java.io.Serializable; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * @author andre * */ @JsonIgnoreProperties(ignoreUnknown=true) @JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY) public class Fiscalizacao implements Serializable { private static final long serialVersionUID = 2048054520603455140L; @JsonIgnore private Long idFiscalizacao; private String municipio; private String estado; private String zonaEleitoral; private String localDaVotacao; private String secaoEleitoral; @JsonIgnore private Integer podeEnviarRedeDados; @JsonIgnore private Integer statusDoEnvio; private Long data; private String email; @JsonIgnore private ArrayList<String> picturePathList; @JsonIgnore private ArrayList<String> picture30PCPathList; private ArrayList<String> pictureURLList; /** * @return the municipio */ public String getMunicipio() { return municipio; } /** * @param municipio the municipio to set */ public void setMunicipio(String municipio) { this.municipio = municipio; } /** * @return the estado */ public String getEstado() { return estado; } /** * @param estado the estado to set */ public void setEstado(String estado) { this.estado = estado; } /** * @return the zonaEleitoral */ public String getZonaEleitoral() { return zonaEleitoral; } /** * @param zonaEleitoral the zonaEleitoral to set */ public void setZonaEleitoral(String zonaEleitoral) { this.zonaEleitoral = zonaEleitoral; } /** * @return the localDaVotacao */ public String getLocalDaVotacao() { return localDaVotacao; } /** * @param localDaVotacao the localDaVotacao to set */ public void setLocalDaVotacao(String localDaVotacao) { this.localDaVotacao = localDaVotacao; } /** * @return the secaoEleitoral */ public String getSecaoEleitoral() { return secaoEleitoral; } /** * @param secaoEleitoral the secaoEleitoral to set */ public void setSecaoEleitoral(String secaoEleitoral) { this.secaoEleitoral = secaoEleitoral; } /** * @return the statusDoEnvio */ public Integer getStatusDoEnvio() { return statusDoEnvio; } /** * @param statusDoEnvio the statusDoEnvio to set */ public void setStatusDoEnvio(Integer statusDoEnvio) { this.statusDoEnvio = statusDoEnvio; } /** * @return the picturePathList */ public ArrayList<String> getPicturePathList() { return picturePathList; } /** * @param picturePathList the picturePathList to set */ public void setPicturePathList(ArrayList<String> picturePathList) { this.picturePathList = picturePathList; } /** * @return the picture30PCPathList */ public ArrayList<String> getPicture30PCPathList() { return picture30PCPathList; } /** * @param picture30pcPathList the picture30PCPathList to set */ public void setPicture30PCPathList(ArrayList<String> picture30pcPathList) { picture30PCPathList = picture30pcPathList; } /** * @return the pictureURLList */ public ArrayList<String> getPictureURLList() { return pictureURLList; } /** * @param pictureURLList the pictureURLList to set */ public void setPictureURLList(ArrayList<String> pictureURLList) { this.pictureURLList = pictureURLList; } /** * @return the podeEnviarRedeDados */ public Integer getPodeEnviarRedeDados() { return podeEnviarRedeDados; } /** * @param podeEnviarRedeDados the podeEnviarRedeDados to set */ public void setPodeEnviarRedeDados(Integer podeEnviarRedeDados) { this.podeEnviarRedeDados = podeEnviarRedeDados; } /** * @return the idFiscalizacao */ public Long getIdFiscalizacao() { return idFiscalizacao; } /** * @param idFiscalizacao the idFiscalizacao to set */ public void setIdFiscalizacao(Long idFiscalizacao) { this.idFiscalizacao = idFiscalizacao; } /** * @return the data */ public Long getData() { return data; } /** * @param data the data to set */ public void setData(Long data) { this.data = data; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((data == null) ? 0 : data.hashCode()); result = prime * result + ((estado == null) ? 0 : estado.hashCode()); result = prime * result + ((idFiscalizacao == null) ? 0 : idFiscalizacao.hashCode()); result = prime * result + ((localDaVotacao == null) ? 0 : localDaVotacao.hashCode()); result = prime * result + ((municipio == null) ? 0 : municipio.hashCode()); result = prime * result + ((picture30PCPathList == null) ? 0 : picture30PCPathList .hashCode()); result = prime * result + ((picturePathList == null) ? 0 : picturePathList.hashCode()); result = prime * result + ((pictureURLList == null) ? 0 : pictureURLList.hashCode()); result = prime * result + ((podeEnviarRedeDados == null) ? 0 : podeEnviarRedeDados .hashCode()); result = prime * result + ((secaoEleitoral == null) ? 0 : secaoEleitoral.hashCode()); result = prime * result + ((statusDoEnvio == null) ? 0 : statusDoEnvio.hashCode()); result = prime * result + ((zonaEleitoral == null) ? 0 : zonaEleitoral.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Fiscalizacao other = (Fiscalizacao) obj; if (data == null) { if (other.data != null) return false; } else if (!data.equals(other.data)) return false; if (estado == null) { if (other.estado != null) return false; } else if (!estado.equals(other.estado)) return false; if (idFiscalizacao == null) { if (other.idFiscalizacao != null) return false; } else if (!idFiscalizacao.equals(other.idFiscalizacao)) return false; if (localDaVotacao == null) { if (other.localDaVotacao != null) return false; } else if (!localDaVotacao.equals(other.localDaVotacao)) return false; if (municipio == null) { if (other.municipio != null) return false; } else if (!municipio.equals(other.municipio)) return false; if (picture30PCPathList == null) { if (other.picture30PCPathList != null) return false; } else if (!picture30PCPathList.equals(other.picture30PCPathList)) return false; if (picturePathList == null) { if (other.picturePathList != null) return false; } else if (!picturePathList.equals(other.picturePathList)) return false; if (pictureURLList == null) { if (other.pictureURLList != null) return false; } else if (!pictureURLList.equals(other.pictureURLList)) return false; if (podeEnviarRedeDados == null) { if (other.podeEnviarRedeDados != null) return false; } else if (!podeEnviarRedeDados.equals(other.podeEnviarRedeDados)) return false; if (secaoEleitoral == null) { if (other.secaoEleitoral != null) return false; } else if (!secaoEleitoral.equals(other.secaoEleitoral)) return false; if (statusDoEnvio == null) { if (other.statusDoEnvio != null) return false; } else if (!statusDoEnvio.equals(other.statusDoEnvio)) return false; if (zonaEleitoral == null) { if (other.zonaEleitoral != null) return false; } else if (!zonaEleitoral.equals(other.zonaEleitoral)) return false; return true; } /** * @return the email */ public String getEmail() { return email; } /** * @param email the email to set */ public void setEmail(String email) { this.email = email; } }
vocefiscal/vocefiscal-android
Code/src/org/vocefiscal/models/Fiscalizacao.java
Java
apache-2.0
7,850
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import absolute_import import unittest from builtins import object from apache_beam.metrics.cells import DistributionData from apache_beam.metrics.execution import MetricKey from apache_beam.metrics.execution import MetricsContainer from apache_beam.metrics.execution import MetricsEnvironment from apache_beam.metrics.metric import MetricResults from apache_beam.metrics.metric import Metrics from apache_beam.metrics.metric import MetricsFilter from apache_beam.metrics.metricbase import MetricName from apache_beam.runners.worker import statesampler from apache_beam.utils import counters class NameTest(unittest.TestCase): def test_basic_metric_name(self): name = MetricName('namespace1', 'name1') self.assertEqual(name.namespace, 'namespace1') self.assertEqual(name.name, 'name1') self.assertEqual(name, MetricName('namespace1', 'name1')) key = MetricKey('step1', name) self.assertEqual(key.step, 'step1') self.assertEqual(key.metric.namespace, 'namespace1') self.assertEqual(key.metric.name, 'name1') self.assertEqual(key, MetricKey('step1', MetricName('namespace1', 'name1'))) class MetricResultsTest(unittest.TestCase): def test_metric_filter_namespace_matching(self): filter = MetricsFilter().with_namespace('ns1') name = MetricName('ns1', 'name1') key = MetricKey('step1', name) self.assertTrue(MetricResults.matches(filter, key)) def test_metric_filter_name_matching(self): filter = MetricsFilter().with_name('name1').with_namespace('ns1') name = MetricName('ns1', 'name1') key = MetricKey('step1', name) self.assertTrue(MetricResults.matches(filter, key)) filter = MetricsFilter().with_name('name1') name = MetricName('ns1', 'name1') key = MetricKey('step1', name) self.assertTrue(MetricResults.matches(filter, key)) def test_metric_filter_step_matching(self): name = MetricName('ns1', 'name1') filter = MetricsFilter().with_step('Step1') key = MetricKey('Step1', name) self.assertTrue(MetricResults.matches(filter, key)) key = MetricKey('Step10', name) self.assertFalse(MetricResults.matches(filter, key)) key = MetricKey('Step10/Step1', name) self.assertTrue(MetricResults.matches(filter, key)) key = MetricKey('Top1/Outer1/Inner1', name) filter = MetricsFilter().with_step('Top1/Outer1/Inner1') self.assertTrue(MetricResults.matches(filter, key)) filter = MetricsFilter().with_step('Top1/Outer1') self.assertTrue(MetricResults.matches(filter, key)) filter = MetricsFilter().with_step('Outer1/Inner1') self.assertTrue(MetricResults.matches(filter, key)) filter = MetricsFilter().with_step('Top1/Inner1') self.assertFalse(MetricResults.matches(filter, key)) class MetricsTest(unittest.TestCase): def test_get_namespace_class(self): class MyClass(object): pass self.assertEqual('{}.{}'.format(MyClass.__module__, MyClass.__name__), Metrics.get_namespace(MyClass)) def test_get_namespace_string(self): namespace = 'MyNamespace' self.assertEqual(namespace, Metrics.get_namespace(namespace)) def test_get_namespace_error(self): with self.assertRaises(ValueError): Metrics.get_namespace(object()) def test_counter_empty_name(self): with self.assertRaises(ValueError): Metrics.counter("namespace", "") def test_counter_empty_namespace(self): with self.assertRaises(ValueError): Metrics.counter("", "names") def test_distribution_empty_name(self): with self.assertRaises(ValueError): Metrics.distribution("namespace", "") def test_distribution_empty_namespace(self): with self.assertRaises(ValueError): Metrics.distribution("", "names") def test_create_counter_distribution(self): sampler = statesampler.StateSampler('', counters.CounterFactory()) statesampler.set_current_tracker(sampler) state1 = sampler.scoped_state('mystep', 'myState', metrics_container=MetricsContainer('mystep')) try: sampler.start() with state1: counter_ns = 'aCounterNamespace' distro_ns = 'aDistributionNamespace' name = 'a_name' counter = Metrics.counter(counter_ns, name) distro = Metrics.distribution(distro_ns, name) counter.inc(10) counter.dec(3) distro.update(10) distro.update(2) self.assertTrue(isinstance(counter, Metrics.DelegatingCounter)) self.assertTrue(isinstance(distro, Metrics.DelegatingDistribution)) del distro del counter container = MetricsEnvironment.current_container() self.assertEqual( container.get_counter( MetricName(counter_ns, name)).get_cumulative(), 7) self.assertEqual( container.get_distribution( MetricName(distro_ns, name)).get_cumulative(), DistributionData(12, 2, 2, 10)) finally: sampler.stop() if __name__ == '__main__': unittest.main()
RyanSkraba/beam
sdks/python/apache_beam/metrics/metric_test.py
Python
apache-2.0
5,846
package earthcube.eager.read; import earthcube.eager.util.Format; import earthcube.eager.data.AguData; import java.util.ArrayList; import java.util.HashMap; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModelSpec; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.util.FileManager; public class QueryAguTurtle { private int abstractIndex = 0; private int queriesToAgu = 0; private OntModel people, meeting; private Format format = new Format (); private final String aguEndpoint = "http://abstractsearch.agu.org:8890/sparql"; private ArrayList <AguData> aguAbstracts = new ArrayList <AguData> (); private HashMap <String, String[]> peopleDetails = new HashMap <String, String[]> (); // authorUri, name,email public int getAguQueryCount () { return queriesToAgu; } public void clearQueriesToAgu () { queriesToAgu = 0; } public ArrayList <AguData> getAbstracts () { return aguAbstracts; } public void clearAguAbstracts () { aguAbstracts.clear(); } private String getPersonData ( String roleUri ) { String[] personData = peopleDetails.get( roleUri ); String pData = personData[0] + ":" + personData[1]; return pData; } private boolean knownPerson ( String roleUri ) { if ( peopleDetails.containsKey(roleUri) ) { return true; } else { return false; } } private String createAllAuthorRolesQuery ( String personUri ) { String query = "SELECT ?authorUri WHERE { " + "<" + personUri + "> <http://tw.rpi.edu/schema/hasRole> ?authorUri . " + "}"; queriesToAgu++; return query; } private String createPersonQuery ( String authorUri ) { String query = "SELECT ?person ?name ?email WHERE { " + "?person <http://tw.rpi.edu/schema/hasRole> <" + authorUri + "> . " + "?person <http://xmlns.com/foaf/0.1/name> ?name . " + "?person <http://xmlns.com/foaf/0.1/mbox> ?email . " + "}"; return query; } private String[] getSparqlQueryResultsPeople ( ResultSet rs ) { String[] results = {null, null}; try { QuerySolution soln = rs.nextSolution(); RDFNode n = soln.get("name"); RDFNode e = soln.get("email"); RDFNode p = soln.get("person"); // output the name and email results[0] = format.removeDataType( n.toString() ); results[1] = format.removeDataType( e.toString() ); // find everything else this person has authored String query = createAllAuthorRolesQuery( p.toString() ); ResultSet authorResults = sparqlQuery( aguEndpoint, query ); // populate the two hashes while ( authorResults.hasNext() ) { QuerySolution soln2 = authorResults.nextSolution(); RDFNode authorUri = soln2.get("authorUri"); String aUri = authorUri.toString(); peopleDetails.put( aUri.trim(), results ); } } catch ( java.util.NoSuchElementException e ) { results[0] = "Unknown Unknown"; results[1] = "Unknown"; } return results; } // SPARQL query public static String abstractQuery = "SELECT ?abstract ?abstractText ?title ?keyword ?authorUri ?authorIndex WHERE { " + "?abstract <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://abstracts.agu.org/ontology#Abstract> . " + "?abstract <http://purl.org/dc/terms/title> ?title . " + "?abstract <http://data.semanticweb.org/ns/swc/ontology#hasTopic> ?keyword . " + "?abstract <http://swrc.ontoware.org/ontology#abstract> ?abstractText . " + "?abstract <http://tw.rpi.edu/schema/hasAgentWithRole> ?authorUri . " + "?authorUri <http://tw.rpi.edu/schema/index> ?authorIndex . " + "}"; // SPARQL query public static String justAbstractQuery = "SELECT ?abstract ?abstractText WHERE { " + "?abstract <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://abstracts.agu.org/ontology#Abstract> . " + "?abstract <http://swrc.ontoware.org/ontology#abstract> ?abstractText . " + "}"; public ResultSet sparqlQuery ( String query, OntModel model ) { // Execute the query QueryExecution qe = QueryExecutionFactory.create(query, model); ResultSet rs = qe.execSelect(); return rs; } public ResultSet sparqlQuery ( String endpoint, String query ) { // Execute the query Query q = QueryFactory.create(query); QueryExecution qe = QueryExecutionFactory.createServiceRequest( endpoint, q ); ResultSet rs = qe.execSelect(); return rs; } public ResultSet sparqlQuery ( String query ) { // Execute the query QueryExecution qe = QueryExecutionFactory.create(query, meeting); ResultSet rs = qe.execSelect(); return rs; } private AguData getExistingAbstract ( String uri ) { AguData result = null; for ( int i=0; i<aguAbstracts.size(); i++ ) { AguData d = aguAbstracts.get(i); if ( d.getAbstractUri().trim().equals( uri.trim() ) ) { result = d; abstractIndex = i; break; } } return result; } public void getSparqlQueryResultsAbstract ( ResultSet rs ) { // Loop through the results while ( rs.hasNext() ) { QuerySolution soln = rs.nextSolution(); RDFNode absText = soln.get("abstractText"); RDFNode titl = soln.get("title"); RDFNode key = soln.get("keyword"); RDFNode abstct = soln.get("abstract"); RDFNode authUri = soln.get("authorUri"); RDFNode authIndex = soln.get("authorIndex"); String abstractUri = abstct.toString(); String authorUri = authUri.toString(); String authorIndex = format.removeDataType(authIndex.toString()); String abstractText = format.removeLanguage( absText.toString() ); String title = format.removeLanguage( titl.toString() ); String keyword = key.toString().replace("http://abstracts", "http://abstractsearch"); // if we already have this person then don't query AGU again String pData; String[] personData; if ( !knownPerson(authorUri) ) { String personQuery = createPersonQuery ( authorUri ); //ResultSet personResult = sparqlQuery ( personQuery, people ); ResultSet personResult = sparqlQuery ( aguEndpoint, personQuery ); personData = getSparqlQueryResultsPeople ( personResult ); pData = personData[0] + ":" + personData[1]; } else { pData = getPersonData( authorUri ); } AguData data = getExistingAbstract( abstractUri ); // if the abstract uri doesn't exist then create a new abstract // otherwise just add the next author and keyword if ( data == null ) { data = new AguData (); data.setAbstractText( abstractText ); data.setAbstractTitle( title ); data.setAbstractUri( abstractUri ); if ( !data.authorExists(authorUri) ) { data.addAuthor( authorUri, authorIndex ); } if ( !data.keywordExists(keyword) ) { data.addKeyword( keyword ); } data.addAuthorData( authorUri, pData ); aguAbstracts.add( data ); } else { if ( !data.authorExists(authorUri) ) { data.addAuthor( authorUri, authorIndex ); } if ( !data.keywordExists(keyword) ) { data.addKeyword( keyword ); } data.addAuthorData( authorUri, pData ); aguAbstracts.set( abstractIndex, data ); } } // end while } public void getSparqlQueryResultsJustAbstract ( ResultSet rs ) { // Loop through the results while ( rs.hasNext() ) { QuerySolution soln = rs.nextSolution(); RDFNode absText = soln.get("abstractText"); RDFNode abs = soln.get("abstract"); AguData data = new AguData (); data.setAbstractText( format.removeLanguage( absText.toString() ) ); data.setAbstractUri( abs.toString() ); aguAbstracts.add( data ); } // end while } public void readPeopleFile ( String file ) { // Read the people turtle data into a graph System.out.println("Reading people turtle data..."); Model model = ModelFactory.createDefaultModel(); OntModelSpec spec = new OntModelSpec( OntModelSpec.OWL_MEM_RDFS_INF ); people = ModelFactory.createOntologyModel( spec, model ); FileManager.get().readModel(people, file) ; } public void readMeetingFile ( String file ) { // Read the turtle data System.out.println("Reading: " + file); Model model = ModelFactory.createDefaultModel(); OntModelSpec spec = new OntModelSpec( OntModelSpec.OWL_MEM_RDFS_INF ); meeting = ModelFactory.createOntologyModel( spec, model ); FileManager.get().readModel(meeting, file) ; } public static void main (String[] args) { String fmFile = args[0] + "\\" + "fm00.ttl"; //String peopleFile = args[0] + "\\" + "people.ttl"; QueryAguTurtle agu = new QueryAguTurtle (); //agu.readPeopleFile( peopleFile ); agu.readMeetingFile( fmFile ); // execute the SPARQL query and get the abstract texts ResultSet rs = agu.sparqlQuery( QueryAguTurtle.abstractQuery ); agu.getSparqlQueryResultsJustAbstract(rs); //ArrayList <AguData> aguAbstracts = agu.getAbstracts(); } }
narock/earthcube-EAGER
src/main/java/earthcube/eager/read/QueryAguTurtle.java
Java
apache-2.0
9,722
/* * Copyright 2012-2013 Andrea De Cesare * * 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.andreadec.musicplayer; import java.util.*; import android.content.*; import android.database.*; import android.database.sqlite.*; import com.andreadec.musicplayer.database.*; public class Playlist { private long id; private String name; private ArrayList<PlaylistSong> songs; public Playlist(long id, String name) { this.id = id; this.name = name; songs = new ArrayList<PlaylistSong>(); PlaylistsDatabase playlistsDatabase = new PlaylistsDatabase(); SQLiteDatabase db = playlistsDatabase.getReadableDatabase(); Cursor cursor = db.rawQuery("SELECT idSong, uri, artist, title, hasImage FROM SongsInPlaylist WHERE idPlaylist="+id+" ORDER BY position", null); while(cursor.moveToNext()) { long songId = cursor.getLong(0); String uri = cursor.getString(1); String artist = cursor.getString(2); String title = cursor.getString(3); boolean hasImage = cursor.getInt(4)==1; PlaylistSong song = new PlaylistSong(uri, artist, title, songId, hasImage, this); songs.add(song); } cursor.close(); db.close(); } public void addSong(BrowserSong song) { long songId = -1; PlaylistsDatabase playlistsDatabase = new PlaylistsDatabase(); SQLiteDatabase db = playlistsDatabase.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("idPlaylist", id); values.put("uri", song.getUri()); values.put("artist", song.getArtist()); values.put("title", song.getTitle()); values.put("hasImage", song.hasImage()); try { songId = db.insertOrThrow("SongsInPlaylist", null, values); } catch(Exception e) { } finally { db.close(); } if(songId==-1) return; // Something went wrong PlaylistSong playlistSong = new PlaylistSong(song.getUri(), song.getArtist(), song.getTitle(), songId, song.hasImage(), this); songs.add(playlistSong); } public void deleteSong(PlaylistSong song) { PlaylistsDatabase playlistsDatabase = new PlaylistsDatabase(); SQLiteDatabase db = playlistsDatabase.getWritableDatabase(); db.delete("SongsInPlaylist", "idSong="+song.getId(), null); db.close(); songs.remove(song); } public void sort(int from, int to) { if(to>from) { Collections.rotate(songs.subList(from, to+1), -1); } else { Collections.rotate(songs.subList(to, from+1), +1); } PlaylistsDatabase playlistsDatabase = new PlaylistsDatabase(); SQLiteDatabase db = playlistsDatabase.getWritableDatabase(); for(int i=0; i<songs.size(); i++) { PlaylistSong song = songs.get(i); ContentValues values = new ContentValues(); values.put("position", i); db.update("SongsInPlaylist", values, "idSong="+song.getId(), null); } db.close(); } public void editName(String newName) { name = newName; PlaylistsDatabase playlistsDatabase = new PlaylistsDatabase(); SQLiteDatabase db = playlistsDatabase.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", newName); db.update("Playlists", values, "id="+id, null); db.close(); } public long getId() { return id; } public String getName() { return name; } public ArrayList<PlaylistSong> getSongs() { return songs; } @Override public boolean equals(Object o) { if(!(o instanceof Playlist)) return false; Playlist p2 = (Playlist)o; return id==p2.id; } }
andreadec/MusicPlayer-OLD
src/com/andreadec/musicplayer/Playlist.java
Java
apache-2.0
3,896
L.Draw.Marker = L.Draw.Feature.extend({ statics: { TYPE: 'marker' }, options: { icon: new L.Icon.Default(), repeatMode: false, zIndexOffset: 2000, // This should be > than the highest z-index any markers buttonIconClass: 'leaflet-mouse-marker', type: 'marker' }, initialize: function (map, options) { // Save the type so super can fire, need to do this as cannot do this.TYPE :( this.type = options.type || this.options.type; L.Draw.Feature.prototype.initialize.call(this, map, options); }, addHooks: function () { L.Draw.Feature.prototype.addHooks.call(this); if (this._map) { this._tooltip.updateContent({text: L.drawLocal.draw.handlers.marker.tooltip.start}); // Same mouseMarker as in Draw.Polyline if (!this._mouseMarker) { this._mouseMarker = L.marker(this._map.getCenter(), { icon: L.divIcon({ className: 'leaflet-mouse-marker', iconAnchor: [20, 20], iconSize: [40, 40] }), opacity: 0, zIndexOffset: this.options.zIndexOffset }); } this._mouseMarker .on('click', this._onClick, this) .addTo(this._map); this._map.on('mousemove', this._onMouseMove, this); } }, removeHooks: function () { L.Draw.Feature.prototype.removeHooks.call(this); if (this._map) { if (this._marker) { this._marker.off('click', this._onClick, this); this._map .off('click', this._onClick, this) .removeLayer(this._marker); delete this._marker; } this._mouseMarker.off('click', this._onClick, this); this._map.removeLayer(this._mouseMarker); delete this._mouseMarker; this._map.off('mousemove', this._onMouseMove, this); } }, _onMouseMove: function (e) { var latlng = e.latlng; this._tooltip.updatePosition(latlng); this._mouseMarker.setLatLng(latlng); if (!this._marker) { this._marker = new L.Marker(latlng, { icon: this.options.icon, zIndexOffset: this.options.zIndexOffset }); // Bind to both marker and map to make sure we get the click event. this._marker.on('click', this._onClick, this); this._map .on('click', this._onClick, this) .addLayer(this._marker); } else { latlng = this._mouseMarker.getLatLng(); this._marker.setLatLng(latlng); } }, _onClick: function () { this._fireCreatedEvent(); this.disable(); if (this.options.repeatMode) { this.enable(); } }, _fireCreatedEvent: function () { var marker = new L.Marker(this._marker.getLatLng(), {icon: this.options.icon}); L.Draw.Feature.prototype._fireCreatedEvent.call(this, marker); } });
IITDU-Spartans/IITDU.SIUSC
FarmerBazaarClient/bower_components/Leaflet.draw-master/src/draw/handler/Draw.Marker.js
JavaScript
apache-2.0
3,241
package org.ovirt.optimizer.service.problemspace; import org.optaplanner.core.impl.domain.variable.listener.VariableListener; import org.optaplanner.core.impl.score.director.ScoreDirector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MigrationStepChangeListener implements VariableListener<Migration> { Logger logger = LoggerFactory.getLogger(MigrationStepChangeListener.class); @Override public void beforeEntityAdded(ScoreDirector scoreDirector, Migration entity) { } @Override public void afterEntityAdded(ScoreDirector scoreDirector, Migration entity) { afterVariableChanged(scoreDirector, entity); // recompute the last step flag OptimalDistributionStepsSolution solution = (OptimalDistributionStepsSolution)scoreDirector.getWorkingSolution(); solution.establishStepOrdering(); } @Override public void beforeVariableChanged(ScoreDirector scoreDirector, Migration entity) { /* not important for us */ } /** * After any variable change, recompute the cluster situation during * migration steps. */ @Override public void afterVariableChanged(ScoreDirector scoreDirector, Migration entity) { logger.trace("Variable changed in {} ({})", entity.toString(), entity.getStepsToFinish()); OptimalDistributionStepsSolution solution = (OptimalDistributionStepsSolution)scoreDirector.getWorkingSolution(); ClusterSituation situation = (ClusterSituation)solution; boolean stillOK = true; for (Migration m: solution.getSteps()) { if (entity == m) { stillOK = false; } if (!stillOK) { logger.trace("Recomputing shadow variables in {} ({})", m.toString(), m.getStepsToFinish()); scoreDirector.beforeVariableChanged(m, "vmToHostAssignments"); scoreDirector.beforeVariableChanged(m, "hostToVmAssignments"); m.recomputeSituationAfter(situation); scoreDirector.afterVariableChanged(m, "vmToHostAssignments"); scoreDirector.afterVariableChanged(m, "hostToVmAssignments"); } situation = m; } } @Override public void beforeEntityRemoved(ScoreDirector scoreDirector, Migration entity) { } @Override public void afterEntityRemoved(ScoreDirector scoreDirector, Migration entity) { // recompute the last step flag OptimalDistributionStepsSolution solution = (OptimalDistributionStepsSolution)scoreDirector.getWorkingSolution(); solution.establishStepOrdering(); } }
eayun/EayunOS-optimizer
ovirt-optimizer-core/src/main/java/org/ovirt/optimizer/service/problemspace/MigrationStepChangeListener.java
Java
apache-2.0
2,662
using Shared.Dtos.Paintings; using Shared.Dtos.Users; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shared.Services.Galleries { public class PhotoThumbnailInfoProvider { private static Dictionary<Type, PhotoThumbnailInfo> DTO_TYPE_TO_GALLERY_SPECIFICATION = CreateTypeToPhotoThumbnailInfo(); public static PhotoThumbnailInfo GetDefault(Type dtoType) { if (!DTO_TYPE_TO_GALLERY_SPECIFICATION.ContainsKey(dtoType)) { return null; } return DTO_TYPE_TO_GALLERY_SPECIFICATION[dtoType]; } private static Dictionary<Type, PhotoThumbnailInfo> CreateTypeToPhotoThumbnailInfo() { return new Dictionary<Type, PhotoThumbnailInfo> { { typeof(PaintingDto), new PhotoThumbnailInfo(340, 255, "/Upload/Paintings/{0}/Galleries/{1}/", 5) }, { typeof(UserDto), new PhotoThumbnailInfo(140, 190, "/Upload/Users/{0}/Galleries/{1}/", 1) } }; } } }
MurielSoftware/MyArt
Shared/Services/Galleries/PhotoThumbnailInfoProvider.cs
C#
apache-2.0
1,110
package com.linchaolong.apktoolplus.utils; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; /** * 命令行工具 * 注意:在Windows下执行批处理不能省略后缀,但exe可以 示例: if(OSUtils.isWindows()){ CmdUtils.exec("ant.bat compile -f "+buildFile.getAbsolutePath()); }else{ CmdUtils.exec("ant compile -f "+buildFile.getAbsolutePath()); } * * Created by linchaolong on 2015/11/12. */ public class CmdUtils { /** * 执行指定命令 * * @param cmd 命令 * @return */ public static boolean exec(String cmd){ return exec(cmd, true); } /** * 执行指定命令 * * @param cmd 命令 * @param isInput 是否输出执行日志 * @return */ public static boolean exec(String cmd, boolean isInput){ return exec(cmd, null, isInput); } /** * 执行指定命令 * * @param cmd 命令 * @param workDir 工作目录 * @return */ public static boolean exec(String cmd, File workDir){ return exec(cmd, workDir, true); } /** * 执行指定命令 * * @param cmd 命令 * @param workDir 工作目录 * @param isOutput 是否输出执行日志 * @return */ public static boolean exec(String cmd, File workDir, boolean isOutput){ return exec(cmd, null, workDir, isOutput); } /** * 执行指定命令 * * @param cmd 命令 * @param env 环境变量 * @param workDir 工作目录 * @param isOutput 是否输出执行日志 * @return */ public static boolean exec(String cmd, String[] env, File workDir, boolean isOutput){ LogUtils.d( "exec=" + cmd); boolean isSuccess = true; if(FileHelper.exists(workDir) && OSUtils.isWindows()){ cmd = String.format("cmd /c %s",cmd); } Runtime runtime = Runtime.getRuntime(); try { if (!isOutput){ runtime.exec(cmd, env, workDir); return true; } Process proc = runtime.exec(cmd, env, workDir); String encoding = System.getProperty("sun.jnu.encoding"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream(),encoding)); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream(),encoding)); // read the _out from the command //LogUtils.d("Here is the standard _out of the command:\n"); String s; while ((s = stdInput.readLine()) != null) { LogUtils.d(s); } // read any errors from the attempted command //LogUtils.e( "Here is the standard error of the command (if any):\n"); while ((s = stdError.readLine()) != null) { LogUtils.e(s); isSuccess = false; } } catch (Exception e) { isSuccess = false; e.printStackTrace(); } return isSuccess; } public static String execAndGetOutput(String cmd){ Runtime runtime = Runtime.getRuntime(); try { Process proc = runtime.exec(cmd); String encoding = System.getProperty("sun.jnu.encoding"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream(),encoding)); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream(),encoding)); String temp; StringBuilder output = new StringBuilder(); while ((temp = stdInput.readLine()) != null) { output.append(temp).append('\n'); } while ((temp = stdError.readLine()) != null) { output.append(temp).append('\n'); } return output.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } }
linchaolong/ApkToolPlus
lib.Utils/src/com/linchaolong/apktoolplus/utils/CmdUtils.java
Java
apache-2.0
4,157
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** 'use strict'; function main(service) { // [START servicemanagement_v1_generated_ServiceManager_CreateService_async] /** * TODO(developer): Uncomment these variables before running the sample. */ /** * Required. Initial values for the service resource. */ // const service = {} // Imports the Servicemanagement library const {ServiceManagerClient} = require('@google-cloud/service-management').v1; // Instantiates a client const servicemanagementClient = new ServiceManagerClient(); async function callCreateService() { // Construct request const request = { service, }; // Run request const [operation] = await servicemanagementClient.createService(request); const [response] = await operation.promise(); console.log(response); } callCreateService(); // [END servicemanagement_v1_generated_ServiceManager_CreateService_async] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));
googleapis/nodejs-service-management
samples/generated/v1/service_manager.create_service.js
JavaScript
apache-2.0
1,829
package de.hpi.bp2013n1.anonymizer; /* * #%L * Anonymizer * %% * Copyright (C) 2013 - 2014 HPI-BP2013N1 * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.io.File; import java.io.IOException; import java.sql.SQLException; import org.dbunit.DatabaseUnitException; import org.junit.After; import org.junit.Before; import org.junit.Test; import de.hpi.bp2013n1.anonymizer.Anonymizer.FatalError; import de.hpi.bp2013n1.anonymizer.shared.Config.DependantWithoutRuleException; import de.hpi.bp2013n1.anonymizer.shared.Config.MalformedException; public class ForeignKeyDeletionsByConfigRuleTest { private TestDataFixture testData; private File logFile; @Before public void createTestData() throws ClassNotFoundException, IOException, DependantWithoutRuleException, SQLException, DatabaseUnitException, MalformedException { testData = new TestSpecificTestDataFixture(this); testData.populateDatabases(); testData.setSchema(); } @Before public void prepareLogFile() throws IOException { logFile = File.createTempFile("anonymizer-test-config-output", null); logFile.delete(); Anonymizer.setUpLogging(logFile.getPath()); } @After public void closeDatabaseConnections() throws SQLException { testData.closeConnections(); } @After public void deleteLogFile() { logFile.delete(); } @Test public void weakDependentRowsAreDeleted() throws FatalError, DatabaseUnitException, SQLException { Anonymizer anonymizer = testData.createAnonymizer(); anonymizer.run(); testData.assertExpectedEqualsActualDataSet(); } }
HPI-BP2013N1/anonymizer
Anonymizer/src/test/java/de/hpi/bp2013n1/anonymizer/ForeignKeyDeletionsByConfigRuleTest.java
Java
apache-2.0
2,087
package in import ( "errors" "io/ioutil" "os" "path" "path/filepath" "github.com/cloudfoundry/gunk/urljoiner" "github.com/concourse/s3-resource" "github.com/concourse/s3-resource/versions" ) type RequestURLProvider struct { s3Client s3resource.S3Client } func (up *RequestURLProvider) GetURL(request InRequest, remotePath string) string { if request.Source.CloudfrontURL != "" { return up.cloudfrontURL(request, remotePath) } return up.s3URL(request, remotePath) } func (up *RequestURLProvider) s3URL(request InRequest, remotePath string) string { return up.s3Client.URL(request.Source.Bucket, remotePath, request.Source.Private, request.Version.VersionID) } func (up *RequestURLProvider) cloudfrontURL(request InRequest, remotePath string) string { url := urljoiner.Join(request.Source.CloudfrontURL, remotePath) if request.Version.VersionID != "" { url = url + "?versionId=" + request.Version.VersionID } return url } type InCommand struct { s3client s3resource.S3Client urlProvider RequestURLProvider } func NewInCommand(s3client s3resource.S3Client) *InCommand { return &InCommand{ s3client: s3client, urlProvider: RequestURLProvider{ s3Client: s3client, }, } } func (command *InCommand) Run(destinationDir string, request InRequest) (InResponse, error) { if ok, message := request.Source.IsValid(); !ok { return InResponse{}, errors.New(message) } err := command.createDirectory(destinationDir) if err != nil { return InResponse{}, err } if request.Source.Regexp != "" { return command.inByRegex(destinationDir, request) } else { return command.inByVersionedFile(destinationDir, request) } } func (command *InCommand) inByRegex(destinationDir string, request InRequest) (InResponse, error) { remotePath, err := command.pathToDownload(request) if err != nil { return InResponse{}, err } extraction, ok := versions.Extract(remotePath, request.Source.Regexp) if ok { err := command.writeVersionFile(extraction.VersionNumber, destinationDir) if err != nil { return InResponse{}, err } } err = command.downloadFile( request.Source.Bucket, remotePath, destinationDir, path.Base(remotePath), ) if err != nil { return InResponse{}, err } url := command.urlProvider.GetURL(request, remotePath) err = command.writeURLFile( destinationDir, url, ) if err != nil { return InResponse{}, err } return InResponse{ Version: s3resource.Version{ Path: remotePath, }, Metadata: command.metadata(remotePath, request.Source.Private, url), }, nil } func (command *InCommand) inByVersionedFile(destinationDir string, request InRequest) (InResponse, error) { err := command.writeVersionFile(request.Version.VersionID, destinationDir) if err != nil { return InResponse{}, err } remotePath := request.Source.VersionedFile versionedPath := remotePath + "?versionId=" + request.Version.VersionID err = command.downloadFile( request.Source.Bucket, versionedPath, destinationDir, path.Base(remotePath), ) if err != nil { return InResponse{}, err } url := command.urlProvider.GetURL(request, remotePath) err = command.writeURLFile( destinationDir, url, ) if err != nil { return InResponse{}, err } return InResponse{ Version: s3resource.Version{ VersionID: request.Version.VersionID, }, Metadata: command.metadata(remotePath, request.Source.Private, url), }, nil } func (command *InCommand) pathToDownload(request InRequest) (string, error) { if request.Version.Path == "" { extractions := versions.GetBucketFileVersions(command.s3client, request.Source) if len(extractions) == 0 { return "", errors.New("no extractions could be found - is your regexp correct?") } lastExtraction := extractions[len(extractions)-1] return lastExtraction.Path, nil } return request.Version.Path, nil } func (command *InCommand) createDirectory(destDir string) error { return os.MkdirAll(destDir, 0755) } func (command *InCommand) writeURLFile(destDir string, url string) error { return ioutil.WriteFile(filepath.Join(destDir, "url"), []byte(url), 0644) } func (command *InCommand) writeVersionFile(versionNumber string, destDir string) error { return ioutil.WriteFile(filepath.Join(destDir, "version"), []byte(versionNumber), 0644) } func (command *InCommand) downloadFile(bucketName string, remotePath string, destinationDir string, destinationFile string) error { localPath := filepath.Join(destinationDir, destinationFile) return command.s3client.DownloadFile( bucketName, remotePath, localPath, ) } func (command *InCommand) metadata(remotePath string, private bool, url string) []s3resource.MetadataPair { remoteFilename := filepath.Base(remotePath) metadata := []s3resource.MetadataPair{ s3resource.MetadataPair{ Name: "filename", Value: remoteFilename, }, } if !private { metadata = append(metadata, s3resource.MetadataPair{ Name: "url", Value: url, }) } return metadata }
pivotal-cf-experimental/s3-resource
in/in_command.go
GO
apache-2.0
4,980
package com.mod_snmp.SmiTools.Generators.Tree; /* Copyright 2000-2013 Harrie Hazewinkel. All rights reserved.*/ import com.mod_snmp.SmiParser.SyntaxTree.NodeList; import com.mod_snmp.SmiTools.Generators.Common.GeneratorInterface; import com.mod_snmp.SmiTools.Generators.Generator; import net.lisanza.CliArgs.ArgsException; /** * Handler for the CLI options that are added for tasks. */ public class TreeGenerator implements GeneratorInterface { private Generator caller; public TreeGenerator() { } public TreeGenerator(Generator top) throws ArgsException { caller = top; } /** * HTML argument parser. */ public int parse(String args[], int idx) throws ArgsException { if (caller.generator == null) { throw new ArgsException("Has already a generator"); } caller.generator = this; idx++; return idx; } public String argument() { return "-tree"; } public String usage() { return ""; } /** * The generator. */ public void generate(NodeList mdl) { } }
hhazewinkel/smi4j
smitranslator/src/main/java/com/mod_snmp/SmiTools/Generators/Tree/TreeGenerator.java
Java
apache-2.0
1,108
/* Copyright 2017 xgfone 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 config import ( "fmt" "os" ) func ExampleConfig_Observe() { conf := NewConfig() conf.RegisterCliOpt("test", Str("watchval", "abc", "test watch value")) conf.Observe(func(gname, name string, value interface{}) { fmt.Printf("group=%s, name=%s, value=%v\n", gname, name, value) }) conf.Parse() // Start the config // Set the option vlaue during the program is running. conf.SetOptValue(0, "test", "watchval", "123") // Output: // group=test, name=watchval, value=abc // group=test, name=watchval, value=123 } func ExampleNewEnvVarParser() { // Simulate the environment variable. os.Setenv("TEST_VAR1", "abc") os.Setenv("TEST_GROUP1_GROUP2_VAR2", "123") conf := NewConfig().AddParser(NewEnvVarParser("test")) opt1 := Str("var1", "", "the environment var 1") opt2 := Int("var2", 0, "the environment var 2") conf.RegisterOpt("", opt1) conf.RegisterOpt("group1.group2", opt2) if err := conf.Parse(); err != nil { fmt.Println(err) return } fmt.Printf("var1=%s\n", conf.String("var1")) fmt.Printf("var2=%d\n", conf.Group("group1.group2").Int("var2")) // Output: // var1=abc // var2=123 } func ExampleConfig() { cliOpts1 := []Opt{ StrOpt("", "required", "", "required").SetValidators(NewStrLenValidator(1, 10)), BoolOpt("", "yes", true, "test bool option"), } cliOpts2 := []Opt{ BoolOpt("", "no", false, "test bool option"), StrOpt("", "optional", "optional", "optional"), } opts := []Opt{ StrOpt("", "opt", "", "test opt"), } conf := NewConfig().AddParser(NewFlagCliParser(nil, true)) conf.RegisterCliOpts("", cliOpts1) conf.RegisterCliOpts("cli", cliOpts2) conf.RegisterCliOpts("group1.group2", opts) cliArgs := []string{ "--cli.no=0", "--required", "required", "--group1.group2.opt", "option", } if err := conf.Parse(cliArgs...); err != nil { fmt.Println(err) return } fmt.Println(conf.StringD("required", "abc")) fmt.Println(conf.Bool("yes")) fmt.Println(conf.Group("cli").String("optional")) fmt.Println(conf.Group("cli").Bool("no")) fmt.Println(conf.Group("group1.group2").StringD("opt", "opt")) fmt.Println(conf.Group("group1").Group("group2").StringD("opt", "opt")) // Output: // required // true // optional // false // option // option } func ExampleConfig_RegisterStruct() { type MySQL struct { Conn string `help:"the connection to mysql server"` MaxConnNum int `name:"maxconn" default:"3" help:"the maximum number of connections"` } type DB struct { MySQL MySQL } type DBWrapper struct { DB1 DB `group:".db111"` // Add the prefix . to reset the parent group. DB2 DB `group:"db222"` DB3 DB } type Config struct { Addr string `default:":80" help:"the address to listen to"` File string `default:"" group:"log" help:"the log file path"` Level string `default:"debug" group:"log" help:"the log level, such as debug, info, etc"` Ignore bool `name:"-" default:"true"` DB1 DB DB2 DB `name:"db02"` DB3 DB `group:"db03"` DB4 DB `name:"db04" group:"db004"` DB5 DBWrapper `group:"db"` } // Set the debug to output the process that handles the configuration. // Conf.SetDebug(true) var config Config Conf.RegisterCliStruct("", &config) // We use RegisterCliStruct instead of RegisterStruct // Only for test cliArgs := []string{ "--addr", "0.0.0.0:80", "--log.file", "/var/log/test.log", "--db1.mysql.conn", "user:pass@tcp(localhost:3306)/db1", "--db02.mysql.conn", "user:pass@tcp(localhost:3306)/db2", "--db03.mysql.conn", "user:pass@tcp(localhost:3306)/db3", "--db004.mysql.conn", "user:pass@tcp(localhost:3306)/db4", "--db111.mysql.conn", "user:pass@tcp(localhost:3306)/db5-1", "--db.db222.mysql.conn", "user:pass@tcp(localhost:3306)/db5-2", "--db.db3.mysql.conn", "user:pass@tcp(localhost:3306)/db5-3", } if err := Conf.Parse(cliArgs...); err != nil { fmt.Println(err) return } // Get the configuration by the struct. fmt.Printf("------ Struct ------\n") fmt.Printf("Addr: %s\n", config.Addr) fmt.Printf("File: %s\n", config.File) fmt.Printf("Level: %s\n", config.Level) fmt.Printf("Ignore: %v\n", config.Ignore) fmt.Printf("DB1.MySQL.Conn: %s\n", config.DB1.MySQL.Conn) fmt.Printf("DB1.MySQL.MaxConnNum: %d\n", config.DB1.MySQL.MaxConnNum) fmt.Printf("DB2.MySQL.Conn: %s\n", config.DB2.MySQL.Conn) fmt.Printf("DB2.MySQL.MaxConnNum: %d\n", config.DB2.MySQL.MaxConnNum) fmt.Printf("DB3.MySQL.Conn: %s\n", config.DB3.MySQL.Conn) fmt.Printf("DB3.MySQL.MaxConnNum: %d\n", config.DB3.MySQL.MaxConnNum) fmt.Printf("DB4.MySQL.Conn: %s\n", config.DB4.MySQL.Conn) fmt.Printf("DB4.MySQL.MaxConnNum: %d\n", config.DB4.MySQL.MaxConnNum) fmt.Printf("DB5.DB1.MySQL.Conn: %s\n", config.DB5.DB1.MySQL.Conn) fmt.Printf("DB5.DB1.MySQL.MaxConnNum: %d\n", config.DB5.DB1.MySQL.MaxConnNum) fmt.Printf("DB5.DB2.MySQL.Conn: %s\n", config.DB5.DB2.MySQL.Conn) fmt.Printf("DB5.DB2.MySQL.MaxConnNum: %d\n", config.DB5.DB2.MySQL.MaxConnNum) fmt.Printf("DB5.DB3.MySQL.Conn: %s\n", config.DB5.DB3.MySQL.Conn) fmt.Printf("DB5.DB3.MySQL.MaxConnNum: %d\n", config.DB5.DB3.MySQL.MaxConnNum) // Get the configuration by the Config. fmt.Printf("\n------ Config ------\n") fmt.Printf("Addr: %s\n", Conf.String("addr")) fmt.Printf("File: %s\n", Conf.Group("log").String("file")) fmt.Printf("Level: %s\n", Conf.Group("log").String("level")) fmt.Printf("Ignore: %v\n", Conf.BoolD("ignore", true)) fmt.Printf("DB1.MySQL.Conn: %s\n", Conf.Group("db1").Group("mysql").String("conn")) fmt.Printf("DB1.MySQL.MaxConnNum: %d\n", Conf.Group("db1.mysql").Int("maxconn")) fmt.Printf("DB2.MySQL.Conn: %s\n", Conf.Group("db02.mysql").String("conn")) fmt.Printf("DB2.MySQL.MaxConnNum: %d\n", Conf.Group("db02").Group("mysql").Int("maxconn")) fmt.Printf("DB3.MySQL.Conn: %s\n", Conf.Group("db03.mysql").String("conn")) fmt.Printf("DB3.MySQL.MaxConnNum: %d\n", Conf.Group("db03").Group("mysql").Int("maxconn")) fmt.Printf("DB4.MySQL.Conn: %s\n", Conf.Group("db004").Group("mysql").String("conn")) fmt.Printf("DB4.MySQL.MaxConnNum: %d\n", Conf.Group("db004.mysql").Int("maxconn")) fmt.Printf("DB5.DB1.MySQL.Conn: %s\n", Conf.Group("db111").Group("mysql").String("conn")) fmt.Printf("DB5.DB1.MySQL.MaxConnNum: %d\n", Conf.Group("db111").Group("mysql").Int("maxconn")) fmt.Printf("DB5.DB2.MySQL.Conn: %s\n", Conf.Group("db").Group("db222").Group("mysql").String("conn")) fmt.Printf("DB5.DB2.MySQL.MaxConnNum: %d\n", Conf.Group("db.db222").Group("mysql").Int("maxconn")) fmt.Printf("DB5.DB3.MySQL.Conn: %s\n", Conf.Group("db").Group("db3.mysql").String("conn")) fmt.Printf("DB5.DB3.MySQL.MaxConnNum: %d\n", Conf.Group("db.db3.mysql").Int("maxconn")) // Print the group tree for debug. fmt.Printf("\n------ Debug ------\n") Conf.PrintGroupTree() // Unordered output: // ------ Struct ------ // Addr: 0.0.0.0:80 // File: /var/log/test.log // Level: debug // Ignore: false // DB1.MySQL.Conn: user:pass@tcp(localhost:3306)/db1 // DB1.MySQL.MaxConnNum: 3 // DB2.MySQL.Conn: user:pass@tcp(localhost:3306)/db2 // DB2.MySQL.MaxConnNum: 3 // DB3.MySQL.Conn: user:pass@tcp(localhost:3306)/db3 // DB3.MySQL.MaxConnNum: 3 // DB4.MySQL.Conn: user:pass@tcp(localhost:3306)/db4 // DB4.MySQL.MaxConnNum: 3 // DB5.DB1.MySQL.Conn: user:pass@tcp(localhost:3306)/db5-1 // DB5.DB1.MySQL.MaxConnNum: 3 // DB5.DB2.MySQL.Conn: user:pass@tcp(localhost:3306)/db5-2 // DB5.DB2.MySQL.MaxConnNum: 3 // DB5.DB3.MySQL.Conn: user:pass@tcp(localhost:3306)/db5-3 // DB5.DB3.MySQL.MaxConnNum: 3 // // ------ Config ------ // Addr: 0.0.0.0:80 // File: /var/log/test.log // Level: debug // Ignore: true // DB1.MySQL.Conn: user:pass@tcp(localhost:3306)/db1 // DB1.MySQL.MaxConnNum: 3 // DB2.MySQL.Conn: user:pass@tcp(localhost:3306)/db2 // DB2.MySQL.MaxConnNum: 3 // DB3.MySQL.Conn: user:pass@tcp(localhost:3306)/db3 // DB3.MySQL.MaxConnNum: 3 // DB4.MySQL.Conn: user:pass@tcp(localhost:3306)/db4 // DB4.MySQL.MaxConnNum: 3 // DB5.DB1.MySQL.Conn: user:pass@tcp(localhost:3306)/db5-1 // DB5.DB1.MySQL.MaxConnNum: 3 // DB5.DB2.MySQL.Conn: user:pass@tcp(localhost:3306)/db5-2 // DB5.DB2.MySQL.MaxConnNum: 3 // DB5.DB3.MySQL.Conn: user:pass@tcp(localhost:3306)/db5-3 // DB5.DB3.MySQL.MaxConnNum: 3 // // ------ Debug ------ // |-->[DEFAULT] // | |--> addr // | |--> config-file // |-->[log] // | |--> file // | |--> level // |-->[db] // | |-->[db222] // | | |-->[mysql] // | | | |--> conn // | | | |--> maxconn // | |-->[db3] // | | |-->[mysql] // | | | |--> conn // | | | |--> maxconn // |-->[db1] // | |-->[mysql] // | | |--> conn // | | |--> maxconn // |-->[db02] // | |-->[mysql] // | | |--> conn // | | |--> maxconn // |-->[db03] // | |-->[mysql] // | | |--> conn // | | |--> maxconn // |-->[db004] // | |-->[mysql] // | | |--> conn // | | |--> maxconn // |-->[db111] // | |-->[mysql] // | | |--> conn // | | |--> maxconn }
xgfone/go-config
manager_test.go
GO
apache-2.0
9,493
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.IO; namespace Plywood.PullService { public partial class PlywoodPullService : ServiceBase { System.Threading.Thread worker; bool stopping; DeploymentConfiguration config; bool reregister = false; public PlywoodPullService() { InitializeComponent(); } protected override void OnStart(string[] args) { try { stopping = false; // Load configuration from registry. config = Utils.Registry.LoadDeploymentConfiguration(); // Update config. UpdateConfig(); // Register instance under target. Register(); if (worker == null) { worker = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc)); worker.Start(); } } catch (Exception ex) { this.EventLog.WriteEntry(string.Format("Failed starting service : ", ex.ToString()), EventLogEntryType.Error); } } private void Register() { try { if (!config.InstanceKey.HasValue || reregister) { try { var instances = new Instances(config); Instance instance = new Instance() { TargetKey = config.TargetKey }; instances.CreateInstance(instance); config.InstanceKey = instance.Key; } catch (Exception ex) { throw new DeploymentException("Failed registering instance.", ex); } try { Utils.Registry.Save(config); } catch (Exception ex) { throw new DeploymentException("Failed updating config after instance registration.", ex); } } } catch (Exception ex) { this.EventLog.WriteEntry("Failed service registration: " + ex.ToString(), EventLogEntryType.Error); throw; } reregister = false; } protected override void OnStop() { stopping = true; worker.Join(TimeSpan.FromSeconds(10)); if (worker.ThreadState == System.Threading.ThreadState.Running) worker.Abort(); worker = null; } private void ThreadProc() { try { while (!stopping) { RunUpdate(); for (int i = 0; i < config.CheckFrequency.TotalSeconds; i++) { if (!stopping) System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1)); } } } catch (Exception ex) { this.EventLog.WriteEntry("Fatal exception in thread: " + ex.ToString(), EventLogEntryType.Error); } } private void UpdateConfig() { try { var userData = UserData.Importer.LoadInstanceLatestUserData(); if (userData.Sections.Any(s => s.Name == "Plywood")) { if (config == null) config = new DeploymentConfiguration() { CheckFrequency = TimeSpan.FromSeconds(30) }; var section = userData["Plywood"]; if (section.Keys.Contains("AwsAccessKeyId")) config.AwsAccessKeyId = section["AwsAccessKeyId"]; if (section.Keys.Contains("AwsSecretAccessKey")) config.AwsSecretAccessKey = section["AwsSecretAccessKey"]; if (section.Keys.Contains("BucketName")) config.BucketName = section["BucketName"]; if (section.Keys.Contains("CheckFrequency")) config.CheckFrequency = TimeSpan.Parse(section["CheckFrequency"]); if (section.Keys.Contains("DeploymentDirectory")) config.DeploymentDirectory = section["DeploymentDirectory"]; if (section.Keys.Contains("TargetKey")) { Guid newTargetKey = Guid.Parse(section["TargetKey"]); if (newTargetKey != config.TargetKey) { reregister = true; config.TargetKey = Guid.Parse(section["TargetKey"]); } } if (section.Keys.Contains("InstanceKey")) { Guid newInstanceKey = Guid.Parse(section["InstanceKey"]); if (newInstanceKey != config.InstanceKey) { config.InstanceKey = Guid.Parse(section["InstanceKey"]); } } Utils.Registry.Save(config); } else { this.EventLog.WriteEntry("Failed updating instance plywood config from user data: Plywood section not found.", EventLogEntryType.Information); } } catch (Exception ex) { this.EventLog.WriteEntry("Failed updating instance plywood config from user data: " + ex.ToString(), EventLogEntryType.Warning); } } private void RunUpdate() { var logWriter = new StringWriter(); var appDeployment = new AppDeployment(config, logWriter); appDeployment.SynchroniseAllApplications(); logWriter.Flush(); string logContent = logWriter.ToString(); if (config.InstanceKey.HasValue && !string.IsNullOrWhiteSpace(logContent)) { var logs = new Logs(config); logs.AddLogEntry(new LogEntry() { InstanceKey = config.InstanceKey.Value, Status = appDeployment.DeploymentStatus, LogContent = logContent }); } } } }
danielrbradley/Plywood
PlywoodPullService/PlywoodPullService.cs
C#
apache-2.0
6,656
/* * Copyright 2011 Matthew Avery, mavery@advancedpwr.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.advancedpwr.record; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Set; import junit.framework.TestCase; public class ClassWriterTest extends TestCase { ClassWriter writer; StringWriter out; @Override protected void setUp() throws Exception { writer = new ClassWriter() { protected Set<Class> classes() { return null; } protected ClassDescriptor createDefaultDescriptor() { return null; } protected void writeObjectBuilderMethod() { }}; out = new StringWriter(); writer.setWriter( new PrintWriter( out ) ); } public void testWriteLine() { writer.writeLine( "package com.advancedpwr.foo" ); assertResult( "package com.advancedpwr.foo;\n" ); } public void assertResult( String inString ) { assertEquals( inString, out.toString().replaceAll( "\r\n", "\n" ) ); } public void testWrite() { writer.write( "if ( foo == null )" ); assertResult( "if ( foo == null )\n"); } public void testOpenCloseBrace() { writer.openBrace(); writer.write( "if ( foo == null )" ); writer.openBrace(); writer.writeLine( "bar" ); writer.closeBrace(); writer.closeBrace(); assertResult( "{\n" + "\tif ( foo == null )\n" + "\t{\n" + "\t\tbar;\n" + "\t}\n" + "}\n"); try { writer.closeBrace(); fail( "Should have thrown an exception"); } catch (Exception e) { assertTrue( e instanceof ClassWriterException ); } } public void testSetClassName() { writer.setClassName( "com.company.BusinessFactory" ); assertEquals( "com.company", writer.getDescriptor().getPackageName() ); assertEquals( "BusinessFactory", writer.getDescriptor().getClassName() ); } }
hani/jtor
src/test/java/com/advancedpwr/record/ClassWriterTest.java
Java
apache-2.0
2,343
package matchers_test import ( "time" . "github.com/atlassian/git-lob/Godeps/_workspace/src/github.com/onsi/ginkgo" . "github.com/atlassian/git-lob/Godeps/_workspace/src/github.com/onsi/gomega" . "github.com/atlassian/git-lob/Godeps/_workspace/src/github.com/onsi/gomega/matchers" ) type kungFuActor interface { DrunkenMaster() bool } type jackie struct { name string } func (j *jackie) DrunkenMaster() bool { return true } var _ = Describe("ReceiveMatcher", func() { Context("with no argument", func() { Context("for a buffered channel", func() { It("should succeed", func() { channel := make(chan bool, 1) Ω(channel).ShouldNot(Receive()) channel <- true Ω(channel).Should(Receive()) }) }) Context("for an unbuffered channel", func() { It("should succeed (eventually)", func() { channel := make(chan bool) Ω(channel).ShouldNot(Receive()) go func() { time.Sleep(10 * time.Millisecond) channel <- true }() Eventually(channel).Should(Receive()) }) }) }) Context("with a pointer argument", func() { Context("of the correct type", func() { It("should write the value received on the channel to the pointer", func() { channel := make(chan int, 1) var value int Ω(channel).ShouldNot(Receive(&value)) Ω(value).Should(BeZero()) channel <- 17 Ω(channel).Should(Receive(&value)) Ω(value).Should(Equal(17)) }) }) Context("to various types of objects", func() { It("should work", func() { //channels of strings stringChan := make(chan string, 1) stringChan <- "foo" var s string Ω(stringChan).Should(Receive(&s)) Ω(s).Should(Equal("foo")) //channels of slices sliceChan := make(chan []bool, 1) sliceChan <- []bool{true, true, false} var sl []bool Ω(sliceChan).Should(Receive(&sl)) Ω(sl).Should(Equal([]bool{true, true, false})) //channels of channels chanChan := make(chan chan bool, 1) c := make(chan bool) chanChan <- c var receivedC chan bool Ω(chanChan).Should(Receive(&receivedC)) Ω(receivedC).Should(Equal(c)) //channels of interfaces jackieChan := make(chan kungFuActor, 1) aJackie := &jackie{name: "Jackie Chan"} jackieChan <- aJackie var theJackie kungFuActor Ω(jackieChan).Should(Receive(&theJackie)) Ω(theJackie).Should(Equal(aJackie)) }) }) Context("of the wrong type", func() { It("should error", func() { channel := make(chan int) var incorrectType bool success, err := (&ReceiveMatcher{Arg: &incorrectType}).Match(channel) Ω(success).Should(BeFalse()) Ω(err).Should(HaveOccurred()) var notAPointer int success, err = (&ReceiveMatcher{Arg: notAPointer}).Match(channel) Ω(success).Should(BeFalse()) Ω(err).Should(HaveOccurred()) }) }) }) Context("with a matcher", func() { It("should defer to the underlying matcher", func() { intChannel := make(chan int, 1) intChannel <- 3 Ω(intChannel).Should(Receive(Equal(3))) intChannel <- 2 Ω(intChannel).ShouldNot(Receive(Equal(3))) stringChannel := make(chan []string, 1) stringChannel <- []string{"foo", "bar", "baz"} Ω(stringChannel).Should(Receive(ContainElement(ContainSubstring("fo")))) stringChannel <- []string{"foo", "bar", "baz"} Ω(stringChannel).ShouldNot(Receive(ContainElement(ContainSubstring("archipelago")))) }) It("should defer to the underlying matcher for the message", func() { matcher := Receive(Equal(3)) channel := make(chan int, 1) channel <- 2 matcher.Match(channel) Ω(matcher.FailureMessage(channel)).Should(MatchRegexp(`Expected\s+<int>: 2\s+to equal\s+<int>: 3`)) channel <- 3 matcher.Match(channel) Ω(matcher.NegatedFailureMessage(channel)).Should(MatchRegexp(`Expected\s+<int>: 3\s+not to equal\s+<int>: 3`)) }) It("should work just fine with Eventually", func() { stringChannel := make(chan string) go func() { time.Sleep(5 * time.Millisecond) stringChannel <- "A" time.Sleep(5 * time.Millisecond) stringChannel <- "B" }() Eventually(stringChannel).Should(Receive(Equal("B"))) }) Context("if the matcher errors", func() { It("should error", func() { channel := make(chan int, 1) channel <- 3 success, err := (&ReceiveMatcher{Arg: ContainSubstring("three")}).Match(channel) Ω(success).Should(BeFalse()) Ω(err).Should(HaveOccurred()) }) }) Context("if nothing is received", func() { It("should fail", func() { channel := make(chan int, 1) success, err := (&ReceiveMatcher{Arg: Equal(1)}).Match(channel) Ω(success).Should(BeFalse()) Ω(err).ShouldNot(HaveOccurred()) }) }) }) Context("When actual is a *closed* channel", func() { Context("for a buffered channel", func() { It("should work until it hits the end of the buffer", func() { channel := make(chan bool, 1) channel <- true close(channel) Ω(channel).Should(Receive()) Ω(channel).ShouldNot(Receive()) }) }) Context("for an unbuffered channel", func() { It("should always fail", func() { channel := make(chan bool) close(channel) Ω(channel).ShouldNot(Receive()) }) }) }) Context("When actual is a send-only channel", func() { It("should error", func() { channel := make(chan bool) var writerChannel chan<- bool writerChannel = channel success, err := (&ReceiveMatcher{}).Match(writerChannel) Ω(success).Should(BeFalse()) Ω(err).Should(HaveOccurred()) }) }) Context("when acutal is a non-channel", func() { It("should error", func() { var nilChannel chan bool success, err := (&ReceiveMatcher{}).Match(nilChannel) Ω(success).Should(BeFalse()) Ω(err).Should(HaveOccurred()) success, err = (&ReceiveMatcher{}).Match(nil) Ω(success).Should(BeFalse()) Ω(err).Should(HaveOccurred()) success, err = (&ReceiveMatcher{}).Match(3) Ω(success).Should(BeFalse()) Ω(err).Should(HaveOccurred()) }) }) Describe("when used with eventually and a custom matcher", func() { It("should return the matcher's error when a failing value is received on the channel, instead of the must receive something failure", func() { failures := InterceptGomegaFailures(func() { c := make(chan string, 0) Eventually(c, 0.01).Should(Receive(Equal("hello"))) }) Ω(failures[0]).Should(ContainSubstring("When passed a matcher, ReceiveMatcher's channel *must* receive something.")) failures = InterceptGomegaFailures(func() { c := make(chan string, 1) c <- "hi" Eventually(c, 0.01).Should(Receive(Equal("hello"))) }) Ω(failures[0]).Should(ContainSubstring("<string>: hello")) }) }) Describe("Bailing early", func() { It("should bail early when passed a closed channel", func() { c := make(chan bool) close(c) t := time.Now() failures := InterceptGomegaFailures(func() { Eventually(c).Should(Receive()) }) Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) Ω(failures).Should(HaveLen(1)) }) It("should bail early when passed a non-channel", func() { t := time.Now() failures := InterceptGomegaFailures(func() { Eventually(3).Should(Receive()) }) Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) Ω(failures).Should(HaveLen(1)) }) }) })
atlassian/git-lob
Godeps/_workspace/src/github.com/onsi/gomega/matchers/receive_matcher_test.go
GO
apache-2.0
7,392
/** * Copyright 2015-2019 OpenCB * * 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 {LitElement, html} from "lit"; import UtilsNew from "../../../core/utilsNew.js"; export default class SampleGenotypeFilter extends LitElement { constructor() { super(); // Set status and init private properties this._init(); } createRenderRoot() { return this; } static get properties() { return { sample: { type: String }, genotypes: { type: Array }, sampleId: { type: String }, config: { type: Object } }; } _init() { this._prefix = UtilsNew.randomString(8); this._config = this.getDefaultConfig(); } update(changedProperties) { if (changedProperties.has("sample") && this.sample) { const keyValue = this.sample.split(":"); if (keyValue.length === 2) { this.sampleId = keyValue[0]; this.genotypes = keyValue[1].split(","); } else { // No genotypes provided this.sampleId = keyValue[0]; this.genotypes = ["0/1", "1/1", "NA"]; } } if (changedProperties.has("config")) { this._config = {...this.getDefaultConfig(), ...this.config}; } super.update(changedProperties); } filterChange(e) { // select-field-filter already emits a bubbled filterChange event. // Prepare sample query filter let sampleFilter = this.sampleId; if (e.detail.value) { sampleFilter += ":" + e.detail.value; } const event = new CustomEvent("filterChange", { detail: { value: sampleFilter }, bubbles: true, composed: true }); this.dispatchEvent(event); } getDefaultConfig() { // HOM_REF, HOM_ALT, HET, HET_REF, HET_ALT and MISS e.g. HG0097:HOM_REF;HG0098:HET_REF,HOM_ALT . 3) return { genotypes: [ { id: "0/1", name: "HET" }, { id: "1/1", name: "HOM ALT" }, { separator: true }, { id: "./.", name: "Missing" }, { id: "NA", name: "NA" } ] }; } render() { return html` <select-field-filter multiple .data="${this._config.genotypes}" .value=${this.genotypes} .multiple="true" @filterChange="${this.filterChange}"> </select-field-filter> `; } } customElements.define("sample-genotype-filter", SampleGenotypeFilter);
opencb/jsorolla
src/webcomponents/commons/filters/sample-genotype-filter.js
JavaScript
apache-2.0
3,559
<?php /* * Copyright 2016 Lukas Metzger <developer@lukas-metzger.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. */ require_once '../config/config-default.php'; require_once '../lib/database.php'; require_once '../lib/checkversion.php'; $input = json_decode(file_get_contents('php://input')); if(isset($input->action) && $input->action == "getVersions") { $retval['from'] = getVersion($db); $retval['to'] = getExpectedVersion(); } if(isset($input->action) && $input->action == "requestUpgrade") { $currentVersion = getVersion($db); $dbType = $config['db_type']; if($currentVersion < 1) { $sql["mysql"] = " CREATE TABLE IF NOT EXISTS remote ( id int(11) NOT NULL AUTO_INCREMENT, record int(11) NOT NULL, description varchar(255) NOT NULL, type varchar(20) NOT NULL, security varchar(2000) NOT NULL, nonce varchar(255) DEFAULT NULL, PRIMARY KEY (id), KEY record (record) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `remote` ADD CONSTRAINT `remote_ibfk_1` FOREIGN KEY (`record`) REFERENCES `records` (`id`); CREATE TABLE IF NOT EXISTS options ( name varchar(255) NOT NULL, value varchar(2000) DEFAULT NULL, PRIMARY KEY (name) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO options(name,value) VALUES ('schema_version', 1); "; $sql["pgsql"] = "INSERT INTO options(name,value) VALUES ('schema_version', 1);"; $queries = explode(";", $sql[$dbType]); $db->beginTransaction(); foreach ($queries as $query) { if (preg_replace('/\s+/', '', $query) != '') { $db->exec($query); } } $db->commit(); } if($currentVersion < 2) { $sql["mysql"] = " ALTER TABLE permissions DROP FOREIGN KEY permissions_ibfk_1; ALTER TABLE permissions DROP FOREIGN KEY permissions_ibfk_2; ALTER TABLE permissions ADD CONSTRAINT permissions_ibfk_1 FOREIGN KEY (domain) REFERENCES domains (id) ON DELETE CASCADE; ALTER TABLE permissions ADD CONSTRAINT permissions_ibfk_2 FOREIGN KEY (user) REFERENCES user (id) ON DELETE CASCADE; ALTER TABLE remote DROP FOREIGN KEY remote_ibfk_1; ALTER TABLE remote ADD CONSTRAINT remote_ibfk_1 FOREIGN KEY (record) REFERENCES records (id) ON DELETE CASCADE; ALTER TABLE records ADD CONSTRAINT records_ibfk_1 FOREIGN KEY (domain_id) REFERENCES domains (id) ON DELETE CASCADE; UPDATE options SET value=2 WHERE name='schema_version'; "; $sql["pgsql"] = "UPDATE options SET value=2 WHERE name='schema_version';"; $queries = explode(";", $sql[$dbType]); $db->beginTransaction(); foreach ($queries as $query) { if (preg_replace('/\s+/', '', $query) != '') { $db->exec($query); } } $db->commit(); } if($currentVersion < 3) { $sql["mysql"] = " CREATE TABLE IF NOT EXISTS domainmetadata ( id INT AUTO_INCREMENT, domain_id INT NOT NULL, kind VARCHAR(32), content TEXT, PRIMARY KEY (id) ) Engine=InnoDB; ALTER TABLE records ADD disabled TINYINT(1) DEFAULT 0; ALTER TABLE records ADD auth TINYINT(1) DEFAULT 1; UPDATE options SET value=3 WHERE name='schema_version'; "; $sql["pgsql"] = "UPDATE options SET value=3 WHERE name='schema_version';"; $queries = explode(";", $sql[$dbType]); $db->beginTransaction(); foreach ($queries as $query) { if (preg_replace('/\s+/', '', $query) != '') { $db->exec($query); } } $db->commit(); } if($currentVersion < 4) { $sql["mysql"] = " ALTER TABLE permissions DROP FOREIGN KEY permissions_ibfk_2; RENAME TABLE user TO users; ALTER TABLE permissions CHANGE user userid INT(11); ALTER TABLE permissions ADD CONSTRAINT permissions_ibfk_2 FOREIGN KEY (userid) REFERENCES users (id) ON DELETE CASCADE; ALTER TABLE users ADD CONSTRAINT UNIQUE KEY user_name_index (name); UPDATE options SET value=4 WHERE name='schema_version'; "; $sql["pgsql"] = "UPDATE options SET value=4 WHERE name='schema_version';"; $queries = explode(";", $sql[$dbType]); $db->beginTransaction(); foreach ($queries as $query) { if (preg_replace('/\s+/', '', $query) != '') { $db->exec($query); } } $db->commit(); } $retval['status'] = "success"; } if(isset($retval)) { echo json_encode($retval); } else { echo "{}"; }
heptalium/pdnsmanager
api/upgrade.php
PHP
apache-2.0
5,601
package com.github.salvatorenovelli.seo.websiteversioning.domain; import com.github.salvatorenovelli.seo.websiteversioning.crawler.Worker; import com.github.salvatorenovelli.seo.websiteversioning.crawler.crawler4j.Crawler4JCrawlerFactory; import org.springframework.stereotype.Component; import java.util.concurrent.atomic.AtomicInteger; @Component public class DefaultWorkerFactory implements WorkerFactory { private final Crawler4JCrawlerFactory crawlerFactory; private final AtomicInteger id = new AtomicInteger(0); public DefaultWorkerFactory(Crawler4JCrawlerFactory crawlerFactory) { this.crawlerFactory = crawlerFactory; } @Override public Worker createWorker() { return new Worker(String.valueOf(id.getAndIncrement()), crawlerFactory.createCrawler()); } }
salvatorenovelli/website-version-history
src/main/java/com/github/salvatorenovelli/seo/websiteversioning/domain/DefaultWorkerFactory.java
Java
apache-2.0
813
var templates = function () { 'use strict'; var handlebars = window.handlebars || window.Handlebars, Handlebars = window.handlebars || window.Handlebars, cache = {}; function get(name) { var promise = new Promise(function (resolve, reject) { //if (cache[name]) { // resolve(cache[name]); // return; //} var url = '/Scripts/app/templates/' + name + '.handlebars'; $.get(url, function (html) { var template = handlebars.compile(html); cache[name] = template; resolve(template); }).then(function(res){ reject(res); }); }); return promise; } return { get: get }; }();
deyantodorov/Zeus-WebServicesCould-TeamWork
Source/ChatSystem/Server/ChatSystem.Server/Scripts/app/templates.js
JavaScript
apache-2.0
804
"""Support for the Hive sensors.""" from datetime import timedelta from homeassistant.components.sensor import SensorDeviceClass, SensorEntity from homeassistant.helpers.entity import DeviceInfo from . import HiveEntity from .const import DOMAIN PARALLEL_UPDATES = 0 SCAN_INTERVAL = timedelta(seconds=15) DEVICETYPE = { "Battery": {"unit": " % ", "type": SensorDeviceClass.BATTERY}, } async def async_setup_entry(hass, entry, async_add_entities): """Set up Hive thermostat based on a config entry.""" hive = hass.data[DOMAIN][entry.entry_id] devices = hive.session.deviceList.get("sensor") entities = [] if devices: for dev in devices: entities.append(HiveSensorEntity(hive, dev)) async_add_entities(entities, True) class HiveSensorEntity(HiveEntity, SensorEntity): """Hive Sensor Entity.""" @property def unique_id(self): """Return unique ID of entity.""" return self._unique_id @property def device_info(self) -> DeviceInfo: """Return device information.""" return DeviceInfo( identifiers={(DOMAIN, self.device["device_id"])}, manufacturer=self.device["deviceData"]["manufacturer"], model=self.device["deviceData"]["model"], name=self.device["device_name"], sw_version=self.device["deviceData"]["version"], via_device=(DOMAIN, self.device["parentDevice"]), ) @property def available(self): """Return if sensor is available.""" return self.device.get("deviceData", {}).get("online") @property def device_class(self): """Device class of the entity.""" return DEVICETYPE[self.device["hiveType"]].get("type") @property def native_unit_of_measurement(self): """Return the unit of measurement.""" return DEVICETYPE[self.device["hiveType"]].get("unit") @property def name(self): """Return the name of the sensor.""" return self.device["haName"] @property def native_value(self): """Return the state of the sensor.""" return self.device["status"]["state"] async def async_update(self): """Update all Node data from Hive.""" await self.hive.session.updateData(self.device) self.device = await self.hive.sensor.getSensor(self.device)
home-assistant/home-assistant
homeassistant/components/hive/sensor.py
Python
apache-2.0
2,371
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; namespace Alchemy4Tridion.Plugins.Clients.CoreService { [GeneratedCode("System.ServiceModel", "4.0.0.0"), DebuggerStepThrough] public class BatchForceFinishProcessCompletedEventArgs : AsyncCompletedEventArgs { private object[] results; public string Result { get { base.RaiseExceptionIfNecessary(); return (string)this.results[0]; } } public BatchForceFinishProcessCompletedEventArgs(object[] results, Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } } }
Alchemy4Tridion/Alchemy4Tridion
Client Proxies/CoreService/Tridion.ContentManager.CoreService.Client/BatchForceFinishProcessCompletedEventArgs.cs
C#
apache-2.0
697
namespace Levolution.TypeSchema.ConceptualType { /// <summary> /// /// </summary> public interface INumericType : IPrimitiveType { /// <summary> /// /// </summary> int Size { get; } } }
LeonAkasaka/Levolution.TypeSchema
Levolution.TypeSchema/ConceptualType/INumericType.cs
C#
apache-2.0
247
#region License Header /* * QUANTLER.COM - Quant Fund Development Platform * Quantler Core Trading Engine. Copyright 2018 Quantler B.V. * * 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. */ #endregion License Header using Quantler.Interfaces; using Quantler.Securities; using System; using Quantler.Account; namespace Quantler.Broker.SettlementModels { /// <summary> /// Delayed settlement by T+N period /// </summary> public class DelayedSettlementModel : SettlementModel { #region Public Constructors /// <summary> /// Create a delayed settlement model implementation /// </summary> /// <param name="daysdelayed">Amount of days before settlement</param> /// <param name="timeofday">Time of day settlement will occur</param> public DelayedSettlementModel(int daysdelayed, TimeSpan timeofday) { if (daysdelayed <= 0) throw new ArgumentException("Provided days should be positive for a delayed model"); DelayedDays = daysdelayed; TimeOfDay = timeofday; } #endregion Public Constructors #region Public Properties /// <summary> /// Amount of days unsettled funds should be delayed before settlement /// </summary> public int DelayedDays { get; } /// <summary> /// Time of day settlement should occur /// </summary> public TimeSpan TimeOfDay { get; } #endregion Public Properties #region Public Methods /// <summary> /// Settle funds, delayed /// </summary> /// <param name="account">The account.</param> /// <param name="quantfund">The quantfund.</param> /// <param name="security">The security.</param> /// <param name="occureddtutc">The occureddtutc.</param> /// <param name="amount">The amount.</param> public void SettleFunds(BrokerAccount account, Security security, DateTime occureddtutc, decimal amount, IQuantFund quantfund = null) { //Added funds if (amount > 0) { //Get exchangeModel based local time DateTime settlementdate = security.Exchange.LocalTime; //Check for date based on market opened date and time for (int i = 0; i < DelayedDays; i++) { settlementdate = settlementdate.AddDays(i); if (!security.Exchange.IsOpenOnDate(settlementdate)) i--; } //Get correct date and time settlementdate = settlementdate.Add(TimeOfDay); //Convert time of day from local exchangeModel timezone to utc based time settlementdate = settlementdate.ConvertTo(security.Exchange.TimeZone, TimeZone.Utc); //Add unsettled funds (to be settled on a later time and date) account.Cash.AddCash(security.BaseCurrency, amount, quantfund, settlementdate); } else //Used funds, settle right away account.Cash.AddCash(security.BaseCurrency, amount, quantfund); } #endregion Public Methods } }
Quantler/Core
Quantler/Broker/SettlementModels/DelayedSettlementModel.cs
C#
apache-2.0
3,753
/* * 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.simpleemailv2.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.simpleemailv2.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * UpdateContactListRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class UpdateContactListRequestMarshaller { private static final MarshallingInfo<String> CONTACTLISTNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PATH).marshallLocationName("ContactListName").build(); private static final MarshallingInfo<List> TOPICS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Topics").build(); private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Description").build(); private static final UpdateContactListRequestMarshaller instance = new UpdateContactListRequestMarshaller(); public static UpdateContactListRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(UpdateContactListRequest updateContactListRequest, ProtocolMarshaller protocolMarshaller) { if (updateContactListRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateContactListRequest.getContactListName(), CONTACTLISTNAME_BINDING); protocolMarshaller.marshall(updateContactListRequest.getTopics(), TOPICS_BINDING); protocolMarshaller.marshall(updateContactListRequest.getDescription(), DESCRIPTION_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-sesv2/src/main/java/com/amazonaws/services/simpleemailv2/model/transform/UpdateContactListRequestMarshaller.java
Java
apache-2.0
2,719
package com.java110.front.components.staff; import com.java110.core.context.IPageData; import com.java110.front.smo.IStaffServiceSMO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; /** * 搜索员工 */ @Component("searchStaff") public class SearchStaffComponent { @Autowired IStaffServiceSMO staffServiceSMOImpl; public ResponseEntity<String> listStaff(IPageData pd) { ResponseEntity<String> responseEntity = null; try { responseEntity = staffServiceSMOImpl.loadData(pd); } catch (Exception e) { responseEntity = new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } finally { return responseEntity; } } public IStaffServiceSMO getStaffServiceSMOImpl() { return staffServiceSMOImpl; } public void setStaffServiceSMOImpl(IStaffServiceSMO staffServiceSMOImpl) { this.staffServiceSMOImpl = staffServiceSMOImpl; } }
java110/MicroCommunity
service-front/src/main/java/com/java110/front/components/staff/SearchStaffComponent.java
Java
apache-2.0
1,130
/* * Copyright 2008-2019 by Emeric Vernat * * This file is part of Java Melody. * * 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 net.bull.javamelody.internal.model; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.Locale; import org.ehcache.Status; import org.junit.Before; import org.junit.Test; import net.bull.javamelody.Utils; import net.bull.javamelody.internal.common.InputOutput; /** * Test unitaire de la classe TransportFormat. * @author Emeric Vernat */ public class TestTransportFormat { /** Check. */ @Before public void setUp() { Utils.initialize(); } private Counter createCounter() { final Counter counter = new Counter("test transport format", null); counter.addRequest("test1", 0, 0, 0, false, 1000); counter.addRequest("test2", 1000, 500, 500, false, 1000); counter.addRequest("test3", 10000, 500, 500, true, 10000); return counter; } /** Test. * @throws IOException e */ @Test public void testWriteSerialized() throws IOException { final Counter counter = createCounter(); final ByteArrayOutputStream output = new ByteArrayOutputStream(); TransportFormat.SERIALIZED.writeSerializableTo(counter, output); final String message = "flux vide"; assertTrue(message, output.size() > 0); output.reset(); TransportFormat.SERIALIZED.writeSerializableTo(null, output); assertTrue(message, output.size() > 0); } /** Test. * @throws IOException e */ @Test public void testWriteXml() throws IOException { final Counter counter = createCounter(); final ByteArrayOutputStream output = new ByteArrayOutputStream(); TransportFormat.XML.writeSerializableTo(counter, output); assertTrue("flux vide", output.size() > 0); } /** Test. * @throws IOException e */ @Test public void testWriteJson() throws IOException { final Counter counter = createCounter(); final ByteArrayOutputStream output = new ByteArrayOutputStream(); TransportFormat.JSON.writeSerializableTo(counter, output); assertTrue("flux vide", output.size() > 0); } /** Test. * @throws IOException e * @throws ClassNotFoundException e */ @Test public void testReadSerializable() throws IOException, ClassNotFoundException { final Counter counter = createCounter(); final Counter after = (Counter) serialize(counter); assertEquals("counter", counter.toString(), after.toString()); assertNull("null", serialize(null)); final String[][] array = {}; assertArrayEquals("array", array, (String[][]) serialize(array)); final boolean[] barray = {}; assertArrayEquals("boolean", barray, (boolean[]) serialize(barray)); final File file = new File("test"); assertEquals("file", file, serialize(file)); try { // objects from not white-listed packages should not be deserialized assertNull("should not return a result", serialize(Status.UNINITIALIZED)); } catch (final ClassNotFoundException e) { assertNotNull("e", e); } } private static Serializable serialize(Serializable serializable) throws IOException, ClassNotFoundException { final ByteArrayOutputStream output = new ByteArrayOutputStream(); TransportFormat.SERIALIZED.writeSerializableTo(serializable, output); final ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray()); return TransportFormat.SERIALIZED.readSerializableFrom(input); } /** Test. * @throws IOException e * @throws ClassNotFoundException e */ @Test public void testReadXml() throws IOException, ClassNotFoundException { final Counter counter = createCounter(); final ByteArrayOutputStream output = new ByteArrayOutputStream(); TransportFormat.XML.writeSerializableTo(counter, output); final ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray()); final Counter after = (Counter) TransportFormat.XML.readSerializableFrom(input); assertEquals("counter", counter.toString(), after.toString()); } /** Test. */ @Test public void testReadJson() { Exception result = null; try { TransportFormat.JSON.readSerializableFrom(new ByteArrayInputStream(new byte[0])); } catch (final Exception e) { result = e; } // la désérialisation d'un flux json n'est pas possible assertNotNull("readJson", result); } /** Test. */ @Test public void testGetCode() { for (final TransportFormat tf : TransportFormat.values()) { assertSame("same", tf, TransportFormat.valueOfIgnoreCase(tf.getCode())); } } /** Test. */ @Test public void testGetMimeType() { for (final TransportFormat tf : TransportFormat.values()) { assertNotNull("mimeType", tf.getMimeType()); } } /** Test. * @throws IOException e */ @Test public void testPump() throws IOException { final Counter counter = createCounter(); final ByteArrayOutputStream output = new ByteArrayOutputStream(); TransportFormat.XML.writeSerializableTo(counter, output); final byte[] byteArray = output.toByteArray(); final ByteArrayInputStream input = new ByteArrayInputStream(byteArray); output.reset(); InputOutput.pump(input, output); assertArrayEquals("array equals", byteArray, output.toByteArray()); } /** Test. */ @Test public void testIsATransportFormat() { final String message = "isATransportFormat"; assertFalse(message, TransportFormat.isATransportFormat(null)); for (final TransportFormat transportFormat : TransportFormat.values()) { final String format = transportFormat.toString(); assertTrue(message, TransportFormat.isATransportFormat(format)); assertTrue(message, TransportFormat.isATransportFormat(format.toLowerCase(Locale.getDefault()))); assertTrue(message, TransportFormat.isATransportFormat(format + ' ')); } assertFalse(message, TransportFormat.isATransportFormat("n'importe quoi")); } }
javamelody/javamelody
javamelody-core/src/test/java/net/bull/javamelody/internal/model/TestTransportFormat.java
Java
apache-2.0
6,871
using UnityEngine; using UnityEditor; using System.IO; namespace NobleMuffins.SoundtrackPlus { public class TrackConfigurationEditor : Editor { [MenuItem("Assets/Create/Music Track Configuration")] public static void CreateInstance() { CreateAsset<MusicTrackConfiguration>("Music Track"); } public static void CreateAsset<T> (string typeName = null) where T : ScriptableObject { T asset = ScriptableObject.CreateInstance<T> (); string path = AssetDatabase.GetAssetPath (Selection.activeObject); if (path == "") { path = "Assets"; } else if (Path.GetExtension (path) != "") { path = path.Replace (Path.GetFileName (AssetDatabase.GetAssetPath (Selection.activeObject)), ""); } string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath (path + "/New " + (typeName ?? typeof(T).ToString()) + ".asset"); AssetDatabase.CreateAsset (asset, assetPathAndName); AssetDatabase.SaveAssets (); EditorUtility.FocusProjectWindow (); Selection.activeObject = asset; } } }
NobleMuffins/SoundtrackController
Guts/Editor/TrackConfigurationEditor.cs
C#
apache-2.0
1,056
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.impl.source; import com.intellij.psi.*; import com.intellij.psi.impl.source.tree.CompositePsiElement; import com.intellij.psi.impl.source.tree.JavaElementType; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import javax.annotation.Nonnull; public class PsiJavaModuleReferenceElementImpl extends CompositePsiElement implements PsiJavaModuleReferenceElement { public PsiJavaModuleReferenceElementImpl() { super(JavaElementType.MODULE_REFERENCE); } @Nonnull @Override public String getReferenceText() { StringBuilder sb = new StringBuilder(); for(PsiElement e = getFirstChild(); e != null; e = e.getNextSibling()) { if(!(e instanceof PsiWhiteSpace) && !(e instanceof PsiComment)) { sb.append(e.getText()); } } return sb.toString(); } @Override public PsiJavaModuleReference getReference() { if(getParent() instanceof PsiJavaModule && !(getContainingFile() instanceof JavaDummyHolder)) { return null; // module name identifier is not a reference } else { return CachedValuesManager.getCachedValue(this, () -> CachedValueProvider.Result.create(new PsiJavaModuleReferenceImpl(this), this)); } } @Override public void accept(@Nonnull PsiElementVisitor visitor) { if(visitor instanceof JavaElementVisitor) { ((JavaElementVisitor) visitor).visitModuleReferenceElement(this); } else { visitor.visitElement(this); } } @Override public String toString() { return "PsiJavaModuleReference"; } }
consulo/consulo-java
java-psi-impl/src/main/java/com/intellij/psi/impl/source/PsiJavaModuleReferenceElementImpl.java
Java
apache-2.0
1,689
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("IconifyXamarin.Meteocons")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IconifyXamarin.Meteocons")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Mitch528/IconifyXamarin
IconifyXamarin.Meteocons/Properties/AssemblyInfo.cs
C#
apache-2.0
1,088
using System; using AutoFrame.AutoImplement.Attribute; using AutoFrame.AutoImplement.Model; namespace AutoFrame.AutoImplement.Utility.Mapper.Property { internal interface IPropertyAttributeMapper { PropertyMapping BuildPropertyMapping(AutoImplementPropertyAttribute propertyAttribute, Type propertyType, Type interfaceType, string propertyName); } }
AutoFrame/AutoImplement
src/AutoFrame.AutoImplement/AutoFrame.AutoImplement/Utility/Mapper/Property/IPropertyAttributeMapper.cs
C#
apache-2.0
386
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.UseCoalesceExpression { internal abstract class AbstractUseCoalesceExpressionForNullableDiagnosticAnalyzer< TSyntaxKind, TExpressionSyntax, TConditionalExpressionSyntax, TBinaryExpressionSyntax, TMemberAccessExpression, TPrefixUnaryExpressionSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TSyntaxKind : struct where TExpressionSyntax : SyntaxNode where TConditionalExpressionSyntax : TExpressionSyntax where TBinaryExpressionSyntax : TExpressionSyntax where TMemberAccessExpression : TExpressionSyntax where TPrefixUnaryExpressionSyntax : TExpressionSyntax { protected AbstractUseCoalesceExpressionForNullableDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseCoalesceExpressionForNullableDiagnosticId, CodeStyleOptions.PreferCoalesceExpression, new LocalizableResourceString(nameof(FeaturesResources.Use_coalesce_expression), FeaturesResources.ResourceManager, typeof(FeaturesResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected abstract TSyntaxKind GetSyntaxKindToAnalyze(); protected abstract ISyntaxFactsService GetSyntaxFactsService(); protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, GetSyntaxKindToAnalyze()); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var conditionalExpression = (TConditionalExpressionSyntax)context.Node; var syntaxTree = context.Node.SyntaxTree; var cancellationToken = context.CancellationToken; var optionSet = context.Options.GetDocumentOptionSetAsync(syntaxTree, cancellationToken).GetAwaiter().GetResult(); if (optionSet == null) { return; } var option = optionSet.GetOption(CodeStyleOptions.PreferCoalesceExpression, conditionalExpression.Language); if (!option.Value) { return; } var syntaxFacts = GetSyntaxFactsService(); syntaxFacts.GetPartsOfConditionalExpression( conditionalExpression, out var conditionNode, out var whenTrueNodeHigh, out var whenFalseNodeHigh); conditionNode = syntaxFacts.WalkDownParentheses(conditionNode); var whenTrueNodeLow = syntaxFacts.WalkDownParentheses(whenTrueNodeHigh); var whenFalseNodeLow = syntaxFacts.WalkDownParentheses(whenFalseNodeHigh); var notHasValueExpression = false; if (syntaxFacts.IsLogicalNotExpression(conditionNode)) { notHasValueExpression = true; conditionNode = syntaxFacts.GetOperandOfPrefixUnaryExpression(conditionNode); } if (!(conditionNode is TMemberAccessExpression conditionMemberAccess)) { return; } syntaxFacts.GetPartsOfMemberAccessExpression(conditionMemberAccess, out var conditionExpression, out var conditionSimpleName); syntaxFacts.GetNameAndArityOfSimpleName(conditionSimpleName, out var conditionName, out var unused); if (conditionName != nameof(Nullable<int>.HasValue)) { return; } var whenPartToCheck = notHasValueExpression ? whenFalseNodeLow : whenTrueNodeLow; if (!(whenPartToCheck is TMemberAccessExpression whenPartMemberAccess)) { return; } syntaxFacts.GetPartsOfMemberAccessExpression(whenPartMemberAccess, out var whenPartExpression, out var whenPartSimpleName); syntaxFacts.GetNameAndArityOfSimpleName(whenPartSimpleName, out var whenPartName, out unused); if (whenPartName != nameof(Nullable<int>.Value)) { return; } if (!syntaxFacts.AreEquivalent(conditionExpression, whenPartExpression)) { return; } // Syntactically this looks like something we can simplify. Make sure we're // actually looking at something Nullable (and not some type that uses a similar // syntactic pattern). var semanticModel = context.SemanticModel; var nullableType = semanticModel.Compilation.GetTypeByMetadataName(typeof(Nullable<>).FullName); if (nullableType == null) { return; } var type = semanticModel.GetTypeInfo(conditionExpression, cancellationToken); if (!nullableType.Equals(type.Type?.OriginalDefinition)) { return; } var whenPartToKeep = notHasValueExpression ? whenTrueNodeHigh : whenFalseNodeHigh; var locations = ImmutableArray.Create( conditionalExpression.GetLocation(), conditionExpression.GetLocation(), whenPartToKeep.GetLocation()); context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, conditionalExpression.GetLocation(), option.Notification.Severity, locations, properties: null)); } } }
aelij/roslyn
src/Features/Core/Portable/UseCoalesceExpression/AbstractUseCoalesceExpressionForNullableDiagnosticAnalyzer.cs
C#
apache-2.0
5,853
/** * @file * @brief Contains a class which represents the splash screen. * * @section LICENSE * * Copyright © 2013 Ebenezer Edelman and others (see the contributors.txt file for a full list). * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this software * 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 tk.ebenezeredelman.inferno.core.splash; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.utils.Timer; import tk.ebenezeredelman.inferno.core.Constants; import tk.ebenezeredelman.inferno.core.engine.EventManager; import tk.ebenezeredelman.inferno.core.engine.Screen; import tk.ebenezeredelman.inferno.core.engine.ScreenManager; import tk.ebenezeredelman.inferno.core.game.events.LevelChangeEvent; import tk.ebenezeredelman.inferno.core.Screens; /** * @brief Represents the splash screen. */ public final class SplashScreen extends Screen { OrthographicCamera m_camera; SpriteBatch m_spriteBatch; Texture m_libgdxLogo; int m_width; int m_height; @Override public void create() { m_camera = new OrthographicCamera(); m_spriteBatch = new SpriteBatch(); m_libgdxLogo = new Texture(Gdx.files.internal("sprites/logos/libgdx.png")); m_width = Gdx.graphics.getWidth(); m_height = Gdx.graphics.getHeight(); super.create(); } @Override public void dispose() { m_libgdxLogo.dispose(); m_spriteBatch.dispose(); super.dispose(); } @Override public void show() { // Switch to gameplay screen after three seconds. Timer.schedule(new Timer.Task() { @Override public void run() { ScreenManager.show(Screens.GAME); EventManager.notify(new LevelChangeEvent(Constants.GAME_DEFAULT_LEVEL)); } }, 3.0f); super.show(); } @Override public void render(float delta) { // Clear the screen. Gdx.gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); // Begin the sprite batch. m_spriteBatch.setProjectionMatrix(m_camera.combined); m_spriteBatch.begin(); // Draw the libgdx logo in the centre of the screen. m_spriteBatch.draw( m_libgdxLogo, m_width / 2.0f - m_libgdxLogo.getWidth() / 2.0f, m_height / 2.0f - m_libgdxLogo.getHeight() / 2.0f); // End the sprite batch. m_spriteBatch.end(); super.render(delta); } @Override public void resize(int width, int height) { m_camera.setToOrtho(false, width, height); m_camera.update(); m_width = width; m_height = height; super.resize(width, height); } }
EbenezerEdelman/inferno
core/src/main/java/tk/ebenezeredelman/inferno/core/splash/SplashScreen.java
Java
apache-2.0
3,080
/* * Copyright 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 software.amazon.awssdk.http.nio.netty.internal.http2; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.HTTP2_CONNECTION; import static software.amazon.awssdk.http.nio.netty.internal.http2.utils.Http2TestUtils.newHttp2Channel; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.pool.ChannelPool; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http2.Http2Connection; import io.netty.handler.codec.http2.Http2LocalFlowController; import io.netty.handler.codec.http2.Http2Stream; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.FailedFuture; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Promise; import java.io.IOException; import java.util.Collections; import java.util.concurrent.CompletableFuture; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mockito; import software.amazon.awssdk.http.HttpMetric; import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricCollector; /** * Tests for {@link Http2MultiplexedChannelPool}. */ public class Http2MultiplexedChannelPoolTest { private static EventLoopGroup loopGroup; @BeforeClass public static void setup() { loopGroup = new NioEventLoopGroup(4); } @AfterClass public static void teardown() { loopGroup.shutdownGracefully().awaitUninterruptibly(); } @Test public void failedConnectionAcquireNotifiesPromise() throws InterruptedException { IOException exception = new IOException(); ChannelPool connectionPool = mock(ChannelPool.class); when(connectionPool.acquire()).thenReturn(new FailedFuture<>(loopGroup.next(), exception)); ChannelPool pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup.next(), null); Future<Channel> acquirePromise = pool.acquire().await(); assertThat(acquirePromise.isSuccess()).isFalse(); assertThat(acquirePromise.cause()).isEqualTo(exception); } @Test public void releaseParentChannelIfReleasingLastChildChannelOnGoAwayChannel() { SocketChannel channel = new NioSocketChannel(); try { loopGroup.register(channel).awaitUninterruptibly(); ChannelPool connectionPool = mock(ChannelPool.class); ArgumentCaptor<Promise> releasePromise = ArgumentCaptor.forClass(Promise.class); when(connectionPool.release(eq(channel), releasePromise.capture())).thenAnswer(invocation -> { Promise<?> promise = releasePromise.getValue(); promise.setSuccess(null); return promise; }); MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null); Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.singleton(record), null); h2Pool.close(); InOrder inOrder = Mockito.inOrder(connectionPool); inOrder.verify(connectionPool).release(eq(channel), isA(Promise.class)); inOrder.verify(connectionPool).close(); } finally { channel.close().awaitUninterruptibly(); } } @Test public void acquireAfterCloseFails() throws InterruptedException { ChannelPool connectionPool = mock(ChannelPool.class); Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup.next(), null); h2Pool.close(); Future<Channel> acquireResult = h2Pool.acquire().await(); assertThat(acquireResult.isSuccess()).isFalse(); assertThat(acquireResult.cause()).isInstanceOf(IOException.class); } @Test public void closeWaitsForConnectionToBeReleasedBeforeClosingConnectionPool() { SocketChannel channel = new NioSocketChannel(); try { loopGroup.register(channel).awaitUninterruptibly(); ChannelPool connectionPool = mock(ChannelPool.class); ArgumentCaptor<Promise> releasePromise = ArgumentCaptor.forClass(Promise.class); when(connectionPool.release(eq(channel), releasePromise.capture())).thenAnswer(invocation -> { Promise<?> promise = releasePromise.getValue(); promise.setSuccess(null); return promise; }); MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null); Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.singleton(record), null); h2Pool.close(); InOrder inOrder = Mockito.inOrder(connectionPool); inOrder.verify(connectionPool).release(eq(channel), isA(Promise.class)); inOrder.verify(connectionPool).close(); } finally { channel.close().awaitUninterruptibly(); } } @Test public void acquire_shouldAcquireAgainIfExistingNotReusable() throws Exception { Channel channel = new EmbeddedChannel(); try { ChannelPool connectionPool = Mockito.mock(ChannelPool.class); loopGroup.register(channel).awaitUninterruptibly(); Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next()); channelPromise.setSuccess(channel); Mockito.when(connectionPool.acquire()).thenReturn(channelPromise); Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.emptySet(), null); h2Pool.acquire().awaitUninterruptibly(); h2Pool.acquire().awaitUninterruptibly(); Mockito.verify(connectionPool, Mockito.times(2)).acquire(); } finally { channel.close(); } } @Test(timeout = 5_000) public void interruptDuringClosePreservesFlag() throws InterruptedException { SocketChannel channel = new NioSocketChannel(); try { loopGroup.register(channel).awaitUninterruptibly(); Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next()); channelPromise.setSuccess(channel); ChannelPool connectionPool = mock(ChannelPool.class); Promise<Void> releasePromise = Mockito.spy(new DefaultPromise<>(loopGroup.next())); when(connectionPool.release(eq(channel))).thenReturn(releasePromise); MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null); Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.singleton(record), null); CompletableFuture<Boolean> interrupteFlagPreserved = new CompletableFuture<>(); Thread t = new Thread(() -> { try { h2Pool.close(); } catch (Exception e) { if (e.getCause() instanceof InterruptedException && Thread.currentThread().isInterrupted()) { interrupteFlagPreserved.complete(true); } } }); t.start(); t.interrupt(); t.join(); assertThat(interrupteFlagPreserved.join()).isTrue(); } finally { channel.close().awaitUninterruptibly(); } } @Test public void acquire_shouldExpandConnectionWindowSizeProportionally() { int maxConcurrentStream = 3; EmbeddedChannel channel = newHttp2Channel(); channel.attr(ChannelAttributeKey.MAX_CONCURRENT_STREAMS).set((long) maxConcurrentStream); try { ChannelPool connectionPool = Mockito.mock(ChannelPool.class); loopGroup.register(channel).awaitUninterruptibly(); Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next()); channelPromise.setSuccess(channel); Mockito.when(connectionPool.acquire()).thenReturn(channelPromise); Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.emptySet(), null); Future<Channel> acquire = h2Pool.acquire(); acquire.awaitUninterruptibly(); channel.runPendingTasks(); Http2Connection http2Connection = channel.attr(HTTP2_CONNECTION).get(); Http2LocalFlowController flowController = http2Connection.local().flowController(); System.out.println(flowController.initialWindowSize()); Http2Stream connectionStream = http2Connection.stream(0); // 1_048_576 (initial configured window size), 65535 (configured initial window size) // (1048576 - 65535) *2 + 65535 = 2031617 assertThat(flowController.windowSize(connectionStream)).isEqualTo(2031617); // 2031617 + 1048576 (configured initial window size) = 3080193 assertThat(flowController.initialWindowSize(connectionStream)).isEqualTo(3080193); // acquire again h2Pool.acquire().awaitUninterruptibly(); channel.runPendingTasks(); // 3080193 + 1048576 (configured initial window size) = 4128769 assertThat(flowController.initialWindowSize(connectionStream)).isEqualTo(4128769); Mockito.verify(connectionPool, Mockito.times(1)).acquire(); } finally { channel.close(); } } @Test public void metricsShouldSumAllChildChannels() throws InterruptedException { int maxConcurrentStream = 2; EmbeddedChannel channel1 = newHttp2Channel(); EmbeddedChannel channel2 = newHttp2Channel(); channel1.attr(ChannelAttributeKey.MAX_CONCURRENT_STREAMS).set((long) maxConcurrentStream); channel2.attr(ChannelAttributeKey.MAX_CONCURRENT_STREAMS).set((long) maxConcurrentStream); try { ChannelPool connectionPool = Mockito.mock(ChannelPool.class); loopGroup.register(channel1).awaitUninterruptibly(); loopGroup.register(channel2).awaitUninterruptibly(); Promise<Channel> channel1Promise = new DefaultPromise<>(loopGroup.next()); Promise<Channel> channel2Promise = new DefaultPromise<>(loopGroup.next()); channel1Promise.setSuccess(channel1); channel2Promise.setSuccess(channel2); Mockito.when(connectionPool.acquire()).thenReturn(channel1Promise, channel2Promise); Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, Http2MultiplexedChannelPoolTest.loopGroup, Collections.emptySet(), null); MetricCollection metrics; metrics = getMetrics(h2Pool); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(0); doAcquire(channel1, channel2, h2Pool); metrics = getMetrics(h2Pool); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(1); doAcquire(channel1, channel2, h2Pool); metrics = getMetrics(h2Pool); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(0); doAcquire(channel1, channel2, h2Pool); metrics = getMetrics(h2Pool); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(1); Channel lastAcquire = doAcquire(channel1, channel2, h2Pool); metrics = getMetrics(h2Pool); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(0); lastAcquire.close(); h2Pool.release(lastAcquire).awaitUninterruptibly(); metrics = getMetrics(h2Pool); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(1); channel1.close(); h2Pool.release(channel1); metrics = getMetrics(h2Pool); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(1); channel2.close(); metrics = getMetrics(h2Pool); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(0); } finally { channel1.close(); channel2.close(); } } private Channel doAcquire(EmbeddedChannel channel1, EmbeddedChannel channel2, Http2MultiplexedChannelPool h2Pool) { Future<Channel> acquire = h2Pool.acquire(); acquire.awaitUninterruptibly(); runPendingTasks(channel1, channel2); return acquire.getNow(); } private void runPendingTasks(EmbeddedChannel channel1, EmbeddedChannel channel2) { channel1.runPendingTasks(); channel2.runPendingTasks(); } private MetricCollection getMetrics(Http2MultiplexedChannelPool h2Pool) { MetricCollector metricCollector = MetricCollector.create("test"); h2Pool.collectChannelPoolMetrics(metricCollector); return metricCollector.collect(); } }
aws/aws-sdk-java-v2
http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2MultiplexedChannelPoolTest.java
Java
apache-2.0
14,878
#include "ZulipWindow.h" #include "ZulipApplication.h" #include "Config.h" #include "Logger.h" #include <QDebug> int main(int argc, char *argv[]) { ZulipApplication a(argc, argv); a.setApplicationName("Zulip Desktop"); a.setOrganizationName("Zulip"); a.setOrganizationDomain("zulip.org"); a.setApplicationVersion(ZULIP_VERSION_STRING); Logging::setupLogging(); if (argc == 2 && QString(argv[1]) == QString("--debug")) { a.setDebugMode(true); } ZulipWindow w; a.setMainWindow(&w); QSettings settings; int numerOfDomains = settings.beginReadArray("InstanceDomains"); settings.endArray(); QString settingsDomain = settings.value("Domain").toString(); // Priority order: // 1. --site command-line flag // 2. Domain= explicit setting // 3. Last domain in the InstanceDomains list QString domain; if (argc == 3 && QString(argv[1]) == QString("--site")) { domain = argv[2]; } else if (!settingsDomain.isEmpty()) { domain = settingsDomain; } else if (numerOfDomains > 0) { settings.beginReadArray("InstanceDomains"); settings.setArrayIndex(numerOfDomains-1); domain = settings.value("url").toString(); settings.endArray(); } // If we still don't have a domain to use, prompt for one if (!domain.isEmpty()) { w.setUrl(QUrl(domain)); a.setExplicitDomain(domain); w.show(); } else { // Hide tray icon until the domain has been selected w.trayIcon()->hide(); a.askForDomain(true); } return a.exec(); }
zofuthan/zulip-desktop
src/main.cpp
C++
apache-2.0
1,618
/* (c) 2014 LinkedIn Corp. 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. */ package com.linkedin.cubert.operator; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.node.ArrayNode; import org.codehaus.jackson.node.ObjectNode; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.linkedin.cubert.block.Block; import com.linkedin.cubert.block.BlockProperties; import com.linkedin.cubert.block.BlockSchema; import com.linkedin.cubert.block.TupleOperatorBlock; import com.linkedin.cubert.operator.CombineOperator; import com.linkedin.cubert.operator.DictionaryEncodeOperator; import com.linkedin.cubert.operator.GroupByOperator; import com.linkedin.cubert.operator.HashJoinOperator; import com.linkedin.cubert.operator.MergeJoinOperator; import com.linkedin.cubert.operator.PhaseContext; import com.linkedin.cubert.operator.SortOperator; import com.linkedin.cubert.operator.TupleOperator; import com.linkedin.cubert.plan.physical.CubertStrings; public class TestOperators { @BeforeClass public void setUp() throws JsonGenerationException, JsonMappingException, IOException { } @SuppressWarnings("rawtypes") @BeforeTest void setupConf() throws IOException { Configuration conf = new JobConf(); conf.setBoolean(CubertStrings.USE_COMPACT_SERIALIZATION, false); PhaseContext.create((Mapper.Context) null, conf); PhaseContext.create((Reducer.Context) null, conf); } public void testDictionaryEncoding() throws IOException, InterruptedException { // create dictionary block Object[][] dictRows = { { 1000, 100, 1 }, { 1000, 101, 2 } }; Block dictionary = new ArrayBlock(Arrays.asList(dictRows), new String[] { "colname", "colvalue", "code" }); // create data block Object[][] dataRows = { { 100, 10 }, { 100, 11 }, { 101, 10 } }; Block dataBlock = new ArrayBlock(Arrays.asList(dataRows), new String[] { "1000", "a" }); // create operator Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", dictionary); input.put("block2", dataBlock); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("dictionary", "block1"); TupleOperator operator = new DictionaryEncodeOperator(); BlockProperties props = new BlockProperties(null, new BlockSchema("INT 1000, INT a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); Object[][] expected = { { 1, 10 }, { 1, 11 }, { 2, 10 } }; ArrayBlock.assertData(output, expected, new String[] { "1000", "a" }); } @Test // when there are multiple rows in one table public void testLeftHashJoin() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0 }, { 2 }, { 2 }, { 5 }, { 10 }, { 100 } }; Object[][] rows2 = { { 1 }, { 2 }, { 7 }, { 9 }, { 100 }, { 100 } }; Object[][] expected = { { 0, null }, { 2, 2 }, { 2, 2 }, { 5, null }, { 10, null }, { 100, 100 }, { 100, 100 } }; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }); Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a" }); TupleOperator operator = new HashJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("leftJoinKeys", "a"); node.put("rightJoinKeys", "a"); node.put("leftBlock", "block1"); node.put("rightBlock", "block2"); node.put("joinType", "left outer"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.a" }); } @Test // when there are multiple rows in one table public void testLeftMergeJoin() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0 }, { 2 }, { 2 }, { 5 }, { 10 }, { 100 } }; Object[][] rows2 = { { 1 }, { 2 }, { 7 }, { 9 }, { 100 }, { 100 } }; Object[][] expected = { { 0, null }, { 2, 2 }, { 2, 2 }, { 5, null }, { 10, null }, { 100, 100 }, { 100, 100 } }; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }); Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a" }); TupleOperator operator = new MergeJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("leftCubeColumns", "a"); node.put("rightCubeColumns", "a"); node.put("leftBlock", "block1"); node.put("rightBlock", "block2"); node.put("joinType", "left outer"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.a" }); } @Test // when there are multiple rows in one table public void testRightMergeJoin() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0 }, { 2 }, { 2 }, { 5 }, { 10 }, { 100 } }; Object[][] rows2 = { { 1 }, { 2 }, { 7 }, { 9 }, { 100 }, { 100 } }; Object[][] expected = { { null, 1 }, { 2, 2 }, { 2, 2 }, { null, 7 }, { null, 9 }, { 100, 100 }, { 100, 100 } }; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }); Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a" }); TupleOperator operator = new MergeJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("leftCubeColumns", "a"); node.put("rightCubeColumns", "a"); node.put("leftBlock", "block1"); node.put("rightBlock", "block2"); node.put("joinType", "right outer"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.a" }); } // @Test // when there are multiple rows in one table public void testRightHashJoin() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0 }, { 2 }, { 2 }, { 5 }, { 10 }, { 100 } }; Object[][] rows2 = { { 1 }, { 2 }, { 7 }, { 9 }, { 100 }, { 100 } }; Object[][] expected = { { 2, 2 }, { 2, 2 }, { 100, 100 }, { 100, 100 }, { null, 7 }, { null, 1 }, { null, 9 }, }; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }); Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a" }); TupleOperator operator = new HashJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("leftJoinKeys", "a"); node.put("rightJoinKeys", "a"); node.put("leftBlock", "block1"); node.put("rightBlock", "block2"); node.put("joinType", "right outer"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.a" }); } @Test // when there are multiple rows in one table public void testMergeJoinFullOuter() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0 }, { 2 }, { 2 }, { 5 }, { 10 }, { 100 } }; Object[][] rows2 = { { 1 }, { 2 }, { 7 }, { 9 }, { 100 }, { 100 } }; Object[][] expected = { { 0, null }, { null, 1 }, { 2, 2 }, { 2, 2 }, { 5, null }, { null, 7 }, { null, 9 }, { 10, null }, { 100, 100 }, { 100, 100 } }; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }); Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a" }); TupleOperator operator = new MergeJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("leftCubeColumns", "a"); node.put("rightCubeColumns", "a"); node.put("leftBlock", "block1"); node.put("rightBlock", "block2"); node.put("joinType", "full outer"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.a" }); System.out.println("Successfully tested MERGE JOIN FULL OUTER"); } @Test public void testMergeJoinFullOuterEmptyRight() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0 }, { 2 }, { 2 }, { 5 }, { 10 }, { 100 } }; Object[][] rows2 = {}; Object[][] expected = { { 0, null }, { 2, null }, { 2, null }, { 5, null }, { 10, null }, { 100, null } }; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }); Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a" }); TupleOperator operator = new MergeJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("leftCubeColumns", "a"); node.put("rightCubeColumns", "a"); node.put("leftBlock", "block1"); node.put("rightBlock", "block2"); node.put("joinType", "full outer"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.a" }); System.out.println("Successfully tested MERGE JOIN FULL OUTER empty block"); } @Test public void testGroupByWith2Dimensions() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0, 0, 100 }, { 0, 0, 100 }, { 2, 2, 100 }, { 2, 5, 100 }, { 5, 6, 100 }, { 6, 6, 100 } }; Block block = new ArrayBlock(Arrays.asList(rows1), new String[] { "a", "b", "c" }, 1); Map<String, Block> input = new HashMap<String, Block>(); input.put("block", block); TupleOperator operator = new GroupByOperator(); ObjectMapper mapper = new ObjectMapper(); ObjectNode json = mapper.createObjectNode(); json.put("input", "block"); ArrayNode anode = mapper.createArrayNode(); anode.add("a"); anode.add("b"); json.put("groupBy", anode); anode = mapper.createArrayNode(); ObjectNode onode = mapper.createObjectNode(); onode.put("type", "SUM"); onode.put("input", "c"); onode.put("output", "sum"); anode.add(onode); json.put("aggregates", anode); BlockProperties props = new BlockProperties(null, new BlockSchema("INT a, INT b, INT sum"), (BlockProperties) null); operator.setInput(input, json, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, new Object[][] { { 0, 0, 200 }, { 2, 2, 100 }, { 2, 5, 100 }, { 5, 6, 100 }, { 6, 6, 100 } }, new String[] { "a", "b", "sum" }); } @Test public void testGroupByDedup() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0, 0 }, { 0, 1 }, { 0, 1 }, { 5, 6 }, { 5, 6 }, { 100, 10 } }; Block block = new ArrayBlock(Arrays.asList(rows1), new String[] { "a", "b" }, 1); Map<String, Block> input = new HashMap<String, Block>(); input.put("block", block); TupleOperator operator = new GroupByOperator(); ObjectMapper mapper = new ObjectMapper(); ObjectNode json = mapper.createObjectNode(); json.put("input", "block"); ArrayNode anode = mapper.createArrayNode(); anode.add("a"); anode.add("b"); json.put("groupBy", anode); BlockProperties props = new BlockProperties(null, new BlockSchema("INT a, INT b"), (BlockProperties) null); operator.setInput(input, json, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, new Object[][] { { 0, 0 }, { 0, 1 }, { 5, 6 }, { 100, 10 } }, new String[] { "a", "b" }); } @Test public void testCombinedBlockRightRunsout() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 3 }, { 5 }, { 10 } }; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }, 1); Object[][] rows2 = { { 2 }, { 7 }, { 9 } }; Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a" }, 1); TupleOperator operator = new CombineOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("cube1", block1); input.put("cube2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); JsonNode ct = mapper.readValue("[\"a\"]", JsonNode.class); node.put("pivotBy", ct); BlockProperties props = new BlockProperties(null, new BlockSchema("INT a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, new Object[][] { { 2 }, { 3 }, { 5 }, { 7 }, { 9 }, { 10 } }, new String[] { "a" }); } @Test public void testCombinedBlockLeftRunsout() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 2 }, { 7 }, { 9 } }; Object[][] rows2 = { { 3 }, { 5 }, { 10 } }; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }, 1); Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a" }, 1); TupleOperator operator = new CombineOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("cube1", block1); input.put("cube2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); JsonNode ct = mapper.readValue("[\"a\"]", JsonNode.class); node.put("pivotBy", ct); BlockProperties props = new BlockProperties(null, new BlockSchema("INT a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, new Object[][] { { 2 }, { 3 }, { 5 }, { 7 }, { 9 }, { 10 } }, new String[] { "a" }); } @Test // when there are multiple rows in one table public void testHashJoin1() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 2 }, { 2 }, { 7 }, { 9 } }; Object[][] rows2 = { { 2 }, { 7 }, { 9 } }; Object[][] expected = { { 2, 2 }, { 2, 2 }, { 7, 7 }, { 9, 9 } }; ArrayBlock block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }); ArrayBlock block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a" }); TupleOperator operator = new HashJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("leftJoinKeys", "a"); node.put("rightJoinKeys", "a"); node.put("leftBlock", "block1"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.a" }); } @Test // when there are multiple rows in one table public void testHashJoin2() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 2 }, { 2 }, { 5 }, { 10 } }; Object[][] rows2 = { { 1 }, { 7 }, { 9 } }; Object[][] expected = {}; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }); Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a" }); TupleOperator operator = new HashJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("leftJoinKeys", "a"); node.put("rightJoinKeys", "a"); node.put("leftBlock", "block1"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.a" }); } @Test // when there are multiple rows in one table public void testHashJoin3() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0 }, { 2 }, { 2 }, { 5 }, { 10 } }; Object[][] rows2 = { { 1 }, { 2 }, { 2 }, { 7 }, { 9 } }; Object[][] expected = { { 2, 2 }, { 2, 2 }, { 2, 2 }, { 2, 2 } }; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }); Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a" }); TupleOperator operator = new HashJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("leftJoinKeys", "a"); node.put("rightJoinKeys", "a"); node.put("leftBlock", "block1"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.a" }); } @Test // when there are multiple rows in one table public void testHashJoin4() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0 }, { 2 }, { 2 }, { 5 }, { 10 }, { 100 } }; Object[][] rows2 = { { 1 }, { 2 }, { 7 }, { 9 }, { 100 }, { 100 } }; Object[][] expected = { { 2, 2 }, { 2, 2 }, { 100, 100 }, { 100, 100 } }; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }); Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a" }); TupleOperator operator = new HashJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("leftJoinKeys", "a"); node.put("rightJoinKeys", "a"); node.put("leftBlock", "block1"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.a" }); } @Test // testing multiple join keys public void testHashJoinMultipleJoinKeys() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0, 1 }, { 2, 1 }, { 2, 2 }, { 5, 1 }, { 10, 1 }, { 100, 1 } }; Object[][] rows2 = { { 1, 1 }, { 2, 0 }, { 2, 1 }, { 5, 1 }, { 100, 2 }, { 100, 3 } }; Object[][] expected = { { 2, 1, 2, 1 }, { 5, 1, 5, 1 } }; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a", "b" }); Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "c", "a" }); TupleOperator operator = new HashJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); ArrayNode lkeys = mapper.createArrayNode(); lkeys.add("a"); lkeys.add("b"); node.put("leftJoinKeys", lkeys); ArrayNode rkeys = mapper.createArrayNode(); rkeys.add("c"); rkeys.add("a"); node.put("rightJoinKeys", rkeys); node.put("leftBlock", "block1"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block1___b, INT block2___c, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.a" }); } @Test // testing multiple join keys public void testHashJoinMultipleJoinKeysInDifferentOrder() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0, 1 }, { 2, 1 }, { 2, 2 }, { 5, 1 }, { 10, 1 }, { 100, 1 } }; Object[][] rows2 = { { 1, 1 }, { 2, 0 }, { 2, 1 }, { 5, 1 }, { 100, 2 }, { 100, 3 } }; Object[][] expected = { { 0, 1, 2, 0 }, { 2, 1, 100, 2 }, { 2, 2, 100, 2 } }; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a", "b" }); Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a", "c" }); TupleOperator operator = new HashJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); ArrayNode lkeys = mapper.createArrayNode(); lkeys.add("a"); node.put("leftJoinKeys", lkeys); ArrayNode rkeys = mapper.createArrayNode(); rkeys.add("c"); node.put("rightJoinKeys", rkeys); node.put("leftBlock", "block1"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block1___b, INT block2___c, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.c" }); } @Test // testing multiple join keys public void testMergeJoinMultipleJoinKeys() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0, 1 }, { 2, 1 }, { 2, 2 }, { 5, 1 }, { 10, 1 }, { 100, 1 } }; Object[][] rows2 = { { 1, 1 }, { 2, 0 }, { 2, 1 }, { 5, 1 }, { 100, 2 }, { 100, 3 } }; Object[][] expected = { { 2, 1, 2, 1 }, { 5, 1, 5, 1 } }; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a", "b" }); Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "c", "a" }); TupleOperator operator = new MergeJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); ArrayNode lkeys = mapper.createArrayNode(); lkeys.add("a"); lkeys.add("b"); node.put("leftCubeColumns", lkeys); ArrayNode rkeys = mapper.createArrayNode(); rkeys.add("c"); rkeys.add("a"); node.put("rightCubeColumns", rkeys); node.put("leftBlock", "block1"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block1___b, INT block2___c, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.a" }); } @Test // when there are multiple rows in one table public void testMergeJoin1() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 2 }, { 2 }, { 7 }, { 9 } }; Object[][] rows2 = { { 2 }, { 7 }, { 9 } }; Object[][] expected = { { 2, 2 }, { 2, 2 }, { 7, 7 }, { 9, 9 } }; ArrayBlock block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }); ArrayBlock block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a" }); TupleOperator operator = new MergeJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("leftCubeColumns", "a"); node.put("rightCubeColumns", "a"); node.put("leftBlock", "block1"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.a" }); } @Test // when there are multiple rows in one table public void testMergeJoin2() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 2 }, { 2 }, { 5 }, { 10 } }; Object[][] rows2 = { { 1 }, { 7 }, { 9 } }; Object[][] expected = {}; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }); Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a" }); TupleOperator operator = new MergeJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("leftCubeColumns", "a"); node.put("rightCubeColumns", "a"); node.put("leftBlock", "block1"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.a" }); } @Test // when there are multiple rows in one table public void testMergeJoin3() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0 }, { 2 }, { 2 }, { 5 }, { 10 } }; Object[][] rows2 = { { 1 }, { 2 }, { 2 }, { 7 }, { 9 } }; Object[][] expected = { { 2, 2 }, { 2, 2 }, { 2, 2 }, { 2, 2 } }; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }); Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a" }); TupleOperator operator = new MergeJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("leftCubeColumns", "a"); node.put("rightCubeColumns", "a"); node.put("leftBlock", "block1"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.a" }); } @Test // when there are multiple rows in one table public void testMergeJoin4() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0 }, { 2 }, { 2 }, { 5 }, { 10 }, { 100 } }; Object[][] rows2 = { { 1 }, { 2 }, { 7 }, { 9 }, { 100 }, { 100 } }; Object[][] expected = { { 2, 2 }, { 2, 2 }, { 100, 100 }, { 100, 100 } }; Block block1 = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }); Block block2 = new ArrayBlock(Arrays.asList(rows2), new String[] { "a" }); TupleOperator operator = new MergeJoinOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("block1", block1); input.put("block2", block2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("leftCubeColumns", "a"); node.put("rightCubeColumns", "a"); node.put("leftBlock", "block1"); BlockProperties props = new BlockProperties(null, new BlockSchema("INT block1___a, INT block2___a"), (BlockProperties) null); operator.setInput(input, node, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, expected, new String[] { "block1.a", "block2.a" }); } @Test public void testGroupByWithSum1() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0 }, { 2 }, { 2 }, { 5 }, { 10 }, { 100 } }; Block block = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }, 1); TupleOperator operator = new GroupByOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("first", block); ObjectMapper mapper = new ObjectMapper(); ObjectNode json = mapper.createObjectNode(); json.put("input", "first"); ArrayNode anode = mapper.createArrayNode(); anode.add("a"); json.put("groupBy", anode); anode = mapper.createArrayNode(); ObjectNode onode = mapper.createObjectNode(); onode.put("type", "SUM"); onode.put("input", "a"); onode.put("output", "sum"); anode.add(onode); json.put("aggregates", anode); BlockProperties props = new BlockProperties(null, new BlockSchema("INT a, INT sum"), (BlockProperties) null); operator.setInput(input, json, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, new Object[][] { { 0, 0 }, { 2, 4 }, { 5, 5 }, { 10, 10 }, { 100, 100 } }, new String[] { "a", "sum" }); } @Test public void testGroupByWithMin() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0, 0 }, { 2, 2 }, { 2, 5 }, { 5, 6 }, { 10, 1 }, { 10, 20 }, { 100, 10 }, { 100, 1 } }; Block block = new ArrayBlock(Arrays.asList(rows1), new String[] { "a", "b" }, 1); TupleOperator operator = new GroupByOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("first", block); ObjectMapper mapper = new ObjectMapper(); ObjectNode json = mapper.createObjectNode(); json.put("input", "first"); ArrayNode anode = mapper.createArrayNode(); anode.add("a"); json.put("groupBy", anode); anode = mapper.createArrayNode(); ObjectNode onode = mapper.createObjectNode(); onode.put("type", "MIN"); onode.put("input", "b"); onode.put("output", "min"); anode.add(onode); json.put("aggregates", anode); BlockProperties props = new BlockProperties(null, new BlockSchema("INT a, INT min"), (BlockProperties) null); operator.setInput(input, json, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, new Object[][] { { 0, 0 }, { 2, 2 }, { 5, 6 }, { 10, 1 }, { 100, 1 } }, new String[] { "a", "min" }); } @Test public void testGroupByWithCount() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0, 0 }, { 2, 2 }, { 2, 5 }, { 5, 6 }, { 10, 1 }, { 10, 20 }, { 100, 10 }, { 100, 1 } }; Block block = new ArrayBlock(Arrays.asList(rows1), new String[] { "a", "b" }, 1); TupleOperator operator = new GroupByOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("first", block); ObjectMapper mapper = new ObjectMapper(); ObjectNode json = mapper.createObjectNode(); json.put("input", "first"); ArrayNode anode = mapper.createArrayNode(); anode.add("a"); json.put("groupBy", anode); anode = mapper.createArrayNode(); ObjectNode onode = mapper.createObjectNode(); onode.put("type", "COUNT"); onode.put("input", "b"); onode.put("output", "countCol"); anode.add(onode); json.put("aggregates", anode); BlockProperties props = new BlockProperties(null, new BlockSchema("INT a, LONG countCol"), (BlockProperties) null); operator.setInput(input, json, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, new Object[][] { { 0, 1L }, { 2, 2L }, { 5, 1L }, { 10, 2L }, { 100, 2L } }, new String[] { "a", "countCol" }); } @Test public void testGroupByWithMax() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0, 0 }, { 2, 2 }, { 2, 5 }, { 5, 6 }, { 10, 1 }, { 10, 20 }, { 100, 10 }, { 100, 1 } }; Block block = new ArrayBlock(Arrays.asList(rows1), new String[] { "a", "b" }, 1); TupleOperator operator = new GroupByOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("first", block); ObjectMapper mapper = new ObjectMapper(); ObjectNode json = mapper.createObjectNode(); json.put("input", "first"); ArrayNode anode = mapper.createArrayNode(); anode.add("a"); json.put("groupBy", anode); anode = mapper.createArrayNode(); ObjectNode onode = mapper.createObjectNode(); onode.put("type", "MAX"); onode.put("input", "b"); onode.put("output", "max"); anode.add(onode); json.put("aggregates", anode); BlockProperties props = new BlockProperties(null, new BlockSchema("INT a, INT max"), (BlockProperties) null); operator.setInput(input, json, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, new Object[][] { { 0, 0 }, { 2, 5 }, { 5, 6 }, { 10, 20 }, { 100, 10 } }, new String[] { "a", "max" }); } @Test public void testGroupByWithSum2() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows1 = { { 0, 0 }, { 2, 2 }, { 2, 5 }, { 5, 6 }, { 10, 1 }, { 100, 10 } }; Block block = new ArrayBlock(Arrays.asList(rows1), new String[] { "a", "b" }, 1); TupleOperator operator = new GroupByOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("first", block); ObjectMapper mapper = new ObjectMapper(); ObjectNode json = mapper.createObjectNode(); json.put("input", "first"); ArrayNode anode = mapper.createArrayNode(); anode.add("a"); json.put("groupBy", anode); anode = mapper.createArrayNode(); ObjectNode onode = mapper.createObjectNode(); onode.put("type", "SUM"); onode.put("input", "b"); onode.put("output", "sum"); anode.add(onode); json.put("aggregates", anode); BlockProperties props = new BlockProperties(null, new BlockSchema("INT a, INT sum"), (BlockProperties) null); operator.setInput(input, json, props); Block output = new TupleOperatorBlock(operator, props); ArrayBlock.assertData(output, new Object[][] { { 0, 0 }, { 2, 7 }, { 5, 6 }, { 10, 1 }, { 100, 10 } }, new String[] { "a", "sum" }); } @Test public void testSortOperator() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { System.out.println("Testing SORT operator"); Object[][] rows1 = { { 0, 10, 0 }, { 2, 5, 2 }, { 2, 8, 5 }, { 5, 9, 6 }, { 10, 11, 1 }, { 100, 6, 10 } }; Block block = new ArrayBlock(Arrays.asList(rows1), new String[] { "a", "b", "c" }, 1); TupleOperator operator = new SortOperator(); Map<String, Block> input = new HashMap<String, Block>(); input.put("unsorted", block); ObjectMapper mapper = new ObjectMapper(); ObjectNode json = mapper.createObjectNode(); json.put("input", "unsorted"); ArrayNode anode = mapper.createArrayNode(); anode.add("b"); anode.add("c"); json.put("sortBy", anode); BlockProperties props = new BlockProperties(null, new BlockSchema("INT a, INT b, INT c"), (BlockProperties) null); operator.setInput(input, json, props); Block output = new TupleOperatorBlock(operator, props); System.out.println("output is " + output); ArrayBlock.assertData(output, new Object[][] { { 2, 5, 2 }, { 100, 6, 10 }, { 2, 8, 5 }, { 5, 9, 6 }, { 0, 10, 0 }, { 10, 11, 1 } }, new String[] { "a", "b", "c" }); } }
aglne/Cubert
src/test/java/com/linkedin/cubert/operator/TestOperators.java
Java
apache-2.0
45,655
/* * Copyright 2016 Mikhail Shiryaev * * 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. * * * Product : Rapid SCADA * Module : ScadaData * Summary : Cache of views * * Author : Mikhail Shiryaev * Created : 2016 * Modified : 2016 */ using Scada.Data.Models; using System; using Utils; namespace Scada.Client { /// <summary> /// Cache of views /// <para>Кэш представлений</para> /// </summary> public class ViewCache { /// <summary> /// Вместимость кэша неограниченная по количеству элементов /// </summary> protected const int Capacity = int.MaxValue; /// <summary> /// Период хранения в кэше с момента последнего доступа /// </summary> protected static readonly TimeSpan StorePeriod = TimeSpan.FromMinutes(10); /// <summary> /// Время актуальности представления в кэше /// </summary> protected static readonly TimeSpan ViewValidSpan = TimeSpan.FromSeconds(1); /// <summary> /// Объект для обмена данными со SCADA-Сервером /// </summary> protected readonly ServerComm serverComm; /// <summary> /// Объект для потокобезопасного доступа к данным кэша клиентов /// </summary> protected readonly DataAccess dataAccess; /// <summary> /// Журнал /// </summary> protected readonly Log log; /// <summary> /// Конструктор, ограничивающий создание объекта без параметров /// </summary> protected ViewCache() { } /// <summary> /// Конструктор /// </summary> public ViewCache(ServerComm serverComm, DataAccess dataAccess, Log log) { if (serverComm == null) throw new ArgumentNullException("serverComm"); if (dataAccess == null) throw new ArgumentNullException("dataAccess"); if (log == null) throw new ArgumentNullException("log"); this.serverComm = serverComm; this.dataAccess = dataAccess; this.log = log; Cache = new Cache<int, BaseView>(StorePeriod, Capacity); } /// <summary> /// Получить объект кэша представлений /// </summary> /// <remarks>Использовать вне данного класса только для получения состояния кэша</remarks> public Cache<int, BaseView> Cache { get; protected set; } /// <summary> /// Получить свойства представления, вызвав исключение в случае неудачи /// </summary> protected UiObjProps GetViewProps(int viewID) { UiObjProps viewProps = dataAccess.GetUiObjProps(viewID); if (viewProps == null) { throw new ScadaException(Localization.UseRussian ? "Отсутствуют свойства представления." : "View properties are missing."); } return viewProps; } /// <summary> /// Загрузить представление от сервера /// </summary> protected bool LoadView(Type viewType, int viewID, DateTime viewAge, ref BaseView view, out DateTime newViewAge) { UiObjProps viewProps = GetViewProps(viewID); newViewAge = serverComm.ReceiveFileAge(ServerComm.Dirs.Itf, viewProps.Path); if (newViewAge == DateTime.MinValue) { throw new ScadaException(Localization.UseRussian ? "Не удалось принять время изменения файла представления." : "Unable to receive view file modification time."); } else if (newViewAge != viewAge) // файл представления изменён { // создание и загрузка нового представления if (view == null) view = (BaseView)Activator.CreateInstance(viewType); view.SetArgs(viewProps.Args); if (serverComm.ReceiveView(viewProps.Path, view)) { view.UpdateTitle(viewProps.ShortTitle); return true; } else { throw new ScadaException(Localization.UseRussian ? "Не удалось принять представление." : "Unable to receive view."); } } else { return false; } } /// <summary> /// Получить представление из кэша или от сервера /// </summary> /// <remarks>Метод используется, если тип предсталения неизвестен на момент компиляции</remarks> public BaseView GetView(Type viewType, int viewID, bool throwOnError = false) { try { if (viewType == null) throw new ArgumentNullException("viewType"); // получение представления из кэша DateTime utcNowDT = DateTime.UtcNow; Cache<int, BaseView>.CacheItem cacheItem = Cache.GetOrCreateItem(viewID, utcNowDT); // блокировка доступа только к одному представлению lock (cacheItem) { BaseView view = null; // представление, которое необходимо получить BaseView viewFromCache = cacheItem.Value; // представление из кэша DateTime viewAge = cacheItem.ValueAge; // время изменения файла представления DateTime newViewAge; // новое время изменения файла представления if (viewFromCache == null) { // создание нового представления view = (BaseView)Activator.CreateInstance(viewType); if (view.StoredOnServer) { if (LoadView(viewType, viewID, viewAge, ref view, out newViewAge)) Cache.UpdateItem(cacheItem, view, newViewAge, utcNowDT); } else { UiObjProps viewProps = GetViewProps(viewID); view.Path = viewProps.Path; view.SetArgs(viewProps.Args); view.UpdateTitle(viewProps.ShortTitle); Cache.UpdateItem(cacheItem, view, DateTime.Now, utcNowDT); } } else if (viewFromCache.StoredOnServer) { // представление могло устареть bool viewIsNotValid = utcNowDT - cacheItem.ValueRefrDT > ViewValidSpan; if (viewIsNotValid && LoadView(viewType, viewID, viewAge, ref view, out newViewAge)) Cache.UpdateItem(cacheItem, view, newViewAge, utcNowDT); } // использование представления из кэша if (view == null && viewFromCache != null) { if (viewFromCache.GetType().Equals(viewType)) view = viewFromCache; else throw new ScadaException(Localization.UseRussian ? "Несоответствие типа представления." : "View type mismatch."); } // привязка свойств каналов или обновление существующей привязки if (view != null) dataAccess.BindCnlProps(view); return view; } } catch (Exception ex) { string errMsg = string.Format(Localization.UseRussian ? "Ошибка при получении представления с ид.={0} из кэша или от сервера: {1}" : "Error getting view with ID={0} from the cache or from the server: {1}", viewID, ex.Message); log.WriteException(ex, errMsg); if (throwOnError) throw new ScadaException(errMsg); else return null; } } /// <summary> /// Получить представление из кэша или от сервера /// </summary> public T GetView<T>(int viewID, bool throwOnError = false) where T : BaseView { return GetView(typeof(T), viewID, throwOnError) as T; } /// <summary> /// Получить уже загруженное представление только из кэша /// </summary> public BaseView GetViewFromCache(int viewID, bool throwOnFail = false) { try { Cache<int, BaseView>.CacheItem cacheItem = Cache.GetItem(viewID, DateTime.UtcNow); BaseView view = cacheItem == null ? null : cacheItem.Value; if (view == null && throwOnFail) throw new ScadaException(string.Format(Localization.UseRussian ? "Представление не найдено в кэше" : "The view is not found in the cache", viewID)); return view; } catch (Exception ex) { string errMsg = string.Format(Localization.UseRussian ? "Ошибка при получении представления с ид.={0} из кэша: {1}" : "Error getting view with ID={0} from the cache: {1}", viewID, ex.Message); log.WriteException(ex, errMsg); if (throwOnFail) throw new ScadaException(errMsg); else return null; } } } }
RapidScada/scada
ScadaData/ScadaData/Client/ViewCache.cs
C#
apache-2.0
11,760
/* * Copyright (c) 2021, 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.alg.distort; import boofcv.struct.distort.PixelTransform; import boofcv.struct.image.GrayU8; import boofcv.struct.image.ImageBase; import georegression.struct.point.Point2D_F32; /** * Copies an image onto another image while applying a transform to the pixel coordinates. * Pixels outside the source image can be handled using the interpolations border or by simply skipping them. This * behavior is set by calling the {@link #setRenderAll(boolean)} flag. By Default it will render the entire image, * even if pixel is outside the source image. * * @author Peter Abeles */ public interface ImageDistort<Input extends ImageBase, Output extends ImageBase> { /** * Specifies how pixel coordinates are transformed from the destination * to source images. * * @param dstToSrc Pixel coordinate transformation. */ void setModel( PixelTransform<Point2D_F32> dstToSrc ); /** * Applies the transform to the entire destination image. * * @param srcImg (Input) Original image. * @param dstImg (Output) Distorted image. */ void apply( Input srcImg, Output dstImg ); /** * Applies the transform, but marks pixels in the mask as 1 = inside, 0 = outside. Where * inside pixels are pixels in the dst image with an equivalent pixel in the src image's bounds * * @param srcImg (Input) Original image. * @param dstImg (Output) Distorted image. * @param mask (Output) Mask of inside pixels. Automatically resized to match dstImg. */ void apply( Input srcImg, Output dstImg, GrayU8 mask ); /** * Applies the transform to only the specified region inside the destination image. * * @param srcImg (Input) Original image. * @param dstImg (Output) Distorted image. * @param dstX0 Left most crop boundary. Inclusive. * @param dstY0 Top most crop boundary. Inclusive. * @param dstX1 Right most crop boundary. Exclusive. * @param dstY1 Bottom most crop boundary. Exclusive. */ void apply( Input srcImg, Output dstImg, int dstX0, int dstY0, int dstX1, int dstY1 ); /** * Specifies if the entire output image should be rendered, even if mapping to the source image is outside * the source image. * * @param renderAll true to render all pixels. If false then only pixels inside the source image */ void setRenderAll( boolean renderAll ); /** * Returns the render all flag * * @return render all flag */ boolean getRenderAll(); /** * Returns the distortion model. * * @return model dst to src */ PixelTransform<Point2D_F32> getModel(); }
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/distort/ImageDistort.java
Java
apache-2.0
3,205
/* * 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 okio; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static okio.Util.checkOffsetAndCount; import static okio.Util.reverseBytesLong; /** * A collection of bytes in memory. * * <p><strong>Moving data from one buffer to another is fast.</strong> Instead * of copying bytes from one place in memory to another, this class just changes * ownership of the underlying byte arrays. * * <p><strong>This buffer grows with your data.</strong> Just like ArrayList, * each buffer starts small. It consumes only the memory it needs to. * * <p><strong>This buffer pools its byte arrays.</strong> When you allocate a * byte array in Java, the runtime must zero-fill the requested array before * returning it to you. Even if you're going to write over that space anyway. * This class avoids zero-fill and GC churn by pooling byte arrays. */ public final class Buffer implements BufferedSource, BufferedSink, Cloneable { private static final byte[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; Segment head; long size; public Buffer() { } /** Returns the number of bytes currently in this buffer. */ public long size() { return size; } @Override public Buffer buffer() { return this; } @Override public OutputStream outputStream() { return new OutputStream() { @Override public void write(int b) { writeByte((byte) b); } @Override public void write(byte[] data, int offset, int byteCount) { Buffer.this.write(data, offset, byteCount); } @Override public void flush() { } @Override public void close() { } @Override public String toString() { return this + ".outputStream()"; } }; } @Override public Buffer emitCompleteSegments() { return this; // Nowhere to emit to! } @Override public BufferedSink emit() { return this; // Nowhere to emit to! } @Override public boolean exhausted() { return size == 0; } @Override public void require(long byteCount) throws EOFException { if (size < byteCount) throw new EOFException(); } @Override public boolean request(long byteCount) { return size >= byteCount; } @Override public InputStream inputStream() { return new InputStream() { @Override public int read() { if (size > 0) return readByte() & 0xff; return -1; } @Override public int read(byte[] sink, int offset, int byteCount) { return Buffer.this.read(sink, offset, byteCount); } @Override public int available() { return (int) Math.min(size, Integer.MAX_VALUE); } @Override public void close() { } @Override public String toString() { return Buffer.this + ".inputStream()"; } }; } /** Copy the contents of this to {@code out}. */ public Buffer copyTo(OutputStream out) throws IOException { return copyTo(out, 0, size); } /** * Copy {@code byteCount} bytes from this, starting at {@code offset}, to * {@code out}. */ public Buffer copyTo(OutputStream out, long offset, long byteCount) throws IOException { if (out == null) throw new IllegalArgumentException("out == null"); checkOffsetAndCount(size, offset, byteCount); if (byteCount == 0) return this; // Skip segments that we aren't copying from. Segment s = head; for (; offset >= (s.limit - s.pos); s = s.next) { offset -= (s.limit - s.pos); } // Copy from one segment at a time. for (; byteCount > 0; s = s.next) { int pos = (int) (s.pos + offset); int toCopy = (int) Math.min(s.limit - pos, byteCount); out.write(s.data, pos, toCopy); byteCount -= toCopy; offset = 0; } return this; } /** Copy {@code byteCount} bytes from this, starting at {@code offset}, to {@code out}. */ public Buffer copyTo(Buffer out, long offset, long byteCount) { if (out == null) throw new IllegalArgumentException("out == null"); checkOffsetAndCount(size, offset, byteCount); if (byteCount == 0) return this; out.size += byteCount; // Skip segments that we aren't copying from. Segment s = head; for (; offset >= (s.limit - s.pos); s = s.next) { offset -= (s.limit - s.pos); } // Copy one segment at a time. for (; byteCount > 0; s = s.next) { Segment copy = new Segment(s); copy.pos += offset; copy.limit = Math.min(copy.pos + (int) byteCount, copy.limit); if (out.head == null) { out.head = copy.next = copy.prev = copy; } else { out.head.prev.push(copy); } byteCount -= copy.limit - copy.pos; offset = 0; } return this; } /** Write the contents of this to {@code out}. */ public Buffer writeTo(OutputStream out) throws IOException { return writeTo(out, size); } /** Write {@code byteCount} bytes from this to {@code out}. */ public Buffer writeTo(OutputStream out, long byteCount) throws IOException { if (out == null) throw new IllegalArgumentException("out == null"); checkOffsetAndCount(size, 0, byteCount); Segment s = head; while (byteCount > 0) { int toCopy = (int) Math.min(byteCount, s.limit - s.pos); out.write(s.data, s.pos, toCopy); s.pos += toCopy; size -= toCopy; byteCount -= toCopy; if (s.pos == s.limit) { Segment toRecycle = s; head = s = toRecycle.pop(); SegmentPool.recycle(toRecycle); } } return this; } /** Read and exhaust bytes from {@code in} to this. */ public Buffer readFrom(InputStream in) throws IOException { readFrom(in, Long.MAX_VALUE, true); return this; } /** Read {@code byteCount} bytes from {@code in} to this. */ public Buffer readFrom(InputStream in, long byteCount) throws IOException { if (byteCount < 0) throw new IllegalArgumentException("byteCount < 0: " + byteCount); readFrom(in, byteCount, false); return this; } private void readFrom(InputStream in, long byteCount, boolean forever) throws IOException { if (in == null) throw new IllegalArgumentException("in == null"); while (byteCount > 0 || forever) { Segment tail = writableSegment(1); int maxToCopy = (int) Math.min(byteCount, Segment.SIZE - tail.limit); int bytesRead = in.read(tail.data, tail.limit, maxToCopy); if (bytesRead == -1) { if (forever) return; throw new EOFException(); } tail.limit += bytesRead; size += bytesRead; byteCount -= bytesRead; } } /** * Returns the number of bytes in segments that are not writable. This is the * number of bytes that can be flushed immediately to an underlying sink * without harming throughput. */ public long completeSegmentByteCount() { long result = size; if (result == 0) return 0; // Omit the tail if it's still writable. Segment tail = head.prev; if (tail.limit < Segment.SIZE && tail.owner) { result -= tail.limit - tail.pos; } return result; } @Override public byte readByte() { if (size == 0) throw new IllegalStateException("size == 0"); Segment segment = head; int pos = segment.pos; int limit = segment.limit; byte[] data = segment.data; byte b = data[pos++]; size -= 1; if (pos == limit) { head = segment.pop(); SegmentPool.recycle(segment); } else { segment.pos = pos; } return b; } /** Returns the byte at {@code pos}. */ public byte getByte(long pos) { checkOffsetAndCount(size, pos, 1); for (Segment s = head; true; s = s.next) { int segmentByteCount = s.limit - s.pos; if (pos < segmentByteCount) return s.data[s.pos + (int) pos]; pos -= segmentByteCount; } } @Override public short readShort() { if (size < 2) throw new IllegalStateException("size < 2: " + size); Segment segment = head; int pos = segment.pos; int limit = segment.limit; // If the short is split across multiple segments, delegate to readByte(). if (limit - pos < 2) { int s = (readByte() & 0xff) << 8 | (readByte() & 0xff); return (short) s; } byte[] data = segment.data; int s = (data[pos++] & 0xff) << 8 | (data[pos++] & 0xff); size -= 2; if (pos == limit) { head = segment.pop(); SegmentPool.recycle(segment); } else { segment.pos = pos; } return (short) s; } @Override public int readInt() { if (size < 4) throw new IllegalStateException("size < 4: " + size); Segment segment = head; int pos = segment.pos; int limit = segment.limit; // If the int is split across multiple segments, delegate to readByte(). if (limit - pos < 4) { return (readByte() & 0xff) << 24 | (readByte() & 0xff) << 16 | (readByte() & 0xff) << 8 | (readByte() & 0xff); } byte[] data = segment.data; int i = (data[pos++] & 0xff) << 24 | (data[pos++] & 0xff) << 16 | (data[pos++] & 0xff) << 8 | (data[pos++] & 0xff); size -= 4; if (pos == limit) { head = segment.pop(); SegmentPool.recycle(segment); } else { segment.pos = pos; } return i; } @Override public long readLong() { if (size < 8) throw new IllegalStateException("size < 8: " + size); Segment segment = head; int pos = segment.pos; int limit = segment.limit; // If the long is split across multiple segments, delegate to readInt(). if (limit - pos < 8) { return (readInt() & 0xffffffffL) << 32 | (readInt() & 0xffffffffL); } byte[] data = segment.data; long v = (data[pos++] & 0xffL) << 56 | (data[pos++] & 0xffL) << 48 | (data[pos++] & 0xffL) << 40 | (data[pos++] & 0xffL) << 32 | (data[pos++] & 0xffL) << 24 | (data[pos++] & 0xffL) << 16 | (data[pos++] & 0xffL) << 8 | (data[pos++] & 0xffL); size -= 8; if (pos == limit) { head = segment.pop(); SegmentPool.recycle(segment); } else { segment.pos = pos; } return v; } @Override public short readShortLe() { return Util.reverseBytesShort(readShort()); } @Override public int readIntLe() { return Util.reverseBytesInt(readInt()); } @Override public long readLongLe() { return Util.reverseBytesLong(readLong()); } @Override public long readDecimalLong() { if (size == 0) throw new IllegalStateException("size == 0"); // This value is always built negatively in order to accommodate Long.MIN_VALUE. long value = 0; int seen = 0; boolean negative = false; boolean done = false; long overflowZone = Long.MIN_VALUE / 10; long overflowDigit = (Long.MIN_VALUE % 10) + 1; do { Segment segment = head; byte[] data = segment.data; int pos = segment.pos; int limit = segment.limit; for (; pos < limit; pos++, seen++) { byte b = data[pos]; if (b >= '0' && b <= '9') { int digit = '0' - b; // Detect when the digit would cause an overflow. if (value < overflowZone || value == overflowZone && digit < overflowDigit) { Buffer buffer = new Buffer().writeDecimalLong(value).writeByte(b); if (!negative) buffer.readByte(); // Skip negative sign. throw new NumberFormatException("Number too large: " + buffer.readUtf8()); } value *= 10; value += digit; } else if (b == '-' && seen == 0) { negative = true; overflowDigit -= 1; } else { if (seen == 0) { throw new NumberFormatException( "Expected leading [0-9] or '-' character but was 0x" + Integer.toHexString(b)); } // Set a flag to stop iteration. We still need to run through segment updating below. done = true; break; } } if (pos == limit) { head = segment.pop(); SegmentPool.recycle(segment); } else { segment.pos = pos; } } while (!done && head != null); size -= seen; return negative ? value : -value; } @Override public long readHexadecimalUnsignedLong() { if (size == 0) throw new IllegalStateException("size == 0"); long value = 0; int seen = 0; boolean done = false; do { Segment segment = head; byte[] data = segment.data; int pos = segment.pos; int limit = segment.limit; for (; pos < limit; pos++, seen++) { int digit; byte b = data[pos]; if (b >= '0' && b <= '9') { digit = b - '0'; } else if (b >= 'a' && b <= 'f') { digit = b - 'a' + 10; } else if (b >= 'A' && b <= 'F') { digit = b - 'A' + 10; // We never write uppercase, but we support reading it. } else { if (seen == 0) { throw new NumberFormatException( "Expected leading [0-9a-fA-F] character but was 0x" + Integer.toHexString(b)); } // Set a flag to stop iteration. We still need to run through segment updating below. done = true; break; } // Detect when the shift will overflow. if ((value & 0xf000000000000000L) != 0) { Buffer buffer = new Buffer().writeHexadecimalUnsignedLong(value).writeByte(b); throw new NumberFormatException("Number too large: " + buffer.readUtf8()); } value <<= 4; value |= digit; } if (pos == limit) { head = segment.pop(); SegmentPool.recycle(segment); } else { segment.pos = pos; } } while (!done && head != null); size -= seen; return value; } @Override public ByteString readByteString() { return new ByteString(readByteArray()); } @Override public ByteString readByteString(long byteCount) throws EOFException { return new ByteString(readByteArray(byteCount)); } @Override public void readFully(Buffer sink, long byteCount) throws EOFException { if (size < byteCount) { sink.write(this, size); // Exhaust ourselves. throw new EOFException(); } sink.write(this, byteCount); } @Override public long readAll(Sink sink) throws IOException { long byteCount = size; if (byteCount > 0) { sink.write(this, byteCount); } return byteCount; } @Override public String readUtf8() { try { return readString(size, Util.UTF_8); } catch (EOFException e) { throw new AssertionError(e); } } @Override public String readUtf8(long byteCount) throws EOFException { return readString(byteCount, Util.UTF_8); } @Override public String readString(Charset charset) { try { return readString(size, charset); } catch (EOFException e) { throw new AssertionError(e); } } @Override public String readString(long byteCount, Charset charset) throws EOFException { checkOffsetAndCount(size, 0, byteCount); if (charset == null) throw new IllegalArgumentException("charset == null"); if (byteCount > Integer.MAX_VALUE) { throw new IllegalArgumentException("byteCount > Integer.MAX_VALUE: " + byteCount); } if (byteCount == 0) return ""; Segment s = head; if (s.pos + byteCount > s.limit) { // If the string spans multiple segments, delegate to readBytes(). return new String(readByteArray(byteCount), charset); } String result = new String(s.data, s.pos, (int) byteCount, charset); s.pos += byteCount; size -= byteCount; if (s.pos == s.limit) { head = s.pop(); SegmentPool.recycle(s); } return result; } @Override public String readUtf8Line() throws EOFException { long newline = indexOf((byte) '\n'); if (newline == -1) { return size != 0 ? readUtf8(size) : null; } return readUtf8Line(newline); } @Override public String readUtf8LineStrict() throws EOFException { long newline = indexOf((byte) '\n'); if (newline == -1) { Buffer data = new Buffer(); copyTo(data, 0, Math.min(32, size)); throw new EOFException("\\n not found: size=" + size() + " content=" + data.readByteString().hex() + "..."); } return readUtf8Line(newline); } String readUtf8Line(long newline) throws EOFException { if (newline > 0 && getByte(newline - 1) == '\r') { // Read everything until '\r\n', then skip the '\r\n'. String result = readUtf8((newline - 1)); skip(2); return result; } else { // Read everything until '\n', then skip the '\n'. String result = readUtf8(newline); skip(1); return result; } } @Override public byte[] readByteArray() { try { return readByteArray(size); } catch (EOFException e) { throw new AssertionError(e); } } @Override public byte[] readByteArray(long byteCount) throws EOFException { checkOffsetAndCount(size, 0, byteCount); if (byteCount > Integer.MAX_VALUE) { throw new IllegalArgumentException("byteCount > Integer.MAX_VALUE: " + byteCount); } byte[] result = new byte[(int) byteCount]; readFully(result); return result; } @Override public int read(byte[] sink) { return read(sink, 0, sink.length); } @Override public void readFully(byte[] sink) throws EOFException { int offset = 0; while (offset < sink.length) { int read = read(sink, offset, sink.length - offset); if (read == -1) throw new EOFException(); offset += read; } } @Override public int read(byte[] sink, int offset, int byteCount) { checkOffsetAndCount(sink.length, offset, byteCount); Segment s = head; if (s == null) return -1; int toCopy = Math.min(byteCount, s.limit - s.pos); System.arraycopy(s.data, s.pos, sink, offset, toCopy); s.pos += toCopy; size -= toCopy; if (s.pos == s.limit) { head = s.pop(); SegmentPool.recycle(s); } return toCopy; } /** * Discards all bytes in this buffer. Calling this method when you're done * with a buffer will return its segments to the pool. */ public void clear() { try { skip(size); } catch (EOFException e) { throw new AssertionError(e); } } /** Discards {@code byteCount} bytes from the head of this buffer. */ @Override public void skip(long byteCount) throws EOFException { while (byteCount > 0) { if (head == null) throw new EOFException(); int toSkip = (int) Math.min(byteCount, head.limit - head.pos); size -= toSkip; byteCount -= toSkip; head.pos += toSkip; if (head.pos == head.limit) { Segment toRecycle = head; head = toRecycle.pop(); SegmentPool.recycle(toRecycle); } } } @Override public Buffer write(ByteString byteString) { if (byteString == null) throw new IllegalArgumentException("byteString == null"); byteString.write(this); return this; } @Override public Buffer writeUtf8(String string) { if (string == null) throw new IllegalArgumentException("string == null"); // Transcode a UTF-16 Java String to UTF-8 bytes. for (int i = 0, length = string.length(); i < length;) { int c = string.charAt(i); if (c < 0x80) { Segment tail = writableSegment(1); byte[] data = tail.data; int segmentOffset = tail.limit - i; int runLimit = Math.min(length, Segment.SIZE - segmentOffset); // Emit a 7-bit character with 1 byte. data[segmentOffset + i++] = (byte) c; // 0xxxxxxx // Fast-path contiguous runs of ASCII characters. This is ugly, but yields a ~4x performance // improvement over independent calls to writeByte(). while (i < runLimit) { c = string.charAt(i); if (c >= 0x80) break; data[segmentOffset + i++] = (byte) c; // 0xxxxxxx } int runSize = i + segmentOffset - tail.limit; // Equivalent to i - (previous i). tail.limit += runSize; size += runSize; } else if (c < 0x800) { // Emit a 11-bit character with 2 bytes. writeByte(c >> 6 | 0xc0); // 110xxxxx writeByte(c & 0x3f | 0x80); // 10xxxxxx i++; } else if (c < 0xd800 || c > 0xdfff) { // Emit a 16-bit character with 3 bytes. writeByte(c >> 12 | 0xe0); // 1110xxxx writeByte(c >> 6 & 0x3f | 0x80); // 10xxxxxx writeByte(c & 0x3f | 0x80); // 10xxxxxx i++; } else { // c is a surrogate. Make sure it is a high surrogate & that its successor is a low // surrogate. If not, the UTF-16 is invalid, in which case we emit a replacement character. int low = i + 1 < length ? string.charAt(i + 1) : 0; if (c > 0xdbff || low < 0xdc00 || low > 0xdfff) { writeByte('?'); i++; continue; } // UTF-16 high surrogate: 110110xxxxxxxxxx (10 bits) // UTF-16 low surrogate: 110111yyyyyyyyyy (10 bits) // Unicode code point: 00010000000000000000 + xxxxxxxxxxyyyyyyyyyy (21 bits) int codePoint = 0x010000 + ((c & ~0xd800) << 10 | low & ~0xdc00); // Emit a 21-bit character with 4 bytes. writeByte(codePoint >> 18 | 0xf0); // 11110xxx writeByte(codePoint >> 12 & 0x3f | 0x80); // 10xxxxxx writeByte(codePoint >> 6 & 0x3f | 0x80); // 10xxyyyy writeByte(codePoint & 0x3f | 0x80); // 10yyyyyy i += 2; } } return this; } @Override public Buffer writeString(String string, Charset charset) { if (string == null) throw new IllegalArgumentException("string == null"); if (charset == null) throw new IllegalArgumentException("charset == null"); if (charset.equals(Util.UTF_8)) return writeUtf8(string); byte[] data = string.getBytes(charset); return write(data, 0, data.length); } @Override public Buffer write(byte[] source) { if (source == null) throw new IllegalArgumentException("source == null"); return write(source, 0, source.length); } @Override public Buffer write(byte[] source, int offset, int byteCount) { if (source == null) throw new IllegalArgumentException("source == null"); checkOffsetAndCount(source.length, offset, byteCount); int limit = offset + byteCount; while (offset < limit) { Segment tail = writableSegment(1); int toCopy = Math.min(limit - offset, Segment.SIZE - tail.limit); System.arraycopy(source, offset, tail.data, tail.limit, toCopy); offset += toCopy; tail.limit += toCopy; } size += byteCount; return this; } @Override public long writeAll(Source source) throws IOException { if (source == null) throw new IllegalArgumentException("source == null"); long totalBytesRead = 0; for (long readCount; (readCount = source.read(this, Segment.SIZE)) != -1; ) { totalBytesRead += readCount; } return totalBytesRead; } @Override public BufferedSink write(Source source, long byteCount) throws IOException { while (byteCount > 0) { long read = source.read(this, byteCount); if (read == -1) throw new EOFException(); byteCount -= read; } return this; } @Override public Buffer writeByte(int b) { Segment tail = writableSegment(1); tail.data[tail.limit++] = (byte) b; size += 1; return this; } @Override public Buffer writeShort(int s) { Segment tail = writableSegment(2); byte[] data = tail.data; int limit = tail.limit; data[limit++] = (byte) ((s >>> 8) & 0xff); data[limit++] = (byte) (s & 0xff); tail.limit = limit; size += 2; return this; } @Override public Buffer writeShortLe(int s) { return writeShort(Util.reverseBytesShort((short) s)); } @Override public Buffer writeInt(int i) { Segment tail = writableSegment(4); byte[] data = tail.data; int limit = tail.limit; data[limit++] = (byte) ((i >>> 24) & 0xff); data[limit++] = (byte) ((i >>> 16) & 0xff); data[limit++] = (byte) ((i >>> 8) & 0xff); data[limit++] = (byte) (i & 0xff); tail.limit = limit; size += 4; return this; } @Override public Buffer writeIntLe(int i) { return writeInt(Util.reverseBytesInt(i)); } @Override public Buffer writeLong(long v) { Segment tail = writableSegment(8); byte[] data = tail.data; int limit = tail.limit; data[limit++] = (byte) ((v >>> 56L) & 0xff); data[limit++] = (byte) ((v >>> 48L) & 0xff); data[limit++] = (byte) ((v >>> 40L) & 0xff); data[limit++] = (byte) ((v >>> 32L) & 0xff); data[limit++] = (byte) ((v >>> 24L) & 0xff); data[limit++] = (byte) ((v >>> 16L) & 0xff); data[limit++] = (byte) ((v >>> 8L) & 0xff); data[limit++] = (byte) (v & 0xff); tail.limit = limit; size += 8; return this; } @Override public Buffer writeLongLe(long v) { return writeLong(reverseBytesLong(v)); } @Override public Buffer writeDecimalLong(long v) { if (v == 0) { // Both a shortcut and required since the following code can't handle zero. return writeByte('0'); } boolean negative = false; if (v < 0) { v = -v; if (v < 0) { // Only true for Long.MIN_VALUE. return writeUtf8("-9223372036854775808"); } negative = true; } // Binary search for character width which favors matching lower numbers. int width = // v < 100000000L ? v < 10000L ? v < 100L ? v < 10L ? 1 : 2 : v < 1000L ? 3 : 4 : v < 1000000L ? v < 100000L ? 5 : 6 : v < 10000000L ? 7 : 8 : v < 1000000000000L ? v < 10000000000L ? v < 1000000000L ? 9 : 10 : v < 100000000000L ? 11 : 12 : v < 1000000000000000L ? v < 10000000000000L ? 13 : v < 100000000000000L ? 14 : 15 : v < 100000000000000000L ? v < 10000000000000000L ? 16 : 17 : v < 1000000000000000000L ? 18 : 19; if (negative) { ++width; } Segment tail = writableSegment(width); byte[] data = tail.data; int pos = tail.limit + width; // We write backwards from right to left. while (v != 0) { int digit = (int) (v % 10); data[--pos] = DIGITS[digit]; v /= 10; } if (negative) { data[--pos] = '-'; } tail.limit += width; this.size += width; return this; } @Override public Buffer writeHexadecimalUnsignedLong(long v) { if (v == 0) { // Both a shortcut and required since the following code can't handle zero. return writeByte('0'); } int width = Long.numberOfTrailingZeros(Long.highestOneBit(v)) / 4 + 1; Segment tail = writableSegment(width); byte[] data = tail.data; for (int pos = tail.limit + width - 1, start = tail.limit; pos >= start; pos--) { data[pos] = DIGITS[(int) (v & 0xF)]; v >>>= 4; } tail.limit += width; size += width; return this; } /** * Returns a tail segment that we can write at least {@code minimumCapacity} * bytes to, creating it if necessary. */ Segment writableSegment(int minimumCapacity) { if (minimumCapacity < 1 || minimumCapacity > Segment.SIZE) throw new IllegalArgumentException(); if (head == null) { head = SegmentPool.take(); // Acquire a first segment. return head.next = head.prev = head; } Segment tail = head.prev; if (tail.limit + minimumCapacity > Segment.SIZE || !tail.owner) { tail = tail.push(SegmentPool.take()); // Append a new empty segment to fill up. } return tail; } @Override public void write(Buffer source, long byteCount) { // Move bytes from the head of the source buffer to the tail of this buffer // while balancing two conflicting goals: don't waste CPU and don't waste // memory. // // // Don't waste CPU (ie. don't copy data around). // // Copying large amounts of data is expensive. Instead, we prefer to // reassign entire segments from one buffer to the other. // // // Don't waste memory. // // As an invariant, adjacent pairs of segments in a buffer should be at // least 50% full, except for the head segment and the tail segment. // // The head segment cannot maintain the invariant because the application is // consuming bytes from this segment, decreasing its level. // // The tail segment cannot maintain the invariant because the application is // producing bytes, which may require new nearly-empty tail segments to be // appended. // // // Moving segments between buffers // // When writing one buffer to another, we prefer to reassign entire segments // over copying bytes into their most compact form. Suppose we have a buffer // with these segment levels [91%, 61%]. If we append a buffer with a // single [72%] segment, that yields [91%, 61%, 72%]. No bytes are copied. // // Or suppose we have a buffer with these segment levels: [100%, 2%], and we // want to append it to a buffer with these segment levels [99%, 3%]. This // operation will yield the following segments: [100%, 2%, 99%, 3%]. That // is, we do not spend time copying bytes around to achieve more efficient // memory use like [100%, 100%, 4%]. // // When combining buffers, we will compact adjacent buffers when their // combined level doesn't exceed 100%. For example, when we start with // [100%, 40%] and append [30%, 80%], the result is [100%, 70%, 80%]. // // // Splitting segments // // Occasionally we write only part of a source buffer to a sink buffer. For // example, given a sink [51%, 91%], we may want to write the first 30% of // a source [92%, 82%] to it. To simplify, we first transform the source to // an equivalent buffer [30%, 62%, 82%] and then move the head segment, // yielding sink [51%, 91%, 30%] and source [62%, 82%]. if (source == null) throw new IllegalArgumentException("source == null"); if (source == this) throw new IllegalArgumentException("source == this"); checkOffsetAndCount(source.size, 0, byteCount); while (byteCount > 0) { // Is a prefix of the source's head segment all that we need to move? if (byteCount < (source.head.limit - source.head.pos)) { Segment tail = head != null ? head.prev : null; if (tail != null && tail.owner && (byteCount + tail.limit - (tail.shared ? 0 : tail.pos) <= Segment.SIZE)) { // Our existing segments are sufficient. Move bytes from source's head to our tail. source.head.writeTo(tail, (int) byteCount); source.size -= byteCount; size += byteCount; return; } else { // We're going to need another segment. Split the source's head // segment in two, then move the first of those two to this buffer. source.head = source.head.split((int) byteCount); } } // Remove the source's head segment and append it to our tail. Segment segmentToMove = source.head; long movedByteCount = segmentToMove.limit - segmentToMove.pos; source.head = segmentToMove.pop(); if (head == null) { head = segmentToMove; head.next = head.prev = head; } else { Segment tail = head.prev; tail = tail.push(segmentToMove); tail.compact(); } source.size -= movedByteCount; size += movedByteCount; byteCount -= movedByteCount; } } @Override public long read(Buffer sink, long byteCount) { if (sink == null) throw new IllegalArgumentException("sink == null"); if (byteCount < 0) throw new IllegalArgumentException("byteCount < 0: " + byteCount); if (size == 0) return -1L; if (byteCount > size) byteCount = size; sink.write(this, byteCount); return byteCount; } @Override public long indexOf(byte b) { return indexOf(b, 0); } /** * Returns the index of {@code b} in this at or beyond {@code fromIndex}, or * -1 if this buffer does not contain {@code b} in that range. */ @Override public long indexOf(byte b, long fromIndex) { if (fromIndex < 0) throw new IllegalArgumentException("fromIndex < 0"); Segment s = head; if (s == null) return -1L; long offset = 0L; do { int segmentByteCount = s.limit - s.pos; if (fromIndex >= segmentByteCount) { fromIndex -= segmentByteCount; } else { byte[] data = s.data; for (long pos = s.pos + fromIndex, limit = s.limit; pos < limit; pos++) { if (data[(int) pos] == b) return offset + pos - s.pos; } fromIndex = 0; } offset += segmentByteCount; s = s.next; } while (s != head); return -1L; } @Override public long indexOfElement(ByteString targetBytes) { return indexOfElement(targetBytes, 0); } @Override public long indexOfElement(ByteString targetBytes, long fromIndex) { if (fromIndex < 0) throw new IllegalArgumentException("fromIndex < 0"); Segment s = head; if (s == null) return -1L; long offset = 0L; byte[] toFind = targetBytes.toByteArray(); do { int segmentByteCount = s.limit - s.pos; if (fromIndex >= segmentByteCount) { fromIndex -= segmentByteCount; } else { byte[] data = s.data; for (long pos = s.pos + fromIndex, limit = s.limit; pos < limit; pos++) { byte b = data[(int) pos]; for (byte targetByte : toFind) { if (b == targetByte) return offset + pos - s.pos; } } fromIndex = 0; } offset += segmentByteCount; s = s.next; } while (s != head); return -1L; } @Override public void flush() { } @Override public void close() { } @Override public Timeout timeout() { return Timeout.NONE; } /** For testing. This returns the sizes of the segments in this buffer. */ List<Integer> segmentSizes() { if (head == null) return Collections.emptyList(); List<Integer> result = new ArrayList<>(); result.add(head.limit - head.pos); for (Segment s = head.next; s != head; s = s.next) { result.add(s.limit - s.pos); } return result; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Buffer)) return false; Buffer that = (Buffer) o; if (size != that.size) return false; if (size == 0) return true; // Both buffers are empty. Segment sa = this.head; Segment sb = that.head; int posA = sa.pos; int posB = sb.pos; for (long pos = 0, count; pos < size; pos += count) { count = Math.min(sa.limit - posA, sb.limit - posB); for (int i = 0; i < count; i++) { if (sa.data[posA++] != sb.data[posB++]) return false; } if (posA == sa.limit) { sa = sa.next; posA = sa.pos; } if (posB == sb.limit) { sb = sb.next; posB = sb.pos; } } return true; } @Override public int hashCode() { Segment s = head; if (s == null) return 0; int result = 1; do { for (int pos = s.pos, limit = s.limit; pos < limit; pos++) { result = 31 * result + s.data[pos]; } s = s.next; } while (s != head); return result; } @Override public String toString() { if (size == 0) { return "Buffer[size=0]"; } if (size <= 16) { ByteString data = clone().readByteString(); return String.format("Buffer[size=%s data=%s]", size, data.hex()); } try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(head.data, head.pos, head.limit - head.pos); for (Segment s = head.next; s != head; s = s.next) { md5.update(s.data, s.pos, s.limit - s.pos); } return String.format("Buffer[size=%s md5=%s]", size, ByteString.of(md5.digest()).hex()); } catch (NoSuchAlgorithmException e) { throw new AssertionError(); } } /** Returns a deep copy of this buffer. */ @Override public Buffer clone() { Buffer result = new Buffer(); if (size == 0) return result; result.head = new Segment(head); result.head.next = result.head.prev = result.head; for (Segment s = head.next; s != head; s = s.next) { result.head.prev.push(new Segment(s)); } result.size = size; return result; } /** Returns an immutable copy of this buffer as a byte string. */ public ByteString snapshot() { if (size > Integer.MAX_VALUE) { throw new IllegalArgumentException("size > Integer.MAX_VALUE: " + size); } return snapshot((int) size); } /** * Returns an immutable copy of the first {@code byteCount} bytes of this buffer as a byte string. */ public ByteString snapshot(int byteCount) { if (byteCount == 0) return ByteString.EMPTY; return new SegmentedByteString(this, byteCount); } }
CyanogenMod/android_external_square_okio
okio/src/main/java/okio/Buffer.java
Java
apache-2.0
38,214
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.wise.core.exception; /** * Exception to be thrown when a give resource is not found/available. * * @author alessio.soldano@jboss.com * @since 07-May-2009 */ public class ResourceNotAvailableException extends Exception { private static final long serialVersionUID = 5563093692694234297L; public ResourceNotAvailableException( String message, Throwable cause ) { super(message, cause); } public ResourceNotAvailableException(String message) { super(message); } }
chtiJBUG/wise-core
core/src/main/java/org/jboss/wise/core/exception/ResourceNotAvailableException.java
Java
apache-2.0
1,579
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var bench = require( '@stdlib/bench' ); var randu = require( '@stdlib/random/iter/randu' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var isIteratorLike = require( '@stdlib/assert/is-iterator-like' ); var pkg = require( './../package.json' ).name; var iterAbs2 = require( './../lib' ); // MAIN // bench( pkg, function benchmark( b ) { var rand; var iter; var i; rand = randu(); b.tic(); for ( i = 0; i < b.iterations; i++ ) { iter = iterAbs2( rand ); if ( typeof iter !== 'object' ) { b.fail( 'should return an object' ); } } b.toc(); if ( !isIteratorLike( iter ) ) { b.fail( 'should return an iterator protocol-compliant object' ); } b.pass( 'benchmark finished' ); b.end(); }); bench( pkg+'::iteration', function benchmark( b ) { var rand; var iter; var z; var i; rand = randu(); iter = iterAbs2( rand ); b.tic(); for ( i = 0; i < b.iterations; i++ ) { z = iter.next().value; if ( isnan( z ) ) { b.fail( 'should not return NaN' ); } } b.toc(); if ( isnan( z ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); });
stdlib-js/stdlib
lib/node_modules/@stdlib/math/iter/special/abs2/benchmark/benchmark.js
JavaScript
apache-2.0
1,768
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v202111; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for getLineItemTemplatesByStatementResponse element declaration. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;element name="getLineItemTemplatesByStatementResponse"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="rval" type="{https://www.google.com/apis/ads/publisher/v202111}LineItemTemplatePage" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "rval" }) @XmlRootElement(name = "getLineItemTemplatesByStatementResponse") public class LineItemTemplateServiceInterfacegetLineItemTemplatesByStatementResponse { protected LineItemTemplatePage rval; /** * Gets the value of the rval property. * * @return * possible object is * {@link LineItemTemplatePage } * */ public LineItemTemplatePage getRval() { return rval; } /** * Sets the value of the rval property. * * @param value * allowed object is * {@link LineItemTemplatePage } * */ public void setRval(LineItemTemplatePage value) { this.rval = value; } }
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202111/LineItemTemplateServiceInterfacegetLineItemTemplatesByStatementResponse.java
Java
apache-2.0
2,295
/** The benchmark is distributed under the Creative Commons, * Attribution-NonCommercial-NoDerivatives. This license includes the benchmark database * and its derivatives. For attribution, please cite this page, and our publications below. * This data is provided free of charge for non-commercial and academic benchmarking and * experimentation use. If you would like to contribute to the benchmark, please contact us. * If you believe you intended usage may be restricted by the license, * please contact us and we can discuss the possibilities. */ import java.applet.Applet; import java.awt.Image; import java.awt.Graphics; import java.awt.Rectangle; import java.util.StringTokenizer; import java.util.Vector; import java.util.Hashtable; import java.net.URL; import java.awt.image.*; import java.net.MalformedURLException; /** * An extensible ImageMap applet class. * The active areas on the image are controlled by ImageArea classes * that can be dynamically loaded over the net. * * @author Jim Graham * @version %I%, %G% */ public class ImageMap extends Applet { /** * The unhighlighted image being mapped. */ Image baseImage; /** * The list of image area handling objects; */ ImageMapArea areas[]; /** * The primary highlight mode to be used. */ static final int BRIGHTER = 0; static final int DARKER = 1; int hlmode = BRIGHTER; /** * The percentage of highlight to apply for the primary highlight mode. */ int hlpercent = 50; /** * Get a rectangular region of the baseImage highlighted according to * the primary highlight specification. */ Image getHighlight(int x, int y, int w, int h) { return getHighlight(x, y, w, h, hlmode, hlpercent); } /** * Get a rectangular region of the baseImage with a specific highlight. */ Image getHighlight(int x, int y, int w, int h, int mode, int percent) { return getHighlight(x, y, w, h, new HighlightFilter(mode == BRIGHTER, percent)); } /** * Get a rectangular region of the baseImage modified by an image filter. */ Image getHighlight(int x, int y, int w, int h, ImageFilter filter) { Image cropped = makeImage(baseImage, new CropImageFilter(x, y, w, h)); return makeImage(cropped, filter); } /** * Make the primary highlighted version of the baseImage. */ Image makeImage(Image orig, ImageFilter filter) { return createImage(new FilteredImageSource(orig.getSource(), filter)); } /** * Parse a string representing the desired highlight to be applied. */ void parseHighlight(String s) { if (s == null) { return; } if (s.startsWith("brighter")) { hlmode = BRIGHTER; if (s.length() > "brighter".length()) { hlpercent = Integer.parseInt(s.substring("brighter".length())); } } else if (s.startsWith("darker")) { hlmode = DARKER; if (s.length() > "darker".length()) { hlpercent = Integer.parseInt(s.substring("darker".length())); } } } /** * Initialize the applet. Get attributes. * * Initialize the ImageAreas. * Each ImageArea is a subclass of the class ImageArea, and is * specified with an attribute of the form: * areaN=ImageAreaClassName,arguments... * The ImageAreaClassName is parsed off and a new instance of that * class is created. The initializer for that class is passed a * reference to the applet and the remainder of the attribute * string, from which the class should retrieve any information it * needs about the area it controls and the actions it needs to * take within that area. */ public void init() { String s; parseHighlight(getParameter("highlight")); baseImage = getImage(getDocumentBase(), getParameter("img")); Vector areaVec = new Vector(); int num = 1; while (true) { ImageMapArea newArea; s = getParameter("area" + num); if (s == null) { s = getParameter("rect" + num); if (s == null) { break; } String url = getParameter("href" + num); if (url != null) s += "," + url; newArea = new HrefArea(); } else { int classend = s.indexOf(","); try { String name = s.substring(0, classend); newArea = (ImageMapArea) Class.forName(name).newInstance(); } catch (Exception e) { e.printStackTrace(); break; } s = s.substring(classend + 1); } newArea.init(this, s); areaVec.addElement(newArea); num++; } areas = new ImageMapArea[areaVec.size()]; areaVec.copyInto(areas); checkSize(); } /** * Check the size of this applet while the image is being loaded. */ synchronized void checkSize() { int w = baseImage.getWidth(this); int h = baseImage.getHeight(this); if (w > 0 && h > 0) { resize(w, h); repaintrect.x = repaintrect.y = 0; repaintrect.width = w; repaintrect.height = h; fullrepaint = true; repaint(); } } private boolean fullrepaint = false; private Rectangle repaintrect = new Rectangle(); private long lastupdate = 0; private static final long UPDATERATE = 100; /** * Handle updates from images being loaded. */ public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { if ((infoflags & (WIDTH | HEIGHT)) != 0) { checkSize(); } if ((infoflags & (SOMEBITS | FRAMEBITS | ALLBITS)) != 0) { repaint(((infoflags & (FRAMEBITS | ALLBITS)) != 0) ? 0 : UPDATERATE, x, y, width, height); } return (infoflags & (ALLBITS | ERROR)) == 0; } /** * Paint the image and all active highlights. */ public void paint(Graphics g) { synchronized (this) { if (fullrepaint) { g = g.create(); g.clipRect(repaintrect.x, repaintrect.y, repaintrect.width, repaintrect.height); fullrepaint = false; } } if (baseImage == null) { return; } g.drawImage(baseImage, 0, 0, this); if (areas != null) { for (int i = areas.length; --i >= 0; ) { if (areas[i].active || areas[i].entered) { areas[i].setState(g, areas[i].entered); } } } } /** * Update the active highlights on the image. */ public void update(Graphics g) { if (fullrepaint) { paint(g); return; } if (baseImage == null) { return; } g.drawImage(baseImage, 0, 0, this); if (areas == null) { return; } for (int i = areas.length; --i >= 0; ) { if (areas[i].active && !areas[i].entered) { areas[i].setState(g, false); } } for (int i = areas.length; --i >= 0; ) { if (areas[i].entered) { areas[i].setState(g, true); } } } /** * Make sure that no ImageAreas are highlighted. */ public void mouseExit() { boolean changed = false; for (int i = 0; i < areas.length; i++) { if (areas[i].active) { areas[i].entered = false; changed = true; } } if (changed) { repaint(); } } /** * Find the ImageAreas that the mouse is in. */ public boolean mouseMove(java.awt.Event evt, int x, int y) { boolean changed = false; boolean propagate = true; for (int i = 0; i < areas.length; i++) { if (areas[i].inside(x, y)) { areas[i].entered = propagate; if (areas[i].terminal) { propagate = false; } } else { areas[i].entered = false; } if (areas[i].active != areas[i].entered) { changed = true; } } if (changed) { repaint(); } return true; } int pressX; int pressY; /** * Inform all active ImageAreas of a mouse press. */ public boolean mouseDown(java.awt.Event evt, int x, int y) { pressX = x; pressY = y; for (int i = 0; i < areas.length; i++) { if (areas[i].inside(x, y)) { areas[i].press(x, y); if (areas[i].terminal) { break; } } } return true; } /** * Inform all active ImageAreas of a mouse release. * Only those areas that were inside the original mouseDown() * are informed of the mouseUp. */ public boolean mouseUp(java.awt.Event evt, int x, int y) { for (int i = 0; i < areas.length; i++) { if (areas[i].inside(pressX, pressY)) { areas[i].lift(x, y); if (areas[i].terminal) { break; } } } return true; } /** * Inform all active ImageAreas of a mouse drag. * Only those areas that were inside the original mouseDown() * are informed of the mouseUp. */ public boolean mouseDrag(java.awt.Event evt, int x, int y) { mouseMove(evt, x, y); for (int i = 0; i < areas.length; i++) { if (areas[i].inside(pressX, pressY)) { areas[i].drag(x, y); if (areas[i].terminal) { break; } } } return true; } } /** * The base ImageArea class. * This class performs the basic functions that most ImageArea * classes will need and delegates specific actions to the subclasses. * * @author Jim Graham * @version %I%, %G% */ class ImageMapArea implements ImageObserver { /** The applet parent that contains this ImageArea. */ ImageMap parent; /** The X location of the area (if rectangular). */ int X; /** The Y location of the area (if rectangular). */ int Y; /** The size().width of the area (if rectangular). */ int W; /** The size().height of the area (if rectangular). */ int H; /** * This flag indicates whether the user was in this area during the * last scan of mouse locations. */ boolean entered = false; /** This flag indicates whether the area is currently highlighted. */ boolean active = false; /** * This flag indicates whether the area is terminal. Terminal areas * prevent any areas which are under them from being activated when * the mouse is inside them. Some areas may wish to change this to * false so that they can augment other areas that they are on top of. */ boolean terminal = true; /** * This is the default highlight image if no special effects are * needed to draw the highlighted image. It is created by the * default "makeImages()" method. */ Image hlImage; /** * Initialize this ImageArea as called from the applet. * If the subclass does not override this initializer, then it * will perform the basic functions of setting the parent applet * and parsing out 4 numbers from the argument string which specify * a rectangular region for the ImageArea to act on. * The remainder of the argument string is passed to the handleArg() * method for more specific handling by the subclass. */ public void init(ImageMap parent, String args) { this.parent = parent; StringTokenizer st = new StringTokenizer(args, ", "); X = Integer.parseInt(st.nextToken()); Y = Integer.parseInt(st.nextToken()); W = Integer.parseInt(st.nextToken()); H = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) { handleArg(st.nextToken("")); } else { handleArg(null); } makeImages(); } /** * This method handles the remainder of the argument string after * the standard initializer has parsed off the 4 rectangular * parameters. If the subclass does not override this method, * the remainder will be ignored. */ public void handleArg(String s) { } /** * This method sets the image to be used to render the ImageArea * when it is highlighted. */ public void setHighlight(Image img) { hlImage = img; } /** * This method handles the construction of the various images * used to highlight this particular ImageArea when the user * interacts with it. */ public void makeImages() { setHighlight(parent.getHighlight(X, Y, W, H)); } /** * This method tests to see if a point is inside this ImageArea. * The standard method assumes a rectangular area as parsed by * the standard initializer. If a more complex area is required * then this method will have to be overridden by the subclass. */ public boolean inside(int x, int y) { return (x >= X && x < (X + W) && y >= Y && y < (Y + H)); } /** * This utility method draws a rectangular subset of a highlight * image. */ public void drawImage(Graphics g, Image img, int imgx, int imgy, int x, int y, int w, int h) { Graphics ng = g.create(); ng.clipRect(x, y, w, h); ng.drawImage(img, imgx, imgy, this); } /** * This method handles the updates from drawing the images. */ public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { if (img == hlImage) { return parent.imageUpdate(img, infoflags, x + X, y + Y, width, height); } else { return false; } } /** * This utility method shows a string in the status bar. */ public void showStatus(String msg) { parent.getAppletContext().showStatus(msg); } /** * This utility method tells the browser to visit a URL. */ public void showDocument(URL u) { parent.getAppletContext().showDocument(u); } /** * This method highlights the specified area when the user enters * it with his mouse. The standard highlight method is to replace * the indicated rectangular area of the image with the primary * highlighted image. */ public void highlight(Graphics g, boolean on) { if (on) { g.drawImage(hlImage, X, Y, this); } else { drawImage(g, parent.baseImage, 0, 0, X, Y, W, H); } } /** * This method changes the active state of the ImageArea, which * indicates whether the user is currently "inside" this area. * It turns around and calls the highlight method which is likely * to have been overridden by subclasses seeking a custom highlight. */ public void setState(Graphics g, boolean on) { highlight(g, on); active = on; } /** * The press method is called when the user presses the mouse * button inside the ImageArea. The location is supplied, but * the standard implementation is to call the overloaded method * with no arguments. */ public void press(int x, int y) { press(); } /** * The overloaded press method is called when the user presses the * mouse button inside the ImageArea. This method can be overridden * if the ImageArea does not need to know the location of the press. */ public void press() { } /** * The lift method is called when the user releases the mouse button. * The location is supplied, but the standard implementation is to * call the overloaded method with no arguments. Only those ImageAreas * that were informed of a press will be informed of the corresponding * release. */ public void lift(int x, int y) { lift(); } /** * The overloaded lift method is called when the user releases the * mouse button. This method can be overridden if the ImageArea * does not need to know the location of the release. */ public void lift() { } /** * The drag method is called when the user moves the mouse while * the button is pressed. Only those ImageAreas that were informed * of a press will be informed of the corresponding mouse movements. */ public void drag(int x, int y) { } } /** * The classic "Fetch a URL" ImageArea class. * This class extends the basic ImageArea Class to fetch a URL when * the user clicks in the area. * * @author Jim Graham * @version %I%, %G% */ class HrefArea extends ImageMapArea { /** The URL to be fetched when the user clicks on this area. */ URL anchor; /** * The argument string is the URL to be fetched. */ public void handleArg(String arg) { try { anchor = new URL(parent.getDocumentBase(), arg); } catch (MalformedURLException e) { anchor = null; } } /** * The status message area is updated to show the destination URL. * The default graphics highlight feedback is used. */ public void highlight(Graphics g, boolean on) { super.highlight(g, on); showStatus((on && anchor != null) ? "Go To " + anchor.toExternalForm() : null); } /** * The new URL is fetched when the user releases the mouse button * only if they are still in the area. */ public void lift(int x, int y) { if (inside(x, y) && anchor != null) { showDocument(anchor); } } } /** * An audio feedback ImageArea class. * This class extends the basic ImageArea Class to play a sound each * time the user enters the area. * * @author Jim Graham * @version %I%, %G% */ class SoundArea extends ImageMapArea { /** The URL of the sound to be played. */ String sound; /** * The argument is the URL of the sound to be played. * This method also sets this type of area to be non-terminal. */ public void handleArg(String arg) { sound = arg; terminal = false; } /** * The highlight method plays the sound in addition to the usual * graphical highlight feedback. */ public void highlight(Graphics g, boolean on) { if (on && !active) { parent.play(parent.getDocumentBase(), sound); } super.highlight(g, on); } } /** * An click feedback ImageArea class. * This class extends the basic ImageArea Class to show the locations * of clicks in the image in the status message area. This utility * ImageArea class is useful when setting up ImageMaps. * * @author Jim Graham * @version %I%, %G% */ class ClickArea extends ImageMapArea { /** The X location of the last mouse press. */ int startx; /** The Y location of the last mouse press. */ int starty; /** * The argument is ignored, but we use this method to set this type * of area to be non-terminal. */ public void handleArg(String arg) { terminal = false; } /** This class overrides the highlight method to prevent highlighting. */ public void highlight(Graphics g, boolean on) { } String ptstr(int x, int y) { return "(" + x + ", " + y + ")"; } /** * When the user presses the mouse button, start showing coordinate * feedback in the status message line. */ public void press(int x, int y) { showStatus("Clicked at " + ptstr(x, y)); startx = x; starty = y; } /** * Update the coordinate feedback every time the user moves the mouse * while he has the button pressed. */ public void drag(int x, int y) { showStatus("Rectangle from " + ptstr(startx, starty) + " to " + ptstr(x, y) + " is " + (x - startx) + "x" + (y - starty)); } /** * Update the coordinate feedback one last time when the user releases * the mouse button. */ public void lift(int x, int y) { drag(x, y); } } /** * A message feedback ImageArea class. * This class extends the basic ImageArea Class to show the a given * message in the status message area when the user enters this area. * * @author Jim Graham * @version %I%, %G% */ class NameArea extends ImageMapArea { /** The string to be shown in the status message area. */ String name; /** * The argument is the string to be displayed in the status message * area. This method also sets this type of area to be non-terminal. */ public void handleArg(String arg) { name = arg; terminal = false; } /** * The highlight method displays the message in addition to the usual * graphical highlight feedback. */ public void highlight(Graphics g, boolean on) { super.highlight(g, on); showStatus(on ? name : null); } } /** * An improved "Fetch a URL" ImageArea class. * This class extends the basic ImageArea Class to fetch a URL when * the user clicks in the area. In addition, special custom highlights * are used to make the area look and feel like a 3-D button. * * @author Jim Graham * @version %I%, %G% */ class HrefButtonArea extends ImageMapArea { /** The URL to be fetched when the user clicks on this area. */ URL anchor; /** The highlight image for when the button is "UP". */ Image upImage; /** The highlight image for when the button is "DOWN". */ Image downImage; /** This flag indicates if the "button" is currently pressed. */ boolean pressed = false; /** The border size for the 3-D effect. */ int border = 5; /** * The argument string is the URL to be fetched. * This method also constructs the various highlight images needed * to achieve the 3-D effect. */ public void handleArg(String arg) { try { anchor = new URL(parent.getDocumentBase(), arg); } catch (MalformedURLException e) { anchor = null; } if (border * 2 > W || border * 2 > H) { border = Math.min(W, H) / 2; } } public void makeImages() { upImage = parent.getHighlight(X, Y, W, H, new ButtonFilter(false, parent.hlpercent, border, W, H)); downImage = parent.getHighlight(X, Y, W, H, new ButtonFilter(true, parent.hlpercent, border, W, H)); } public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { if (img == (pressed ? downImage : upImage)) { return parent.imageUpdate(img, infoflags, x + X, y + Y, width, height); } else { return (img == downImage || img == upImage); } } /** * The status message area is updated to show the destination URL. * The graphical highlight is achieved using the ButtonFilter. */ public void highlight(Graphics g, boolean on) { if (on) { setHighlight(pressed ? downImage : upImage); } super.highlight(g, on); showStatus((on && anchor != null) ? "Go To " + anchor.toExternalForm() : null); } /** * Since the highlight changes when the button is pressed, we need * to record the "pressed" state and induce a repaint. */ public void press() { parent.repaint(); pressed = true; } /** * The new URL is fetched when the user releases the mouse button * only if they are still in the area. */ public void lift(int x, int y) { pressed = false; parent.repaint(); if (inside(x, y) && anchor != null) { showDocument(anchor); } } } /** * An improved, round, "Fetch a URL" ImageArea class. * This class extends the HrefButtonArea Class to make the 3D button * a rounded ellipse. All of the same feedback and operational * charactistics as the HrefButtonArea apply. * * @author Jim Graham * @version %I%, %G% */ class RoundHrefButtonArea extends HrefButtonArea { public void makeImages() { upImage = parent.getHighlight(X, Y, W, H, new RoundButtonFilter(false, parent.hlpercent, border, W, H)); downImage = parent.getHighlight(X, Y, W, H, new RoundButtonFilter(true, parent.hlpercent, border, W, H)); } } class HighlightFilter extends RGBImageFilter { boolean brighter; int percent; public HighlightFilter(boolean b, int p) { brighter = b; percent = p; canFilterIndexColorModel = true; } public int filterRGB(int x, int y, int rgb) { int r = (rgb >> 16) & 0xff; int g = (rgb >> 8) & 0xff; int b = (rgb >> 0) & 0xff; if (brighter) { r = (255 - ((255 - r) * (100 - percent) / 100)); g = (255 - ((255 - g) * (100 - percent) / 100)); b = (255 - ((255 - b) * (100 - percent) / 100)); } else { r = (r * (100 - percent) / 100); g = (g * (100 - percent) / 100); b = (b * (100 - percent) / 100); } if (r < 0) r = 0; if (r > 255) r = 255; if (g < 0) g = 0; if (g > 255) g = 255; if (b < 0) b = 0; if (b > 255) b = 255; return (rgb & 0xff000000) | (r << 16) | (g << 8) | (b << 0); } } class ButtonFilter extends RGBImageFilter { boolean pressed; int defpercent; int border; int width; int height; ColorModel models[] = new ColorModel[7]; ColorModel origbuttonmodel; public ButtonFilter(boolean press, int p, int b, int w, int h) { pressed = press; defpercent = p; border = b; width = w; height = h; } public void setHints(int hints) { super.setHints(hints & (~ImageConsumer.COMPLETESCANLINES)); } public void setColorModel(ColorModel model) { if (model instanceof IndexColorModel && true) { IndexColorModel icm = (IndexColorModel) model; models[0] = filterIndexColorModel(icm, false, false, 0); models[1] = filterIndexColorModel(icm, true, !pressed, defpercent); models[2] = null; if (pressed) { models[3] = filterIndexColorModel(icm, true, false, defpercent / 2); } else { models[3] = models[0]; } models[4] = null; models[5] = filterIndexColorModel(icm, true, pressed, defpercent); models[6] = models[0]; origbuttonmodel = model; consumer.setColorModel(models[3]); } else { super.setColorModel(model); } } public IndexColorModel filterIndexColorModel(IndexColorModel icm, boolean opaque, boolean brighter, int percent) { byte r[] = new byte[256]; byte g[] = new byte[256]; byte b[] = new byte[256]; byte a[] = new byte[256]; int mapsize = icm.getMapSize(); icm.getReds(r); icm.getGreens(g); icm.getBlues(b); if (opaque) { icm.getAlphas(a); for (int i = 0; i < mapsize; i++) { int rgb = filterRGB(icm.getRGB(i), brighter, percent); a[i] = (byte) (rgb >> 24); r[i] = (byte) (rgb >> 16); g[i] = (byte) (rgb >> 8); b[i] = (byte) (rgb >> 0); } } return new IndexColorModel(icm.getPixelSize(), mapsize, r, g, b, a); } /** * Define the ranges of varying highlight for the button. * ranges is an array of 8 values which split up a scanline into * 7 different regions of highlighting effect: * * ranges[0-1] = area outside of left edge of button * ranges[1-2] = area inside UpperLeft highlight region left of center * ranges[2-3] = area requiring custom highlighting left of center * ranges[3-4] = area inside center of button * ranges[4-5] = area requiring custom highlighting right of center * ranges[5-6] = area inside LowerRight highlight region right of center * ranges[6-7] = area outside of right edge of button * * Note that ranges[0-1] and ranges[6-7] are empty where the edges of * the button touch the left and right edges of the image (everywhere * on a square button) and ranges[2-3] and ranges[4-5] are only nonempty * in those regions where the UpperLeft highlighting has leaked over * the "top" of the button onto parts of its right edge or where the * LowerRight highlighting has leaked under the "bottom" of the button * onto parts of its left edge (can't happen on square buttons, happens * occasionally on round buttons). */ public void buttonRanges(int y, int ranges[]) { ranges[0] = ranges[1] = 0; if (y < border) { ranges[2] = ranges[3] = ranges[4] = ranges[5] = width - y; } else if (y > height - border) { ranges[2] = ranges[3] = ranges[4] = ranges[5] = height - y; } else { ranges[2] = ranges[3] = border; ranges[4] = ranges[5] = width - border; } ranges[6] = ranges[7] = width; } public void setPixels(int x, int y, int w, int h, ColorModel model, byte pixels[], int off, int scansize) { if (model == origbuttonmodel) { int ranges[] = new int[8]; int x2 = x + w; for (int cy = y; cy < y + h; cy++) { buttonRanges(cy, ranges); for (int i = 0; i < 7; i++) { if (x2 > ranges[i] && x < ranges[i + 1]) { int cx1 = Math.max(x, ranges[i]); int cx2 = Math.min(x2, ranges[i + 1]); if (models[i] == null) { super.setPixels(cx1, cy, cx2 - cx1, 1, model, pixels, off + (cx1 - x), scansize); } else { if (cx1 < cx2) { consumer.setPixels(cx1, cy, cx2 - cx1, 1, models[i], pixels, off + (cx1 - x), scansize); } } } } off += scansize; } } else { super.setPixels(x, y, w, h, model, pixels, off, scansize); } } public int filterRGB(int x, int y, int rgb) { boolean brighter; int percent; if ((x < border && y < height - x) || (y < border && x < width - y)) { brighter = !pressed; percent = defpercent; } else if (x >= width - border || y >= height - border) { brighter = pressed; percent = defpercent; } else if (pressed) { brighter = false; percent = defpercent / 2; } else { return rgb & 0x00ffffff; } return filterRGB(rgb, brighter, percent); } public int filterRGB(int rgb, boolean brighter, int percent) { int r = (rgb >> 16) & 0xff; int g = (rgb >> 8) & 0xff; int b = (rgb >> 0) & 0xff; if (brighter) { r = (255 - ((255 - r) * (100 - percent) / 100)); g = (255 - ((255 - g) * (100 - percent) / 100)); b = (255 - ((255 - b) * (100 - percent) / 100)); } else { r = (r * (100 - percent) / 100); g = (g * (100 - percent) / 100); b = (b * (100 - percent) / 100); } if (r < 0) r = 0; if (g < 0) g = 0; if (b < 0) b = 0; if (r > 255) r = 255; if (g > 255) g = 255; if (b > 255) b = 255; return (rgb & 0xff000000) | (r << 16) | (g << 8) | (b << 0); } } class RoundButtonFilter extends ButtonFilter { int Xcenter; int Ycenter; int Yradsq; int innerW; int innerH; int Yrad2sq; public RoundButtonFilter(boolean press, int p, int b, int w, int h) { super(press, p, b, w, h); Xcenter = w / 2; Ycenter = h / 2; Yradsq = h * h / 4; innerW = w - border * 2; innerH = h - border * 2; Yrad2sq = innerH * innerH / 4; } public void buttonRanges(int y, int ranges[]) { int yrel = Math.abs(Ycenter - y); int xrel = (int) (Math.sqrt(Yradsq - yrel * yrel) * width / height); int xslash = width - (y * width / height); ranges[0] = 0; ranges[1] = Xcenter - xrel; ranges[6] = Xcenter + xrel; ranges[7] = width; if (y < border) { ranges[2] = ranges[3] = ranges[4] = Xcenter; ranges[5] = ranges[6]; } else if (y + border >= height) { ranges[2] = ranges[1]; ranges[3] = ranges[4] = ranges[5] = Xcenter; } else { int xrel2 = (int) (Math.sqrt(Yrad2sq - yrel * yrel) * innerW / innerH); ranges[3] = Xcenter - xrel2; ranges[4] = Xcenter + xrel2; if (y < Ycenter) { ranges[2] = ranges[3]; ranges[5] = ranges[6]; } else { ranges[2] = ranges[1]; ranges[5] = ranges[4]; } } } private int savedranges[]; private int savedy; private synchronized int[] getRanges(int y) { if (savedranges == null || savedy != y) { if (savedranges == null) { savedranges = new int[8]; } buttonRanges(y, savedranges); savedy = y; } return savedranges; } public int filterRGB(int x, int y, int rgb) { boolean brighter; int percent; int i; int ranges[] = getRanges(y); for (i = 0; i < 7; i++) { if (x >= ranges[i] && x < ranges[i + 1]) { break; } } double angle; switch(i) { default: case 0: case 6: return rgb & 0x00ffffff; case 1: brighter = !pressed; percent = defpercent; break; case 5: brighter = pressed; percent = defpercent; break; case 2: angle = Math.atan2(y - Ycenter, Xcenter - x); percent = defpercent - ((int) (Math.cos(angle) * 2 * defpercent)); if (!pressed) { percent = -percent; } if (percent == 0) { return rgb; } else if (percent < 0) { percent = -percent; brighter = false; } else { brighter = true; } break; case 4: angle = Math.atan2(Ycenter - y, x - Xcenter); percent = defpercent - ((int) (Math.cos(angle) * 2 * defpercent)); if (pressed) { percent = -percent; } if (percent == 0) { return rgb; } else if (percent < 0) { percent = -percent; brighter = false; } else { brighter = true; } break; case 3: if (!pressed) { return rgb & 0x00ffffff; } brighter = false; percent = defpercent; break; } return filterRGB(rgb, brighter, percent); } }
LudditeLabs/query-reform
data/samples/Java/75184.java
Java
apache-2.0
36,301
/* * Copyright 2017 Sebastien Callier * * 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 sebastien.callier.serialization.stream; import java.io.InputStream; /** * @author Sebastien Callier * @since 2017 */ public final class FastInputStream extends InputStream { private byte bytes[]; private int mark; private int position; private int byteCount; private int byteOffset; public FastInputStream(byte bytes[]) { this.bytes = bytes; this.byteCount = bytes.length; } public FastInputStream( byte bytes[], int offset, int length) { this.bytes = bytes; this.byteOffset = offset; this.position = offset; this.mark = offset; this.byteCount = Math.min(offset + length, bytes.length); } @Override public int read() { return (position < byteCount) ? (bytes[position++] & 0xFF) : -1; } @Override public int read( byte[] data, int offset, int length) { if (offset < 0 || length < 0 || length + offset > data.length) { throw new IndexOutOfBoundsException(); } if (position >= byteCount) { return -1; } length = (position + length > byteCount) ? byteCount - position : length; if (length <= 0) { return 0; } System.arraycopy(bytes, position, data, offset, length); position += length; return length; } @Override public boolean markSupported() { return true; } @Override public void mark(int readAheadLimit) { mark = position; } @Override public void reset() { position = mark; } @Override public long skip(long n) { if (n <= 0) { return 0; } n = (position + n > byteCount) ? byteCount - position : n; position += n; return n; } @Override public int available() { return byteCount - position; } @Override public void close() { //nothing to do } public int getPosition() { return position; } public int getSize() { return byteCount - byteOffset; } }
S-Callier/serialization
src/main/java/sebastien/callier/serialization/stream/FastInputStream.java
Java
apache-2.0
2,802
// Copyright 2014 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 // // 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 oomparser import ( "bufio" "fmt" "io" "os" "os/exec" "path" "regexp" "strconv" "time" "github.com/golang/glog" "github.com/Clever/cadvisor/utils" ) var containerRegexp *regexp.Regexp = regexp.MustCompile( `Task in (.*) killed as a result of limit of (.*)`) var lastLineRegexp *regexp.Regexp = regexp.MustCompile( `(^[A-Z]{1}[a-z]{2} .*[0-9]{1,2} [0-9]{1,2}:[0-9]{2}:[0-9]{2}) .* Killed process ([0-9]+) \(([0-9A-Za-z_]+)\)`) var firstLineRegexp *regexp.Regexp = regexp.MustCompile( `invoked oom-killer:`) // struct to hold file from which we obtain OomInstances type OomParser struct { ioreader *bufio.Reader } // struct that contains information related to an OOM kill instance type OomInstance struct { // process id of the killed process Pid int // the name of the killed process ProcessName string // the time that the process was reported to be killed, // accurate to the minute TimeOfDeath time.Time // the absolute name of the container that OOMed ContainerName string // the absolute name of the container that was killed // due to the OOM. VictimContainerName string } // gets the container name from a line and adds it to the oomInstance. func getContainerName(line string, currentOomInstance *OomInstance) error { parsedLine := containerRegexp.FindStringSubmatch(line) if parsedLine == nil { return nil } currentOomInstance.ContainerName = path.Join("/", parsedLine[1]) currentOomInstance.VictimContainerName = path.Join("/", parsedLine[2]) return nil } // gets the pid, name, and date from a line and adds it to oomInstance func getProcessNamePid(line string, currentOomInstance *OomInstance) (bool, error) { reList := lastLineRegexp.FindStringSubmatch(line) if reList == nil { return false, nil } const longForm = "Jan _2 15:04:05 2006" stringYear := strconv.Itoa(time.Now().Year()) linetime, err := time.ParseInLocation(longForm, reList[1]+" "+stringYear, time.Local) if err != nil { return false, err } currentOomInstance.TimeOfDeath = linetime pid, err := strconv.Atoi(reList[2]) if err != nil { return false, err } currentOomInstance.Pid = pid currentOomInstance.ProcessName = reList[3] return true, nil } // uses regex to see if line is the start of a kernel oom log func checkIfStartOfOomMessages(line string) bool { potential_oom_start := firstLineRegexp.MatchString(line) if potential_oom_start { return true } return false } // reads the file and sends only complete lines over a channel to analyzeLines. // Should prevent EOF errors that occur when lines are read before being fully // written to the log. It reads line by line splitting on // the "\n" character. func readLinesFromFile(lineChannel chan string, ioreader *bufio.Reader) { linefragment := "" var line string var err error for true { line, err = ioreader.ReadString('\n') if err == io.EOF { if line != "" { linefragment += line } time.Sleep(100 * time.Millisecond) } else if err == nil { if linefragment != "" { line = linefragment + line linefragment = "" } lineChannel <- line } else if err != nil && err != io.EOF { glog.Errorf("exiting analyzeLinesHelper with error %v", err) } } } // Calls goroutine for readLinesFromFile, which feeds it complete lines. // Lines are checked against a regexp to check for the pid, process name, etc. // At the end of an oom message group, StreamOoms adds the new oomInstance to // oomLog func (self *OomParser) StreamOoms(outStream chan *OomInstance) { lineChannel := make(chan string, 10) go func() { readLinesFromFile(lineChannel, self.ioreader) }() for line := range lineChannel { in_oom_kernel_log := checkIfStartOfOomMessages(line) if in_oom_kernel_log { oomCurrentInstance := &OomInstance{ ContainerName: "/", } finished := false for !finished { err := getContainerName(line, oomCurrentInstance) if err != nil { glog.Errorf("%v", err) } finished, err = getProcessNamePid(line, oomCurrentInstance) if err != nil { glog.Errorf("%v", err) } line = <-lineChannel } in_oom_kernel_log = false outStream <- oomCurrentInstance } } glog.Infof("exiting analyzeLines") } func callJournalctl() (io.ReadCloser, error) { cmd := exec.Command("journalctl", "-f") readcloser, err := cmd.StdoutPipe() if err != nil { return nil, err } if err := cmd.Start(); err != nil { return nil, err } return readcloser, err } func trySystemd() (*OomParser, error) { readcloser, err := callJournalctl() if err != nil { return nil, err } glog.Infof("oomparser using systemd") return &OomParser{ ioreader: bufio.NewReader(readcloser), }, nil } // List of possible kernel log files. These are prioritized in order so that // we will use the first one that is available. var kernelLogFiles = []string{"/var/log/kern.log", "/var/log/messages", "/var/log/syslog"} // looks for system files that contain kernel messages and if one is found, sets // the systemFile attribute of the OomParser object func getSystemFile() (string, error) { for _, logFile := range kernelLogFiles { if utils.FileExists(logFile) { glog.Infof("OOM parser using kernel log file: %q", logFile) return logFile, nil } } return "", fmt.Errorf("unable to find any kernel log file available from our set: %v", kernelLogFiles) } // initializes an OomParser object and calls getSystemFile to set the systemFile // attribute. Returns and OomParser object and an error func New() (*OomParser, error) { systemFile, err := getSystemFile() if err != nil { return trySystemd() } file, err := os.Open(systemFile) if err != nil { return trySystemd() } return &OomParser{ ioreader: bufio.NewReader(file), }, nil }
Clever/cadvisor
utils/oomparser/oomparser.go
GO
apache-2.0
6,339
/* AODV Overlay v0.5.3 Copyright 2007-2010 Lancaster University Rajiv Ramdhany This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package msg; import interfaces.IState.IAodvState; import java.net.*; import aodvstate.*; import jpcap.*; import jpcap.packet.UDPPacket; /** * This Class represents a Route Reply Acknowledgement Message (RREPACK) in AODV as * defined in RFC 3561. It includes the DatagramPacket that represents * the UDP packet. * * @author : Koojana Kuladinithi * @date : 08-aug-2007 * @email : koo@comnets.uni-bremen.de * */ public class RREPACK extends AODVMessage { // variables of AODV RREPACK message /** * Constructor to create a RREPACK using the contents of a * DatagramPacket. This is how a RREPACK is created as a * response to RREP message with the A bit set. * * @param ConfigInfo cfg - the config info object * @param CurrentInfo cur - the current info object * @param jpcap.UDPPacket up - the Datagram from which this RREPACK * is created * @param String iface - the interface on whiuch the RREPACK was received */ public RREPACK(ConfigInfo cfg, IAodvState cur, UDPPacket up, String iface) throws Exception { super(cfg, cur, up, iface); } /** * Constructor to create a RREPACK. This is required when the protocol handler * requires to generate a RREPACK * * @param ConfigInfo cfg - the config info object * @param CurrentInfo cur - the current info object * @param boolean mf - when sending, multicast or unicast * @param InetAddress sendto - the address to which this is sent * @param short ttl - TTL value on the message * */ public RREPACK(ConfigInfo cfg, IAodvState cur, boolean mf, InetAddress sendto, short ttl) throws Exception { super(cfg, cur, mf, sendto, ttl); if(cfgInfo.ipVersionVal == ConfigInfo.IPv4_VERSION_VAL) buildDgramUsingIPv4RREPACK(); else if(cfgInfo.ipVersionVal == ConfigInfo.IPv6_VERSION_VAL) buildDgramUsingIPv6RREPACK(); else throw new Exception("Invalid IP version"); } /** * Method to build the DatagramPacket using the information * in the IPv4 RREPACK * */ private void buildDgramUsingIPv4RREPACK() throws Exception { byte msg[] = new byte[2]; msg[0] = AODV_RREPACK_MSG_CODE; javaUDPDgram = new DatagramPacket(msg, msg.length, toIPAddr, AODV_PORT); } /** * Method to build the DatagramPacket using the information * in the IPv6 RREPACK * @exception Exception - if error, exception thrown */ private void buildDgramUsingIPv6RREPACK() throws Exception { } /** * Method to return the values in RREPACK message * @return String - RREPACK Message contents as a string */ public String toString() { String str = super.toString(); str = "RREP-ACK Message " + ", " + str; return str; } }
ramdhany/AODV
AODVOverlay/msg/RREPACK.java
Java
apache-2.0
3,377
import os import calliope import pytest # pylint: disable=unused-import import tempfile from calliope.core.attrdict import AttrDict from calliope.test.common.util import check_error_or_warning, python36_or_higher HTML_STRINGS = AttrDict.from_yaml( os.path.join(os.path.dirname(__file__), 'common', 'html_strings.yaml') ) class TestPlotting: @pytest.fixture(scope="module") def national_scale_example(self): model = calliope.examples.national_scale( override_dict={'model.subset_time': '2005-01-01'} ) model.run() return model @python36_or_higher def test_national_scale_plotting(self, national_scale_example): model = national_scale_example plot_html_outputs = { 'capacity': model.plot.capacity(html_only=True), 'timeseries': model.plot.timeseries(html_only=True), 'transmission': model.plot.transmission(html_only=True), 'flows': model.plot.flows(html_only=True), } for plot_type in HTML_STRINGS['national_scale']: for string in HTML_STRINGS['national_scale'][plot_type]: assert string in plot_html_outputs[plot_type] # Also just try plotting the summary model.plot.summary() # Testing that the model can handle not having supply_plus technologies # Wrapped in temporary directory as we can't stop it saving an HTML file model._model_data = model._model_data.drop('resource_con') with tempfile.TemporaryDirectory() as tempdir: out_path = os.path.join(tempdir, 'test_plot.html') model.plot.timeseries( plotly_kwarg_updates={'auto_open': False, 'filename': out_path} ) @python36_or_higher def test_milp_plotting(self): override = {'model.subset_time': '2005-07-01'} model = calliope.examples.milp(override_dict=override) model.run() plot_html_outputs = { 'capacity': model.plot.capacity(html_only=True), 'timeseries': model.plot.timeseries(html_only=True), 'transmission': model.plot.transmission(html_only=True), 'flows': model.plot.flows(html_only=True), } for plot_type in HTML_STRINGS['milp']: for string in HTML_STRINGS['milp'][plot_type]: assert string in plot_html_outputs[plot_type] # Also just try plotting the summary model.plot.summary() def test_failed_cap_plotting(self, national_scale_example): model = national_scale_example # should fail, not in array with pytest.raises(ValueError): model.plot.capacity(array='carrier_prod') model.plot.capacity(array=['energy_eff', 'energy_cap']) # orient has to be 'v', 'vertical', 'h', or 'horizontal' model.plot.capacity(orient='g') def test_failed_timeseries_plotting(self, national_scale_example): model = national_scale_example # should fail, not in array with pytest.raises(ValueError): model.plot.timeseries(array='energy_cap') model.plot.timeseries(squeeze=False) model.plot.timeseries(sum_dims=None) @python36_or_higher def test_clustered_plotting(self): override = {'model.time.function_options.k': 2} model = calliope.examples.time_clustering(override_dict=override) # While we have a model that hasn't been run, try plotting transmission and capacity model.plot.transmission(html_only=True) model.plot.capacity(html_only=True) model.run() plot_html = model.plot.timeseries(html_only=True) for string in HTML_STRINGS['clustering']['timeseries']: assert string in plot_html def test_subset_plotting(self, national_scale_example): model = national_scale_example model.plot.capacity( html_only=True, subset={'timesteps': ['2015-01-01 01:00']} ) # should raise, subsetting with a tech that does not exist with pytest.raises(ValueError) as excinfo: model.plot.capacity( html_only=True, subset={'techs': ['foobar']} ) assert check_error_or_warning(excinfo, 'No data to plot') def test_subset_array(self, national_scale_example): model = national_scale_example model.plot.capacity(html_only=True, array='inputs') model.plot.capacity(html_only=True, array='results') model.plot.capacity(html_only=True, array='energy_cap') model.plot.capacity(html_only=True, array='storage_cap') model.plot.capacity( html_only=True, array=['systemwide_levelised_cost', 'storage_cap'] ) model.plot.timeseries(html_only=True, array='inputs') model.plot.timeseries(html_only=True, array='results') model.plot.timeseries(html_only=True, array='power') model.plot.timeseries(html_only=True, array='resource') model.plot.timeseries( html_only=True, array=['resource_con', 'cost_var'] ) def test_long_name(self, national_scale_example): model = national_scale_example model._model_data['names'] = model._model_data.names.astype('<U100') model._model_data.names.loc['ccgt'] = ( 'a long name for a technology, longer than 30 characters' ) model._model_data.names.loc['csp'] = ( 'a really very long name for a technology that is longer than 60 characters' ) model._model_data.names.loc['battery'] = ( 'another_long_name_but_without_space_to_break_at' ) model._model_data.names.loc['ac_transmission'] = ( 'long_transmission_name_which_has two break types in technology name' ) broken_names = [ 'a long name for a technology,<br>longer than 30 characters', 'another_long_name_but_without_...<br>space_to_break_at', 'a really very long name for a<br>technology that is longer<br>than 60 characters' ] html_cap = model.plot.capacity(html_only=True) html_timeseries = model.plot.timeseries(html_only=True) html_transmission = model.plot.transmission(html_only=True) for i in broken_names: assert i in html_cap assert i in html_timeseries assert ( 'long_transmission_name_which_h...<br>as two break types in<br>technology name' in html_transmission ) def test_plot_cost(self): model = calliope.examples.national_scale( override_dict={ 'techs.ccgt.costs.carbon': {'energy_cap': 10, 'interest_rate': 0.01} } ) model.run() # should fail, multiple costs provided, can only plot one with pytest.raises(ValueError): model.plot.capacity(html_only=True, array='results') # should succeed, multiple costs provided, subset to one model.plot.capacity( html_only=True, array='results', subset={'costs': 'carbon'} ) # FIXME: sum_dims doesn't seem to work at all # model.plot.capacity(html_only=True, sum_dims=['locs']) def test_to_file(self, national_scale_example): model = national_scale_example # should fail, 'gif' not in allowed extensions with pytest.raises(TypeError): model.plot.capacity( to_file='plot_to_save.gif', plotly_kwarg_updates={'auto_open': False}) # FIXME: currently throws up save dialogue rather than just # saving the file # with tempfile.TemporaryDirectory() as tempdir: # for extension in ['png', 'jpeg', 'svg', 'webp']: # out_path = os.path.join(tempdir, 'plot_to_save.' + extension) # model.plot.capacity(array='energy_cap', to_file=out_path, auto_open=False) # assert os.path.isfile(out_path) # should fail, cannot save a plot with multiple DataArrays being plotted with pytest.raises(ValueError): model.plot.capacity( to_file='plot_to_save.svg', plotly_kwarg_updates={'auto_open': False}) # test saving summary to file with tempfile.TemporaryDirectory() as tempdir: out_path = os.path.join(tempdir, 'test_summary.html') model.plot.summary(to_file=out_path) assert os.path.isfile(out_path)
brynpickering/calliope
calliope/test/test_analysis.py
Python
apache-2.0
8,658
package com.pCloudy.testNG; import java.io.File; import java.io.IOException; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import io.appium.java_client.AppiumDriver; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.service.local.AppiumDriverLocalService; public class Runner { AppiumDriverLocalService service; AppiumDriver<WebElement> driver; String folder_name; DateFormat df; @BeforeTest public void setUpSuite() throws Exception { } @BeforeMethod public void prepareTest() throws IOException, InterruptedException { DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("pCloudy_Username", "Enter your email-id"); capabilities.setCapability("pCloudy_ApiKey", "Enter your API Key"); capabilities.setCapability("pCloudy_DurationInMinutes", 10); capabilities.setCapability("pCloudy_DeviceManafacturer", "Samsung"); //capabilities.setCapability("pCloudy_DeviceVersion", "8.0.0"); //capabilities.setCapability("pCloudy_DeviceFullName", "Samsung_GalaxyTabA_Android_7.1.1"); capabilities.setCapability("automationName", "uiautomator2"); capabilities.setCapability("newCommandTimeout", 600); capabilities.setCapability("launchTimeout", 90000); capabilities.setBrowserName("Chrome"); driver = new AndroidDriver(new URL("https://device.pcloudy.com/appiumcloud/wd/hub"), capabilities); } @Test public void Test() throws IOException, InterruptedException { driver.navigate().to("http://www.google.com"); captureScreenShots(); String strPageTitle = driver.getTitle(); System.out.println("Page title: - "+strPageTitle); Assert.assertTrue(strPageTitle.equalsIgnoreCase("Google"), "Page title doesn't match"); } @AfterMethod public void endTest() throws IOException { driver.quit(); } //Capture screenshot public void captureScreenShots() throws IOException { folder_name="screenshot"; File f=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); //Date format for screenshot file name df=new SimpleDateFormat("dd-MMM-yyyy__hh_mm_ssaa"); //create dir with given folder name new File(folder_name).mkdir(); //Setting file name String file_name=df.format(new Date())+".png"; //copy screenshot file into screenshot folder. FileUtils.copyFile(f, new File(folder_name + "/" + file_name)); } }
pankyopkey/pCloudy-sample-projects
Java/NewAppium_SampleProjects/Chapter3-TestNg+OnWeb(Android)/src/com/pCloudy/testNG/Runner.java
Java
apache-2.0
2,917
""" Auth module, contains of login, logout and social network authorization modules, now vk only """ from flask import request, redirect, render_template, url_for, g, session, Blueprint from flask_login import login_user, logout_user, current_user from app import lm from app.models import User, ROLE_USER from app.vk_api import VkApi from app.secrets import vk_client_id, vk_secret_key from urllib.request import urlopen, Request import json auth_module = Blueprint('auth', __name__, template_folder='templates') @auth_module.route('/login', methods=['GET', 'POST']) def login(): if g.user is not None and g.user.is_authenticated: return redirect(url_for('pomodoro.index')) return render_template('login.html') @auth_module.route('/logout') def logout(): logout_user() return redirect(url_for('auth.login')) @lm.user_loader def load_user(email): """ function for flask_login package, it checks exist user or not :param email: the id of user :return: None if no user in base, user if user exists """ user = User.objects(email=email) if not user: return None return User.objects.get(email=email) @auth_module.route('/try_vk_auth') def try_vk_auth(): """ try get code from vk.com for authorization :return: redirect to vk_auth page with code or error """ vk_auth_page = url_for('auth.vk_auth', _external=True) req_url = 'https://oauth.vk.com/authorize?client_id=' + vk_client_id + \ '&scope=email&redirect_uri=' + vk_auth_page + \ '&response_type=code&v=5.52' return redirect(req_url) @auth_module.route('/vk_auth') def vk_auth(): """ Authorization using vk OAuth, getting user email, first name, last name and avatar :return: redirect to index page if all is ok else redirect to login page again """ vk_auth_page = url_for('auth.vk_auth', _external=True) code = request.args.get('code', '') access_token_url = 'https://oauth.vk.com/access_token?client_id=' + vk_client_id + \ '&client_secret=' + vk_secret_key + '&code=' + code + '&redirect_uri=' + vk_auth_page req = Request(url=access_token_url) response = urlopen(req).read() response = json.loads(response.decode('utf-8')) if 'access_token' in response and 'email' in response: access_token = response['access_token'] email = response['email'] user = User.objects(email=email) user_id = response['user_id'] vk_api = VkApi(token=access_token) req_result = vk_api.call_api('users.get', params={'user_id': user_id, 'fields': 'photo_50,screen_name'}) nickname = email.split('@')[0] avatar_url = '' if req_result: if 'last_name' in req_result[0].keys() and 'first_name' in req_result[0].keys(): nickname = req_result[0]['first_name'] + ' ' + req_result[0]['last_name'] if 'photo_50' in req_result[0].keys(): avatar_url = req_result[0]['photo_50'] if not user: user = User(nickname=nickname, email=email, role=ROLE_USER, avatar_url=avatar_url) else: user = User.objects.get(email=email) user.nickname = nickname if avatar_url: user.avatar_url = avatar_url user.save() remember_me = False if 'remember_me' in session: remember_me = session['remember_me'] session.pop('remember_me', None) login_user(user, remember=remember_me) return redirect(request.args.get('next') or url_for('pomodoro.index')) elif 'error' in response: return redirect(url_for('auth.login')) @auth_module.before_request def before_request(): g.user = current_user
Kwentar/Dream-Crusher
app/auth_views.py
Python
apache-2.0
3,770
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <base href="<?php echo base_url(); ?>" /> <title>:: HIZMETUZMANI::</title> <link href="css/admin/style.css" rel="stylesheet" type="text/css" media="screen" /> <!--<script type="text/javascript" src="js/admin/curvycorners.src.js"></script>--> <? /////////Jquery////// ?> <script language="javascript" type="text/javascript" src="js/jquery/jquery-1.4.2.js"></script> <?php /*<link type="text/css" rel="stylesheet" media="screen" href="js/jquery/themes/redmond/jquery.ui.all.css" />*/?> <link type="text/css" rel="stylesheet" media="screen" href="js/jquery/themes/ui-darkness/ui.all.css" /> <link type="text/css" rel="stylesheet" media="screen" href="js/jquery/themes/jquery.ui.tooltip.css" /> <script language="javascript" type="text/javascript" src="js/jquery/ui/jquery.ui.core.js"></script> <script language="javascript" type="text/javascript" src="js/jquery/ui/jquery-ui-1.8.4.custom.js"></script> <script language="javascript" type="text/javascript" src="js/jquery/ui/jquery.ui.tooltip.js"></script> <script language="javascript" type="text/javascript" src="js/jquery/ui/jquery.blockUI.js"></script> <script language="javascript" type="text/javascript" src="js/jquery/ui/jquery.ui.dialog.js"></script> <link type="text/css" rel="stylesheet" media="screen" href="js/jquery/themes/prettyPhoto/prettyPhoto.css" /> <script language="javascript" type="text/javascript" src="js/jquery/ui/jquery.prettyPhoto.js"></script> <? /////////end Jquery////// ?> <script type="text/javascript" language="javascript" > jQuery.noConflict();///$ can be used by other prototype which is not jquery jQuery(function($) { $(document).ready(function(){ $("#frm_login").submit(function(){ $.blockUI({ message: 'Just a moment please...' }); var b_valid=true; var s_err=""; $("#div_err").hide("slow"); if($.trim($("#txt_user_name").val())=="") { s_err='<div id="err_msg" class="error_massage">Please provide user name.</div>'; b_valid=false; } if($.trim($("#txt_password").val())=="") { s_err+='<div id="err_msg" class="error_massage">Please provide password.</div>'; b_valid=false; } /////////validating////// if(!b_valid) { $.unblockUI(); $("#div_err").html(s_err).show("slow"); } return b_valid; }); })}); </script> </head> <body> <div id="header"> <!--<div id="logo"><img src="images/admin/logo_bak.jpg" alt="###SITE_NAME_UC###" title="###SITE_NAME_UC###" /></div>--> <div id="logo"><img src="images/admin/logo.png" alt="###SITE_NAME_UC###" title="###SITE_NAME_UC###" /></div> <div class="clr"></div> </div> <div class="clr"></div> <div id="navigation">&nbsp;</div> <div class="clr"></div> <div id="content"> <div id="welcome_box">Welcome to ###SITE_NAME_LC### admin panel</div> <div id="black_box"> <form id="frm_login" action="" method="post"> <p> <div id="div_err"> <?php show_msg("error"); echo validation_errors(); ?> </div> </p> <p>&nbsp;</p> <div class="lable">User Name :</div> <div class="field"><input id="txt_user_name" name="txt_user_name" value="<?php if(isset($txt_user_name))echo $txt_user_name;?>" type="text" size="34" maxlength="20" /></div> <br class="clr" /> <div class="lable">Password :</div> <div class="field"><input id="txt_password" name="txt_password" type="password" size="34" maxlength="12" /></div> <br class="clr" /> <div class="lable">&nbsp;</div> <div class="field"><input type="submit" value="Submit" /> </div> <br class="clr" /> <div class="lable">&nbsp;</div> <div class="field"><a href="<?php echo admin_base_url()?>forgot_password" style="color:#FFFFFF;text-decoration:none;">Forgot Password?</a></div> <br class="clr" /> </form> </div> </div> <div class="clr"></div> <div id="footer"> <p>&copy; 2012 Copyright ###SITE_NAME_LC###</p> <p>&nbsp;</p> </div> </body> </html>
mrinsss/Full-Repo
hizmetuzmani/system/application/views/admin/index.tpl.php
PHP
apache-2.0
4,468
package openflow13 // This file has all group related defs import ( "encoding/binary" log "github.com/Sirupsen/logrus" "github.com/shaleman/libOpenflow/common" ) const ( OFPG_MAX = 0xffffff00 /* Last usable group number. */ /* Fake groups. */ OFPG_ALL = 0xfffffffc /* Represents all groups for group delete commands. */ OFPG_ANY = 0xffffffff /* Wildcard group used only for flow stats requests. Selects all flows regardless of group (including flows with no group). */ ) const ( OFPGC_ADD = 0 /* New group. */ OFPGC_MODIFY = 1 /* Modify all matching groups. */ OFPGC_DELETE = 2 /* Delete all matching groups. */ ) const ( OFPGT_ALL = 0 /* All (multicast/broadcast) group. */ OFPGT_SELECT = 1 /* Select group. */ OFPGT_INDIRECT = 2 /* Indirect group. */ OFPGT_FF = 3 /* Fast failover group. */ ) // GroupMod message type GroupMod struct { common.Header Command uint16 /* One of OFPGC_*. */ Type uint8 /* One of OFPGT_*. */ pad uint8 /* Pad to 64 bits. */ GroupId uint32 /* Group identifier. */ Buckets []Bucket /* List of buckets */ } // Create a new group mode message func NewGroupMod() *GroupMod { g := new(GroupMod) g.Header = NewOfp13Header() g.Header.Type = Type_GroupMod g.Command = OFPGC_ADD g.Type = OFPGT_ALL g.GroupId = 0 g.Buckets = make([]Bucket, 0) return g } // Add a bucket to group mod func (g *GroupMod) AddBucket(bkt Bucket) { g.Buckets = append(g.Buckets, bkt) } func (g *GroupMod) Len() (n uint16) { n = g.Header.Len() n += 8 if g.Command == OFPGC_DELETE { return } for _, b := range g.Buckets { n += b.Len() } return } func (g *GroupMod) MarshalBinary() (data []byte, err error) { g.Header.Length = g.Len() data, err = g.Header.MarshalBinary() bytes := make([]byte, 8) n := 0 binary.BigEndian.PutUint16(bytes[n:], g.Command) n += 2 bytes[n] = g.Type n += 1 bytes[n] = g.pad n += 1 binary.BigEndian.PutUint32(bytes[n:], g.GroupId) n += 4 data = append(data, bytes...) for _, bkt := range g.Buckets { bytes, err = bkt.MarshalBinary() data = append(data, bytes...) log.Debugf("Groupmod bucket: %v", bytes) } log.Debugf("GroupMod(%d): %v", len(data), data) return } func (g *GroupMod) UnmarshalBinary(data []byte) error { n := 0 g.Header.UnmarshalBinary(data[n:]) n += int(g.Header.Len()) g.Command = binary.BigEndian.Uint16(data[n:]) n += 2 g.Type = data[n] n += 1 g.pad = data[n] n += 1 g.GroupId = binary.BigEndian.Uint32(data[n:]) n += 4 for n < int(g.Header.Length) { bkt := new(Bucket) bkt.UnmarshalBinary(data[n:]) g.Buckets = append(g.Buckets, *bkt) n += int(bkt.Len()) } return nil } type Bucket struct { Length uint16 /* Length the bucket in bytes, including this header and any padding to make it 64-bit aligned. */ Weight uint16 /* Relative weight of bucket. Only defined for select groups. */ WatchPort uint32 /* Used for FRR groups */ WatchGroup uint32 /* Used for FRR groups */ pad []byte /* 4 bytes */ Actions []Action /* zero or more actions */ } // Create a new Bucket func NewBucket() *Bucket { bkt := new(Bucket) bkt.Weight = 0 bkt.pad = make([]byte, 4) bkt.Actions = make([]Action, 0) bkt.WatchPort = P_ANY bkt.WatchGroup = OFPG_ANY bkt.Length = bkt.Len() return bkt } // Add an action to the bucket func (b *Bucket) AddAction(act Action) { b.Actions = append(b.Actions, act) } func (b *Bucket) Len() (n uint16) { n = 16 for _, a := range b.Actions { n += a.Len() } // Round it to closest multiple of 8 n = ((n + 7) / 8) * 8 return } func (b *Bucket) MarshalBinary() (data []byte, err error) { bytes := make([]byte, 16) n := 0 b.Length = b.Len() // Calculate length first binary.BigEndian.PutUint16(bytes[n:], b.Length) n += 2 binary.BigEndian.PutUint16(bytes[n:], b.Weight) n += 2 binary.BigEndian.PutUint32(bytes[n:], b.WatchPort) n += 4 binary.BigEndian.PutUint32(bytes[n:], b.WatchGroup) n += 4 data = append(data, bytes...) for _, a := range b.Actions { bytes, err = a.MarshalBinary() data = append(data, bytes...) } return } func (b *Bucket) UnmarshalBinary(data []byte) error { n := 0 b.Length = binary.BigEndian.Uint16(data[n:]) n += 2 b.Weight = binary.BigEndian.Uint16(data[n:]) n += 2 b.WatchPort = binary.BigEndian.Uint32(data[n:]) n += 4 b.WatchGroup = binary.BigEndian.Uint32(data[n:]) n += 4 n += 4 // for padding for n < int(b.Length) { a := DecodeAction(data[n:]) b.Actions = append(b.Actions, a) n += int(a.Len()) } return nil }
shaleman/libOpenflow
openflow13/group.go
GO
apache-2.0
4,531
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ package org.springframework.security.config.annotation.authentication.configurers.userdetails; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.ProviderManagerBuilder; import org.springframework.security.core.userdetails.UserDetailsService; /** * Allows configuring a {@link DaoAuthenticationProvider} * * @author Rob Winch * @since 3.2 * * @param <B> The type of {@link ProviderManagerBuilder} this is * @param <U> The type of {@link UserDetailsService} that is being used * */ public class DaoAuthenticationConfigurer<B extends ProviderManagerBuilder<B>, U extends UserDetailsService> extends AbstractDaoAuthenticationConfigurer<B, DaoAuthenticationConfigurer<B, U>, U> { /** * Creates a new instance * @param userDetailsService */ public DaoAuthenticationConfigurer(U userDetailsService) { super(userDetailsService); } }
eddumelendez/spring-security
config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/userdetails/DaoAuthenticationConfigurer.java
Java
apache-2.0
1,575
package com.sun.corba.se.spi.activation; /** * com/sun/corba/se/spi/activation/POANameHolder.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from c:/re/workspace/8-2-build-windows-amd64-cygwin/jdk8u112/7884/corba/src/share/classes/com/sun/corba/se/spi/activation/activation.idl * Thursday, September 22, 2016 9:33:08 PM PDT */ public final class POANameHolder implements org.omg.CORBA.portable.Streamable { public String value[] = null; public POANameHolder () { } public POANameHolder (String[] initialValue) { value = initialValue; } public void _read (org.omg.CORBA.portable.InputStream i) { value = POANameHelper.read (i); } public void _write (org.omg.CORBA.portable.OutputStream o) { POANameHelper.write (o, value); } public org.omg.CORBA.TypeCode _type () { return POANameHelper.type (); } }
wapalxj/Java
javaworkplace/source/src/com/sun/corba/se/spi/activation/POANameHolder.java
Java
apache-2.0
883
package apple.coregraphics; import java.io.*; import java.nio.*; import java.util.*; import com.google.j2objc.annotations.*; import com.google.j2objc.runtime.*; import com.google.j2objc.runtime.block.*; import apple.audiotoolbox.*; import apple.corefoundation.*; import apple.coregraphics.*; import apple.coreservices.*; import apple.foundation.*; import apple.uikit.*; /*<javadoc>*/ /*</javadoc>*/ public class CGPDFString extends Object { protected CGPDFString() {} }
Sellegit/j2objc
runtime/src/main/java/apple/coregraphics/CGPDFString.java
Java
apache-2.0
516
using Adaptive.Aeron.Exceptions; namespace Adaptive.Cluster.Client { /// <summary> /// Exceptions specific to Cluster operation. /// </summary> public class ClusterException : AeronException { /// <summary> /// Cluster exception with provided message and <seealso cref="Category.ERROR"/>. /// </summary> /// <param name="message"> to detail the exception. </param> public ClusterException(string message) : base(message) { } /// <summary> /// Cluster exception with a detailed message and provided <seealso cref="Category"/>. /// </summary> /// <param name="message"> providing detail on the error. </param> /// <param name="category"> of the exception. </param> public ClusterException(string message, Category category) : base(message, category) { } } }
AdaptiveConsulting/Aeron.NET
src/Adaptive.Cluster/Client/ClusterException.cs
C#
apache-2.0
906
package org.apereo.cas.configuration.model.support.saml.shibboleth; import org.apereo.cas.configuration.support.RequiresModule; import lombok.Getter; import lombok.Setter; import java.io.Serializable; /** * This is {@link ShibbolethIdPProperties}. * * @author Misagh Moayyed * @since 5.1.0 */ @RequiresModule(name = "cas-server-support-shibboleth") @Getter @Setter public class ShibbolethIdPProperties implements Serializable { private static final long serialVersionUID = 1741075420882227768L; /** * The server url of the shibboleth idp deployment. */ private String serverUrl; }
robertoschwald/cas
api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/support/saml/shibboleth/ShibbolethIdPProperties.java
Java
apache-2.0
614
/* * Copyright (c) 2015 mariotaku * * 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.mariotaku.restfu.annotation.param; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by mariotaku on 15/2/6. */ @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface Raw { String contentType() default ""; String encoding() default ""; }
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/annotation/param/Raw.java
Java
apache-2.0
1,016
/** * Copyright 2021 The Google Earth Engine Community 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 * * 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. */ // [START earthengine__apidocs__ee_geometry_multipolygon_length] // Define a MultiPolygon object. var multiPolygon = ee.Geometry.MultiPolygon( [[[[-122.092, 37.424], [-122.086, 37.418], [-122.079, 37.425], [-122.085, 37.423]]], [[[-122.081, 37.417], [-122.086, 37.421], [-122.089, 37.416]]]]); // Apply the length method to the MultiPolygon object. var multiPolygonLength = multiPolygon.length(); // Print the result to the console. print('multiPolygon.length(...) =', multiPolygonLength); // Display relevant geometries on the map. Map.setCenter(-122.085, 37.422, 15); Map.addLayer(multiPolygon, {'color': 'black'}, 'Geometry [black]: multiPolygon'); // [END earthengine__apidocs__ee_geometry_multipolygon_length]
google/earthengine-community
samples/javascript/apidocs/ee-geometry-multipolygon-length.js
JavaScript
apache-2.0
1,415
var Backbone = require('backbone') , _ = require('underscore') , Garam = require('../../Garam') , Cluster = require('cluster') , Base = require('../../Base') , assert = require('assert') , fs = require('fs') , async = require('async'); var ModelFactory = function(namespace,config) { assert(config); this.namespace = namespace; this.models = {}; this.config = config; if (this.config.redisModel) { this.type = 'redis'; } else { assert(this.config.type); this.type = this.config.type; } } module.exports = ModelFactory; _.extend(ModelFactory.prototype, Base.prototype, { addModel : function(model) { if (typeof model.modelType ==='undefined') { model.modelType = 'redis'; } model._create(model.dbName); var db = Garam.getDB(this.namespace); db.addProcedure(model.name,model); //Garam.setModel(model.name,model); }, create : function(model_dir) { var self = this; var namespace = this.namespace; var modelDir = this.appDir + '/model/'+namespace; this.appDir = Garam.getInstance().get('appDir'); this._sql = {}; if(!fs.existsSync(this.appDir + '/model/'+namespace)) { Garam.getInstance().log.error(modelDir,'not find model dir'); return; } var dir = process.cwd()+'/'+ this.appDir + '/model/'+namespace; read(dir); function read(dir) { var list = fs.readdirSync(dir); var total =list.length; list.forEach(function (file,i) { var stats = fs.statSync(dir + '/'+ file); if (stats.isFile()) { var Model = require(dir + '/'+ file); var t = new Model(this.type,self.config.namespace); self.addModel(t); } else { read(dir+'/'+file); } if (total === (i+1)) { Garam.getInstance().emit('completeWork',namespace); Garam.getInstance().emit('databaseOnReady',namespace); } }); } }, addCreateModel : function() { } }); ModelFactory.extend = Garam.extend;
ssdosso/garam
server/lib/database/model/ModelFactory.js
JavaScript
apache-2.0
2,328
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.transaction.api; import net.sf.mmm.util.event.api.EventListener; /** * This is the interface for a {@link EventListener listener} of * {@link TransactionEvent}s. * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) */ public interface TransactionEventListener extends EventListener<TransactionEvent> { // nothing to add, just bound generic }
m-m-m/transaction
api/src/main/java/net/sf/mmm/transaction/api/TransactionEventListener.java
Java
apache-2.0
513
<?php /** * Contains all client objects for the CreativeService * service. * * PHP version 5 * * Copyright 2014, 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 * * 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 GoogleApiAdsDfp * @subpackage v201403 * @category WebServices * @copyright 2014, Google Inc. All Rights Reserved. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, * Version 2.0 */ /** Required classes. **/ require_once "Google/Api/Ads/Dfp/Lib/DfpSoapClient.php"; if (!class_exists("BaseCreativeTemplateVariableValue", false)) { /** * A base class for storing values of the {@link CreativeTemplateVariable}. * @package GoogleApiAdsDfp * @subpackage v201403 */ class BaseCreativeTemplateVariableValue { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "BaseCreativeTemplateVariableValue"; /** * @access public * @var string */ public $uniqueName; /** * @access public * @var string */ public $BaseCreativeTemplateVariableValueType; private $_parameterMap = array( "BaseCreativeTemplateVariableValue.Type" => "BaseCreativeTemplateVariableValueType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get * @return mixed Variable value */ public function __get($var) { if (!isset($this->_parameterMap[$var])) { return null; } return $this->{$this->_parameterMap[$var]}; } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($uniqueName = null, $BaseCreativeTemplateVariableValueType = null) { $this->uniqueName = $uniqueName; $this->BaseCreativeTemplateVariableValueType = $BaseCreativeTemplateVariableValueType; } } } if (!class_exists("ApiError", false)) { /** * The API error base class that provides details about an error that occurred * while processing a service request. * * <p>The OGNL field path is provided for parsers to identify the request data * element that may have caused the error.</p> * @package GoogleApiAdsDfp * @subpackage v201403 */ class ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ApiError"; /** * @access public * @var string */ public $fieldPath; /** * @access public * @var string */ public $trigger; /** * @access public * @var string */ public $errorString; /** * @access public * @var string */ public $ApiErrorType; private $_parameterMap = array( "ApiError.Type" => "ApiErrorType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get * @return mixed Variable value */ public function __get($var) { if (!isset($this->_parameterMap[$var])) { return null; } return $this->{$this->_parameterMap[$var]}; } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("ApiVersionError", false)) { /** * Errors related to the usage of API versions. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ApiVersionError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ApiVersionError"; /** * @access public * @var tnsApiVersionErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("ApplicationException", false)) { /** * Base class for exceptions. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ApplicationException { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ApplicationException"; /** * @access public * @var string */ public $message; /** * @access public * @var string */ public $ApplicationExceptionType; private $_parameterMap = array( "ApplicationException.Type" => "ApplicationExceptionType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get * @return mixed Variable value */ public function __get($var) { if (!isset($this->_parameterMap[$var])) { return null; } return $this->{$this->_parameterMap[$var]}; } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($message = null, $ApplicationExceptionType = null) { $this->message = $message; $this->ApplicationExceptionType = $ApplicationExceptionType; } } } if (!class_exists("AppliedLabel", false)) { /** * Represents a {@link Label} that can be applied to an entity. To negate an * inherited label, create an {@code AppliedLabel} with {@code labelId} as the * inherited label's ID and {@code isNegated} set to true. * @package GoogleApiAdsDfp * @subpackage v201403 */ class AppliedLabel { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "AppliedLabel"; /** * @access public * @var integer */ public $labelId; /** * @access public * @var boolean */ public $isNegated; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($labelId = null, $isNegated = null) { $this->labelId = $labelId; $this->isNegated = $isNegated; } } } if (!class_exists("AssetCreativeTemplateVariableValue", false)) { /** * Stores values of {@link CreativeTemplateVariable} of {@link VariableType#ASSET}. * @package GoogleApiAdsDfp * @subpackage v201403 */ class AssetCreativeTemplateVariableValue extends BaseCreativeTemplateVariableValue { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "AssetCreativeTemplateVariableValue"; /** * @access public * @var integer */ public $assetId; /** * @access public * @var base64Binary */ public $assetByteArray; /** * @access public * @var string */ public $fileName; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($assetId = null, $assetByteArray = null, $fileName = null, $uniqueName = null, $BaseCreativeTemplateVariableValueType = null) { parent::__construct(); $this->assetId = $assetId; $this->assetByteArray = $assetByteArray; $this->fileName = $fileName; $this->uniqueName = $uniqueName; $this->BaseCreativeTemplateVariableValueType = $BaseCreativeTemplateVariableValueType; } } } if (!class_exists("Asset", false)) { /** * Base asset properties. * @package GoogleApiAdsDfp * @subpackage v201403 */ class Asset { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "Asset"; /** * @access public * @var string */ public $AssetType; private $_parameterMap = array( "Asset.Type" => "AssetType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get * @return mixed Variable value */ public function __get($var) { if (!isset($this->_parameterMap[$var])) { return null; } return $this->{$this->_parameterMap[$var]}; } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($AssetType = null) { $this->AssetType = $AssetType; } } } if (!class_exists("AssetError", false)) { /** * Lists all errors associated with assets. * @package GoogleApiAdsDfp * @subpackage v201403 */ class AssetError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "AssetError"; /** * @access public * @var tnsAssetErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("Authentication", false)) { /** * A representation of the authentication protocols that can be used. * @package GoogleApiAdsDfp * @subpackage v201403 */ class Authentication { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "Authentication"; /** * @access public * @var string */ public $AuthenticationType; private $_parameterMap = array( "Authentication.Type" => "AuthenticationType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get * @return mixed Variable value */ public function __get($var) { if (!isset($this->_parameterMap[$var])) { return null; } return $this->{$this->_parameterMap[$var]}; } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($AuthenticationType = null) { $this->AuthenticationType = $AuthenticationType; } } } if (!class_exists("AuthenticationError", false)) { /** * An error for an exception that occurred when authenticating. * @package GoogleApiAdsDfp * @subpackage v201403 */ class AuthenticationError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "AuthenticationError"; /** * @access public * @var tnsAuthenticationErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("BaseCustomFieldValue", false)) { /** * The value of a {@link CustomField} for a particular entity. * @package GoogleApiAdsDfp * @subpackage v201403 */ class BaseCustomFieldValue { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "BaseCustomFieldValue"; /** * @access public * @var integer */ public $customFieldId; /** * @access public * @var string */ public $BaseCustomFieldValueType; private $_parameterMap = array( "BaseCustomFieldValue.Type" => "BaseCustomFieldValueType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get * @return mixed Variable value */ public function __get($var) { if (!isset($this->_parameterMap[$var])) { return null; } return $this->{$this->_parameterMap[$var]}; } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($customFieldId = null, $BaseCustomFieldValueType = null) { $this->customFieldId = $customFieldId; $this->BaseCustomFieldValueType = $BaseCustomFieldValueType; } } } if (!class_exists("CommonError", false)) { /** * A place for common errors that can be used across services. * @package GoogleApiAdsDfp * @subpackage v201403 */ class CommonError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "CommonError"; /** * @access public * @var tnsCommonErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("ConversionEvent_TrackingUrlsMapEntry", false)) { /** * This represents an entry in a map with a key of type ConversionEvent * and value of type TrackingUrls. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ConversionEvent_TrackingUrlsMapEntry { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ConversionEvent_TrackingUrlsMapEntry"; /** * @access public * @var tnsConversionEvent */ public $key; /** * @access public * @var TrackingUrls */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($key = null, $value = null) { $this->key = $key; $this->value = $value; } } } if (!class_exists("CreativeAsset", false)) { /** * A {@code CreativeAsset} is an asset that can be used in creatives. * @package GoogleApiAdsDfp * @subpackage v201403 */ class CreativeAsset { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "CreativeAsset"; /** * @access public * @var integer */ public $assetId; /** * @access public * @var base64Binary */ public $assetByteArray; /** * @access public * @var string */ public $fileName; /** * @access public * @var integer */ public $fileSize; /** * @access public * @var string */ public $assetUrl; /** * @access public * @var Size */ public $size; /** * @access public * @var tnsImageDensity */ public $imageDensity; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($assetId = null, $assetByteArray = null, $fileName = null, $fileSize = null, $assetUrl = null, $size = null, $imageDensity = null) { $this->assetId = $assetId; $this->assetByteArray = $assetByteArray; $this->fileName = $fileName; $this->fileSize = $fileSize; $this->assetUrl = $assetUrl; $this->size = $size; $this->imageDensity = $imageDensity; } } } if (!class_exists("CustomCreativeAsset", false)) { /** * A {@code CustomCreativeAsset} is an association between a * {@link CustomCreative} and an asset. Any assets that are associated with a * creative can be inserted into its HTML snippet. * @package GoogleApiAdsDfp * @subpackage v201403 */ class CustomCreativeAsset { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "CustomCreativeAsset"; /** * @access public * @var string */ public $macroName; /** * @access public * @var integer */ public $assetId; /** * @access public * @var base64Binary */ public $assetByteArray; /** * @access public * @var string */ public $fileName; /** * @access public * @var integer */ public $fileSize; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($macroName = null, $assetId = null, $assetByteArray = null, $fileName = null, $fileSize = null) { $this->macroName = $macroName; $this->assetId = $assetId; $this->assetByteArray = $assetByteArray; $this->fileName = $fileName; $this->fileSize = $fileSize; } } } if (!class_exists("CreativeAssetMacroError", false)) { /** * Lists all errors associated with creative asset macros. * @package GoogleApiAdsDfp * @subpackage v201403 */ class CreativeAssetMacroError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "CreativeAssetMacroError"; /** * @access public * @var tnsCreativeAssetMacroErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("Creative", false)) { /** * A {@code Creative} represents the media for the ad being served. * @package GoogleApiAdsDfp * @subpackage v201403 */ class Creative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "Creative"; /** * @access public * @var integer */ public $advertiserId; /** * @access public * @var integer */ public $id; /** * @access public * @var string */ public $name; /** * @access public * @var Size */ public $size; /** * @access public * @var string */ public $previewUrl; /** * @access public * @var AppliedLabel[] */ public $appliedLabels; /** * @access public * @var DateTime */ public $lastModifiedDateTime; /** * @access public * @var BaseCustomFieldValue[] */ public $customFieldValues; /** * @access public * @var string */ public $CreativeType; private $_parameterMap = array( "Creative.Type" => "CreativeType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get * @return mixed Variable value */ public function __get($var) { if (!isset($this->_parameterMap[$var])) { return null; } return $this->{$this->_parameterMap[$var]}; } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($advertiserId = null, $id = null, $name = null, $size = null, $previewUrl = null, $appliedLabels = null, $lastModifiedDateTime = null, $customFieldValues = null, $CreativeType = null) { $this->advertiserId = $advertiserId; $this->id = $id; $this->name = $name; $this->size = $size; $this->previewUrl = $previewUrl; $this->appliedLabels = $appliedLabels; $this->lastModifiedDateTime = $lastModifiedDateTime; $this->customFieldValues = $customFieldValues; $this->CreativeType = $CreativeType; } } } if (!class_exists("CreativeError", false)) { /** * Lists all errors associated with creatives. * @package GoogleApiAdsDfp * @subpackage v201403 */ class CreativeError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "CreativeError"; /** * @access public * @var tnsCreativeErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("CreativePage", false)) { /** * Captures a page of {@link Creative} objects. * @package GoogleApiAdsDfp * @subpackage v201403 */ class CreativePage { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "CreativePage"; /** * @access public * @var integer */ public $totalResultSetSize; /** * @access public * @var integer */ public $startIndex; /** * @access public * @var Creative[] */ public $results; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($totalResultSetSize = null, $startIndex = null, $results = null) { $this->totalResultSetSize = $totalResultSetSize; $this->startIndex = $startIndex; $this->results = $results; } } } if (!class_exists("CreativeSetError", false)) { /** * Errors relating to creative sets & subclasses. * @package GoogleApiAdsDfp * @subpackage v201403 */ class CreativeSetError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "CreativeSetError"; /** * @access public * @var tnsCreativeSetErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("CustomCreativeError", false)) { /** * Lists all errors associated with custom creatives. * @package GoogleApiAdsDfp * @subpackage v201403 */ class CustomCreativeError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "CustomCreativeError"; /** * @access public * @var tnsCustomCreativeErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("CustomFieldValue", false)) { /** * The value of a {@link CustomField} that does not have a {@link CustomField#dataType} * of {@link CustomFieldDataType#DROP_DOWN}. * @package GoogleApiAdsDfp * @subpackage v201403 */ class CustomFieldValue extends BaseCustomFieldValue { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "CustomFieldValue"; /** * @access public * @var Value */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null, $customFieldId = null, $BaseCustomFieldValueType = null) { parent::__construct(); $this->value = $value; $this->customFieldId = $customFieldId; $this->BaseCustomFieldValueType = $BaseCustomFieldValueType; } } } if (!class_exists("Date", false)) { /** * Represents a date. * @package GoogleApiAdsDfp * @subpackage v201403 */ class Date { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "Date"; /** * @access public * @var integer */ public $year; /** * @access public * @var integer */ public $month; /** * @access public * @var integer */ public $day; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($year = null, $month = null, $day = null) { $this->year = $year; $this->month = $month; $this->day = $day; } } } if (!class_exists("DfpDateTime", false)) { /** * Represents a date combined with the time of day. * @package GoogleApiAdsDfp * @subpackage v201403 */ class DfpDateTime { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "DateTime"; /** * @access public * @var Date */ public $date; /** * @access public * @var integer */ public $hour; /** * @access public * @var integer */ public $minute; /** * @access public * @var integer */ public $second; /** * @access public * @var string */ public $timeZoneID; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($date = null, $hour = null, $minute = null, $second = null, $timeZoneID = null) { $this->date = $date; $this->hour = $hour; $this->minute = $minute; $this->second = $second; $this->timeZoneID = $timeZoneID; } } } if (!class_exists("DropDownCustomFieldValue", false)) { /** * A {@link CustomFieldValue} for a {@link CustomField} that has a {@link CustomField#dataType} * of {@link CustomFieldDataType#DROP_DOWN} * @package GoogleApiAdsDfp * @subpackage v201403 */ class DropDownCustomFieldValue extends BaseCustomFieldValue { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "DropDownCustomFieldValue"; /** * @access public * @var integer */ public $customFieldOptionId; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($customFieldOptionId = null, $customFieldId = null, $BaseCustomFieldValueType = null) { parent::__construct(); $this->customFieldOptionId = $customFieldOptionId; $this->customFieldId = $customFieldId; $this->BaseCustomFieldValueType = $BaseCustomFieldValueType; } } } if (!class_exists("EntityLimitReachedError", false)) { /** * An error that occurs when creating an entity if the limit on the number of allowed entities for * a network has already been reached. * @package GoogleApiAdsDfp * @subpackage v201403 */ class EntityLimitReachedError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "EntityLimitReachedError"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("FeatureError", false)) { /** * Errors related to feature management. If you attempt using a feature that is not available to * the current network you'll receive a FeatureError with the missing feature as the trigger. * @package GoogleApiAdsDfp * @subpackage v201403 */ class FeatureError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "FeatureError"; /** * @access public * @var tnsFeatureErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("FileError", false)) { /** * A list of all errors to be used for problems related to files. * @package GoogleApiAdsDfp * @subpackage v201403 */ class FileError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "FileError"; /** * @access public * @var tnsFileErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("HasDestinationUrlCreative", false)) { /** * A {@code Creative} that has a destination url * @package GoogleApiAdsDfp * @subpackage v201403 */ class HasDestinationUrlCreative extends Creative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "HasDestinationUrlCreative"; /** * @access public * @var string */ public $destinationUrl; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($destinationUrl = null, $advertiserId = null, $id = null, $name = null, $size = null, $previewUrl = null, $appliedLabels = null, $lastModifiedDateTime = null, $customFieldValues = null, $CreativeType = null) { parent::__construct(); $this->destinationUrl = $destinationUrl; $this->advertiserId = $advertiserId; $this->id = $id; $this->name = $name; $this->size = $size; $this->previewUrl = $previewUrl; $this->appliedLabels = $appliedLabels; $this->lastModifiedDateTime = $lastModifiedDateTime; $this->customFieldValues = $customFieldValues; $this->CreativeType = $CreativeType; } } } if (!class_exists("ImageError", false)) { /** * Lists all errors associated with images. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ImageError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ImageError"; /** * @access public * @var tnsImageErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("InternalApiError", false)) { /** * Indicates that a server-side error has occured. {@code InternalApiError}s * are generally not the result of an invalid request or message sent by the * client. * @package GoogleApiAdsDfp * @subpackage v201403 */ class InternalApiError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "InternalApiError"; /** * @access public * @var tnsInternalApiErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("InternalRedirectCreative", false)) { /** * A {@code Creative} hosted by either DoubleClick for Advertisers (DFA) or DART * for Publishers. * <p> * Similar to third-party creatives, a DoubleClick tag is used to retrieve a * creative asset. However, DoubleClick tags are not sent to the user's browser. * Instead, they are processed internally within the DoubleClick system.. * @package GoogleApiAdsDfp * @subpackage v201403 */ class InternalRedirectCreative extends Creative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "InternalRedirectCreative"; /** * @access public * @var Size */ public $assetSize; /** * @access public * @var string */ public $internalRedirectUrl; /** * @access public * @var boolean */ public $overrideSize; /** * @access public * @var boolean */ public $isInterstitial; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($assetSize = null, $internalRedirectUrl = null, $overrideSize = null, $isInterstitial = null, $advertiserId = null, $id = null, $name = null, $size = null, $previewUrl = null, $appliedLabels = null, $lastModifiedDateTime = null, $customFieldValues = null, $CreativeType = null) { parent::__construct(); $this->assetSize = $assetSize; $this->internalRedirectUrl = $internalRedirectUrl; $this->overrideSize = $overrideSize; $this->isInterstitial = $isInterstitial; $this->advertiserId = $advertiserId; $this->id = $id; $this->name = $name; $this->size = $size; $this->previewUrl = $previewUrl; $this->appliedLabels = $appliedLabels; $this->lastModifiedDateTime = $lastModifiedDateTime; $this->customFieldValues = $customFieldValues; $this->CreativeType = $CreativeType; } } } if (!class_exists("InvalidUrlError", false)) { /** * Lists all errors associated with URLs. * @package GoogleApiAdsDfp * @subpackage v201403 */ class InvalidUrlError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "InvalidUrlError"; /** * @access public * @var tnsInvalidUrlErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("LabelEntityAssociationError", false)) { /** * Errors specific to creating label entity associations. * @package GoogleApiAdsDfp * @subpackage v201403 */ class LabelEntityAssociationError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "LabelEntityAssociationError"; /** * @access public * @var tnsLabelEntityAssociationErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("LegacyDfpCreative", false)) { /** * A {@code Creative} that isn't supported by Google DFP, but was migrated * from DART. Creatives of this type cannot be created or modified. * @package GoogleApiAdsDfp * @subpackage v201403 */ class LegacyDfpCreative extends Creative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "LegacyDfpCreative"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($advertiserId = null, $id = null, $name = null, $size = null, $previewUrl = null, $appliedLabels = null, $lastModifiedDateTime = null, $customFieldValues = null, $CreativeType = null) { parent::__construct(); $this->advertiserId = $advertiserId; $this->id = $id; $this->name = $name; $this->size = $size; $this->previewUrl = $previewUrl; $this->appliedLabels = $appliedLabels; $this->lastModifiedDateTime = $lastModifiedDateTime; $this->customFieldValues = $customFieldValues; $this->CreativeType = $CreativeType; } } } if (!class_exists("LineItemCreativeAssociationError", false)) { /** * Lists all errors associated with line item-to-creative association dates. * @package GoogleApiAdsDfp * @subpackage v201403 */ class LineItemCreativeAssociationError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "LineItemCreativeAssociationError"; /** * @access public * @var tnsLineItemCreativeAssociationErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("LongCreativeTemplateVariableValue", false)) { /** * Stores values of {@link CreativeTemplateVariable} of {@link VariableType#LONG}. * @package GoogleApiAdsDfp * @subpackage v201403 */ class LongCreativeTemplateVariableValue extends BaseCreativeTemplateVariableValue { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "LongCreativeTemplateVariableValue"; /** * @access public * @var integer */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null, $uniqueName = null, $BaseCreativeTemplateVariableValueType = null) { parent::__construct(); $this->value = $value; $this->uniqueName = $uniqueName; $this->BaseCreativeTemplateVariableValueType = $BaseCreativeTemplateVariableValueType; } } } if (!class_exists("NotNullError", false)) { /** * Caused by supplying a null value for an attribute that cannot be null. * @package GoogleApiAdsDfp * @subpackage v201403 */ class NotNullError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "NotNullError"; /** * @access public * @var tnsNotNullErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("NullError", false)) { /** * Errors associated with violation of a NOT NULL check. * @package GoogleApiAdsDfp * @subpackage v201403 */ class NullError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "NullError"; /** * @access public * @var tnsNullErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("DfpOAuth", false)) { /** * The credentials for the {@code OAuth} authentication protocol. * * See {@link http://oauth.net/}. * @package GoogleApiAdsDfp * @subpackage v201403 */ class DfpOAuth extends Authentication { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "OAuth"; /** * @access public * @var string */ public $parameters; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($parameters = null, $AuthenticationType = null) { parent::__construct(); $this->parameters = $parameters; $this->AuthenticationType = $AuthenticationType; } } } if (!class_exists("ParseError", false)) { /** * Lists errors related to parsing. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ParseError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ParseError"; /** * @access public * @var tnsParseErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("PermissionError", false)) { /** * Errors related to incorrect permission. * @package GoogleApiAdsDfp * @subpackage v201403 */ class PermissionError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "PermissionError"; /** * @access public * @var tnsPermissionErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("PublisherQueryLanguageContextError", false)) { /** * An error that occurs while executing a PQL query contained in * a {@link Statement} object. * @package GoogleApiAdsDfp * @subpackage v201403 */ class PublisherQueryLanguageContextError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "PublisherQueryLanguageContextError"; /** * @access public * @var tnsPublisherQueryLanguageContextErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("PublisherQueryLanguageSyntaxError", false)) { /** * An error that occurs while parsing a PQL query contained in a * {@link Statement} object. * @package GoogleApiAdsDfp * @subpackage v201403 */ class PublisherQueryLanguageSyntaxError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "PublisherQueryLanguageSyntaxError"; /** * @access public * @var tnsPublisherQueryLanguageSyntaxErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("QuotaError", false)) { /** * Describes a client-side error on which a user is attempting * to perform an action to which they have no quota remaining. * @package GoogleApiAdsDfp * @subpackage v201403 */ class QuotaError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "QuotaError"; /** * @access public * @var tnsQuotaErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("RangeError", false)) { /** * A list of all errors associated with the Range constraint. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RangeError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RangeError"; /** * @access public * @var tnsRangeErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("RedirectAsset", false)) { /** * An externally hosted asset. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RedirectAsset extends Asset { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RedirectAsset"; /** * @access public * @var string */ public $redirectUrl; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($redirectUrl = null, $AssetType = null) { parent::__construct(); $this->redirectUrl = $redirectUrl; $this->AssetType = $AssetType; } } } if (!class_exists("RequiredCollectionError", false)) { /** * A list of all errors to be used for validating sizes of collections. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RequiredCollectionError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RequiredCollectionError"; /** * @access public * @var tnsRequiredCollectionErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("RequiredError", false)) { /** * Errors due to missing required field. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RequiredError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RequiredError"; /** * @access public * @var tnsRequiredErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("RequiredNumberError", false)) { /** * A list of all errors to be used in conjunction with required number * validators. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RequiredNumberError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RequiredNumberError"; /** * @access public * @var tnsRequiredNumberErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("RequiredSizeError", false)) { /** * A list of all errors to be used for validating {@link Size}. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RequiredSizeError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RequiredSizeError"; /** * @access public * @var tnsRequiredSizeErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("RichMediaStudioChildAssetProperty", false)) { /** * Represents a child asset in {@code RichMediaStudioCreative}. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RichMediaStudioChildAssetProperty { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RichMediaStudioChildAssetProperty"; /** * @access public * @var string */ public $name; /** * @access public * @var tnsRichMediaStudioChildAssetPropertyType */ public $type; /** * @access public * @var integer */ public $totalFileSize; /** * @access public * @var integer */ public $width; /** * @access public * @var integer */ public $height; /** * @access public * @var string */ public $url; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($name = null, $type = null, $totalFileSize = null, $width = null, $height = null, $url = null) { $this->name = $name; $this->type = $type; $this->totalFileSize = $totalFileSize; $this->width = $width; $this->height = $height; $this->url = $url; } } } if (!class_exists("RichMediaStudioCreativeError", false)) { /** * Lists all errors associated with Rich Media Studio creatives. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RichMediaStudioCreativeError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RichMediaStudioCreativeError"; /** * @access public * @var tnsRichMediaStudioCreativeErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("ServerError", false)) { /** * Errors related to the server. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ServerError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ServerError"; /** * @access public * @var tnsServerErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("Size", false)) { /** * Represents the dimensions of an {@link AdUnit}, {@link LineItem} or {@link Creative}. * <p> * For interstitial size (out-of-page), {@code Size} must be 1x1. * @package GoogleApiAdsDfp * @subpackage v201403 */ class Size { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "Size"; /** * @access public * @var integer */ public $width; /** * @access public * @var integer */ public $height; /** * @access public * @var boolean */ public $isAspectRatio; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($width = null, $height = null, $isAspectRatio = null) { $this->width = $width; $this->height = $height; $this->isAspectRatio = $isAspectRatio; } } } if (!class_exists("SoapRequestHeader", false)) { /** * Represents the SOAP request header used by API requests. * @package GoogleApiAdsDfp * @subpackage v201403 */ class SoapRequestHeader { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "SoapRequestHeader"; /** * @access public * @var string */ public $networkCode; /** * @access public * @var string */ public $applicationName; /** * @access public * @var Authentication */ public $authentication; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($networkCode = null, $applicationName = null, $authentication = null) { $this->networkCode = $networkCode; $this->applicationName = $applicationName; $this->authentication = $authentication; } } } if (!class_exists("SoapResponseHeader", false)) { /** * Represents the SOAP request header used by API responses. * @package GoogleApiAdsDfp * @subpackage v201403 */ class SoapResponseHeader { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "SoapResponseHeader"; /** * @access public * @var string */ public $requestId; /** * @access public * @var integer */ public $responseTime; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($requestId = null, $responseTime = null) { $this->requestId = $requestId; $this->responseTime = $responseTime; } } } if (!class_exists("Statement", false)) { /** * Captures the {@code WHERE}, {@code ORDER BY} and {@code LIMIT} clauses of a * PQL query. Statements are typically used to retrieve objects of a predefined * domain type, which makes SELECT clause unnecessary. * <p> * An example query text might be {@code "WHERE status = 'ACTIVE' ORDER BY id * LIMIT 30"}. * </p> * <p> * Statements support bind variables. These are substitutes for literals * and can be thought of as input parameters to a PQL query. * </p> * <p> * An example of such a query might be {@code "WHERE id = :idValue"}. * </p> * <p> * Statements also support use of the LIKE keyword. This provides partial and * wildcard string matching. * </p> * <p> * An example of such a query might be {@code "WHERE name LIKE 'startswith%'"}. * </p> * If using an API version newer than V201010, the value for the variable * idValue must then be set with an object of type {@link Value} and is one of * {@link NumberValue}, {@link TextValue} or {@link BooleanValue}. * <p> * If using an API version older than or equal to V201010, the value for the * variable idValue must then be set with an object of type {@link Param} and is * one of {@link DoubleParam}, {@link LongParam} or {@link StringParam}. * </p> * @package GoogleApiAdsDfp * @subpackage v201403 */ class Statement { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "Statement"; /** * @access public * @var string */ public $query; /** * @access public * @var String_ValueMapEntry[] */ public $values; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($query = null, $values = null) { $this->query = $query; $this->values = $values; } } } if (!class_exists("StatementError", false)) { /** * An error that occurs while parsing {@link Statement} objects. * @package GoogleApiAdsDfp * @subpackage v201403 */ class StatementError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "StatementError"; /** * @access public * @var tnsStatementErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("StringCreativeTemplateVariableValue", false)) { /** * Stores values of {@link CreativeTemplateVariable} of * {@link VariableType#STRING} and {@link VariableType#LIST}. * @package GoogleApiAdsDfp * @subpackage v201403 */ class StringCreativeTemplateVariableValue extends BaseCreativeTemplateVariableValue { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "StringCreativeTemplateVariableValue"; /** * @access public * @var string */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null, $uniqueName = null, $BaseCreativeTemplateVariableValueType = null) { parent::__construct(); $this->value = $value; $this->uniqueName = $uniqueName; $this->BaseCreativeTemplateVariableValueType = $BaseCreativeTemplateVariableValueType; } } } if (!class_exists("StringLengthError", false)) { /** * Errors for Strings which do not meet given length constraints. * @package GoogleApiAdsDfp * @subpackage v201403 */ class StringLengthError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "StringLengthError"; /** * @access public * @var tnsStringLengthErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("String_ValueMapEntry", false)) { /** * This represents an entry in a map with a key of type String * and value of type Value. * @package GoogleApiAdsDfp * @subpackage v201403 */ class String_ValueMapEntry { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "String_ValueMapEntry"; /** * @access public * @var string */ public $key; /** * @access public * @var Value */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($key = null, $value = null) { $this->key = $key; $this->value = $value; } } } if (!class_exists("SwiffyConversionError", false)) { /** * Error for converting flash to swiffy asset. * @package GoogleApiAdsDfp * @subpackage v201403 */ class SwiffyConversionError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "SwiffyConversionError"; /** * @access public * @var tnsSwiffyConversionErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("SwiffyFallbackAsset", false)) { /** * A fallback swiffy asset used for flash creatives. * @package GoogleApiAdsDfp * @subpackage v201403 */ class SwiffyFallbackAsset { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "SwiffyFallbackAsset"; /** * @access public * @var CreativeAsset */ public $asset; /** * @access public * @var tnsHtml5Feature[] */ public $html5Features; /** * @access public * @var string[] */ public $localizedInfoMessages; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($asset = null, $html5Features = null, $localizedInfoMessages = null) { $this->asset = $asset; $this->html5Features = $html5Features; $this->localizedInfoMessages = $localizedInfoMessages; } } } if (!class_exists("TemplateCreative", false)) { /** * A {@code Creative} that is created by the specified creative template. * @package GoogleApiAdsDfp * @subpackage v201403 */ class TemplateCreative extends Creative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "TemplateCreative"; /** * @access public * @var integer */ public $creativeTemplateId; /** * @access public * @var boolean */ public $isInterstitial; /** * @access public * @var string */ public $destinationUrl; /** * @access public * @var BaseCreativeTemplateVariableValue[] */ public $creativeTemplateVariableValues; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($creativeTemplateId = null, $isInterstitial = null, $destinationUrl = null, $creativeTemplateVariableValues = null, $advertiserId = null, $id = null, $name = null, $size = null, $previewUrl = null, $appliedLabels = null, $lastModifiedDateTime = null, $customFieldValues = null, $CreativeType = null) { parent::__construct(); $this->creativeTemplateId = $creativeTemplateId; $this->isInterstitial = $isInterstitial; $this->destinationUrl = $destinationUrl; $this->creativeTemplateVariableValues = $creativeTemplateVariableValues; $this->advertiserId = $advertiserId; $this->id = $id; $this->name = $name; $this->size = $size; $this->previewUrl = $previewUrl; $this->appliedLabels = $appliedLabels; $this->lastModifiedDateTime = $lastModifiedDateTime; $this->customFieldValues = $customFieldValues; $this->CreativeType = $CreativeType; } } } if (!class_exists("TemplateInstantiatedCreativeError", false)) { /** * Lists all errors associated with template instantiated creatives. * @package GoogleApiAdsDfp * @subpackage v201403 */ class TemplateInstantiatedCreativeError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "TemplateInstantiatedCreativeError"; /** * @access public * @var tnsTemplateInstantiatedCreativeErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("ThirdPartyCreative", false)) { /** * A {@code Creative} that is served by a 3rd-party vendor. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ThirdPartyCreative extends Creative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ThirdPartyCreative"; /** * @access public * @var string */ public $snippet; /** * @access public * @var string */ public $expandedSnippet; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($snippet = null, $expandedSnippet = null, $advertiserId = null, $id = null, $name = null, $size = null, $previewUrl = null, $appliedLabels = null, $lastModifiedDateTime = null, $customFieldValues = null, $CreativeType = null) { parent::__construct(); $this->snippet = $snippet; $this->expandedSnippet = $expandedSnippet; $this->advertiserId = $advertiserId; $this->id = $id; $this->name = $name; $this->size = $size; $this->previewUrl = $previewUrl; $this->appliedLabels = $appliedLabels; $this->lastModifiedDateTime = $lastModifiedDateTime; $this->customFieldValues = $customFieldValues; $this->CreativeType = $CreativeType; } } } if (!class_exists("TrackingUrls", false)) { /** * A list of URLs that should be pinged for a conversion event. * @package GoogleApiAdsDfp * @subpackage v201403 */ class TrackingUrls { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "TrackingUrls"; /** * @access public * @var string[] */ public $urls; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($urls = null) { $this->urls = $urls; } } } if (!class_exists("TypeError", false)) { /** * An error for a field which is an invalid type. * @package GoogleApiAdsDfp * @subpackage v201403 */ class TypeError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "TypeError"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("UniqueError", false)) { /** * An error for a field which must satisfy a uniqueness constraint * @package GoogleApiAdsDfp * @subpackage v201403 */ class UniqueError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "UniqueError"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("UnsupportedCreative", false)) { /** * A {@code Creative} that isn't supported by this version of the API. * This object is readonly and when encountered should be reported * on the DFP API forum. * @package GoogleApiAdsDfp * @subpackage v201403 */ class UnsupportedCreative extends Creative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "UnsupportedCreative"; /** * @access public * @var string */ public $unsupportedCreativeType; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($unsupportedCreativeType = null, $advertiserId = null, $id = null, $name = null, $size = null, $previewUrl = null, $appliedLabels = null, $lastModifiedDateTime = null, $customFieldValues = null, $CreativeType = null) { parent::__construct(); $this->unsupportedCreativeType = $unsupportedCreativeType; $this->advertiserId = $advertiserId; $this->id = $id; $this->name = $name; $this->size = $size; $this->previewUrl = $previewUrl; $this->appliedLabels = $appliedLabels; $this->lastModifiedDateTime = $lastModifiedDateTime; $this->customFieldValues = $customFieldValues; $this->CreativeType = $CreativeType; } } } if (!class_exists("UrlCreativeTemplateVariableValue", false)) { /** * Stores values of {@link CreativeTemplateVariable} of {@link VariableType#URL}. * @package GoogleApiAdsDfp * @subpackage v201403 */ class UrlCreativeTemplateVariableValue extends BaseCreativeTemplateVariableValue { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "UrlCreativeTemplateVariableValue"; /** * @access public * @var string */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null, $uniqueName = null, $BaseCreativeTemplateVariableValueType = null) { parent::__construct(); $this->value = $value; $this->uniqueName = $uniqueName; $this->BaseCreativeTemplateVariableValueType = $BaseCreativeTemplateVariableValueType; } } } if (!class_exists("Value", false)) { /** * {@code Value} represents a value. * @package GoogleApiAdsDfp * @subpackage v201403 */ class Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "Value"; /** * @access public * @var string */ public $ValueType; private $_parameterMap = array( "Value.Type" => "ValueType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get * @return mixed Variable value */ public function __get($var) { if (!isset($this->_parameterMap[$var])) { return null; } return $this->{$this->_parameterMap[$var]}; } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($ValueType = null) { $this->ValueType = $ValueType; } } } if (!class_exists("VastRedirectCreative", false)) { /** * A {@code Creative} that points to an externally hosted VAST ad and is * served via VAST XML as a VAST Wrapper. * @package GoogleApiAdsDfp * @subpackage v201403 */ class VastRedirectCreative extends Creative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "VastRedirectCreative"; /** * @access public * @var string */ public $vastXmlUrl; /** * @access public * @var tnsVastRedirectType */ public $vastRedirectType; /** * @access public * @var integer */ public $duration; /** * @access public * @var integer[] */ public $companionCreativeIds; /** * @access public * @var ConversionEvent_TrackingUrlsMapEntry[] */ public $trackingUrls; /** * @access public * @var string */ public $vastPreviewUrl; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($vastXmlUrl = null, $vastRedirectType = null, $duration = null, $companionCreativeIds = null, $trackingUrls = null, $vastPreviewUrl = null, $advertiserId = null, $id = null, $name = null, $size = null, $previewUrl = null, $appliedLabels = null, $lastModifiedDateTime = null, $customFieldValues = null, $CreativeType = null) { parent::__construct(); $this->vastXmlUrl = $vastXmlUrl; $this->vastRedirectType = $vastRedirectType; $this->duration = $duration; $this->companionCreativeIds = $companionCreativeIds; $this->trackingUrls = $trackingUrls; $this->vastPreviewUrl = $vastPreviewUrl; $this->advertiserId = $advertiserId; $this->id = $id; $this->name = $name; $this->size = $size; $this->previewUrl = $previewUrl; $this->appliedLabels = $appliedLabels; $this->lastModifiedDateTime = $lastModifiedDateTime; $this->customFieldValues = $customFieldValues; $this->CreativeType = $CreativeType; } } } if (!class_exists("VideoRedirectAsset", false)) { /** * An externally-hosted video asset. * @package GoogleApiAdsDfp * @subpackage v201403 */ class VideoRedirectAsset extends RedirectAsset { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "VideoRedirectAsset"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($redirectUrl = null) { parent::__construct(); $this->redirectUrl = $redirectUrl; } } } if (!class_exists("VpaidLinearCreative", false)) { /** * A {@code Creative} that displays a DFP-hosted Flash-based ad * and is served via VAST 2.0 XML. It is displayed in a linear fashion * with a video (before, after, interrupting). This creative is read only. * @package GoogleApiAdsDfp * @subpackage v201403 */ class VpaidLinearCreative extends HasDestinationUrlCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "VpaidLinearCreative"; /** * @access public * @var string */ public $flashName; /** * @access public * @var base64Binary */ public $flashByteArray; /** * @access public * @var boolean */ public $overrideSize; /** * @access public * @var Size */ public $flashAssetSize; /** * @access public * @var integer[] */ public $companionCreativeIds; /** * @access public * @var ConversionEvent_TrackingUrlsMapEntry[] */ public $trackingUrls; /** * @access public * @var string */ public $customParameters; /** * @access public * @var integer */ public $duration; /** * @access public * @var string */ public $vastPreviewUrl; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($flashName = null, $flashByteArray = null, $overrideSize = null, $flashAssetSize = null, $companionCreativeIds = null, $trackingUrls = null, $customParameters = null, $duration = null, $vastPreviewUrl = null, $destinationUrl = null) { parent::__construct(); $this->flashName = $flashName; $this->flashByteArray = $flashByteArray; $this->overrideSize = $overrideSize; $this->flashAssetSize = $flashAssetSize; $this->companionCreativeIds = $companionCreativeIds; $this->trackingUrls = $trackingUrls; $this->customParameters = $customParameters; $this->duration = $duration; $this->vastPreviewUrl = $vastPreviewUrl; $this->destinationUrl = $destinationUrl; } } } if (!class_exists("VpaidLinearRedirectCreative", false)) { /** * A {@code Creative} that displays an externally hosted Flash-based ad * and is served via VAST 2.0 XML. It is displayed in a linear fashion * with a video (before, after, interrupting). This creative is read only. * @package GoogleApiAdsDfp * @subpackage v201403 */ class VpaidLinearRedirectCreative extends HasDestinationUrlCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "VpaidLinearRedirectCreative"; /** * @access public * @var integer[] */ public $companionCreativeIds; /** * @access public * @var ConversionEvent_TrackingUrlsMapEntry[] */ public $trackingUrls; /** * @access public * @var string */ public $customParameters; /** * @access public * @var integer */ public $duration; /** * @access public * @var string */ public $flashUrl; /** * @access public * @var Size */ public $flashAssetSize; /** * @access public * @var string */ public $vastPreviewUrl; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($companionCreativeIds = null, $trackingUrls = null, $customParameters = null, $duration = null, $flashUrl = null, $flashAssetSize = null, $vastPreviewUrl = null, $destinationUrl = null) { parent::__construct(); $this->companionCreativeIds = $companionCreativeIds; $this->trackingUrls = $trackingUrls; $this->customParameters = $customParameters; $this->duration = $duration; $this->flashUrl = $flashUrl; $this->flashAssetSize = $flashAssetSize; $this->vastPreviewUrl = $vastPreviewUrl; $this->destinationUrl = $destinationUrl; } } } if (!class_exists("ApiFramework", false)) { /** * The various ApiFramework types. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ApiFramework { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ApiFramework"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ApiVersionErrorReason", false)) { /** * Indicates that the operation is not allowed in the version the request * was made in. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ApiVersionErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ApiVersionError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("AssetErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201403 */ class AssetErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "AssetError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("AuthenticationErrorReason", false)) { /** * The SOAP message contains a request header with an ambiguous definition * of the authentication header fields. This means either the {@code * authToken} and {@code oAuthToken} fields were both null or both were * specified. Exactly one value should be specified with each request. * @package GoogleApiAdsDfp * @subpackage v201403 */ class AuthenticationErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "AuthenticationError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("CommonErrorReason", false)) { /** * Describes reasons for common errors * @package GoogleApiAdsDfp * @subpackage v201403 */ class CommonErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "CommonError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ConversionEvent", false)) { /** * All possible tracking event types. Not all events are supported by every * kind of creative. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ConversionEvent { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ConversionEvent"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("CreativeAssetMacroErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201403 */ class CreativeAssetMacroErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "CreativeAssetMacroError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("CreativeErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201403 */ class CreativeErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "CreativeError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("CreativeSetErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201403 */ class CreativeSetErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "CreativeSetError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("CustomCreativeErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201403 */ class CustomCreativeErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "CustomCreativeError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("FeatureErrorReason", false)) { /** * A feature is being used that is not enabled on the current network. * @package GoogleApiAdsDfp * @subpackage v201403 */ class FeatureErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "FeatureError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("FileErrorReason", false)) { /** * The provided byte array is empty. * @package GoogleApiAdsDfp * @subpackage v201403 */ class FileErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "FileError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("Html5Feature", false)) { /** * An HTML5 features required by HTML5 assets. * @package GoogleApiAdsDfp * @subpackage v201403 */ class Html5Feature { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "Html5Feature"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ImageDensity", false)) { /** * Image densities. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ImageDensity { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ImageDensity"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ImageErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ImageErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ImageError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("InternalApiErrorReason", false)) { /** * The single reason for the internal API error. * @package GoogleApiAdsDfp * @subpackage v201403 */ class InternalApiErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "InternalApiError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("InvalidUrlErrorReason", false)) { /** * The URL contains invalid characters. * @package GoogleApiAdsDfp * @subpackage v201403 */ class InvalidUrlErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "InvalidUrlError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("LabelEntityAssociationErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201403 */ class LabelEntityAssociationErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "LabelEntityAssociationError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("LineItemCreativeAssociationErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201403 */ class LineItemCreativeAssociationErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "LineItemCreativeAssociationError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("NotNullErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201403 */ class NotNullErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "NotNullError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("NullErrorReason", false)) { /** * The reasons for the validation error. * @package GoogleApiAdsDfp * @subpackage v201403 */ class NullErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "NullError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ParseErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ParseErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ParseError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("PermissionErrorReason", false)) { /** * Describes reasons for permission errors. * @package GoogleApiAdsDfp * @subpackage v201403 */ class PermissionErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "PermissionError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("PublisherQueryLanguageContextErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201403 */ class PublisherQueryLanguageContextErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "PublisherQueryLanguageContextError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("PublisherQueryLanguageSyntaxErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201403 */ class PublisherQueryLanguageSyntaxErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "PublisherQueryLanguageSyntaxError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("QuotaErrorReason", false)) { /** * The number of requests made per second is too high and has exceeded the * allowable limit. The recommended approach to handle this error is to wait * about 5 seconds and then retry the request. Note that this does not * guarantee the request will succeed. If it fails again, try increasing the * wait time. * <p> * Another way to mitigate this error is to limit requests to 2 per second. * Once again this does not guarantee that every request will succeed, but * may help reduce the number of times you receive this error. * </p> * @package GoogleApiAdsDfp * @subpackage v201403 */ class QuotaErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "QuotaError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RangeErrorReason", false)) { /** * The value returned if the actual value is not exposed by the requested API version. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RangeErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RangeError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RequiredCollectionErrorReason", false)) { /** * A required collection is missing. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RequiredCollectionErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RequiredCollectionError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RequiredErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RequiredErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RequiredError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RequiredNumberErrorReason", false)) { /** * Describes reasons for a number to be invalid. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RequiredNumberErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RequiredNumberError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RequiredSizeErrorReason", false)) { /** * {@link Creative#size} or {@link LineItem#creativeSizes} is * missing. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RequiredSizeErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RequiredSizeError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RichMediaStudioChildAssetPropertyType", false)) { /** * Type of {@code RichMediaStudioChildAssetProperty} * @package GoogleApiAdsDfp * @subpackage v201403 */ class RichMediaStudioChildAssetPropertyType { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RichMediaStudioChildAssetProperty.Type"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RichMediaStudioCreativeArtworkType", false)) { /** * Rich Media Studio creative artwork types. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RichMediaStudioCreativeArtworkType { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RichMediaStudioCreativeArtworkType"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RichMediaStudioCreativeBillingAttribute", false)) { /** * Rich Media Studio creative supported billing attributes. * <p> * This is determined by Rich Media Studio based on the content * of the creative and is not updateable. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RichMediaStudioCreativeBillingAttribute { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RichMediaStudioCreativeBillingAttribute"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RichMediaStudioCreativeErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RichMediaStudioCreativeErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RichMediaStudioCreativeError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RichMediaStudioCreativeFormat", false)) { /** * Different creative format supported by Rich Media Studio creative. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RichMediaStudioCreativeFormat { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RichMediaStudioCreativeFormat"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ServerErrorReason", false)) { /** * Describes reasons for server errors * @package GoogleApiAdsDfp * @subpackage v201403 */ class ServerErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ServerError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("StatementErrorReason", false)) { /** * A bind variable has not been bound to a value. * @package GoogleApiAdsDfp * @subpackage v201403 */ class StatementErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "StatementError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("StringLengthErrorReason", false)) { /** * The value returned if the actual value is not exposed by the requested API version. * @package GoogleApiAdsDfp * @subpackage v201403 */ class StringLengthErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "StringLengthError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("SwiffyConversionErrorReason", false)) { /** * Error reason for {@link SwiffyConversionError}. * @package GoogleApiAdsDfp * @subpackage v201403 */ class SwiffyConversionErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "SwiffyConversionError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("TemplateInstantiatedCreativeErrorReason", false)) { /** * The reason for the error * @package GoogleApiAdsDfp * @subpackage v201403 */ class TemplateInstantiatedCreativeErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "TemplateInstantiatedCreativeError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("VastRedirectType", false)) { /** * The types of VAST ads that a {@link VastRedirectCreative} can point to. * @package GoogleApiAdsDfp * @subpackage v201403 */ class VastRedirectType { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "VastRedirectType"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("CreateCreatives", false)) { /** * Creates new {@link Creative} objects. * * @param creatives the creatives to create * @return the created creatives with their IDs filled in * @package GoogleApiAdsDfp * @subpackage v201403 */ class CreateCreatives { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = ""; /** * @access public * @var Creative[] */ public $creatives; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($creatives = null) { $this->creatives = $creatives; } } } if (!class_exists("CreateCreativesResponse", false)) { /** * * @package GoogleApiAdsDfp * @subpackage v201403 */ class CreateCreativesResponse { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = ""; /** * @access public * @var Creative[] */ public $rval; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($rval = null) { $this->rval = $rval; } } } if (!class_exists("GetCreativesByStatement", false)) { /** * Gets a {@link CreativePage} of {@link Creative} objects that satisfy the * given {@link Statement#query}. The following fields are supported for * filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link Creative#id}</td> * </tr> * <tr> * <td>{@code name}</td> * <td>{@link Creative#name}</td> * </tr> * <tr> * <td>{@code advertiserId}</td> * <td>{@link Creative#advertiserId}</td> * </tr> * <tr> * <td>{@code width}</td> * <td>{@link Creative#size}</td> * </tr> * <tr> * <td>{@code height}</td> * <td>{@link Creative#size}</td> * </tr> * <tr> * <td>{@code lastModifiedDateTime}</td> * <td>{@link Creative#lastModifiedDateTime}</td> * </tr> * </table> * * @param filterStatement a Publisher Query Language statement used to filter * a set of creatives * @return the creatives that match the given filter * @package GoogleApiAdsDfp * @subpackage v201403 */ class GetCreativesByStatement { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = ""; /** * @access public * @var Statement */ public $filterStatement; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($filterStatement = null) { $this->filterStatement = $filterStatement; } } } if (!class_exists("GetCreativesByStatementResponse", false)) { /** * * @package GoogleApiAdsDfp * @subpackage v201403 */ class GetCreativesByStatementResponse { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = ""; /** * @access public * @var CreativePage */ public $rval; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($rval = null) { $this->rval = $rval; } } } if (!class_exists("UpdateCreatives", false)) { /** * Updates the specified {@link Creative} objects. * * @param creatives the creatives to update * @return the updated creatives * @package GoogleApiAdsDfp * @subpackage v201403 */ class UpdateCreatives { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = ""; /** * @access public * @var Creative[] */ public $creatives; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($creatives = null) { $this->creatives = $creatives; } } } if (!class_exists("UpdateCreativesResponse", false)) { /** * * @package GoogleApiAdsDfp * @subpackage v201403 */ class UpdateCreativesResponse { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = ""; /** * @access public * @var Creative[] */ public $rval; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($rval = null) { $this->rval = $rval; } } } if (!class_exists("BaseDynamicAllocationCreative", false)) { /** * A base class for dynamic allocation creatives. * @package GoogleApiAdsDfp * @subpackage v201403 */ class BaseDynamicAllocationCreative extends Creative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "BaseDynamicAllocationCreative"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($advertiserId = null, $id = null, $name = null, $size = null, $previewUrl = null, $appliedLabels = null, $lastModifiedDateTime = null, $customFieldValues = null, $CreativeType = null) { parent::__construct(); $this->advertiserId = $advertiserId; $this->id = $id; $this->name = $name; $this->size = $size; $this->previewUrl = $previewUrl; $this->appliedLabels = $appliedLabels; $this->lastModifiedDateTime = $lastModifiedDateTime; $this->customFieldValues = $customFieldValues; $this->CreativeType = $CreativeType; } } } if (!class_exists("AdMobBackfillCreative", false)) { /** * An AdMob backfill creative. * @package GoogleApiAdsDfp * @subpackage v201403 */ class AdMobBackfillCreative extends BaseDynamicAllocationCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "AdMobBackfillCreative"; /** * @access public * @var string */ public $additionalParameters; /** * @access public * @var string */ public $publisherId; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($additionalParameters = null, $publisherId = null) { parent::__construct(); $this->additionalParameters = $additionalParameters; $this->publisherId = $publisherId; } } } if (!class_exists("ApiException", false)) { /** * Exception class for holding a list of service errors. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ApiException extends ApplicationException { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ApiException"; /** * @access public * @var ApiError[] */ public $errors; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($errors = null, $message = null, $ApplicationExceptionType = null) { parent::__construct(); $this->errors = $errors; $this->message = $message; $this->ApplicationExceptionType = $ApplicationExceptionType; } } } if (!class_exists("AspectRatioImageCreative", false)) { /** * A {@code Creative} intended for mobile platforms that displays an image, * whose {@link LineItem#creativePlaceholders size} is defined as an * {@link CreativeSizeType#ASPECT_RATIO aspect ratio}, i.e. * {@link Size#isAspectRatio}. It can have multiple images whose dimensions * conform to that aspect ratio. * @package GoogleApiAdsDfp * @subpackage v201403 */ class AspectRatioImageCreative extends HasDestinationUrlCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "AspectRatioImageCreative"; /** * @access public * @var CreativeAsset[] */ public $imageAssets; /** * @access public * @var string */ public $altText; /** * @access public * @var string */ public $thirdPartyImpressionUrl; /** * @access public * @var boolean */ public $overrideSize; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($imageAssets = null, $altText = null, $thirdPartyImpressionUrl = null, $overrideSize = null, $destinationUrl = null) { parent::__construct(); $this->imageAssets = $imageAssets; $this->altText = $altText; $this->thirdPartyImpressionUrl = $thirdPartyImpressionUrl; $this->overrideSize = $overrideSize; $this->destinationUrl = $destinationUrl; } } } if (!class_exists("BaseFlashCreative", false)) { /** * A base type for creatives that display a Flash-based ad. If the Flash ad * cannot load, a fallback image is displayed instead. * @package GoogleApiAdsDfp * @subpackage v201403 */ class BaseFlashCreative extends HasDestinationUrlCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "BaseFlashCreative"; /** * @access public * @var string */ public $flashName; /** * @access public * @var base64Binary */ public $flashByteArray; /** * @access public * @var string */ public $fallbackImageName; /** * @access public * @var base64Binary */ public $fallbackImageByteArray; /** * @access public * @var boolean */ public $overrideSize; /** * @access public * @var boolean */ public $clickTagRequired; /** * @access public * @var string */ public $fallbackPreviewUrl; /** * @access public * @var Size */ public $flashAssetSize; /** * @access public * @var Size */ public $fallbackAssetSize; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($flashName = null, $flashByteArray = null, $fallbackImageName = null, $fallbackImageByteArray = null, $overrideSize = null, $clickTagRequired = null, $fallbackPreviewUrl = null, $flashAssetSize = null, $fallbackAssetSize = null, $destinationUrl = null) { parent::__construct(); $this->flashName = $flashName; $this->flashByteArray = $flashByteArray; $this->fallbackImageName = $fallbackImageName; $this->fallbackImageByteArray = $fallbackImageByteArray; $this->overrideSize = $overrideSize; $this->clickTagRequired = $clickTagRequired; $this->fallbackPreviewUrl = $fallbackPreviewUrl; $this->flashAssetSize = $flashAssetSize; $this->fallbackAssetSize = $fallbackAssetSize; $this->destinationUrl = $destinationUrl; } } } if (!class_exists("BaseFlashRedirectCreative", false)) { /** * The base type for creatives that load a Flash asset from a specified URL. * If the remote flash asset cannot be served, a fallback image is used at an * alternate URL. * @package GoogleApiAdsDfp * @subpackage v201403 */ class BaseFlashRedirectCreative extends HasDestinationUrlCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "BaseFlashRedirectCreative"; /** * @access public * @var string */ public $flashUrl; /** * @access public * @var string */ public $fallbackUrl; /** * @access public * @var string */ public $fallbackPreviewUrl; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($flashUrl = null, $fallbackUrl = null, $fallbackPreviewUrl = null, $destinationUrl = null) { parent::__construct(); $this->flashUrl = $flashUrl; $this->fallbackUrl = $fallbackUrl; $this->fallbackPreviewUrl = $fallbackPreviewUrl; $this->destinationUrl = $destinationUrl; } } } if (!class_exists("BaseImageCreative", false)) { /** * The base type for creatives that display an image. * @package GoogleApiAdsDfp * @subpackage v201403 */ class BaseImageCreative extends HasDestinationUrlCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "BaseImageCreative"; /** * @access public * @var boolean */ public $overrideSize; /** * @access public * @var CreativeAsset */ public $primaryImageAsset; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($overrideSize = null, $primaryImageAsset = null, $destinationUrl = null) { parent::__construct(); $this->overrideSize = $overrideSize; $this->primaryImageAsset = $primaryImageAsset; $this->destinationUrl = $destinationUrl; } } } if (!class_exists("BaseImageRedirectCreative", false)) { /** * The base type for creatives that load an image asset from a specified URL. * @package GoogleApiAdsDfp * @subpackage v201403 */ class BaseImageRedirectCreative extends HasDestinationUrlCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "BaseImageRedirectCreative"; /** * @access public * @var string */ public $imageUrl; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($imageUrl = null, $destinationUrl = null) { parent::__construct(); $this->imageUrl = $imageUrl; $this->destinationUrl = $destinationUrl; } } } if (!class_exists("BaseRichMediaStudioCreative", false)) { /** * A {@code Creative} that is created by a Rich Media Studio. * @package GoogleApiAdsDfp * @subpackage v201403 */ class BaseRichMediaStudioCreative extends Creative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "BaseRichMediaStudioCreative"; /** * @access public * @var integer */ public $studioCreativeId; /** * @access public * @var tnsRichMediaStudioCreativeFormat */ public $creativeFormat; /** * @access public * @var tnsRichMediaStudioCreativeArtworkType */ public $artworkType; /** * @access public * @var integer */ public $totalFileSize; /** * @access public * @var string[] */ public $adTagKeys; /** * @access public * @var string[] */ public $customKeyValues; /** * @access public * @var string */ public $surveyUrl; /** * @access public * @var string */ public $allImpressionsUrl; /** * @access public * @var string */ public $richMediaImpressionsUrl; /** * @access public * @var string */ public $backupImageImpressionsUrl; /** * @access public * @var string */ public $overrideCss; /** * @access public * @var string */ public $requiredFlashPluginVersion; /** * @access public * @var integer */ public $duration; /** * @access public * @var tnsRichMediaStudioCreativeBillingAttribute */ public $billingAttribute; /** * @access public * @var RichMediaStudioChildAssetProperty[] */ public $richMediaStudioChildAssetProperties; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($studioCreativeId = null, $creativeFormat = null, $artworkType = null, $totalFileSize = null, $adTagKeys = null, $customKeyValues = null, $surveyUrl = null, $allImpressionsUrl = null, $richMediaImpressionsUrl = null, $backupImageImpressionsUrl = null, $overrideCss = null, $requiredFlashPluginVersion = null, $duration = null, $billingAttribute = null, $richMediaStudioChildAssetProperties = null, $advertiserId = null, $id = null, $name = null, $size = null, $previewUrl = null, $appliedLabels = null, $lastModifiedDateTime = null, $customFieldValues = null, $CreativeType = null) { parent::__construct(); $this->studioCreativeId = $studioCreativeId; $this->creativeFormat = $creativeFormat; $this->artworkType = $artworkType; $this->totalFileSize = $totalFileSize; $this->adTagKeys = $adTagKeys; $this->customKeyValues = $customKeyValues; $this->surveyUrl = $surveyUrl; $this->allImpressionsUrl = $allImpressionsUrl; $this->richMediaImpressionsUrl = $richMediaImpressionsUrl; $this->backupImageImpressionsUrl = $backupImageImpressionsUrl; $this->overrideCss = $overrideCss; $this->requiredFlashPluginVersion = $requiredFlashPluginVersion; $this->duration = $duration; $this->billingAttribute = $billingAttribute; $this->richMediaStudioChildAssetProperties = $richMediaStudioChildAssetProperties; $this->advertiserId = $advertiserId; $this->id = $id; $this->name = $name; $this->size = $size; $this->previewUrl = $previewUrl; $this->appliedLabels = $appliedLabels; $this->lastModifiedDateTime = $lastModifiedDateTime; $this->customFieldValues = $customFieldValues; $this->CreativeType = $CreativeType; } } } if (!class_exists("BaseVideoCreative", false)) { /** * A base type for video creatives. * @package GoogleApiAdsDfp * @subpackage v201403 */ class BaseVideoCreative extends HasDestinationUrlCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "BaseVideoCreative"; /** * @access public * @var integer */ public $duration; /** * @access public * @var boolean */ public $allowDurationOverride; /** * @access public * @var ConversionEvent_TrackingUrlsMapEntry[] */ public $trackingUrls; /** * @access public * @var integer[] */ public $companionCreativeIds; /** * @access public * @var string */ public $customParameters; /** * @access public * @var string */ public $vastPreviewUrl; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($duration = null, $allowDurationOverride = null, $trackingUrls = null, $companionCreativeIds = null, $customParameters = null, $vastPreviewUrl = null, $destinationUrl = null) { parent::__construct(); $this->duration = $duration; $this->allowDurationOverride = $allowDurationOverride; $this->trackingUrls = $trackingUrls; $this->companionCreativeIds = $companionCreativeIds; $this->customParameters = $customParameters; $this->vastPreviewUrl = $vastPreviewUrl; $this->destinationUrl = $destinationUrl; } } } if (!class_exists("BooleanValue", false)) { /** * Contains a boolean value. * @package GoogleApiAdsDfp * @subpackage v201403 */ class BooleanValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "BooleanValue"; /** * @access public * @var boolean */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null, $ValueType = null) { parent::__construct(); $this->value = $value; $this->ValueType = $ValueType; } } } if (!class_exists("ClickTrackingCreative", false)) { /** * A creative that is used for tracking clicks on ads that are served directly * from the customers' web servers or media servers. * NOTE: The size attribute is not used for click tracking creative and it will * not be persisted upon save. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ClickTrackingCreative extends Creative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ClickTrackingCreative"; /** * @access public * @var string */ public $clickTrackingUrl; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($clickTrackingUrl = null, $advertiserId = null, $id = null, $name = null, $size = null, $previewUrl = null, $appliedLabels = null, $lastModifiedDateTime = null, $customFieldValues = null, $CreativeType = null) { parent::__construct(); $this->clickTrackingUrl = $clickTrackingUrl; $this->advertiserId = $advertiserId; $this->id = $id; $this->name = $name; $this->size = $size; $this->previewUrl = $previewUrl; $this->appliedLabels = $appliedLabels; $this->lastModifiedDateTime = $lastModifiedDateTime; $this->customFieldValues = $customFieldValues; $this->CreativeType = $CreativeType; } } } if (!class_exists("CustomCreative", false)) { /** * A {@code Creative} that contains an arbitrary HTML snippet and file assets. * @package GoogleApiAdsDfp * @subpackage v201403 */ class CustomCreative extends HasDestinationUrlCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "CustomCreative"; /** * @access public * @var string */ public $htmlSnippet; /** * @access public * @var CustomCreativeAsset[] */ public $customCreativeAssets; /** * @access public * @var boolean */ public $isInterstitial; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($htmlSnippet = null, $customCreativeAssets = null, $isInterstitial = null, $destinationUrl = null) { parent::__construct(); $this->htmlSnippet = $htmlSnippet; $this->customCreativeAssets = $customCreativeAssets; $this->isInterstitial = $isInterstitial; $this->destinationUrl = $destinationUrl; } } } if (!class_exists("DateTimeValue", false)) { /** * Contains a date-time value. * @package GoogleApiAdsDfp * @subpackage v201403 */ class DateTimeValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "DateTimeValue"; /** * @access public * @var DateTime */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null, $ValueType = null) { parent::__construct(); $this->value = $value; $this->ValueType = $ValueType; } } } if (!class_exists("DateValue", false)) { /** * Contains a date value. * @package GoogleApiAdsDfp * @subpackage v201403 */ class DateValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "DateValue"; /** * @access public * @var Date */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null, $ValueType = null) { parent::__construct(); $this->value = $value; $this->ValueType = $ValueType; } } } if (!class_exists("LegacyDfpMobileCreative", false)) { /** * A mobile {@code Creative} that isn't supported by Google DFP, but was * migrated from DART. Creatives of this type cannot be created or modified. * @package GoogleApiAdsDfp * @subpackage v201403 */ class LegacyDfpMobileCreative extends HasDestinationUrlCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "LegacyDfpMobileCreative"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($destinationUrl = null) { parent::__construct(); $this->destinationUrl = $destinationUrl; } } } if (!class_exists("FlashCreative", false)) { /** * A {@code Creative} that displays a Flash-based ad. If the Flash ad cannot * load, a fallback image is displayed instead. * @package GoogleApiAdsDfp * @subpackage v201403 */ class FlashCreative extends BaseFlashCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "FlashCreative"; /** * @access public * @var SwiffyFallbackAsset */ public $swiffyAsset; /** * @access public * @var boolean */ public $createSwiffyAsset; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($swiffyAsset = null, $createSwiffyAsset = null, $flashName = null, $flashByteArray = null, $fallbackImageName = null, $fallbackImageByteArray = null, $overrideSize = null, $clickTagRequired = null, $fallbackPreviewUrl = null, $flashAssetSize = null, $fallbackAssetSize = null) { parent::__construct(); $this->swiffyAsset = $swiffyAsset; $this->createSwiffyAsset = $createSwiffyAsset; $this->flashName = $flashName; $this->flashByteArray = $flashByteArray; $this->fallbackImageName = $fallbackImageName; $this->fallbackImageByteArray = $fallbackImageByteArray; $this->overrideSize = $overrideSize; $this->clickTagRequired = $clickTagRequired; $this->fallbackPreviewUrl = $fallbackPreviewUrl; $this->flashAssetSize = $flashAssetSize; $this->fallbackAssetSize = $fallbackAssetSize; } } } if (!class_exists("FlashOverlayCreative", false)) { /** * An overlay {@code Creative} that displays a Flash-based ad and is * served via VAST 2.0 XML. Overlays cover part of the video content * they are displayed on top of. This creative is read-only. * @package GoogleApiAdsDfp * @subpackage v201403 */ class FlashOverlayCreative extends BaseFlashCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "FlashOverlayCreative"; /** * @access public * @var integer[] */ public $companionCreativeIds; /** * @access public * @var ConversionEvent_TrackingUrlsMapEntry[] */ public $trackingUrls; /** * @access public * @var string */ public $customParameters; /** * @access public * @var tnsApiFramework */ public $apiFramework; /** * @access public * @var integer */ public $duration; /** * @access public * @var string */ public $vastPreviewUrl; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($companionCreativeIds = null, $trackingUrls = null, $customParameters = null, $apiFramework = null, $duration = null, $vastPreviewUrl = null, $flashName = null, $flashByteArray = null, $fallbackImageName = null, $fallbackImageByteArray = null, $overrideSize = null, $clickTagRequired = null, $fallbackPreviewUrl = null, $flashAssetSize = null, $fallbackAssetSize = null) { parent::__construct(); $this->companionCreativeIds = $companionCreativeIds; $this->trackingUrls = $trackingUrls; $this->customParameters = $customParameters; $this->apiFramework = $apiFramework; $this->duration = $duration; $this->vastPreviewUrl = $vastPreviewUrl; $this->flashName = $flashName; $this->flashByteArray = $flashByteArray; $this->fallbackImageName = $fallbackImageName; $this->fallbackImageByteArray = $fallbackImageByteArray; $this->overrideSize = $overrideSize; $this->clickTagRequired = $clickTagRequired; $this->fallbackPreviewUrl = $fallbackPreviewUrl; $this->flashAssetSize = $flashAssetSize; $this->fallbackAssetSize = $fallbackAssetSize; } } } if (!class_exists("FlashRedirectCreative", false)) { /** * A {@code Creative} that loads a Flash asset from a specified URL. If the * remote flash asset cannot be served, a fallback image is used at an * alternate URL. * @package GoogleApiAdsDfp * @subpackage v201403 */ class FlashRedirectCreative extends BaseFlashRedirectCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "FlashRedirectCreative"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($flashUrl = null, $fallbackUrl = null, $fallbackPreviewUrl = null) { parent::__construct(); $this->flashUrl = $flashUrl; $this->fallbackUrl = $fallbackUrl; $this->fallbackPreviewUrl = $fallbackPreviewUrl; } } } if (!class_exists("FlashRedirectOverlayCreative", false)) { /** * An overlay {@code Creative} that loads a Flash asset from a specified URL * and is served via VAST 2.0 XML. Overlays cover part of the video content * they are displayed on top of. * @package GoogleApiAdsDfp * @subpackage v201403 */ class FlashRedirectOverlayCreative extends BaseFlashRedirectCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "FlashRedirectOverlayCreative"; /** * @access public * @var integer[] */ public $companionCreativeIds; /** * @access public * @var ConversionEvent_TrackingUrlsMapEntry[] */ public $trackingUrls; /** * @access public * @var string */ public $customParameters; /** * @access public * @var tnsApiFramework */ public $apiFramework; /** * @access public * @var integer */ public $duration; /** * @access public * @var Size */ public $flashAssetSize; /** * @access public * @var string */ public $vastPreviewUrl; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($companionCreativeIds = null, $trackingUrls = null, $customParameters = null, $apiFramework = null, $duration = null, $flashAssetSize = null, $vastPreviewUrl = null, $flashUrl = null, $fallbackUrl = null, $fallbackPreviewUrl = null) { parent::__construct(); $this->companionCreativeIds = $companionCreativeIds; $this->trackingUrls = $trackingUrls; $this->customParameters = $customParameters; $this->apiFramework = $apiFramework; $this->duration = $duration; $this->flashAssetSize = $flashAssetSize; $this->vastPreviewUrl = $vastPreviewUrl; $this->flashUrl = $flashUrl; $this->fallbackUrl = $fallbackUrl; $this->fallbackPreviewUrl = $fallbackPreviewUrl; } } } if (!class_exists("HasHtmlSnippetDynamicAllocationCreative", false)) { /** * Dynamic allocation creative with a backfill code snippet. * @package GoogleApiAdsDfp * @subpackage v201403 */ class HasHtmlSnippetDynamicAllocationCreative extends BaseDynamicAllocationCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "HasHtmlSnippetDynamicAllocationCreative"; /** * @access public * @var string */ public $codeSnippet; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($codeSnippet = null) { parent::__construct(); $this->codeSnippet = $codeSnippet; } } } if (!class_exists("ImageCreative", false)) { /** * A {@code Creative} that displays an image. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ImageCreative extends BaseImageCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ImageCreative"; /** * @access public * @var string */ public $altText; /** * @access public * @var string */ public $thirdPartyImpressionUrl; /** * @access public * @var CreativeAsset[] */ public $secondaryImageAssets; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($altText = null, $thirdPartyImpressionUrl = null, $secondaryImageAssets = null, $overrideSize = null, $primaryImageAsset = null) { parent::__construct(); $this->altText = $altText; $this->thirdPartyImpressionUrl = $thirdPartyImpressionUrl; $this->secondaryImageAssets = $secondaryImageAssets; $this->overrideSize = $overrideSize; $this->primaryImageAsset = $primaryImageAsset; } } } if (!class_exists("ImageOverlayCreative", false)) { /** * An overlay {@code Creative} that displays an image and is served via VAST * 2.0 XML. Overlays cover part of the video content they are displayed on * top of. This creative is read only. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ImageOverlayCreative extends BaseImageCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ImageOverlayCreative"; /** * @access public * @var integer[] */ public $companionCreativeIds; /** * @access public * @var ConversionEvent_TrackingUrlsMapEntry[] */ public $trackingUrls; /** * @access public * @var string */ public $customParameters; /** * @access public * @var integer */ public $duration; /** * @access public * @var string */ public $vastPreviewUrl; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($companionCreativeIds = null, $trackingUrls = null, $customParameters = null, $duration = null, $vastPreviewUrl = null, $overrideSize = null, $primaryImageAsset = null) { parent::__construct(); $this->companionCreativeIds = $companionCreativeIds; $this->trackingUrls = $trackingUrls; $this->customParameters = $customParameters; $this->duration = $duration; $this->vastPreviewUrl = $vastPreviewUrl; $this->overrideSize = $overrideSize; $this->primaryImageAsset = $primaryImageAsset; } } } if (!class_exists("ImageRedirectCreative", false)) { /** * A {@code Creative} that loads an image asset from a specified URL. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ImageRedirectCreative extends BaseImageRedirectCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ImageRedirectCreative"; /** * @access public * @var string */ public $altText; /** * @access public * @var string */ public $thirdPartyImpressionUrl; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($altText = null, $thirdPartyImpressionUrl = null, $imageUrl = null) { parent::__construct(); $this->altText = $altText; $this->thirdPartyImpressionUrl = $thirdPartyImpressionUrl; $this->imageUrl = $imageUrl; } } } if (!class_exists("ImageRedirectOverlayCreative", false)) { /** * An overlay {@code Creative} that loads an image asset from a specified URL * and is served via VAST 2.0 XML. Overlays cover part of the video content * they are displayed on top of. This creative is read only. * @package GoogleApiAdsDfp * @subpackage v201403 */ class ImageRedirectOverlayCreative extends BaseImageRedirectCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "ImageRedirectOverlayCreative"; /** * @access public * @var Size */ public $assetSize; /** * @access public * @var integer */ public $duration; /** * @access public * @var integer[] */ public $companionCreativeIds; /** * @access public * @var ConversionEvent_TrackingUrlsMapEntry[] */ public $trackingUrls; /** * @access public * @var string */ public $customParameters; /** * @access public * @var string */ public $vastPreviewUrl; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($assetSize = null, $duration = null, $companionCreativeIds = null, $trackingUrls = null, $customParameters = null, $vastPreviewUrl = null, $imageUrl = null) { parent::__construct(); $this->assetSize = $assetSize; $this->duration = $duration; $this->companionCreativeIds = $companionCreativeIds; $this->trackingUrls = $trackingUrls; $this->customParameters = $customParameters; $this->vastPreviewUrl = $vastPreviewUrl; $this->imageUrl = $imageUrl; } } } if (!class_exists("NumberValue", false)) { /** * Contains a numeric value. * @package GoogleApiAdsDfp * @subpackage v201403 */ class NumberValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "NumberValue"; /** * @access public * @var string */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null, $ValueType = null) { parent::__construct(); $this->value = $value; $this->ValueType = $ValueType; } } } if (!class_exists("RichMediaStudioCreative", false)) { /** * A {@code Creative} that is created by a Rich Media Studio. You cannot create this creative, * but you can update some fields of this creative. * @package GoogleApiAdsDfp * @subpackage v201403 */ class RichMediaStudioCreative extends BaseRichMediaStudioCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "RichMediaStudioCreative"; /** * @access public * @var boolean */ public $isInterstitial; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($isInterstitial = null, $studioCreativeId = null, $creativeFormat = null, $artworkType = null, $totalFileSize = null, $adTagKeys = null, $customKeyValues = null, $surveyUrl = null, $allImpressionsUrl = null, $richMediaImpressionsUrl = null, $backupImageImpressionsUrl = null, $overrideCss = null, $requiredFlashPluginVersion = null, $duration = null, $billingAttribute = null, $richMediaStudioChildAssetProperties = null) { parent::__construct(); $this->isInterstitial = $isInterstitial; $this->studioCreativeId = $studioCreativeId; $this->creativeFormat = $creativeFormat; $this->artworkType = $artworkType; $this->totalFileSize = $totalFileSize; $this->adTagKeys = $adTagKeys; $this->customKeyValues = $customKeyValues; $this->surveyUrl = $surveyUrl; $this->allImpressionsUrl = $allImpressionsUrl; $this->richMediaImpressionsUrl = $richMediaImpressionsUrl; $this->backupImageImpressionsUrl = $backupImageImpressionsUrl; $this->overrideCss = $overrideCss; $this->requiredFlashPluginVersion = $requiredFlashPluginVersion; $this->duration = $duration; $this->billingAttribute = $billingAttribute; $this->richMediaStudioChildAssetProperties = $richMediaStudioChildAssetProperties; } } } if (!class_exists("SetValue", false)) { /** * Contains a set of {@link Value Values}. May not contain duplicates. * @package GoogleApiAdsDfp * @subpackage v201403 */ class SetValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "SetValue"; /** * @access public * @var Value[] */ public $values; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($values = null, $ValueType = null) { parent::__construct(); $this->values = $values; $this->ValueType = $ValueType; } } } if (!class_exists("TextValue", false)) { /** * Contains a string value. * @package GoogleApiAdsDfp * @subpackage v201403 */ class TextValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "TextValue"; /** * @access public * @var string */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null, $ValueType = null) { parent::__construct(); $this->value = $value; $this->ValueType = $ValueType; } } } if (!class_exists("VideoCreative", false)) { /** * A {@code Creative} that contains DFP-hosted video ads and is served * via VAST 2.0 XML. This creative is read-only. * @package GoogleApiAdsDfp * @subpackage v201403 */ class VideoCreative extends BaseVideoCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "VideoCreative"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($duration = null, $allowDurationOverride = null, $trackingUrls = null, $companionCreativeIds = null, $customParameters = null, $vastPreviewUrl = null) { parent::__construct(); $this->duration = $duration; $this->allowDurationOverride = $allowDurationOverride; $this->trackingUrls = $trackingUrls; $this->companionCreativeIds = $companionCreativeIds; $this->customParameters = $customParameters; $this->vastPreviewUrl = $vastPreviewUrl; } } } if (!class_exists("VideoRedirectCreative", false)) { /** * A {@code Creative} that contains externally hosted video ads and * is served via VAST 2.0 XML. This creative is read-only. * @package GoogleApiAdsDfp * @subpackage v201403 */ class VideoRedirectCreative extends BaseVideoCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "VideoRedirectCreative"; /** * @access public * @var VideoRedirectAsset[] */ public $videoAssets; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($videoAssets = null, $duration = null, $allowDurationOverride = null, $trackingUrls = null, $companionCreativeIds = null, $customParameters = null, $vastPreviewUrl = null) { parent::__construct(); $this->videoAssets = $videoAssets; $this->duration = $duration; $this->allowDurationOverride = $allowDurationOverride; $this->trackingUrls = $trackingUrls; $this->companionCreativeIds = $companionCreativeIds; $this->customParameters = $customParameters; $this->vastPreviewUrl = $vastPreviewUrl; } } } if (!class_exists("AdExchangeCreative", false)) { /** * An Ad Exchange dynamic allocation creative. * @package GoogleApiAdsDfp * @subpackage v201403 */ class AdExchangeCreative extends HasHtmlSnippetDynamicAllocationCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "AdExchangeCreative"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($codeSnippet = null) { parent::__construct(); $this->codeSnippet = $codeSnippet; } } } if (!class_exists("AdSenseCreative", false)) { /** * An AdSense dynamic allocation creative. * @package GoogleApiAdsDfp * @subpackage v201403 */ class AdSenseCreative extends HasHtmlSnippetDynamicAllocationCreative { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const XSI_TYPE = "AdSenseCreative"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($codeSnippet = null) { parent::__construct(); $this->codeSnippet = $codeSnippet; } } } if (!class_exists("CreativeService", false)) { /** * CreativeService * @package GoogleApiAdsDfp * @subpackage v201403 */ class CreativeService extends DfpSoapClient { const SERVICE_NAME = "CreativeService"; const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403"; const ENDPOINT = "https://www.google.com/apis/ads/publisher/v201403/CreativeService"; /** * The endpoint of the service * @var string */ public static $endpoint = "https://www.google.com/apis/ads/publisher/v201403/CreativeService"; /** * Default class map for wsdl=>php * @access private * @var array */ public static $classmap = array( "BaseDynamicAllocationCreative" => "BaseDynamicAllocationCreative", "BaseCreativeTemplateVariableValue" => "BaseCreativeTemplateVariableValue", "AdExchangeCreative" => "AdExchangeCreative", "AdMobBackfillCreative" => "AdMobBackfillCreative", "AdSenseCreative" => "AdSenseCreative", "ApiError" => "ApiError", "ApiException" => "ApiException", "ApiVersionError" => "ApiVersionError", "ApplicationException" => "ApplicationException", "AppliedLabel" => "AppliedLabel", "AspectRatioImageCreative" => "AspectRatioImageCreative", "AssetCreativeTemplateVariableValue" => "AssetCreativeTemplateVariableValue", "Asset" => "Asset", "AssetError" => "AssetError", "Authentication" => "Authentication", "AuthenticationError" => "AuthenticationError", "BaseCustomFieldValue" => "BaseCustomFieldValue", "BaseFlashCreative" => "BaseFlashCreative", "BaseFlashRedirectCreative" => "BaseFlashRedirectCreative", "BaseImageCreative" => "BaseImageCreative", "BaseImageRedirectCreative" => "BaseImageRedirectCreative", "BaseRichMediaStudioCreative" => "BaseRichMediaStudioCreative", "BaseVideoCreative" => "BaseVideoCreative", "BooleanValue" => "BooleanValue", "ClickTrackingCreative" => "ClickTrackingCreative", "CommonError" => "CommonError", "ConversionEvent_TrackingUrlsMapEntry" => "ConversionEvent_TrackingUrlsMapEntry", "CreativeAsset" => "CreativeAsset", "CustomCreativeAsset" => "CustomCreativeAsset", "CreativeAssetMacroError" => "CreativeAssetMacroError", "Creative" => "Creative", "CreativeError" => "CreativeError", "CreativePage" => "CreativePage", "CreativeSetError" => "CreativeSetError", "CustomCreative" => "CustomCreative", "CustomCreativeError" => "CustomCreativeError", "CustomFieldValue" => "CustomFieldValue", "Date" => "Date", "DateTime" => "DfpDateTime", "DateTimeValue" => "DateTimeValue", "DateValue" => "DateValue", "LegacyDfpMobileCreative" => "LegacyDfpMobileCreative", "DropDownCustomFieldValue" => "DropDownCustomFieldValue", "EntityLimitReachedError" => "EntityLimitReachedError", "FeatureError" => "FeatureError", "FileError" => "FileError", "FlashCreative" => "FlashCreative", "FlashOverlayCreative" => "FlashOverlayCreative", "FlashRedirectCreative" => "FlashRedirectCreative", "FlashRedirectOverlayCreative" => "FlashRedirectOverlayCreative", "HasDestinationUrlCreative" => "HasDestinationUrlCreative", "HasHtmlSnippetDynamicAllocationCreative" => "HasHtmlSnippetDynamicAllocationCreative", "ImageCreative" => "ImageCreative", "ImageError" => "ImageError", "ImageOverlayCreative" => "ImageOverlayCreative", "ImageRedirectCreative" => "ImageRedirectCreative", "ImageRedirectOverlayCreative" => "ImageRedirectOverlayCreative", "InternalApiError" => "InternalApiError", "InternalRedirectCreative" => "InternalRedirectCreative", "InvalidUrlError" => "InvalidUrlError", "LabelEntityAssociationError" => "LabelEntityAssociationError", "LegacyDfpCreative" => "LegacyDfpCreative", "LineItemCreativeAssociationError" => "LineItemCreativeAssociationError", "LongCreativeTemplateVariableValue" => "LongCreativeTemplateVariableValue", "NotNullError" => "NotNullError", "NullError" => "NullError", "NumberValue" => "NumberValue", "OAuth" => "DfpOAuth", "ParseError" => "ParseError", "PermissionError" => "PermissionError", "PublisherQueryLanguageContextError" => "PublisherQueryLanguageContextError", "PublisherQueryLanguageSyntaxError" => "PublisherQueryLanguageSyntaxError", "QuotaError" => "QuotaError", "RangeError" => "RangeError", "RedirectAsset" => "RedirectAsset", "RequiredCollectionError" => "RequiredCollectionError", "RequiredError" => "RequiredError", "RequiredNumberError" => "RequiredNumberError", "RequiredSizeError" => "RequiredSizeError", "RichMediaStudioChildAssetProperty" => "RichMediaStudioChildAssetProperty", "RichMediaStudioCreative" => "RichMediaStudioCreative", "RichMediaStudioCreativeError" => "RichMediaStudioCreativeError", "ServerError" => "ServerError", "SetValue" => "SetValue", "Size" => "Size", "SoapRequestHeader" => "SoapRequestHeader", "SoapResponseHeader" => "SoapResponseHeader", "Statement" => "Statement", "StatementError" => "StatementError", "StringCreativeTemplateVariableValue" => "StringCreativeTemplateVariableValue", "StringLengthError" => "StringLengthError", "String_ValueMapEntry" => "String_ValueMapEntry", "SwiffyConversionError" => "SwiffyConversionError", "SwiffyFallbackAsset" => "SwiffyFallbackAsset", "TemplateCreative" => "TemplateCreative", "TemplateInstantiatedCreativeError" => "TemplateInstantiatedCreativeError", "TextValue" => "TextValue", "ThirdPartyCreative" => "ThirdPartyCreative", "TrackingUrls" => "TrackingUrls", "TypeError" => "TypeError", "UniqueError" => "UniqueError", "UnsupportedCreative" => "UnsupportedCreative", "UrlCreativeTemplateVariableValue" => "UrlCreativeTemplateVariableValue", "Value" => "Value", "VastRedirectCreative" => "VastRedirectCreative", "VideoCreative" => "VideoCreative", "VideoRedirectAsset" => "VideoRedirectAsset", "VideoRedirectCreative" => "VideoRedirectCreative", "VpaidLinearCreative" => "VpaidLinearCreative", "VpaidLinearRedirectCreative" => "VpaidLinearRedirectCreative", "ApiFramework" => "ApiFramework", "ApiVersionError.Reason" => "ApiVersionErrorReason", "AssetError.Reason" => "AssetErrorReason", "AuthenticationError.Reason" => "AuthenticationErrorReason", "CommonError.Reason" => "CommonErrorReason", "ConversionEvent" => "ConversionEvent", "CreativeAssetMacroError.Reason" => "CreativeAssetMacroErrorReason", "CreativeError.Reason" => "CreativeErrorReason", "CreativeSetError.Reason" => "CreativeSetErrorReason", "CustomCreativeError.Reason" => "CustomCreativeErrorReason", "FeatureError.Reason" => "FeatureErrorReason", "FileError.Reason" => "FileErrorReason", "Html5Feature" => "Html5Feature", "ImageDensity" => "ImageDensity", "ImageError.Reason" => "ImageErrorReason", "InternalApiError.Reason" => "InternalApiErrorReason", "InvalidUrlError.Reason" => "InvalidUrlErrorReason", "LabelEntityAssociationError.Reason" => "LabelEntityAssociationErrorReason", "LineItemCreativeAssociationError.Reason" => "LineItemCreativeAssociationErrorReason", "NotNullError.Reason" => "NotNullErrorReason", "NullError.Reason" => "NullErrorReason", "ParseError.Reason" => "ParseErrorReason", "PermissionError.Reason" => "PermissionErrorReason", "PublisherQueryLanguageContextError.Reason" => "PublisherQueryLanguageContextErrorReason", "PublisherQueryLanguageSyntaxError.Reason" => "PublisherQueryLanguageSyntaxErrorReason", "QuotaError.Reason" => "QuotaErrorReason", "RangeError.Reason" => "RangeErrorReason", "RequiredCollectionError.Reason" => "RequiredCollectionErrorReason", "RequiredError.Reason" => "RequiredErrorReason", "RequiredNumberError.Reason" => "RequiredNumberErrorReason", "RequiredSizeError.Reason" => "RequiredSizeErrorReason", "RichMediaStudioChildAssetProperty.Type" => "RichMediaStudioChildAssetPropertyType", "RichMediaStudioCreativeArtworkType" => "RichMediaStudioCreativeArtworkType", "RichMediaStudioCreativeBillingAttribute" => "RichMediaStudioCreativeBillingAttribute", "RichMediaStudioCreativeError.Reason" => "RichMediaStudioCreativeErrorReason", "RichMediaStudioCreativeFormat" => "RichMediaStudioCreativeFormat", "ServerError.Reason" => "ServerErrorReason", "StatementError.Reason" => "StatementErrorReason", "StringLengthError.Reason" => "StringLengthErrorReason", "SwiffyConversionError.Reason" => "SwiffyConversionErrorReason", "TemplateInstantiatedCreativeError.Reason" => "TemplateInstantiatedCreativeErrorReason", "VastRedirectType" => "VastRedirectType", "createCreatives" => "CreateCreatives", "createCreativesResponse" => "CreateCreativesResponse", "getCreativesByStatement" => "GetCreativesByStatement", "getCreativesByStatementResponse" => "GetCreativesByStatementResponse", "updateCreatives" => "UpdateCreatives", "updateCreativesResponse" => "UpdateCreativesResponse", ); /** * Constructor using wsdl location and options array * @param string $wsdl WSDL location for this service * @param array $options Options for the SoapClient */ public function __construct($wsdl, $options, $user) { $options["classmap"] = self::$classmap; parent::__construct($wsdl, $options, $user, self::SERVICE_NAME, self::WSDL_NAMESPACE); } /** * Creates new {@link Creative} objects. * * @param creatives the creatives to create * @return the created creatives with their IDs filled in */ public function createCreatives($creatives) { $args = new CreateCreatives($creatives); $result = $this->__soapCall("createCreatives", array($args)); return $result->rval; } /** * Gets a {@link CreativePage} of {@link Creative} objects that satisfy the * given {@link Statement#query}. The following fields are supported for * filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link Creative#id}</td> * </tr> * <tr> * <td>{@code name}</td> * <td>{@link Creative#name}</td> * </tr> * <tr> * <td>{@code advertiserId}</td> * <td>{@link Creative#advertiserId}</td> * </tr> * <tr> * <td>{@code width}</td> * <td>{@link Creative#size}</td> * </tr> * <tr> * <td>{@code height}</td> * <td>{@link Creative#size}</td> * </tr> * <tr> * <td>{@code lastModifiedDateTime}</td> * <td>{@link Creative#lastModifiedDateTime}</td> * </tr> * </table> * * @param filterStatement a Publisher Query Language statement used to filter * a set of creatives * @return the creatives that match the given filter */ public function getCreativesByStatement($filterStatement) { $args = new GetCreativesByStatement($filterStatement); $result = $this->__soapCall("getCreativesByStatement", array($args)); return $result->rval; } /** * Updates the specified {@link Creative} objects. * * @param creatives the creatives to update * @return the updated creatives */ public function updateCreatives($creatives) { $args = new UpdateCreatives($creatives); $result = $this->__soapCall("updateCreatives", array($args)); return $result->rval; } } }
cornernote/googleads-php-lib
src/Google/Api/Ads/Dfp/v201403/CreativeService.php
PHP
apache-2.0
205,738
//package pl.matisoft.soy.example; // //import com.google.common.collect.Lists; //import com.google.common.util.concurrent.Futures; //import com.google.gson.Gson; //import com.google.gson.GsonBuilder; //import com.ning.http.client.AsyncCompletionHandler; //import com.ning.http.client.AsyncHttpClient; //import com.ning.http.client.ListenableFuture; //import com.ning.http.client.Response; //import com.spotify.trickle.Func0; //import com.spotify.trickle.Func1; //import com.spotify.trickle.Func2; //import org.springframework.stereotype.Controller; //import org.springframework.web.bind.annotation.RequestMapping; //import org.springframework.web.context.request.async.DeferredResult; //import org.springframework.web.servlet.ModelAndView; //import pl.matisoft.soy.example.ecb.Cube; //import pl.matisoft.soy.example.ecb.Envelope; //import pl.matisoft.soy.example.model.CurrencyEntry; //import pl.matisoft.soy.example.model.CurrencyModel; // //import javax.xml.bind.JAXBContext; //import javax.xml.bind.JAXBException; //import java.io.IOException; //import java.io.StringReader; //import java.util.List; //import java.util.Map; //import java.util.concurrent.*; // //@Controller //public class CurrencyAsyncController3 { // // private final static Gson gson = new GsonBuilder().create(); // // private ExecutorService executorService = new ForkJoinPool(); // // @RequestMapping(value="/async3") // public DeferredResult<ModelAndView> openHomepage() throws IOException, JAXBException, InterruptedException, ExecutionException, TimeoutException { // final AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); // final DeferredResult<ModelAndView> result = new DeferredResult<ModelAndView>(); // // final Func0<Envelope> findCurrencyRates = new Func0<Envelope>() { // // @Override // public com.google.common.util.concurrent.ListenableFuture<Envelope> run() { // try { // asyncHttpClient.prepareGet("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml").execute(new AsyncCompletionHandler<Envelope>() { // // @Override // public Envelope onCompleted(final Response response) throws Exception { // return parseCurrencyRates(response.getResponseBody()); // } // // @Override // public void onThrowable(final Throwable t) { // result.setErrorResult(t); // Futures.immediateFailedFuture(t); // } // // }); // // } catch (IOException e) { // e.printStackTrace(); // } // } // // }; // // final Func1<Void, Map<String, Map>> findCurrencyNames = new Func1<Void, Map<String, Map>>() { // // @Override // public com.google.common.util.concurrent.ListenableFuture< Map<String, Map>> run(Void aVoid) { // return null; // } // // }; // // final Func2<Envelope, Map<String, Map>, List<CurrencyEntry>> combined = new Func2<Envelope, Map<String, Map>, List<CurrencyEntry>>() { // // @Override // public com.google.common.util.concurrent.ListenableFuture<List<CurrencyEntry>> run(final Envelope envelope, final Map<String, Map> entryMap) { // final List<CurrencyEntry> currencyEntryList = Lists.newArrayList(); // if (!envelope.getCube().getCubes().isEmpty()) { // for (final Cube cube : envelope.getCube().getCubes().iterator().next().getCubes()) { // final String symbol = cube.getCurrency(); // final Double rate = cube.getRate(); // final String desc = (String) entryMap.get(symbol).get("name"); // currencyEntryList.add(new CurrencyEntry(symbol, desc, rate)); // } // } // // return Futures.immediateFuture(currencyEntryList); // } // }; // // return result; // } // // private void processRates(final Envelope envelope, Map<String,Map> entryMap, final DeferredResult<ModelAndView> result) throws IOException, JAXBException { // final List<CurrencyEntry> currencyEntryList = Lists.newArrayList(); // if (!envelope.getCube().getCubes().isEmpty()) { // for (final Cube cube : envelope.getCube().getCubes().iterator().next().getCubes()) { // final String symbol = cube.getCurrency(); // final Double rate = cube.getRate(); // final String desc = (String) entryMap.get(symbol).get("name"); // currencyEntryList.add(new CurrencyEntry(symbol, desc, rate)); // } // } // // result.setResult(new ModelAndView("soy:soy.example.index", "model", new CurrencyModel(currencyEntryList))); // } // // private Envelope parseCurrencyRates(final String xml) throws Exception { // final JAXBContext jaxbContext = JAXBContext.newInstance(Envelope.class); // final Envelope envelope = (Envelope) jaxbContext.createUnmarshaller().unmarshal(new StringReader(xml)); // // return envelope; // } // // private Map<String,Map> parseCurrencyNames(final String json) { // return gson.fromJson(json, Map.class); // } // //}
matiwinnetou/spring-async-currency-rates
src/main/java/pl/matisoft/soy/example/CurrencyAsyncController3.java
Java
apache-2.0
5,451
/* * Copyright 2018 FIX Protocol Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * */ package io.fixprotocol.orchestra.docgen; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.nio.file.Path; /** * Abstracts file systems * * @author Don Mendelson * */ interface PathManager extends AutoCloseable { long copyStreamToPath(InputStream in, Path path) throws IOException; OutputStream getOutputStream(Path path) throws IOException; Writer getWriter(Path path) throws IOException; boolean isSupported(String path); Path makeDirectory(Path path) throws IOException; Path makeRootPath(String path) throws IOException; }
FIXTradingCommunity/fix-orchestra
orchestra2doc/src/main/java/io/fixprotocol/orchestra/docgen/PathManager.java
Java
apache-2.0
1,228
/** * Copyright (C) 2011-2012 by Jochen Mader (pflanzenmoerder@gmail.com) * ============================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.codepitbull.session; import org.apache.wicket.util.tester.WicketTester; import org.junit.Before; import org.junit.Test; /** * Simple test using the WicketTester */ public class TestHomePage { private WicketTester tester; @Before public void setUp() { tester = new WicketTester(new WicketApplication()); } @Test public void homepageRendersSuccessfully() { //start and render the test page tester.startPage(HomePage.class); //assert rendered page class tester.assertRenderedPage(HomePage.class); } }
codepitbull/wicket-buch
teil2-session/src/test/java/de/codepitbull/session/TestHomePage.java
Java
apache-2.0
1,241
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2014 Thibaut Lapierre <git@epheo.eu>. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from jinja2 import Template import os.path import yaml class ModelDefinition(object): """Container definition This class is loading the model from the yaml files and provides different methods to read from it more easily. We can pass it a set of yaml files or directly a Python dictionary. It can contain 'projects', 'clusters' and 'services' It takes and return only dictionaries. """ def __init__(self, model=None, app_args=None, cluster_name=None): """Return a cluster list from the model. This method return the differents clusters as a list of dicts. """ self.model = 'shaddock.yml' if model: self.model = model self.app_args = app_args self.cluster_name = cluster_name if app_args and app_args.shdk_cluster: self.cluster_name = app_args.shdk_cluster Loader.add_constructor('!include', Loader.include) # Services are first imported as single string # They are then re loaded from yaml after jinja2. # Loader.add_constructor('services:', Loader.import_str) with open(self.model) as f: model = yaml.load(f, Loader) self.cluster_list = [] if model.get('projects') is not None: for project in model['projects']: for cluster in project['clusters']: self.cluster_list.append(cluster) if model.get('clusters') is not None: for cluster in model['clusters']: self.cluster_list.append(cluster) def get_cluster(self, name): """Return a cluster object by its name """ try: cluster = [clu for clu in self.cluster_list if clu['name'] == name] if len(cluster) > 1: raise TemplateFileError( "There is more than one definition matching" " 'name: {}' in your model".format(name)) cluster = cluster[0] except IndexError: raise TemplateFileError( "There is no cluster definition containing" " 'name: {}' in your model".format(name)) except KeyError: raise TemplateFileError( "At least one cluster definition " "is missing the name property") return cluster def _get_cluster_services(self, cluster): """Return a list of services from a cluster name """ services_list = [] if ('vars' in cluster): try: j2 = Template(str(cluster['services'])) services_yaml = j2.render(cluster['vars']) services = yaml.load(services_yaml) except ValueError: for l in cluster['vars']: j2 = Template(str(cluster['services'])) services_yaml = j2.render(l) services = yaml.load(services_yaml) cluster['services'] = services for service in cluster['services']: service['cluster'] = {} service['cluster']['images'] = cluster['images'] service['cluster']['name'] = cluster['name'] service['cluster']['hosts'] = cluster.get('hosts') service['cluster']['vars'] = cluster.get('vars') services_list.append(service) return services_list def get_services_list(self): """This method returns a service list as a dict list. """ if self.cluster_name is None: svc_list = [] for clu in self.cluster_list: clu_svc_list = self._get_cluster_services(clu) svc_list = svc_list + clu_svc_list else: cluster = self.get_cluster(self.cluster_name) svc_list = self._get_cluster_services(cluster) return svc_list def get_service(self, name): """This method returns a service as a dict. It can only return a service from a specific cluster. A service name is allowed only once per cluster. """ services_list = self.get_services_list() try: service = [svc for svc in services_list if svc['name'] == name] if len(service) > 1: raise TemplateFileError( "There is more than one definition matching" " 'name: {}' in this cluster".format(name)) service = service[0] except IndexError: raise TemplateFileError( "There is no container definition containing" " 'name: {}' in your model".format(name)) except KeyError: raise TemplateFileError( "At least one container definition in your model" " is missing the name property") service = self.build_service_dict(service) return service def build_service_dict(self, service): """Build a service dictionary """ # Image dir definition: # try: service['images_dir'] = os.path.join( os.path.dirname(self.model), service['cluster']['images']) except TypeError: raise TemplateFileError( "Cluster definition in your model is missing the images" " key.") try: service['image'] except KeyError: raise TemplateFileError( "Container definition of: '{}' in your model is" " missing the image property".format(service['name'])) service['path'] = '{}/{}'.format(service['images_dir'], service['image'].split(":")[0]) clu_name = service['cluster']['name'] service['service_name'] = clu_name + '_' + service['name'] # Host API Definition: # api_cfg = {} try: api_cfg = [api for api in service['cluster']['hosts'] if api['name'] == service['host']] if len(api_cfg) > 1: raise TemplateFileError( "There is more than one definition matching" " 'name: {}' in your model".format(service['name'])) api_cfg = api_cfg[0] except KeyError: pass except IndexError: raise TemplateFileError( "There is no Docker Host definition containing" " 'name: {}' in your model.".format(service['host'])) except TypeError: pass service['api_cfg'] = api_cfg return service class TemplateFileError(Exception): pass class Loader(yaml.Loader): """Include This class change the Yaml Load fct to allow file inclusion using the !include keywork. """ def __init__(self, stream): self._root = os.path.split(stream.name)[0] super(Loader, self).__init__(stream) def include(self, node): filename = os.path.join(self._root, self.construct_scalar(node)) # try: with open(filename, 'r') as f: return yaml.load(f, Loader) # except Exception: # raise TemplateFileError( # "The file {} you're trying to include doesn't" # "exist.".format(filename)) def import_str(self, node): return str(self.construct_scalar(node))
epheo/shaddock
shaddock/model.py
Python
apache-2.0
8,118
package net.aquadc.livelists.greendao; import net.aquadc.livelists.LiveDataLayer; import net.aquadc.livelists.LiveList; import org.greenrobot.greendao.query.Query; import java.util.List; import static net.aquadc.livelists.greendao.GreenDataLayer.required; /** * Created by miha on 07.03.17 */ public final class GreenLiveList<T extends LiveDataLayer.WithId> implements LiveList<T> { private final GreenDataLayer<T> layer; private final Query<T> query; public GreenLiveList(GreenDataLayer<T> layer, Query<T> query) { this.layer = layer; this.query = query; } @Override public void subscribeOnList(LiveDataLayer.BaseListSubscriber<? super T> subscriber) { layer.subscribeOnList(query, subscriber); } @Override public void unsubscribe(LiveDataLayer.BaseListSubscriber<? super T> subscriber) { layer.unsubscribe(subscriber); } @Override public List<? extends T> snapshot() { return layer.snapshot(query); } @Override public int size() { return layer.size(query); } @Override public void moveTo(LiveDataLayer.BaseListSubscriber<? super T> subscriber, LiveList<?> another) { required(subscriber, "subscriber"); if (!(another instanceof GreenLiveList)) { throw new IllegalArgumentException("Can move only to a LiveList of the same type. " + "This is GreenLiveList, another is " + (another == null ? "null" : another.getClass().getSimpleName())); } GreenLiveList<? extends T> anotherGreen = (GreenLiveList<? extends T>) another; if (layer != anotherGreen.layer) { throw new IllegalArgumentException("Can move only to a LiveList hosted on the same GreenDataLayer. " + "this.layer = " + layer + ", another.layer = " + anotherGreen.layer); } layer.changeQuery(subscriber, anotherGreen.query); } }
Miha-x64/LiveLists4GreenDAO
greenLiveLists/src/main/java/net/aquadc/livelists/greendao/GreenLiveList.java
Java
apache-2.0
1,929
// Copyright 2018 PingCAP, 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 executor_test import ( "fmt" "math" "strconv" "strings" "sync" "time" . "github.com/pingcap/check" "github.com/pingcap/tidb/errno" "github.com/pingcap/tidb/executor" "github.com/pingcap/tidb/meta/autoid" "github.com/pingcap/tidb/parser/terror" "github.com/pingcap/tidb/sessionctx/variable" "github.com/pingcap/tidb/table" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/collate" "github.com/pingcap/tidb/util/execdetails" "github.com/pingcap/tidb/util/israce" "github.com/pingcap/tidb/util/testkit" "github.com/pingcap/tidb/util/testutil" ) func (s *testSuite8) TestInsertOnDuplicateKey(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.MustExec(`drop table if exists t1, t2;`) tk.MustExec(`create table t1(a1 bigint primary key, b1 bigint);`) tk.MustExec(`create table t2(a2 bigint primary key, b2 bigint);`) tk.MustExec(`insert into t1 values(1, 100);`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(1)) tk.CheckLastMessage("") tk.MustExec(`insert into t2 values(1, 200);`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(1)) tk.CheckLastMessage("") tk.MustExec(`insert into t1 select a2, b2 from t2 on duplicate key update b1 = a2;`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(2)) tk.CheckLastMessage("Records: 1 Duplicates: 1 Warnings: 0") tk.MustQuery(`select * from t1;`).Check(testkit.Rows("1 1")) tk.MustExec(`insert into t1 select a2, b2 from t2 on duplicate key update b1 = b2;`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(2)) tk.CheckLastMessage("Records: 1 Duplicates: 1 Warnings: 0") tk.MustQuery(`select * from t1;`).Check(testkit.Rows("1 200")) tk.MustExec(`insert into t1 select a2, b2 from t2 on duplicate key update a1 = a2;`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(0)) tk.CheckLastMessage("Records: 1 Duplicates: 0 Warnings: 0") tk.MustQuery(`select * from t1;`).Check(testkit.Rows("1 200")) tk.MustExec(`insert into t1 select a2, b2 from t2 on duplicate key update b1 = 300;`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(2)) tk.CheckLastMessage("Records: 1 Duplicates: 1 Warnings: 0") tk.MustQuery(`select * from t1;`).Check(testkit.Rows("1 300")) tk.MustExec(`insert into t1 values(1, 1) on duplicate key update b1 = 400;`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(2)) tk.CheckLastMessage("") tk.MustQuery(`select * from t1;`).Check(testkit.Rows("1 400")) tk.MustExec(`insert into t1 select 1, 500 from t2 on duplicate key update b1 = 400;`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(0)) tk.CheckLastMessage("Records: 1 Duplicates: 0 Warnings: 0") tk.MustQuery(`select * from t1;`).Check(testkit.Rows("1 400")) tk.MustExec(`drop table if exists t1, t2;`) tk.MustExec(`create table t1(a bigint primary key, b bigint);`) tk.MustExec(`create table t2(a bigint primary key, b bigint);`) _, err := tk.Exec(`insert into t1 select * from t2 on duplicate key update c = t2.b;`) c.Assert(err.Error(), Equals, `[planner:1054]Unknown column 'c' in 'field list'`) tk.MustExec(`drop table if exists t1, t2;`) tk.MustExec(`create table t1(a bigint primary key, b bigint);`) tk.MustExec(`create table t2(a bigint primary key, b bigint);`) _, err = tk.Exec(`insert into t1 select * from t2 on duplicate key update a = b;`) c.Assert(err.Error(), Equals, `[planner:1052]Column 'b' in field list is ambiguous`) tk.MustExec(`drop table if exists t1, t2;`) tk.MustExec(`create table t1(a bigint primary key, b bigint);`) tk.MustExec(`create table t2(a bigint primary key, b bigint);`) _, err = tk.Exec(`insert into t1 select * from t2 on duplicate key update c = b;`) c.Assert(err.Error(), Equals, `[planner:1054]Unknown column 'c' in 'field list'`) tk.MustExec(`drop table if exists t1, t2;`) tk.MustExec(`create table t1(a1 bigint primary key, b1 bigint);`) tk.MustExec(`create table t2(a2 bigint primary key, b2 bigint);`) _, err = tk.Exec(`insert into t1 select * from t2 on duplicate key update a1 = values(b2);`) c.Assert(err.Error(), Equals, `[planner:1054]Unknown column 'b2' in 'field list'`) tk.MustExec(`drop table if exists t1, t2;`) tk.MustExec(`create table t1(a1 bigint primary key, b1 bigint);`) tk.MustExec(`create table t2(a2 bigint primary key, b2 bigint);`) tk.MustExec(`insert into t1 values(1, 100);`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(1)) tk.CheckLastMessage("") tk.MustExec(`insert into t2 values(1, 200);`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(1)) tk.CheckLastMessage("") tk.MustExec(`insert into t1 select * from t2 on duplicate key update b1 = values(b1) + b2;`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(2)) tk.CheckLastMessage("Records: 1 Duplicates: 1 Warnings: 0") tk.MustQuery(`select * from t1`).Check(testkit.Rows("1 400")) tk.MustExec(`insert into t1 select * from t2 on duplicate key update b1 = values(b1) + b2;`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(0)) tk.CheckLastMessage("Records: 1 Duplicates: 0 Warnings: 0") tk.MustQuery(`select * from t1`).Check(testkit.Rows("1 400")) tk.MustExec(`drop table if exists t;`) tk.MustExec(`create table t(k1 bigint, k2 bigint, val bigint, primary key(k1, k2));`) tk.MustExec(`insert into t (val, k1, k2) values (3, 1, 2);`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(1)) tk.CheckLastMessage("") tk.MustQuery(`select * from t;`).Check(testkit.Rows(`1 2 3`)) tk.MustExec(`insert into t (val, k1, k2) select c, a, b from (select 1 as a, 2 as b, 4 as c) tmp on duplicate key update val = tmp.c;`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(2)) tk.CheckLastMessage("Records: 1 Duplicates: 1 Warnings: 0") tk.MustQuery(`select * from t;`).Check(testkit.Rows(`1 2 4`)) tk.MustExec(`drop table if exists t;`) tk.MustExec(`create table t(k1 double, k2 double, v double, primary key(k1, k2));`) tk.MustExec(`insert into t (v, k1, k2) select c, a, b from (select "3" c, "1" a, "2" b) tmp on duplicate key update v=c;`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(1)) tk.CheckLastMessage("Records: 1 Duplicates: 0 Warnings: 0") tk.MustQuery(`select * from t;`).Check(testkit.Rows(`1 2 3`)) tk.MustExec(`insert into t (v, k1, k2) select c, a, b from (select "3" c, "1" a, "2" b) tmp on duplicate key update v=c;`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(0)) tk.CheckLastMessage("Records: 1 Duplicates: 0 Warnings: 0") tk.MustQuery(`select * from t;`).Check(testkit.Rows(`1 2 3`)) tk.MustExec(`drop table if exists t1, t2;`) tk.MustExec(`create table t1(id int, a int, b int);`) tk.MustExec(`insert into t1 values (1, 1, 1);`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(1)) tk.CheckLastMessage("") tk.MustExec(`insert into t1 values (2, 2, 1);`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(1)) tk.CheckLastMessage("") tk.MustExec(`insert into t1 values (3, 3, 1);`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(1)) tk.CheckLastMessage("") tk.MustExec(`create table t2(a int primary key, b int, unique(b));`) tk.MustExec(`insert into t2 select a, b from t1 order by id on duplicate key update a=t1.a, b=t1.b;`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(5)) tk.CheckLastMessage("Records: 3 Duplicates: 2 Warnings: 0") tk.MustQuery(`select * from t2 order by a;`).Check(testkit.Rows(`3 1`)) tk.MustExec(`drop table if exists t1, t2;`) tk.MustExec(`create table t1(id int, a int, b int);`) tk.MustExec(`insert into t1 values (1, 1, 1);`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(1)) tk.CheckLastMessage("") tk.MustExec(`insert into t1 values (2, 1, 2);`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(1)) tk.CheckLastMessage("") tk.MustExec(`insert into t1 values (3, 3, 1);`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(1)) tk.CheckLastMessage("") tk.MustExec(`create table t2(a int primary key, b int, unique(b));`) tk.MustExec(`insert into t2 select a, b from t1 order by id on duplicate key update a=t1.a, b=t1.b;`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(4)) tk.CheckLastMessage("Records: 3 Duplicates: 1 Warnings: 0") tk.MustQuery(`select * from t2 order by a;`).Check(testkit.Rows(`1 2`, `3 1`)) tk.MustExec(`drop table if exists t1, t2;`) tk.MustExec(`create table t1(id int, a int, b int, c int);`) tk.MustExec(`insert into t1 values (1, 1, 1, 1);`) tk.MustExec(`insert into t1 values (2, 2, 1, 2);`) tk.MustExec(`insert into t1 values (3, 3, 2, 2);`) tk.MustExec(`insert into t1 values (4, 4, 2, 2);`) tk.MustExec(`create table t2(a int primary key, b int, c int, unique(b), unique(c));`) tk.MustExec(`insert into t2 select a, b, c from t1 order by id on duplicate key update b=t2.b, c=t2.c;`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(2)) tk.CheckLastMessage("Records: 4 Duplicates: 0 Warnings: 0") tk.MustQuery(`select * from t2 order by a;`).Check(testkit.Rows(`1 1 1`, `3 2 2`)) tk.MustExec(`drop table if exists t1`) tk.MustExec(`create table t1(a int primary key, b int);`) tk.MustExec(`insert into t1 values(1,1),(2,2),(3,3),(4,4),(5,5);`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(5)) tk.CheckLastMessage("Records: 5 Duplicates: 0 Warnings: 0") tk.MustExec(`insert into t1 values(4,14),(5,15),(6,16),(7,17),(8,18) on duplicate key update b=b+10`) c.Assert(tk.Se.AffectedRows(), Equals, uint64(7)) tk.CheckLastMessage("Records: 5 Duplicates: 2 Warnings: 0") tk.MustExec("drop table if exists a, b") tk.MustExec("create table a(x int primary key)") tk.MustExec("create table b(x int, y int)") tk.MustExec("insert into a values(1)") tk.MustExec("insert into b values(1, 2)") tk.MustExec("insert into a select x from b ON DUPLICATE KEY UPDATE a.x=b.y") c.Assert(tk.Se.AffectedRows(), Equals, uint64(2)) tk.MustQuery("select * from a").Check(testkit.Rows("2")) // reproduce insert on duplicate key update bug under new row format. tk.MustExec(`drop table if exists t1`) tk.MustExec(`create table t1(c1 decimal(6,4), primary key(c1))`) tk.MustExec(`insert into t1 set c1 = 0.1`) tk.MustExec(`insert into t1 set c1 = 0.1 on duplicate key update c1 = 1`) tk.MustQuery(`select * from t1 use index(primary)`).Check(testkit.Rows(`1.0000`)) } func (s *testSuite8) TestClusterIndexInsertOnDuplicateKey(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("drop database if exists cluster_index_duplicate_entry_error;") tk.MustExec("create database cluster_index_duplicate_entry_error;") tk.MustExec("use cluster_index_duplicate_entry_error;") tk.Se.GetSessionVars().EnableClusteredIndex = variable.ClusteredIndexDefModeOn tk.MustExec("create table t(a char(20), b int, primary key(a));") tk.MustExec("insert into t values('aa', 1), ('bb', 1);") _, err := tk.Exec("insert into t values('aa', 2);") c.Assert(err, ErrorMatches, ".*Duplicate entry 'aa' for.*") tk.MustExec("drop table t;") tk.MustExec("create table t(a char(20), b varchar(30), c varchar(10), primary key(a, b, c));") tk.MustExec("insert into t values ('a', 'b', 'c'), ('b', 'a', 'c');") _, err = tk.Exec("insert into t values ('a', 'b', 'c');") c.Assert(err, ErrorMatches, ".*Duplicate entry 'a-b-c' for.*") } func (s *testSuite10) TestPaddingCommonHandle(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.Se.GetSessionVars().EnableClusteredIndex = variable.ClusteredIndexDefModeOn tk.MustExec("drop table if exists t1;") tk.MustExec(`create table t1(c1 decimal(6,4), primary key(c1))`) tk.MustExec(`insert into t1 set c1 = 0.1`) tk.MustExec(`insert into t1 set c1 = 0.1 on duplicate key update c1 = 1`) tk.MustQuery(`select * from t1`).Check(testkit.Rows(`1.0000`)) } func (s *testSuite2) TestInsertReorgDelete(c *C) { if israce.RaceEnabled { c.Skip("exhaustive types test, skip race test") } tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") inputs := []struct { typ string dat string }{ {"year", "'2004'"}, {"year", "2004"}, {"bit", "1"}, {"smallint unsigned", "1"}, {"int unsigned", "1"}, {"smallint", "-1"}, {"int", "-1"}, {"decimal(6,4)", "'1.1'"}, {"decimal", "1.1"}, {"numeric", "-1"}, {"float", "1.2"}, {"double", "1.2"}, {"double", "1.3"}, {"real", "1.4"}, {"date", "'2020-01-01'"}, {"time", "'20:00:00'"}, {"datetime", "'2020-01-01 22:22:22'"}, {"timestamp", "'2020-01-01 22:22:22'"}, {"year", "'2020'"}, {"char(15)", "'test'"}, {"varchar(15)", "'test'"}, {"binary(3)", "'a'"}, {"varbinary(3)", "'b'"}, {"blob", "'test'"}, {"text", "'test'"}, {"enum('a', 'b')", "'a'"}, {"set('a', 'b')", "'a,b'"}, } for _, i := range inputs { tk.MustExec(`drop table if exists t1`) tk.MustExec(fmt.Sprintf(`create table t1(c1 %s)`, i.typ)) tk.MustExec(fmt.Sprintf(`insert into t1 set c1 = %s`, i.dat)) switch i.typ { case "blob", "text": tk.MustExec(`alter table t1 add index idx(c1(3))`) default: tk.MustExec(`alter table t1 add index idx(c1)`) } tk.MustExec(`delete from t1`) tk.MustExec(`admin check table t1`) } } func (s *testSuite3) TestUpdateDuplicateKey(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.MustExec(`drop table if exists t;`) tk.MustExec(`create table c(i int,j int,k int,primary key(i,j,k));`) tk.MustExec(`insert into c values(1,2,3);`) tk.MustExec(`insert into c values(1,2,4);`) _, err := tk.Exec(`update c set i=1,j=2,k=4 where i=1 and j=2 and k=3;`) c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '1-2-4' for key 'PRIMARY'") } func (s *testSuite3) TestInsertWrongValueForField(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.MustExec(`drop table if exists t1;`) tk.MustExec(`create table t1(a bigint);`) _, err := tk.Exec(`insert into t1 values("asfasdfsajhlkhlksdaf");`) c.Assert(terror.ErrorEqual(err, table.ErrTruncatedWrongValueForField), IsTrue) tk.MustExec(`drop table if exists t1;`) tk.MustExec(`create table t1(a varchar(10)) charset ascii;`) _, err = tk.Exec(`insert into t1 values('我');`) c.Assert(terror.ErrorEqual(err, table.ErrTruncatedWrongValueForField), IsTrue) tk.MustExec(`drop table if exists t1;`) tk.MustExec(`create table t1(a char(10) charset utf8);`) tk.MustExec(`insert into t1 values('我');`) tk.MustExec(`alter table t1 add column b char(10) charset ascii as ((a));`) tk.MustQuery(`select * from t1;`).Check(testkit.Rows("我 ?")) tk.MustExec(`drop table if exists t;`) tk.MustExec(`create table t (a year);`) tk.MustGetErrMsg(`insert into t values(2156);`, "[types:1264]Out of range value for column 'a' at row 1") tk.MustExec(`DROP TABLE IF EXISTS ts`) tk.MustExec(`CREATE TABLE ts (id int DEFAULT NULL, time1 TIMESTAMP NULL DEFAULT NULL)`) tk.MustExec(`SET @@sql_mode=''`) tk.MustExec(`INSERT INTO ts (id, time1) VALUES (1, TIMESTAMP '1018-12-23 00:00:00')`) tk.MustQuery(`SHOW WARNINGS`).Check(testkit.Rows(`Warning 1292 Incorrect timestamp value: '1018-12-23 00:00:00'`)) tk.MustQuery(`SELECT * FROM ts ORDER BY id`).Check(testkit.Rows(`1 0000-00-00 00:00:00`)) tk.MustExec(`SET @@sql_mode='STRICT_TRANS_TABLES'`) _, err = tk.Exec(`INSERT INTO ts (id, time1) VALUES (2, TIMESTAMP '1018-12-24 00:00:00')`) c.Assert(err.Error(), Equals, `[table:1292]Incorrect timestamp value: '1018-12-24 00:00:00' for column 'time1' at row 1`) tk.MustExec(`DROP TABLE ts`) } func (s *testSuite3) TestInsertValueForCastDecimalField(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.MustExec(`drop table if exists t1;`) tk.MustExec(`create table t1(a decimal(15,2));`) tk.MustExec(`insert into t1 values (1111111111111.01);`) tk.MustQuery(`select * from t1;`).Check(testkit.Rows(`1111111111111.01`)) tk.MustQuery(`select cast(a as decimal) from t1;`).Check(testkit.Rows(`9999999999`)) } func (s *testSuite3) TestInsertDateTimeWithTimeZone(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test;`) tk.MustExec(`set time_zone="+09:00";`) tk.MustExec(`drop table if exists t;`) tk.MustExec(`create table t (id int, c1 datetime not null default CURRENT_TIMESTAMP);`) tk.MustExec(`set TIMESTAMP = 1234;`) tk.MustExec(`insert t (id) values (1);`) tk.MustQuery(`select * from t;`).Check(testkit.Rows( `1 1970-01-01 09:20:34`, )) // test for ambiguous cases cases := []struct { lit string expect string }{ {"2020-10-22", "2020-10-22 00:00:00"}, {"2020-10-22-16", "2020-10-22 16:00:00"}, {"2020-10-22 16-31", "2020-10-22 16:31:00"}, {"2020-10-22 16:31-15", "2020-10-22 16:31:15"}, {"2020-10-22T16:31:15-10", "2020-10-23 10:31:15"}, {"2020.10-22", "2020-10-22 00:00:00"}, {"2020-10.22-16", "2020-10-22 16:00:00"}, {"2020-10-22.16-31", "2020-10-22 16:31:00"}, {"2020-10-22 16.31-15", "2020-10-22 16:31:15"}, {"2020-10-22T16.31.15+14", "2020-10-22 10:31:15"}, {"2020-10:22", "2020-10-22 00:00:00"}, {"2020-10-22:16", "2020-10-22 16:00:00"}, {"2020-10-22-16:31", "2020-10-22 16:31:00"}, {"2020-10-22 16-31:15", "2020-10-22 16:31:15"}, {"2020-10-22T16.31.15+09:30", "2020-10-22 15:01:15"}, {"2020.10-22:16", "2020-10-22 16:00:00"}, {"2020-10.22-16:31", "2020-10-22 16:31:00"}, {"2020-10-22.16-31:15", "2020-10-22 16:31:15"}, {"2020-10-22T16:31.15+09:30", "2020-10-22 15:01:15"}, } tk.MustExec(`drop table if exists t`) tk.MustExec(`create table t (dt datetime)`) tk.MustExec(`set @@time_zone='+08:00'`) for _, ca := range cases { tk.MustExec(`delete from t`) tk.MustExec(fmt.Sprintf("insert into t values ('%s')", ca.lit)) tk.MustQuery(`select * from t`).Check(testkit.Rows(ca.expect)) } // test for time zone change tzcCases := []struct { tz1 string lit string tz2 string exp1 string exp2 string }{ {"+08:00", "2020-10-22T16:53:40Z", "+00:00", "2020-10-23 00:53:40", "2020-10-22 16:53:40"}, {"-08:00", "2020-10-22T16:53:40Z", "+08:00", "2020-10-22 08:53:40", "2020-10-23 00:53:40"}, {"-03:00", "2020-10-22T16:53:40+03:00", "+08:00", "2020-10-22 10:53:40", "2020-10-22 21:53:40"}, {"+08:00", "2020-10-22T16:53:40+08:00", "+08:00", "2020-10-22 16:53:40", "2020-10-22 16:53:40"}, } tk.MustExec("drop table if exists t") tk.MustExec("create table t (dt datetime, ts timestamp)") for _, ca := range tzcCases { tk.MustExec("delete from t") tk.MustExec(fmt.Sprintf("set @@time_zone='%s'", ca.tz1)) tk.MustExec(fmt.Sprintf("insert into t values ('%s', '%s')", ca.lit, ca.lit)) tk.MustExec(fmt.Sprintf("set @@time_zone='%s'", ca.tz2)) tk.MustQuery("select * from t").Check(testkit.Rows(ca.exp1 + " " + ca.exp2)) } // test for datetime in compare tk.MustExec("drop table if exists t") tk.MustExec("create table t (ts timestamp)") tk.MustExec("insert into t values ('2020-10-22T12:00:00Z'), ('2020-10-22T13:00:00Z'), ('2020-10-22T14:00:00Z')") tk.MustQuery("select count(*) from t where ts > '2020-10-22T12:00:00Z'").Check(testkit.Rows("2")) // test for datetime with fsp fspCases := []struct { fsp uint lit string exp1 string exp2 string }{ {2, "2020-10-27T14:39:10.10+00:00", "2020-10-27 22:39:10.10", "2020-10-27 22:39:10.10"}, {1, "2020-10-27T14:39:10.3+0200", "2020-10-27 20:39:10.3", "2020-10-27 20:39:10.3"}, {6, "2020-10-27T14:39:10.3-02", "2020-10-28 00:39:10.300000", "2020-10-28 00:39:10.300000"}, {2, "2020-10-27T14:39:10.10Z", "2020-10-27 22:39:10.10", "2020-10-27 22:39:10.10"}, } tk.MustExec("set @@time_zone='+08:00'") for _, ca := range fspCases { tk.MustExec("drop table if exists t") tk.MustExec(fmt.Sprintf("create table t (dt datetime(%d), ts timestamp(%d))", ca.fsp, ca.fsp)) tk.MustExec(fmt.Sprintf("insert into t values ('%s', '%s')", ca.lit, ca.lit)) tk.MustQuery("select * from t").Check(testkit.Rows(ca.exp1 + " " + ca.exp2)) } } func (s *testSuite3) TestInsertZeroYear(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.MustExec(`drop table if exists t1;`) tk.MustExec(`create table t1(a year(4));`) tk.MustExec(`insert into t1 values(0000),(00),("0000"),("000"), ("00"), ("0"), (79), ("79");`) tk.MustQuery(`select * from t1;`).Check(testkit.Rows( `0`, `0`, `0`, `2000`, `2000`, `2000`, `1979`, `1979`, )) tk.MustExec(`drop table if exists t;`) tk.MustExec(`create table t(f_year year NOT NULL DEFAULT '0000')ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;`) tk.MustExec(`insert into t values();`) tk.MustQuery(`select * from t;`).Check(testkit.Rows( `0`, )) tk.MustExec(`insert into t values('0000');`) tk.MustQuery(`select * from t;`).Check(testkit.Rows( `0`, `0`, )) } func (s *testSuiteP1) TestAllowInvalidDates(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec(`drop table if exists t1, t2, t3, t4;`) tk.MustExec(`create table t1(d date);`) tk.MustExec(`create table t2(d datetime);`) tk.MustExec(`create table t3(d date);`) tk.MustExec(`create table t4(d datetime);`) runWithMode := func(mode string) { inputs := []string{"0000-00-00", "2019-00-00", "2019-01-00", "2019-00-01", "2019-02-31"} results := testkit.Rows(`0 0 0`, `2019 0 0`, `2019 1 0`, `2019 0 1`, `2019 2 31`) oldMode := tk.MustQuery(`select @@sql_mode`).Rows()[0][0] defer func() { tk.MustExec(fmt.Sprintf(`set sql_mode='%s'`, oldMode)) }() tk.MustExec(`truncate t1;truncate t2;truncate t3;truncate t4;`) tk.MustExec(fmt.Sprintf(`set sql_mode='%s';`, mode)) for _, input := range inputs { tk.MustExec(fmt.Sprintf(`insert into t1 values ('%s')`, input)) tk.MustExec(fmt.Sprintf(`insert into t2 values ('%s')`, input)) } tk.MustQuery(`select year(d), month(d), day(d) from t1;`).Check(results) tk.MustQuery(`select year(d), month(d), day(d) from t2;`).Check(results) tk.MustExec(`insert t3 select d from t1;`) tk.MustQuery(`select year(d), month(d), day(d) from t3;`).Check(results) tk.MustExec(`insert t4 select d from t2;`) tk.MustQuery(`select year(d), month(d), day(d) from t4;`).Check(results) } runWithMode("STRICT_TRANS_TABLES,ALLOW_INVALID_DATES") runWithMode("ALLOW_INVALID_DATES") } func (s *testSuite3) TestInsertWithAutoidSchema(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec(`create table t1(id int primary key auto_increment, n int);`) tk.MustExec(`create table t2(id int unsigned primary key auto_increment, n int);`) tk.MustExec(`create table t3(id tinyint primary key auto_increment, n int);`) tk.MustExec(`create table t4(id int primary key, n float auto_increment, key I_n(n));`) tk.MustExec(`create table t5(id int primary key, n float unsigned auto_increment, key I_n(n));`) tk.MustExec(`create table t6(id int primary key, n double auto_increment, key I_n(n));`) tk.MustExec(`create table t7(id int primary key, n double unsigned auto_increment, key I_n(n));`) // test for inserting multiple values tk.MustExec(`create table t8(id int primary key auto_increment, n int);`) tests := []struct { insert string query string result [][]interface{} }{ { `insert into t1(id, n) values(1, 1)`, `select * from t1 where id = 1`, testkit.Rows(`1 1`), }, { `insert into t1(n) values(2)`, `select * from t1 where id = 2`, testkit.Rows(`2 2`), }, { `insert into t1(n) values(3)`, `select * from t1 where id = 3`, testkit.Rows(`3 3`), }, { `insert into t1(id, n) values(-1, 4)`, `select * from t1 where id = -1`, testkit.Rows(`-1 4`), }, { `insert into t1(n) values(5)`, `select * from t1 where id = 4`, testkit.Rows(`4 5`), }, { `insert into t1(id, n) values('5', 6)`, `select * from t1 where id = 5`, testkit.Rows(`5 6`), }, { `insert into t1(n) values(7)`, `select * from t1 where id = 6`, testkit.Rows(`6 7`), }, { `insert into t1(id, n) values(7.4, 8)`, `select * from t1 where id = 7`, testkit.Rows(`7 8`), }, { `insert into t1(id, n) values(7.5, 9)`, `select * from t1 where id = 8`, testkit.Rows(`8 9`), }, { `insert into t1(n) values(9)`, `select * from t1 where id = 9`, testkit.Rows(`9 9`), }, // test last insert id { `insert into t1 values(3000, -1), (null, -2)`, `select * from t1 where id = 3000`, testkit.Rows(`3000 -1`), }, { `;`, `select * from t1 where id = 3001`, testkit.Rows(`3001 -2`), }, { `;`, `select last_insert_id()`, testkit.Rows(`3001`), }, { `insert into t2(id, n) values(1, 1)`, `select * from t2 where id = 1`, testkit.Rows(`1 1`), }, { `insert into t2(n) values(2)`, `select * from t2 where id = 2`, testkit.Rows(`2 2`), }, { `insert into t2(n) values(3)`, `select * from t2 where id = 3`, testkit.Rows(`3 3`), }, { `insert into t3(id, n) values(1, 1)`, `select * from t3 where id = 1`, testkit.Rows(`1 1`), }, { `insert into t3(n) values(2)`, `select * from t3 where id = 2`, testkit.Rows(`2 2`), }, { `insert into t3(n) values(3)`, `select * from t3 where id = 3`, testkit.Rows(`3 3`), }, { `insert into t3(id, n) values(-1, 4)`, `select * from t3 where id = -1`, testkit.Rows(`-1 4`), }, { `insert into t3(n) values(5)`, `select * from t3 where id = 4`, testkit.Rows(`4 5`), }, { `insert into t4(id, n) values(1, 1)`, `select * from t4 where id = 1`, testkit.Rows(`1 1`), }, { `insert into t4(id) values(2)`, `select * from t4 where id = 2`, testkit.Rows(`2 2`), }, { `insert into t4(id, n) values(3, -1)`, `select * from t4 where id = 3`, testkit.Rows(`3 -1`), }, { `insert into t4(id) values(4)`, `select * from t4 where id = 4`, testkit.Rows(`4 3`), }, { `insert into t4(id, n) values(5, 5.5)`, `select * from t4 where id = 5`, testkit.Rows(`5 5.5`), }, { `insert into t4(id) values(6)`, `select * from t4 where id = 6`, testkit.Rows(`6 7`), }, { `insert into t4(id, n) values(7, '7.7')`, `select * from t4 where id = 7`, testkit.Rows(`7 7.7`), }, { `insert into t4(id) values(8)`, `select * from t4 where id = 8`, testkit.Rows(`8 9`), }, { `insert into t4(id, n) values(9, 10.4)`, `select * from t4 where id = 9`, testkit.Rows(`9 10.4`), }, { `insert into t4(id) values(10)`, `select * from t4 where id = 10`, testkit.Rows(`10 11`), }, { `insert into t5(id, n) values(1, 1)`, `select * from t5 where id = 1`, testkit.Rows(`1 1`), }, { `insert into t5(id) values(2)`, `select * from t5 where id = 2`, testkit.Rows(`2 2`), }, { `insert into t5(id) values(3)`, `select * from t5 where id = 3`, testkit.Rows(`3 3`), }, { `insert into t6(id, n) values(1, 1)`, `select * from t6 where id = 1`, testkit.Rows(`1 1`), }, { `insert into t6(id) values(2)`, `select * from t6 where id = 2`, testkit.Rows(`2 2`), }, { `insert into t6(id, n) values(3, -1)`, `select * from t6 where id = 3`, testkit.Rows(`3 -1`), }, { `insert into t6(id) values(4)`, `select * from t6 where id = 4`, testkit.Rows(`4 3`), }, { `insert into t6(id, n) values(5, 5.5)`, `select * from t6 where id = 5`, testkit.Rows(`5 5.5`), }, { `insert into t6(id) values(6)`, `select * from t6 where id = 6`, testkit.Rows(`6 7`), }, { `insert into t6(id, n) values(7, '7.7')`, `select * from t4 where id = 7`, testkit.Rows(`7 7.7`), }, { `insert into t6(id) values(8)`, `select * from t4 where id = 8`, testkit.Rows(`8 9`), }, { `insert into t6(id, n) values(9, 10.4)`, `select * from t6 where id = 9`, testkit.Rows(`9 10.4`), }, { `insert into t6(id) values(10)`, `select * from t6 where id = 10`, testkit.Rows(`10 11`), }, { `insert into t7(id, n) values(1, 1)`, `select * from t7 where id = 1`, testkit.Rows(`1 1`), }, { `insert into t7(id) values(2)`, `select * from t7 where id = 2`, testkit.Rows(`2 2`), }, { `insert into t7(id) values(3)`, `select * from t7 where id = 3`, testkit.Rows(`3 3`), }, // the following is test for insert multiple values. { `insert into t8(n) values(1),(2)`, `select * from t8 where id = 1`, testkit.Rows(`1 1`), }, { `;`, `select * from t8 where id = 2`, testkit.Rows(`2 2`), }, { `;`, `select last_insert_id();`, testkit.Rows(`1`), }, // test user rebase and auto alloc mixture. { `insert into t8 values(null, 3),(-1, -1),(null,4),(null, 5)`, `select * from t8 where id = 3`, testkit.Rows(`3 3`), }, // -1 won't rebase allocator here cause -1 < base. { `;`, `select * from t8 where id = -1`, testkit.Rows(`-1 -1`), }, { `;`, `select * from t8 where id = 4`, testkit.Rows(`4 4`), }, { `;`, `select * from t8 where id = 5`, testkit.Rows(`5 5`), }, { `;`, `select last_insert_id();`, testkit.Rows(`3`), }, { `insert into t8 values(null, 6),(10, 7),(null, 8)`, `select * from t8 where id = 6`, testkit.Rows(`6 6`), }, // 10 will rebase allocator here. { `;`, `select * from t8 where id = 10`, testkit.Rows(`10 7`), }, { `;`, `select * from t8 where id = 11`, testkit.Rows(`11 8`), }, { `;`, `select last_insert_id()`, testkit.Rows(`6`), }, // fix bug for last_insert_id should be first allocated id in insert rows (skip the rebase id). { `insert into t8 values(100, 9),(null,10),(null,11)`, `select * from t8 where id = 100`, testkit.Rows(`100 9`), }, { `;`, `select * from t8 where id = 101`, testkit.Rows(`101 10`), }, { `;`, `select * from t8 where id = 102`, testkit.Rows(`102 11`), }, { `;`, `select last_insert_id()`, testkit.Rows(`101`), }, // test with sql_mode: NO_AUTO_VALUE_ON_ZERO. { `;`, `select @@sql_mode`, testkit.Rows(`ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION`), }, { `;`, "set session sql_mode = `ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,NO_AUTO_VALUE_ON_ZERO`", nil, }, { `insert into t8 values (0, 12), (null, 13)`, `select * from t8 where id = 0`, testkit.Rows(`0 12`), }, { `;`, `select * from t8 where id = 103`, testkit.Rows(`103 13`), }, { `;`, `select last_insert_id()`, testkit.Rows(`103`), }, // test without sql_mode: NO_AUTO_VALUE_ON_ZERO. { `;`, "set session sql_mode = `ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION`", nil, }, // value 0 will be substitute by autoid. { `insert into t8 values (0, 14), (null, 15)`, `select * from t8 where id = 104`, testkit.Rows(`104 14`), }, { `;`, `select * from t8 where id = 105`, testkit.Rows(`105 15`), }, { `;`, `select last_insert_id()`, testkit.Rows(`104`), }, // last test : auto increment allocation can find in retryInfo. { `retry : insert into t8 values (null, 16), (null, 17)`, `select * from t8 where id = 1000`, testkit.Rows(`1000 16`), }, { `;`, `select * from t8 where id = 1001`, testkit.Rows(`1001 17`), }, { `;`, `select last_insert_id()`, // this insert doesn't has the last_insert_id, should be same as the last insert case. testkit.Rows(`104`), }, } for _, tt := range tests { if strings.HasPrefix(tt.insert, "retry : ") { // it's the last retry insert case, change the sessionVars. retryInfo := &variable.RetryInfo{Retrying: true} retryInfo.AddAutoIncrementID(1000) retryInfo.AddAutoIncrementID(1001) tk.Se.GetSessionVars().RetryInfo = retryInfo tk.MustExec(tt.insert[8:]) tk.Se.GetSessionVars().RetryInfo = &variable.RetryInfo{} } else { tk.MustExec(tt.insert) } if tt.query == "set session sql_mode = `ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,NO_AUTO_VALUE_ON_ZERO`" || tt.query == "set session sql_mode = `ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION`" { tk.MustExec(tt.query) } else { tk.MustQuery(tt.query).Check(tt.result) } } } func (s *testSuite3) TestPartitionInsertOnDuplicate(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec(`create table t1 (a int,b int,primary key(a,b)) partition by range(a) (partition p0 values less than (100),partition p1 values less than (1000))`) tk.MustExec(`insert into t1 set a=1, b=1`) tk.MustExec(`insert into t1 set a=1,b=1 on duplicate key update a=1,b=1`) tk.MustQuery(`select * from t1`).Check(testkit.Rows("1 1")) tk.MustExec(`create table t2 (a int,b int,primary key(a,b)) partition by hash(a) partitions 4`) tk.MustExec(`insert into t2 set a=1,b=1;`) tk.MustExec(`insert into t2 set a=1,b=1 on duplicate key update a=1,b=1`) tk.MustQuery(`select * from t2`).Check(testkit.Rows("1 1")) tk.MustExec(`CREATE TABLE t3 (a int, b int, c int, d int, e int, PRIMARY KEY (a,b), UNIQUE KEY (b,c,d) ) PARTITION BY RANGE ( b ) ( PARTITION p0 VALUES LESS THAN (4), PARTITION p1 VALUES LESS THAN (7), PARTITION p2 VALUES LESS THAN (11) )`) tk.MustExec("insert into t3 values (1,2,3,4,5)") tk.MustExec("insert into t3 values (1,2,3,4,5),(6,2,3,4,6) on duplicate key update e = e + values(e)") tk.MustQuery("select * from t3").Check(testkit.Rows("1 2 3 4 16")) } func (s *testSuite3) TestBit(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec(`create table t1 (a bit(3))`) _, err := tk.Exec("insert into t1 values(-1)") c.Assert(types.ErrDataTooLong.Equal(err), IsTrue) c.Assert(err.Error(), Matches, ".*Data too long for column 'a' at.*") _, err = tk.Exec("insert into t1 values(9)") c.Assert(err.Error(), Matches, ".*Data too long for column 'a' at.*") tk.MustExec(`create table t64 (a bit(64))`) tk.MustExec("insert into t64 values(-1)") tk.MustExec("insert into t64 values(18446744073709551615)") // 2^64 - 1 _, err = tk.Exec("insert into t64 values(18446744073709551616)") // z^64 c.Assert(err.Error(), Matches, ".*Out of range value for column 'a' at.*") } func (s *testSuiteP1) TestAllocateContinuousRowID(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec(`create table t1 (a int,b int, key I_a(a));`) wg := sync.WaitGroup{} for i := 0; i < 5; i++ { wg.Add(1) go func(idx int) { defer wg.Done() tk := testkit.NewTestKitWithInit(c, s.store) for j := 0; j < 10; j++ { k := strconv.Itoa(idx*100 + j) sql := "insert into t1(a,b) values (" + k + ", 2)" for t := 0; t < 20; t++ { sql += ",(" + k + ",2)" } tk.MustExec(sql) q := "select _tidb_rowid from t1 where a=" + k rows := tk.MustQuery(q).Rows() c.Assert(len(rows), Equals, 21) last := 0 for _, r := range rows { c.Assert(len(r), Equals, 1) v, err := strconv.Atoi(r[0].(string)) c.Assert(err, Equals, nil) if last > 0 { c.Assert(last+1, Equals, v) } last = v } } }(i) } wg.Wait() } func (s *testSuite3) TestJiraIssue5366(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec(`create table bug (a varchar(100))`) tk.MustExec(` insert into bug select ifnull(JSON_UNQUOTE(JSON_EXTRACT('[{"amount":2000,"feeAmount":0,"merchantNo":"20190430140319679394","shareBizCode":"20160311162_SECOND"}]', '$[0].merchantNo')),'') merchant_no union SELECT '20180531557' merchant_no;`) tk.MustQuery(`select * from bug`).Sort().Check(testkit.Rows("20180531557", "20190430140319679394")) } func (s *testSuite3) TestDMLCast(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec(`create table t (a int, b double)`) tk.MustExec(`insert into t values (ifnull('',0)+0, 0)`) tk.MustExec(`insert into t values (0, ifnull('',0)+0)`) tk.MustQuery(`select * from t`).Check(testkit.Rows("0 0", "0 0")) _, err := tk.Exec(`insert into t values ('', 0)`) c.Assert(err, NotNil) _, err = tk.Exec(`insert into t values (0, '')`) c.Assert(err, NotNil) _, err = tk.Exec(`update t set a = ''`) c.Assert(err, NotNil) _, err = tk.Exec(`update t set b = ''`) c.Assert(err, NotNil) tk.MustExec("update t set a = ifnull('',0)+0") tk.MustExec("update t set b = ifnull('',0)+0") tk.MustExec("delete from t where a = ''") tk.MustQuery(`select * from t`).Check(testkit.Rows()) } func (s *testSuite3) TestInsertFloatOverflow(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.MustExec(`drop table if exists t,t1;`) tk.MustExec("create table t(col1 FLOAT, col2 FLOAT(10,2), col3 DOUBLE, col4 DOUBLE(10,2), col5 DECIMAL, col6 DECIMAL(10,2));") _, err := tk.Exec("insert into t values (-3.402823466E+68, -34028234.6611, -1.7976931348623157E+308, -17976921.34, -9999999999, -99999999.99);") c.Assert(err.Error(), Equals, "[types:1264]Out of range value for column 'col1' at row 1") _, err = tk.Exec("insert into t values (-34028234.6611, -3.402823466E+68, -1.7976931348623157E+308, -17976921.34, -9999999999, -99999999.99);") c.Assert(err.Error(), Equals, "[types:1264]Out of range value for column 'col2' at row 1") _, err = tk.Exec("create table t1(id1 float,id2 float)") c.Assert(err, IsNil) _, err = tk.Exec("insert ignore into t1 values(999999999999999999999999999999999999999,-999999999999999999999999999999999999999)") c.Assert(err, IsNil) tk.MustQuery("select @@warning_count").Check(testutil.RowsWithSep("|", "2")) tk.MustQuery("select convert(id1,decimal(65)),convert(id2,decimal(65)) from t1").Check(testkit.Rows("340282346638528860000000000000000000000 -340282346638528860000000000000000000000")) tk.MustExec("drop table if exists t,t1") } // TestAutoIDIncrementAndOffset There is a potential issue in MySQL: when the value of auto_increment_offset is greater // than that of auto_increment_increment, the value of auto_increment_offset is ignored // (https://dev.mysql.com/doc/refman/8.0/en/replication-options-master.html#sysvar_auto_increment_increment), // This issue is a flaw of the implementation of MySQL and it doesn't exist in TiDB. func (s *testSuite3) TestAutoIDIncrementAndOffset(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) // Test for offset is larger than increment. tk.Se.GetSessionVars().AutoIncrementIncrement = 5 tk.Se.GetSessionVars().AutoIncrementOffset = 10 tk.MustExec(`create table io (a int key auto_increment)`) tk.MustExec(`insert into io values (null),(null),(null)`) tk.MustQuery(`select * from io`).Check(testkit.Rows("10", "15", "20")) tk.MustExec(`drop table io`) // Test handle is PK. tk.MustExec(`create table io (a int key auto_increment)`) tk.Se.GetSessionVars().AutoIncrementOffset = 10 tk.Se.GetSessionVars().AutoIncrementIncrement = 2 tk.MustExec(`insert into io values (),(),()`) tk.MustQuery(`select * from io`).Check(testkit.Rows("10", "12", "14")) tk.MustExec(`delete from io`) // Test reset the increment. tk.Se.GetSessionVars().AutoIncrementIncrement = 5 tk.MustExec(`insert into io values (),(),()`) tk.MustQuery(`select * from io`).Check(testkit.Rows("15", "20", "25")) tk.MustExec(`delete from io`) tk.Se.GetSessionVars().AutoIncrementIncrement = 10 tk.MustExec(`insert into io values (),(),()`) tk.MustQuery(`select * from io`).Check(testkit.Rows("30", "40", "50")) tk.MustExec(`delete from io`) tk.Se.GetSessionVars().AutoIncrementIncrement = 5 tk.MustExec(`insert into io values (),(),()`) tk.MustQuery(`select * from io`).Check(testkit.Rows("55", "60", "65")) tk.MustExec(`drop table io`) // Test handle is not PK. tk.Se.GetSessionVars().AutoIncrementIncrement = 2 tk.Se.GetSessionVars().AutoIncrementOffset = 10 tk.MustExec(`create table io (a int, b int auto_increment, key(b))`) tk.MustExec(`insert into io(b) values (null),(null),(null)`) // AutoID allocation will take increment and offset into consideration. tk.MustQuery(`select b from io`).Check(testkit.Rows("10", "12", "14")) // HandleID allocation will ignore the increment and offset. tk.MustQuery(`select _tidb_rowid from io`).Check(testkit.Rows("15", "16", "17")) tk.MustExec(`delete from io`) tk.Se.GetSessionVars().AutoIncrementIncrement = 10 tk.MustExec(`insert into io(b) values (null),(null),(null)`) tk.MustQuery(`select b from io`).Check(testkit.Rows("20", "30", "40")) tk.MustQuery(`select _tidb_rowid from io`).Check(testkit.Rows("41", "42", "43")) // Test invalid value. tk.Se.GetSessionVars().AutoIncrementIncrement = -1 tk.Se.GetSessionVars().AutoIncrementOffset = -2 _, err := tk.Exec(`insert into io(b) values (null),(null),(null)`) c.Assert(err, NotNil) c.Assert(err.Error(), Equals, "[autoid:8060]Invalid auto_increment settings: auto_increment_increment: -1, auto_increment_offset: -2, both of them must be in range [1..65535]") tk.MustExec(`delete from io`) tk.Se.GetSessionVars().AutoIncrementIncrement = 65536 tk.Se.GetSessionVars().AutoIncrementOffset = 65536 _, err = tk.Exec(`insert into io(b) values (null),(null),(null)`) c.Assert(err, NotNil) c.Assert(err.Error(), Equals, "[autoid:8060]Invalid auto_increment settings: auto_increment_increment: 65536, auto_increment_offset: 65536, both of them must be in range [1..65535]") } var _ = Suite(&testSuite9{&baseTestSuite{}}) type testSuite9 struct { *baseTestSuite } func (s *testSuite9) TestAutoRandomID(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec(`drop table if exists ar`) tk.MustExec(`create table ar (id bigint key clustered auto_random, name char(10))`) tk.MustExec(`insert into ar(id) values (null)`) rs := tk.MustQuery(`select id from ar`) c.Assert(len(rs.Rows()), Equals, 1) firstValue, err := strconv.Atoi(rs.Rows()[0][0].(string)) c.Assert(err, IsNil) c.Assert(firstValue, Greater, 0) tk.MustQuery(`select last_insert_id()`).Check(testkit.Rows(fmt.Sprintf("%d", firstValue))) tk.MustExec(`delete from ar`) tk.MustExec(`insert into ar(id) values (0)`) rs = tk.MustQuery(`select id from ar`) c.Assert(len(rs.Rows()), Equals, 1) firstValue, err = strconv.Atoi(rs.Rows()[0][0].(string)) c.Assert(err, IsNil) c.Assert(firstValue, Greater, 0) tk.MustQuery(`select last_insert_id()`).Check(testkit.Rows(fmt.Sprintf("%d", firstValue))) tk.MustExec(`delete from ar`) tk.MustExec(`insert into ar(name) values ('a')`) rs = tk.MustQuery(`select id from ar`) c.Assert(len(rs.Rows()), Equals, 1) firstValue, err = strconv.Atoi(rs.Rows()[0][0].(string)) c.Assert(err, IsNil) c.Assert(firstValue, Greater, 0) tk.MustQuery(`select last_insert_id()`).Check(testkit.Rows(fmt.Sprintf("%d", firstValue))) tk.MustExec(`drop table ar`) tk.MustExec(`create table ar (id bigint key clustered auto_random(15), name char(10))`) overflowVal := 1 << (64 - 5) errMsg := fmt.Sprintf(autoid.AutoRandomRebaseOverflow, overflowVal, 1<<(64-16)-1) _, err = tk.Exec(fmt.Sprintf("alter table ar auto_random_base = %d", overflowVal)) c.Assert(err, NotNil) c.Assert(strings.Contains(err.Error(), errMsg), IsTrue) } func (s *testSuite9) TestMultiAutoRandomID(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec(`drop table if exists ar`) tk.MustExec(`create table ar (id bigint key clustered auto_random, name char(10))`) tk.MustExec(`insert into ar(id) values (null),(null),(null)`) rs := tk.MustQuery(`select id from ar order by id`) c.Assert(len(rs.Rows()), Equals, 3) firstValue, err := strconv.Atoi(rs.Rows()[0][0].(string)) c.Assert(err, IsNil) c.Assert(firstValue, Greater, 0) c.Assert(rs.Rows()[1][0].(string), Equals, fmt.Sprintf("%d", firstValue+1)) c.Assert(rs.Rows()[2][0].(string), Equals, fmt.Sprintf("%d", firstValue+2)) tk.MustQuery(`select last_insert_id()`).Check(testkit.Rows(fmt.Sprintf("%d", firstValue))) tk.MustExec(`delete from ar`) tk.MustExec(`insert into ar(id) values (0),(0),(0)`) rs = tk.MustQuery(`select id from ar order by id`) c.Assert(len(rs.Rows()), Equals, 3) firstValue, err = strconv.Atoi(rs.Rows()[0][0].(string)) c.Assert(err, IsNil) c.Assert(firstValue, Greater, 0) c.Assert(rs.Rows()[1][0].(string), Equals, fmt.Sprintf("%d", firstValue+1)) c.Assert(rs.Rows()[2][0].(string), Equals, fmt.Sprintf("%d", firstValue+2)) tk.MustQuery(`select last_insert_id()`).Check(testkit.Rows(fmt.Sprintf("%d", firstValue))) tk.MustExec(`delete from ar`) tk.MustExec(`insert into ar(name) values ('a'),('a'),('a')`) rs = tk.MustQuery(`select id from ar order by id`) c.Assert(len(rs.Rows()), Equals, 3) firstValue, err = strconv.Atoi(rs.Rows()[0][0].(string)) c.Assert(err, IsNil) c.Assert(firstValue, Greater, 0) c.Assert(rs.Rows()[1][0].(string), Equals, fmt.Sprintf("%d", firstValue+1)) c.Assert(rs.Rows()[2][0].(string), Equals, fmt.Sprintf("%d", firstValue+2)) tk.MustQuery(`select last_insert_id()`).Check(testkit.Rows(fmt.Sprintf("%d", firstValue))) tk.MustExec(`drop table ar`) } func (s *testSuite9) TestAutoRandomIDAllowZero(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec(`drop table if exists ar`) tk.MustExec(`create table ar (id bigint key clustered auto_random, name char(10))`) rs := tk.MustQuery(`select @@session.sql_mode`) sqlMode := rs.Rows()[0][0].(string) tk.MustExec(fmt.Sprintf(`set session sql_mode="%s,%s"`, sqlMode, "NO_AUTO_VALUE_ON_ZERO")) tk.MustExec(`insert into ar(id) values (0)`) rs = tk.MustQuery(`select id from ar`) c.Assert(len(rs.Rows()), Equals, 1) firstValue, err := strconv.Atoi(rs.Rows()[0][0].(string)) c.Assert(err, IsNil) c.Assert(firstValue, Equals, 0) tk.MustQuery(`select last_insert_id()`).Check(testkit.Rows(fmt.Sprintf("%d", firstValue))) tk.MustExec(`delete from ar`) tk.MustExec(`insert into ar(id) values (null)`) rs = tk.MustQuery(`select id from ar`) c.Assert(len(rs.Rows()), Equals, 1) firstValue, err = strconv.Atoi(rs.Rows()[0][0].(string)) c.Assert(err, IsNil) c.Assert(firstValue, Greater, 0) tk.MustQuery(`select last_insert_id()`).Check(testkit.Rows(fmt.Sprintf("%d", firstValue))) tk.MustExec(`drop table ar`) } func (s *testSuite9) TestAutoRandomIDExplicit(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("set @@allow_auto_random_explicit_insert = true") tk.MustExec(`use test`) tk.MustExec(`drop table if exists ar`) tk.MustExec(`create table ar (id bigint key clustered auto_random, name char(10))`) tk.MustExec(`insert into ar(id) values (1)`) tk.MustQuery(`select id from ar`).Check(testkit.Rows("1")) tk.MustQuery(`select last_insert_id()`).Check(testkit.Rows("0")) tk.MustExec(`delete from ar`) tk.MustExec(`insert into ar(id) values (1), (2)`) tk.MustQuery(`select id from ar`).Check(testkit.Rows("1", "2")) tk.MustQuery(`select last_insert_id()`).Check(testkit.Rows("0")) tk.MustExec(`delete from ar`) tk.MustExec(`drop table ar`) } func (s *testSuite9) TestInsertErrorMsg(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec(`drop table if exists t`) tk.MustExec(`create table t (a int primary key, b datetime, d date)`) _, err := tk.Exec(`insert into t values (1, '2019-02-11 30:00:00', '2019-01-31')`) c.Assert(err, NotNil) c.Assert(strings.Contains(err.Error(), "Incorrect datetime value: '2019-02-11 30:00:00' for column 'b' at row 1"), IsTrue, Commentf("%v", err)) } func (s *testSuite9) TestIssue16366(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test;`) tk.MustExec(`drop table if exists t;`) tk.MustExec(`create table t(c numeric primary key);`) tk.MustExec("insert ignore into t values(null);") _, err := tk.Exec(`insert into t values(0);`) c.Assert(err, NotNil) c.Assert(strings.Contains(err.Error(), "Duplicate entry '0' for key 'PRIMARY'"), IsTrue, Commentf("%v", err)) } var _ = SerialSuites(&testSuite10{&baseTestSuite{}}) type testSuite10 struct { *baseTestSuite } func (s *testSuite10) TestClusterPrimaryTablePlainInsert(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.Se.GetSessionVars().EnableClusteredIndex = variable.ClusteredIndexDefModeOn tk.MustExec(`drop table if exists t1pk`) tk.MustExec(`create table t1pk(id varchar(200) primary key, v int)`) tk.MustExec(`insert into t1pk(id, v) values('abc', 1)`) tk.MustQuery(`select * from t1pk`).Check(testkit.Rows("abc 1")) tk.MustExec(`set @@tidb_constraint_check_in_place=true`) tk.MustGetErrCode(`insert into t1pk(id, v) values('abc', 2)`, errno.ErrDupEntry) tk.MustExec(`set @@tidb_constraint_check_in_place=false`) tk.MustGetErrCode(`insert into t1pk(id, v) values('abc', 3)`, errno.ErrDupEntry) tk.MustQuery(`select v, id from t1pk`).Check(testkit.Rows("1 abc")) tk.MustQuery(`select id from t1pk where id = 'abc'`).Check(testkit.Rows("abc")) tk.MustQuery(`select v, id from t1pk where id = 'abc'`).Check(testkit.Rows("1 abc")) tk.MustExec(`drop table if exists t3pk`) tk.MustExec(`create table t3pk(id1 varchar(200), id2 varchar(200), v int, id3 int, primary key(id1, id2, id3))`) tk.MustExec(`insert into t3pk(id1, id2, id3, v) values('abc', 'xyz', 100, 1)`) tk.MustQuery(`select * from t3pk`).Check(testkit.Rows("abc xyz 1 100")) tk.MustExec(`set @@tidb_constraint_check_in_place=true`) tk.MustGetErrCode(`insert into t3pk(id1, id2, id3, v) values('abc', 'xyz', 100, 2)`, errno.ErrDupEntry) tk.MustExec(`set @@tidb_constraint_check_in_place=false`) tk.MustGetErrCode(`insert into t3pk(id1, id2, id3, v) values('abc', 'xyz', 100, 3)`, errno.ErrDupEntry) tk.MustQuery(`select v, id3, id2, id1 from t3pk`).Check(testkit.Rows("1 100 xyz abc")) tk.MustQuery(`select id3, id2, id1 from t3pk where id3 = 100 and id2 = 'xyz' and id1 = 'abc'`).Check(testkit.Rows("100 xyz abc")) tk.MustQuery(`select id3, id2, id1, v from t3pk where id3 = 100 and id2 = 'xyz' and id1 = 'abc'`).Check(testkit.Rows("100 xyz abc 1")) tk.MustExec(`insert into t3pk(id1, id2, id3, v) values('abc', 'xyz', 101, 1)`) tk.MustExec(`insert into t3pk(id1, id2, id3, v) values('abc', 'zzz', 101, 1)`) tk.MustExec(`drop table if exists t1pku`) tk.MustExec(`create table t1pku(id varchar(200) primary key, uk int, v int, unique key ukk(uk))`) tk.MustExec(`insert into t1pku(id, uk, v) values('abc', 1, 2)`) tk.MustQuery(`select * from t1pku where id = 'abc'`).Check(testkit.Rows("abc 1 2")) tk.MustGetErrCode(`insert into t1pku(id, uk, v) values('aaa', 1, 3)`, errno.ErrDupEntry) tk.MustQuery(`select * from t1pku`).Check(testkit.Rows("abc 1 2")) tk.MustQuery(`select * from t3pk where (id1, id2, id3) in (('abc', 'xyz', 100), ('abc', 'xyz', 101), ('abc', 'zzz', 101))`). Check(testkit.Rows("abc xyz 1 100", "abc xyz 1 101", "abc zzz 1 101")) } func (s *testSuite10) TestClusterPrimaryTableInsertIgnore(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.Se.GetSessionVars().EnableClusteredIndex = variable.ClusteredIndexDefModeOn tk.MustExec(`drop table if exists it1pk`) tk.MustExec(`create table it1pk(id varchar(200) primary key, v int)`) tk.MustExec(`insert into it1pk(id, v) values('abc', 1)`) tk.MustExec(`insert ignore into it1pk(id, v) values('abc', 2)`) tk.MustQuery(`select * from it1pk where id = 'abc'`).Check(testkit.Rows("abc 1")) tk.MustExec(`drop table if exists it2pk`) tk.MustExec(`create table it2pk(id1 varchar(200), id2 varchar(200), v int, primary key(id1, id2))`) tk.MustExec(`insert into it2pk(id1, id2, v) values('abc', 'cba', 1)`) tk.MustQuery(`select * from it2pk where id1 = 'abc' and id2 = 'cba'`).Check(testkit.Rows("abc cba 1")) tk.MustExec(`insert ignore into it2pk(id1, id2, v) values('abc', 'cba', 2)`) tk.MustQuery(`select * from it2pk where id1 = 'abc' and id2 = 'cba'`).Check(testkit.Rows("abc cba 1")) tk.MustExec(`drop table if exists it1pku`) tk.MustExec(`create table it1pku(id varchar(200) primary key, uk int, v int, unique key ukk(uk))`) tk.MustExec(`insert into it1pku(id, uk, v) values('abc', 1, 2)`) tk.MustQuery(`select * from it1pku where id = 'abc'`).Check(testkit.Rows("abc 1 2")) tk.MustExec(`insert ignore into it1pku(id, uk, v) values('aaa', 1, 3), ('bbb', 2, 1)`) tk.MustQuery(`select * from it1pku`).Check(testkit.Rows("abc 1 2", "bbb 2 1")) } func (s *testSuite10) TestClusterPrimaryTableInsertDuplicate(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.Se.GetSessionVars().EnableClusteredIndex = variable.ClusteredIndexDefModeOn tk.MustExec(`drop table if exists dt1pi`) tk.MustExec(`create table dt1pi(id varchar(200) primary key, v int)`) tk.MustExec(`insert into dt1pi(id, v) values('abb', 1),('acc', 2)`) tk.MustExec(`insert into dt1pi(id, v) values('abb', 2) on duplicate key update v = v + 1`) tk.MustQuery(`select * from dt1pi`).Check(testkit.Rows("abb 2", "acc 2")) tk.MustExec(`insert into dt1pi(id, v) values('abb', 2) on duplicate key update v = v + 1, id = 'xxx'`) tk.MustQuery(`select * from dt1pi`).Check(testkit.Rows("acc 2", "xxx 3")) tk.MustExec(`drop table if exists dt1piu`) tk.MustExec(`create table dt1piu(id varchar(200) primary key, uk int, v int, unique key uuk(uk))`) tk.MustExec(`insert into dt1piu(id, uk, v) values('abb', 1, 10),('acc', 2, 20)`) tk.MustExec(`insert into dt1piu(id, uk, v) values('xyz', 1, 100) on duplicate key update v = v + 1`) tk.MustQuery(`select * from dt1piu`).Check(testkit.Rows("abb 1 11", "acc 2 20")) tk.MustExec(`insert into dt1piu(id, uk, v) values('abb', 1, 2) on duplicate key update v = v + 1, id = 'xxx'`) tk.MustQuery(`select * from dt1piu`).Check(testkit.Rows("acc 2 20", "xxx 1 12")) tk.MustExec(`drop table if exists ts1pk`) tk.MustExec(`create table ts1pk(id1 timestamp, id2 timestamp, v int, primary key(id1, id2))`) ts := "2018-01-01 11:11:11" tk.MustExec(`insert into ts1pk (id1, id2, v) values(?, ?, ?)`, ts, ts, 1) tk.MustQuery(`select id1, id2, v from ts1pk`).Check(testkit.Rows("2018-01-01 11:11:11 2018-01-01 11:11:11 1")) tk.MustExec(`insert into ts1pk (id1, id2, v) values(?, ?, ?) on duplicate key update v = values(v)`, ts, ts, 2) tk.MustQuery(`select id1, id2, v from ts1pk`).Check(testkit.Rows("2018-01-01 11:11:11 2018-01-01 11:11:11 2")) tk.MustExec(`insert into ts1pk (id1, id2, v) values(?, ?, ?) on duplicate key update v = values(v), id1 = ?`, ts, ts, 2, "2018-01-01 11:11:12") tk.MustQuery(`select id1, id2, v from ts1pk`).Check(testkit.Rows("2018-01-01 11:11:12 2018-01-01 11:11:11 2")) } func (s *testSuite10) TestClusterPrimaryKeyForIndexScan(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.Se.GetSessionVars().EnableClusteredIndex = variable.ClusteredIndexDefModeOn tk.MustExec("drop table if exists pkt1;") tk.MustExec("CREATE TABLE pkt1 (a varchar(255), b int, index idx(b), primary key(a,b));") tk.MustExec("insert into pkt1 values ('aaa',1);") tk.MustQuery(`select b from pkt1 where b = 1;`).Check(testkit.Rows("1")) tk.MustExec("drop table if exists pkt2;") tk.MustExec("CREATE TABLE pkt2 (a varchar(255), b int, unique index idx(b), primary key(a,b));") tk.MustExec("insert into pkt2 values ('aaa',1);") tk.MustQuery(`select b from pkt2 where b = 1;`).Check(testkit.Rows("1")) tk.MustExec("drop table if exists issue_18232;") tk.MustExec("create table issue_18232 (a int, b int, c int, d int, primary key (a, b), index idx(c));") iter, cnt := combination([]string{"a", "b", "c", "d"}), 0 for { comb := iter() if comb == nil { break } selField := strings.Join(comb, ",") sql := fmt.Sprintf("select %s from issue_18232 use index (idx);", selField) tk.MustExec(sql) cnt++ } c.Assert(cnt, Equals, 15) } func (s *testSuite10) TestInsertRuntimeStat(c *C) { stats := &executor.InsertRuntimeStat{ BasicRuntimeStats: &execdetails.BasicRuntimeStats{}, SnapshotRuntimeStats: nil, CheckInsertTime: 2 * time.Second, Prefetch: 1 * time.Second, } stats.BasicRuntimeStats.Record(5*time.Second, 1) c.Assert(stats.String(), Equals, "prepare: 3s, check_insert: {total_time: 2s, mem_insert_time: 1s, prefetch: 1s}") c.Assert(stats.String(), Equals, stats.Clone().String()) stats.Merge(stats.Clone()) c.Assert(stats.String(), Equals, "prepare: 6s, check_insert: {total_time: 4s, mem_insert_time: 2s, prefetch: 2s}") } func (s *testSerialSuite) TestDuplicateEntryMessage(c *C) { collate.SetNewCollationEnabledForTest(true) defer collate.SetNewCollationEnabledForTest(false) tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test;") for _, enable := range []variable.ClusteredIndexDefMode{variable.ClusteredIndexDefModeOn, variable.ClusteredIndexDefModeOff, variable.ClusteredIndexDefModeIntOnly} { tk.Se.GetSessionVars().EnableClusteredIndex = enable tk.MustExec("drop table if exists t;") tk.MustExec("create table t(a int, b char(10), unique key(b)) collate utf8mb4_general_ci;") tk.MustExec("insert into t value (34, '12Ak');") tk.MustGetErrMsg("insert into t value (34, '12Ak');", "[kv:1062]Duplicate entry '12Ak' for key 'b'") tk.MustExec("begin optimistic;") tk.MustExec("insert into t value (34, '12ak');") tk.MustExec("delete from t where b = '12ak';") tk.MustGetErrMsg("commit;", "previous statement: delete from t where b = '12ak';: [kv:1062]Duplicate entry '12ak' for key 'b'") tk.MustExec("drop table if exists t;") tk.MustExec("create table t (a datetime primary key);") tk.MustExec("insert into t values ('2020-01-01');") tk.MustGetErrMsg("insert into t values ('2020-01-01');", "[kv:1062]Duplicate entry '2020-01-01 00:00:00' for key 'PRIMARY'") tk.MustExec("begin optimistic;") tk.MustExec("insert into t values ('2020-01-01');") tk.MustExec("delete from t where a = '2020-01-01';") tk.MustGetErrMsg("commit;", "previous statement: delete from t where a = '2020-01-01';: [kv:1062]Duplicate entry '2020-01-01 00:00:00' for key 'PRIMARY'") tk.MustExec("drop table if exists t;") tk.MustExec("create table t (a int primary key );") tk.MustExec("insert into t value (1);") tk.MustGetErrMsg("insert into t value (1);", "[kv:1062]Duplicate entry '1' for key 'PRIMARY'") tk.MustExec("drop table if exists t;") tk.MustExec("create table t (a datetime unique);") tk.MustExec("insert into t values ('2020-01-01');") tk.MustGetErrMsg("insert into t values ('2020-01-01');", "[kv:1062]Duplicate entry '2020-01-01 00:00:00' for key 'a'") tk.MustExec("drop table if exists t;") tk.MustExec("create table t (a datetime, b int, c varchar(10), primary key (a, b, c)) collate utf8mb4_general_ci;") tk.MustExec("insert into t values ('2020-01-01', 1, 'aSDd');") tk.MustGetErrMsg("insert into t values ('2020-01-01', 1, 'ASDD');", "[kv:1062]Duplicate entry '2020-01-01 00:00:00-1-ASDD' for key 'PRIMARY'") tk.MustExec("drop table if exists t;") tk.MustExec("create table t (a datetime, b int, c varchar(10), unique key (a, b, c)) collate utf8mb4_general_ci;") tk.MustExec("insert into t values ('2020-01-01', 1, 'aSDd');") tk.MustGetErrMsg("insert into t values ('2020-01-01', 1, 'ASDD');", "[kv:1062]Duplicate entry '2020-01-01 00:00:00-1-ASDD' for key 'a'") tk.MustExec("drop table if exists t;") tk.MustExec("create table t (a char(10) collate utf8mb4_unicode_ci, b char(20) collate utf8mb4_general_ci, c int(11), primary key (a, b, c), unique key (a));") tk.MustExec("insert ignore into t values ('$', 'C', 10);") tk.MustExec("insert ignore into t values ('$', 'C', 10);") tk.MustQuery("show warnings;").Check(testutil.RowsWithSep("|", "Warning|1062|Duplicate entry '$-C-10' for key 'PRIMARY'")) tk.MustExec("begin pessimistic;") tk.MustExec("insert into t values ('a7', 'a', 10);") tk.MustGetErrMsg("insert into t values ('a7', 'a', 10);", "[kv:1062]Duplicate entry 'a7-a-10' for key 'PRIMARY'") tk.MustExec("rollback;") // Test for large unsigned integer handle. // See https://github.com/pingcap/tidb/issues/12420. tk.MustExec("drop table if exists t;") tk.MustExec("create table t(a bigint unsigned primary key);") tk.MustExec("insert into t values(18446744073709551615);") tk.MustGetErrMsg("insert into t values(18446744073709551615);", "[kv:1062]Duplicate entry '18446744073709551615' for key 'PRIMARY'") } } func (s *testSerialSuite) TestIssue20768(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.MustExec("drop table if exists t1, t2") tk.MustExec("create table t1(a year, primary key(a))") tk.MustExec("insert ignore into t1 values(null)") tk.MustExec("create table t2(a int, key(a))") tk.MustExec("insert into t2 values(0)") tk.MustQuery("select /*+ hash_join(t1) */ * from t1 join t2 on t1.a = t2.a").Check(testkit.Rows("0 0")) tk.MustQuery("select /*+ inl_join(t1) */ * from t1 join t2 on t1.a = t2.a").Check(testkit.Rows("0 0")) tk.MustQuery("select /*+ inl_join(t2) */ * from t1 join t2 on t1.a = t2.a").Check(testkit.Rows("0 0")) tk.MustQuery("select /*+ inl_hash_join(t1) */ * from t1 join t2 on t1.a = t2.a").Check(testkit.Rows("0 0")) tk.MustQuery("select /*+ inl_merge_join(t1) */ * from t1 join t2 on t1.a = t2.a").Check(testkit.Rows("0 0")) tk.MustQuery("select /*+ merge_join(t1) */ * from t1 join t2 on t1.a = t2.a").Check(testkit.Rows("0 0")) } func (s *testSuite9) TestIssue10402(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.MustExec("create table vctt (v varchar(4), c char(4))") tk.MustExec("insert into vctt values ('ab ', 'ab ')") tk.MustQuery("select * from vctt").Check(testkit.Rows("ab ab")) tk.MustExec("delete from vctt") tk.Se.GetSessionVars().StmtCtx.SetWarnings(nil) tk.MustExec("insert into vctt values ('ab\\n\\n\\n', 'ab\\n\\n\\n'), ('ab\\t\\t\\t', 'ab\\t\\t\\t'), ('ab ', 'ab '), ('ab\\r\\r\\r', 'ab\\r\\r\\r')") c.Check(tk.Se.GetSessionVars().StmtCtx.WarningCount(), Equals, uint16(4)) warns := tk.Se.GetSessionVars().StmtCtx.GetWarnings() c.Check(fmt.Sprintf("%v", warns), Equals, "[{Warning [types:1265]Data truncated, field len 4, data len 5} {Warning [types:1265]Data truncated, field len 4, data len 5} {Warning [types:1265]Data truncated, field len 4, data len 6} {Warning [types:1265]Data truncated, field len 4, data len 5}]") tk.MustQuery("select * from vctt").Check(testkit.Rows("ab\n\n ab\n\n", "ab\t\t ab\t\t", "ab ab", "ab\r\r ab\r\r")) tk.MustQuery("select length(v), length(c) from vctt").Check(testkit.Rows("4 4", "4 4", "4 2", "4 4")) } func combination(items []string) func() []string { current := 1 buf := make([]string, len(items)) return func() []string { if current >= int(math.Pow(2, float64(len(items)))) { return nil } buf = buf[:0] for i, e := range items { if (1<<i)&current != 0 { buf = append(buf, e) } } current++ return buf } } // TestDuplicatedEntryErr See https://github.com/pingcap/tidb/issues/24582 func (s *testSuite10) TestDuplicatedEntryErr(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") tk.MustExec("drop table if exists t1;") tk.MustExec("create table t1(a int, b varchar(20), primary key(a,b(3)) clustered);") tk.MustExec("insert into t1 values(1,'aaaaa');") err := tk.ExecToErr("insert into t1 values(1,'aaaaa');") c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '1-aaa' for key 'PRIMARY'") err = tk.ExecToErr("insert into t1 select 1, 'aaa'") c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '1-aaa' for key 'PRIMARY'") tk.MustExec("insert into t1 select 1, 'bb'") err = tk.ExecToErr("insert into t1 select 1, 'bb'") c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '1-bb' for key 'PRIMARY'") } func (s *testSuite10) TestBinaryLiteralInsertToEnum(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec("drop table if exists bintest") tk.MustExec("create table bintest (h enum(0x61, '1', 'b')) character set utf8mb4") tk.MustExec("insert into bintest(h) values(0x61)") tk.MustQuery("select * from bintest").Check(testkit.Rows("a")) } func (s *testSuite10) TestBinaryLiteralInsertToSet(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec("drop table if exists bintest") tk.MustExec("create table bintest (h set(0x61, '1', 'b')) character set utf8mb4") tk.MustExec("insert into bintest(h) values(0x61)") tk.MustQuery("select * from bintest").Check(testkit.Rows("a")) } var _ = SerialSuites(&testSuite13{&baseTestSuite{}}) type testSuite13 struct { *baseTestSuite } func (s *testSuite13) TestGlobalTempTableAutoInc(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec("drop table if exists temp_test") tk.MustExec("create global temporary table temp_test(id int primary key auto_increment) on commit delete rows") defer tk.MustExec("drop table if exists temp_test") // Data is cleared after transaction auto commits. tk.MustExec("insert into temp_test(id) values(0)") tk.MustQuery("select * from temp_test").Check(testkit.Rows()) // Data is not cleared inside a transaction. tk.MustExec("begin") tk.MustExec("insert into temp_test(id) values(0)") tk.MustQuery("select * from temp_test").Check(testkit.Rows("1")) tk.MustExec("commit") // AutoID allocator is cleared. tk.MustExec("begin") tk.MustExec("insert into temp_test(id) values(0)") tk.MustQuery("select * from temp_test").Check(testkit.Rows("1")) // Test whether auto-inc is incremental tk.MustExec("insert into temp_test(id) values(0)") tk.MustQuery("select id from temp_test order by id").Check(testkit.Rows("1", "2")) tk.MustExec("commit") // multi-value insert tk.MustExec("begin") tk.MustExec("insert into temp_test(id) values(0), (0)") tk.MustQuery("select id from temp_test order by id").Check(testkit.Rows("1", "2")) tk.MustExec("insert into temp_test(id) values(0), (0)") tk.MustQuery("select id from temp_test order by id").Check(testkit.Rows("1", "2", "3", "4")) tk.MustExec("commit") // rebase tk.MustExec("begin") tk.MustExec("insert into temp_test(id) values(10)") tk.MustExec("insert into temp_test(id) values(0)") tk.MustQuery("select id from temp_test order by id").Check(testkit.Rows("10", "11")) tk.MustExec("insert into temp_test(id) values(20), (30)") tk.MustExec("insert into temp_test(id) values(0), (0)") tk.MustQuery("select id from temp_test order by id").Check(testkit.Rows("10", "11", "20", "30", "31", "32")) tk.MustExec("commit") } func (s *testSuite13) TestGlobalTempTableRowID(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec("drop table if exists temp_test") tk.MustExec("create global temporary table temp_test(id int) on commit delete rows") defer tk.MustExec("drop table if exists temp_test") // Data is cleared after transaction auto commits. tk.MustExec("insert into temp_test(id) values(0)") tk.MustQuery("select _tidb_rowid from temp_test").Check(testkit.Rows()) // Data is not cleared inside a transaction. tk.MustExec("begin") tk.MustExec("insert into temp_test(id) values(0)") tk.MustQuery("select _tidb_rowid from temp_test").Check(testkit.Rows("1")) tk.MustExec("commit") // AutoID allocator is cleared. tk.MustExec("begin") tk.MustExec("insert into temp_test(id) values(0)") tk.MustQuery("select _tidb_rowid from temp_test").Check(testkit.Rows("1")) // Test whether row id is incremental tk.MustExec("insert into temp_test(id) values(0)") tk.MustQuery("select _tidb_rowid from temp_test order by _tidb_rowid").Check(testkit.Rows("1", "2")) tk.MustExec("commit") // multi-value insert tk.MustExec("begin") tk.MustExec("insert into temp_test(id) values(0), (0)") tk.MustQuery("select _tidb_rowid from temp_test order by _tidb_rowid").Check(testkit.Rows("1", "2")) tk.MustExec("insert into temp_test(id) values(0), (0)") tk.MustQuery("select _tidb_rowid from temp_test order by _tidb_rowid").Check(testkit.Rows("1", "2", "3", "4")) tk.MustExec("commit") } func (s *testSuite13) TestGlobalTempTableParallel(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec("drop table if exists temp_test") tk.MustExec("create global temporary table temp_test(id int primary key auto_increment) on commit delete rows") defer tk.MustExec("drop table if exists temp_test") threads := 8 loops := 1 wg := sync.WaitGroup{} wg.Add(threads) insertFunc := func() { defer wg.Done() newTk := testkit.NewTestKitWithInit(c, s.store) newTk.MustExec("begin") for i := 0; i < loops; i++ { newTk.MustExec("insert temp_test value(0)") newTk.MustExec("insert temp_test value(0), (0)") } maxID := strconv.Itoa(loops * 3) newTk.MustQuery("select max(id) from temp_test").Check(testkit.Rows(maxID)) newTk.MustExec("commit") } for i := 0; i < threads; i++ { go insertFunc() } wg.Wait() } func (s *testSuite13) TestIssue26762(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec("drop table if exists t1;") tk.MustExec("create table t1(c1 date);") _, err := tk.Exec("insert into t1 values('2020-02-31');") c.Assert(err.Error(), Equals, `[table:1292]Incorrect date value: '2020-02-31' for column 'c1' at row 1`) tk.MustExec("set @@sql_mode='ALLOW_INVALID_DATES';") tk.MustExec("insert into t1 values('2020-02-31');") tk.MustQuery("select * from t1").Check(testkit.Rows("2020-02-31")) tk.MustExec("set @@sql_mode='STRICT_TRANS_TABLES';") _, err = tk.Exec("insert into t1 values('2020-02-31');") c.Assert(err.Error(), Equals, `[table:1292]Incorrect date value: '2020-02-31' for column 'c1' at row 1`) } func (s *testSuite13) TestIssue17745(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec(`use test`) tk.MustExec("drop table if exists tt1") tk.MustExec("create table tt1 (c1 decimal(64))") tk.MustGetErrCode("insert into tt1 values(89000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)", errno.ErrWarnDataOutOfRange) tk.MustGetErrCode("insert into tt1 values(89123456789012345678901234567890123456789012345678901234567890123456789012345678900000000)", errno.ErrWarnDataOutOfRange) tk.MustExec("insert ignore into tt1 values(89123456789012345678901234567890123456789012345678901234567890123456789012345678900000000)") tk.MustQuery("show warnings;").Check(testkit.Rows(`Warning 1690 DECIMAL value is out of range in '(64, 0)'`, `Warning 1292 Truncated incorrect DECIMAL value: '789012345678901234567890123456789012345678901234567890123456789012345678900000000'`)) tk.MustQuery("select c1 from tt1").Check(testkit.Rows("9999999999999999999999999999999999999999999999999999999999999999")) tk.MustGetErrCode("update tt1 set c1 = 89123456789012345678901234567890123456789012345678901234567890123456789012345678900000000", errno.ErrWarnDataOutOfRange) tk.MustExec("drop table if exists tt1") tk.MustGetErrCode("insert into tt1 values(4556414e723532)", errno.ErrIllegalValueForType) tk.MustQuery("select 888888888888888888888888888888888888888888888888888888888888888888888888888888888888").Check(testkit.Rows("99999999999999999999999999999999999999999999999999999999999999999")) tk.MustQuery("show warnings;").Check(testutil.RowsWithSep("|", "Warning|1292|Truncated incorrect DECIMAL value: '888888888888888888888888888888888888888888888888888888888888888888888888888888888'")) }
c4pt0r/tidb
executor/insert_test.go
GO
apache-2.0
71,519
//===- tools/dsymutil/DwarfStreamer.cpp - Dwarf Streamer ------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "DwarfStreamer.h" #include "CompileUnit.h" #include "LinkUtils.h" #include "MachOUtils.h" #include "llvm/ADT/Triple.h" #include "llvm/DebugInfo/DWARF/DWARFContext.h" #include "llvm/MC/MCTargetOptions.h" #include "llvm/MC/MCTargetOptionsCommandFlags.inc" #include "llvm/Support/LEB128.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" namespace llvm { namespace dsymutil { /// Retrieve the section named \a SecName in \a Obj. /// /// To accommodate for platform discrepancies, the name passed should be /// (for example) 'debug_info' to match either '__debug_info' or '.debug_info'. /// This function will strip the initial platform-specific characters. static Optional<object::SectionRef> getSectionByName(const object::ObjectFile &Obj, StringRef SecName) { for (const object::SectionRef &Section : Obj.sections()) { StringRef SectionName; Section.getName(SectionName); SectionName = SectionName.substr(SectionName.find_first_not_of("._")); if (SectionName != SecName) continue; return Section; } return None; } bool DwarfStreamer::init(Triple TheTriple) { std::string ErrorStr; std::string TripleName; StringRef Context = "dwarf streamer init"; // Get the target. const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr); if (!TheTarget) return error(ErrorStr, Context); TripleName = TheTriple.getTriple(); // Create all the MC Objects. MRI.reset(TheTarget->createMCRegInfo(TripleName)); if (!MRI) return error(Twine("no register info for target ") + TripleName, Context); MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName)); if (!MAI) return error("no asm info for target " + TripleName, Context); MOFI.reset(new MCObjectFileInfo); MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get())); MOFI->InitMCObjectFileInfo(TheTriple, /*PIC*/ false, *MC); MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", "")); if (!MSTI) return error("no subtarget info for target " + TripleName, Context); MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags(); MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, MCOptions); if (!MAB) return error("no asm backend for target " + TripleName, Context); MII.reset(TheTarget->createMCInstrInfo()); if (!MII) return error("no instr info info for target " + TripleName, Context); MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC); if (!MCE) return error("no code emitter for target " + TripleName, Context); switch (Options.FileType) { case OutputFileType::Assembly: { MIP = TheTarget->createMCInstPrinter(TheTriple, MAI->getAssemblerDialect(), *MAI, *MII, *MRI); MS = TheTarget->createAsmStreamer( *MC, llvm::make_unique<formatted_raw_ostream>(OutFile), true, true, MIP, std::unique_ptr<MCCodeEmitter>(MCE), std::unique_ptr<MCAsmBackend>(MAB), true); break; } case OutputFileType::Object: { MS = TheTarget->createMCObjectStreamer( TheTriple, *MC, std::unique_ptr<MCAsmBackend>(MAB), MAB->createObjectWriter(OutFile), std::unique_ptr<MCCodeEmitter>(MCE), *MSTI, MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible, /*DWARFMustBeAtTheEnd*/ false); break; } } if (!MS) return error("no object streamer for target " + TripleName, Context); // Finally create the AsmPrinter we'll use to emit the DIEs. TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions(), None)); if (!TM) return error("no target machine for target " + TripleName, Context); Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS))); if (!Asm) return error("no asm printer for target " + TripleName, Context); RangesSectionSize = 0; LocSectionSize = 0; LineSectionSize = 0; FrameSectionSize = 0; return true; } bool DwarfStreamer::finish(const DebugMap &DM, SymbolMapTranslator &T) { bool Result = true; if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty() && Options.FileType == OutputFileType::Object) Result = MachOUtils::generateDsymCompanion(DM, T, *MS, OutFile); else MS->Finish(); return Result; } void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) { MS->SwitchSection(MOFI->getDwarfInfoSection()); MC->setDwarfVersion(DwarfVersion); } /// Emit the compilation unit header for \p Unit in the debug_info section. /// /// A Dwarf section header is encoded as: /// uint32_t Unit length (omitting this field) /// uint16_t Version /// uint32_t Abbreviation table offset /// uint8_t Address size /// /// Leading to a total of 11 bytes. void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) { unsigned Version = Unit.getOrigUnit().getVersion(); switchToDebugInfoSection(Version); /// The start of the unit within its section. Unit.setLabelBegin(Asm->createTempSymbol("cu_begin")); Asm->OutStreamer->EmitLabel(Unit.getLabelBegin()); // Emit size of content not including length itself. The size has already // been computed in CompileUnit::computeOffsets(). Subtract 4 to that size to // account for the length field. Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4); Asm->emitInt16(Version); // We share one abbreviations table across all units so it's always at the // start of the section. Asm->emitInt32(0); Asm->emitInt8(Unit.getOrigUnit().getAddressByteSize()); // Remember this CU. EmittedUnits.push_back({Unit.getUniqueID(), Unit.getLabelBegin()}); } /// Emit the \p Abbrevs array as the shared abbreviation table /// for the linked Dwarf file. void DwarfStreamer::emitAbbrevs( const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs, unsigned DwarfVersion) { MS->SwitchSection(MOFI->getDwarfAbbrevSection()); MC->setDwarfVersion(DwarfVersion); Asm->emitDwarfAbbrevs(Abbrevs); } /// Recursively emit the DIE tree rooted at \p Die. void DwarfStreamer::emitDIE(DIE &Die) { MS->SwitchSection(MOFI->getDwarfInfoSection()); Asm->emitDwarfDIE(Die); } /// Emit the debug_str section stored in \p Pool. void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) { Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection()); std::vector<DwarfStringPoolEntryRef> Entries = Pool.getEntriesForEmission(); for (auto Entry : Entries) { // Emit the string itself. Asm->OutStreamer->EmitBytes(Entry.getString()); // Emit a null terminator. Asm->emitInt8(0); } } void DwarfStreamer::emitDebugNames( AccelTable<DWARF5AccelTableStaticData> &Table) { if (EmittedUnits.empty()) return; // Build up data structures needed to emit this section. std::vector<MCSymbol *> CompUnits; DenseMap<unsigned, size_t> UniqueIdToCuMap; unsigned Id = 0; for (auto &CU : EmittedUnits) { CompUnits.push_back(CU.LabelBegin); // We might be omitting CUs, so we need to remap them. UniqueIdToCuMap[CU.ID] = Id++; } Asm->OutStreamer->SwitchSection(MOFI->getDwarfDebugNamesSection()); emitDWARF5AccelTable( Asm.get(), Table, CompUnits, [&UniqueIdToCuMap](const DWARF5AccelTableStaticData &Entry) { return UniqueIdToCuMap[Entry.getCUIndex()]; }); } void DwarfStreamer::emitAppleNamespaces( AccelTable<AppleAccelTableStaticOffsetData> &Table) { Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelNamespaceSection()); auto *SectionBegin = Asm->createTempSymbol("namespac_begin"); Asm->OutStreamer->EmitLabel(SectionBegin); emitAppleAccelTable(Asm.get(), Table, "namespac", SectionBegin); } void DwarfStreamer::emitAppleNames( AccelTable<AppleAccelTableStaticOffsetData> &Table) { Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelNamesSection()); auto *SectionBegin = Asm->createTempSymbol("names_begin"); Asm->OutStreamer->EmitLabel(SectionBegin); emitAppleAccelTable(Asm.get(), Table, "names", SectionBegin); } void DwarfStreamer::emitAppleObjc( AccelTable<AppleAccelTableStaticOffsetData> &Table) { Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelObjCSection()); auto *SectionBegin = Asm->createTempSymbol("objc_begin"); Asm->OutStreamer->EmitLabel(SectionBegin); emitAppleAccelTable(Asm.get(), Table, "objc", SectionBegin); } void DwarfStreamer::emitAppleTypes( AccelTable<AppleAccelTableStaticTypeData> &Table) { Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelTypesSection()); auto *SectionBegin = Asm->createTempSymbol("types_begin"); Asm->OutStreamer->EmitLabel(SectionBegin); emitAppleAccelTable(Asm.get(), Table, "types", SectionBegin); } /// Emit the swift_ast section stored in \p Buffers. void DwarfStreamer::emitSwiftAST(StringRef Buffer) { MCSection *SwiftASTSection = MOFI->getDwarfSwiftASTSection(); SwiftASTSection->setAlignment(1 << 5); MS->SwitchSection(SwiftASTSection); MS->EmitBytes(Buffer); } /// Emit the debug_range section contents for \p FuncRange by /// translating the original \p Entries. The debug_range section /// format is totally trivial, consisting just of pairs of address /// sized addresses describing the ranges. void DwarfStreamer::emitRangesEntries( int64_t UnitPcOffset, uint64_t OrigLowPc, const FunctionIntervals::const_iterator &FuncRange, const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries, unsigned AddressSize) { MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection()); // Offset each range by the right amount. int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset; for (const auto &Range : Entries) { if (Range.isBaseAddressSelectionEntry(AddressSize)) { warn("unsupported base address selection operation", "emitting debug_ranges"); break; } // Do not emit empty ranges. if (Range.StartAddress == Range.EndAddress) continue; // All range entries should lie in the function range. if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() && Range.EndAddress + OrigLowPc <= FuncRange.stop())) warn("inconsistent range data.", "emitting debug_ranges"); MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize); MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize); RangesSectionSize += 2 * AddressSize; } // Add the terminator entry. MS->EmitIntValue(0, AddressSize); MS->EmitIntValue(0, AddressSize); RangesSectionSize += 2 * AddressSize; } /// Emit the debug_aranges contribution of a unit and /// if \p DoDebugRanges is true the debug_range contents for a /// compile_unit level DW_AT_ranges attribute (Which are basically the /// same thing with a different base address). /// Just aggregate all the ranges gathered inside that unit. void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit, bool DoDebugRanges) { unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize(); // Gather the ranges in a vector, so that we can simplify them. The // IntervalMap will have coalesced the non-linked ranges, but here // we want to coalesce the linked addresses. std::vector<std::pair<uint64_t, uint64_t>> Ranges; const auto &FunctionRanges = Unit.getFunctionRanges(); for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end(); Range != End; ++Range) Ranges.push_back(std::make_pair(Range.start() + Range.value(), Range.stop() + Range.value())); // The object addresses where sorted, but again, the linked // addresses might end up in a different order. llvm::sort(Ranges); if (!Ranges.empty()) { MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection()); MCSymbol *BeginLabel = Asm->createTempSymbol("Barange"); MCSymbol *EndLabel = Asm->createTempSymbol("Earange"); unsigned HeaderSize = sizeof(int32_t) + // Size of contents (w/o this field sizeof(int16_t) + // DWARF ARange version number sizeof(int32_t) + // Offset of CU in the .debug_info section sizeof(int8_t) + // Pointer Size (in bytes) sizeof(int8_t); // Segment Size (in bytes) unsigned TupleSize = AddressSize * 2; unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize); Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length Asm->OutStreamer->EmitLabel(BeginLabel); Asm->emitInt16(dwarf::DW_ARANGES_VERSION); // Version number Asm->emitInt32(Unit.getStartOffset()); // Corresponding unit's offset Asm->emitInt8(AddressSize); // Address size Asm->emitInt8(0); // Segment size Asm->OutStreamer->emitFill(Padding, 0x0); for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) { uint64_t RangeStart = Range->first; MS->EmitIntValue(RangeStart, AddressSize); while ((Range + 1) != End && Range->second == (Range + 1)->first) ++Range; MS->EmitIntValue(Range->second - RangeStart, AddressSize); } // Emit terminator Asm->OutStreamer->EmitIntValue(0, AddressSize); Asm->OutStreamer->EmitIntValue(0, AddressSize); Asm->OutStreamer->EmitLabel(EndLabel); } if (!DoDebugRanges) return; MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection()); // Offset each range by the right amount. int64_t PcOffset = -Unit.getLowPc(); // Emit coalesced ranges. for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) { MS->EmitIntValue(Range->first + PcOffset, AddressSize); while (Range + 1 != End && Range->second == (Range + 1)->first) ++Range; MS->EmitIntValue(Range->second + PcOffset, AddressSize); RangesSectionSize += 2 * AddressSize; } // Add the terminator entry. MS->EmitIntValue(0, AddressSize); MS->EmitIntValue(0, AddressSize); RangesSectionSize += 2 * AddressSize; } /// Emit location lists for \p Unit and update attributes to point to the new /// entries. void DwarfStreamer::emitLocationsForUnit( const CompileUnit &Unit, DWARFContext &Dwarf, std::function<void(StringRef, SmallVectorImpl<uint8_t> &)> ProcessExpr) { const auto &Attributes = Unit.getLocationAttributes(); if (Attributes.empty()) return; MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection()); unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize(); uint64_t BaseAddressMarker = (AddressSize == 8) ? std::numeric_limits<uint64_t>::max() : std::numeric_limits<uint32_t>::max(); const DWARFSection &InputSec = Dwarf.getDWARFObj().getLocSection(); DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize); DWARFUnit &OrigUnit = Unit.getOrigUnit(); auto OrigUnitDie = OrigUnit.getUnitDIE(false); int64_t UnitPcOffset = 0; if (auto OrigLowPc = dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc))) UnitPcOffset = int64_t(*OrigLowPc) - Unit.getLowPc(); SmallVector<uint8_t, 32> Buffer; for (const auto &Attr : Attributes) { uint64_t Offset = Attr.first.get(); Attr.first.set(LocSectionSize); // This is the quantity to add to the old location address to get // the correct address for the new one. int64_t LocPcOffset = Attr.second + UnitPcOffset; while (Data.isValidOffset(Offset)) { uint64_t Low = Data.getUnsigned(&Offset, AddressSize); uint64_t High = Data.getUnsigned(&Offset, AddressSize); LocSectionSize += 2 * AddressSize; // End of list entry. if (Low == 0 && High == 0) { Asm->OutStreamer->EmitIntValue(0, AddressSize); Asm->OutStreamer->EmitIntValue(0, AddressSize); break; } // Base address selection entry. if (Low == BaseAddressMarker) { Asm->OutStreamer->EmitIntValue(BaseAddressMarker, AddressSize); Asm->OutStreamer->EmitIntValue(High + Attr.second, AddressSize); LocPcOffset = 0; continue; } // Location list entry. Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize); Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize); uint64_t Length = Data.getU16(&Offset); Asm->OutStreamer->EmitIntValue(Length, 2); // Copy the bytes into to the buffer, process them, emit them. Buffer.reserve(Length); Buffer.resize(0); StringRef Input = InputSec.Data.substr(Offset, Length); ProcessExpr(Input, Buffer); Asm->OutStreamer->EmitBytes( StringRef((const char *)Buffer.data(), Length)); Offset += Length; LocSectionSize += Length + 2; } } } void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params, StringRef PrologueBytes, unsigned MinInstLength, std::vector<DWARFDebugLine::Row> &Rows, unsigned PointerSize) { // Switch to the section where the table will be emitted into. MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection()); MCSymbol *LineStartSym = MC->createTempSymbol(); MCSymbol *LineEndSym = MC->createTempSymbol(); // The first 4 bytes is the total length of the information for this // compilation unit (not including these 4 bytes for the length). Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4); Asm->OutStreamer->EmitLabel(LineStartSym); // Copy Prologue. MS->EmitBytes(PrologueBytes); LineSectionSize += PrologueBytes.size() + 4; SmallString<128> EncodingBuffer; raw_svector_ostream EncodingOS(EncodingBuffer); if (Rows.empty()) { // We only have the dummy entry, dsymutil emits an entry with a 0 // address in that case. MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0, EncodingOS); MS->EmitBytes(EncodingOS.str()); LineSectionSize += EncodingBuffer.size(); MS->EmitLabel(LineEndSym); return; } // Line table state machine fields unsigned FileNum = 1; unsigned LastLine = 1; unsigned Column = 0; unsigned IsStatement = 1; unsigned Isa = 0; uint64_t Address = -1ULL; unsigned RowsSinceLastSequence = 0; for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) { auto &Row = Rows[Idx]; int64_t AddressDelta; if (Address == -1ULL) { MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1); MS->EmitULEB128IntValue(PointerSize + 1); MS->EmitIntValue(dwarf::DW_LNE_set_address, 1); MS->EmitIntValue(Row.Address.Address, PointerSize); LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1); AddressDelta = 0; } else { AddressDelta = (Row.Address.Address - Address) / MinInstLength; } // FIXME: code copied and transformed from MCDwarf.cpp::EmitDwarfLineTable. // We should find a way to share this code, but the current compatibility // requirement with classic dsymutil makes it hard. Revisit that once this // requirement is dropped. if (FileNum != Row.File) { FileNum = Row.File; MS->EmitIntValue(dwarf::DW_LNS_set_file, 1); MS->EmitULEB128IntValue(FileNum); LineSectionSize += 1 + getULEB128Size(FileNum); } if (Column != Row.Column) { Column = Row.Column; MS->EmitIntValue(dwarf::DW_LNS_set_column, 1); MS->EmitULEB128IntValue(Column); LineSectionSize += 1 + getULEB128Size(Column); } // FIXME: We should handle the discriminator here, but dsymutil doesn't // consider it, thus ignore it for now. if (Isa != Row.Isa) { Isa = Row.Isa; MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1); MS->EmitULEB128IntValue(Isa); LineSectionSize += 1 + getULEB128Size(Isa); } if (IsStatement != Row.IsStmt) { IsStatement = Row.IsStmt; MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1); LineSectionSize += 1; } if (Row.BasicBlock) { MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1); LineSectionSize += 1; } if (Row.PrologueEnd) { MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1); LineSectionSize += 1; } if (Row.EpilogueBegin) { MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1); LineSectionSize += 1; } int64_t LineDelta = int64_t(Row.Line) - LastLine; if (!Row.EndSequence) { MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS); MS->EmitBytes(EncodingOS.str()); LineSectionSize += EncodingBuffer.size(); EncodingBuffer.resize(0); Address = Row.Address.Address; LastLine = Row.Line; RowsSinceLastSequence++; } else { if (LineDelta) { MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1); MS->EmitSLEB128IntValue(LineDelta); LineSectionSize += 1 + getSLEB128Size(LineDelta); } if (AddressDelta) { MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1); MS->EmitULEB128IntValue(AddressDelta); LineSectionSize += 1 + getULEB128Size(AddressDelta); } MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0, EncodingOS); MS->EmitBytes(EncodingOS.str()); LineSectionSize += EncodingBuffer.size(); EncodingBuffer.resize(0); Address = -1ULL; LastLine = FileNum = IsStatement = 1; RowsSinceLastSequence = Column = Isa = 0; } } if (RowsSinceLastSequence) { MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0, EncodingOS); MS->EmitBytes(EncodingOS.str()); LineSectionSize += EncodingBuffer.size(); EncodingBuffer.resize(0); } MS->EmitLabel(LineEndSym); } /// Copy the debug_line over to the updated binary while unobfuscating the file /// names and directories. void DwarfStreamer::translateLineTable(DataExtractor Data, uint64_t Offset) { MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection()); StringRef Contents = Data.getData(); // We have to deconstruct the line table header, because it contains to // length fields that will need to be updated when we change the length of // the files and directories in there. unsigned UnitLength = Data.getU32(&Offset); uint64_t UnitEnd = Offset + UnitLength; MCSymbol *BeginLabel = MC->createTempSymbol(); MCSymbol *EndLabel = MC->createTempSymbol(); unsigned Version = Data.getU16(&Offset); if (Version > 5) { warn("Unsupported line table version: dropping contents and not " "unobfsucating line table."); return; } Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); Asm->OutStreamer->EmitLabel(BeginLabel); Asm->emitInt16(Version); LineSectionSize += 6; MCSymbol *HeaderBeginLabel = MC->createTempSymbol(); MCSymbol *HeaderEndLabel = MC->createTempSymbol(); Asm->EmitLabelDifference(HeaderEndLabel, HeaderBeginLabel, 4); Asm->OutStreamer->EmitLabel(HeaderBeginLabel); Offset += 4; LineSectionSize += 4; uint64_t AfterHeaderLengthOffset = Offset; // Skip to the directories. Offset += (Version >= 4) ? 5 : 4; unsigned OpcodeBase = Data.getU8(&Offset); Offset += OpcodeBase - 1; Asm->OutStreamer->EmitBytes(Contents.slice(AfterHeaderLengthOffset, Offset)); LineSectionSize += Offset - AfterHeaderLengthOffset; // Offset points to the first directory. while (const char *Dir = Data.getCStr(&Offset)) { if (Dir[0] == 0) break; StringRef Translated = Options.Translator(Dir); Asm->OutStreamer->EmitBytes(Translated); Asm->emitInt8(0); LineSectionSize += Translated.size() + 1; } Asm->emitInt8(0); LineSectionSize += 1; while (const char *File = Data.getCStr(&Offset)) { if (File[0] == 0) break; StringRef Translated = Options.Translator(File); Asm->OutStreamer->EmitBytes(Translated); Asm->emitInt8(0); LineSectionSize += Translated.size() + 1; uint64_t OffsetBeforeLEBs = Offset; Asm->EmitULEB128(Data.getULEB128(&Offset)); Asm->EmitULEB128(Data.getULEB128(&Offset)); Asm->EmitULEB128(Data.getULEB128(&Offset)); LineSectionSize += Offset - OffsetBeforeLEBs; } Asm->emitInt8(0); LineSectionSize += 1; Asm->OutStreamer->EmitLabel(HeaderEndLabel); // Copy the actual line table program over. Asm->OutStreamer->EmitBytes(Contents.slice(Offset, UnitEnd)); LineSectionSize += UnitEnd - Offset; Asm->OutStreamer->EmitLabel(EndLabel); Offset = UnitEnd; } static void emitSectionContents(const object::ObjectFile &Obj, StringRef SecName, MCStreamer *MS) { if (auto Sec = getSectionByName(Obj, SecName)) { if (Expected<StringRef> E = Sec->getContents()) MS->EmitBytes(*E); else consumeError(E.takeError()); } } void DwarfStreamer::copyInvariantDebugSection(const object::ObjectFile &Obj) { if (!Options.Translator) { MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection()); emitSectionContents(Obj, "debug_line", MS); } MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection()); emitSectionContents(Obj, "debug_loc", MS); MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection()); emitSectionContents(Obj, "debug_ranges", MS); MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection()); emitSectionContents(Obj, "debug_frame", MS); MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection()); emitSectionContents(Obj, "debug_aranges", MS); } /// Emit the pubnames or pubtypes section contribution for \p /// Unit into \p Sec. The data is provided in \p Names. void DwarfStreamer::emitPubSectionForUnit( MCSection *Sec, StringRef SecName, const CompileUnit &Unit, const std::vector<CompileUnit::AccelInfo> &Names) { if (Names.empty()) return; // Start the dwarf pubnames section. Asm->OutStreamer->SwitchSection(Sec); MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin"); MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end"); bool HeaderEmitted = false; // Emit the pubnames for this compilation unit. for (const auto &Name : Names) { if (Name.SkipPubSection) continue; if (!HeaderEmitted) { // Emit the header. Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length Asm->OutStreamer->EmitLabel(BeginLabel); Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); // Version Asm->emitInt32(Unit.getStartOffset()); // Unit offset Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size HeaderEmitted = true; } Asm->emitInt32(Name.Die->getOffset()); // Emit the string itself. Asm->OutStreamer->EmitBytes(Name.Name.getString()); // Emit a null terminator. Asm->emitInt8(0); } if (!HeaderEmitted) return; Asm->emitInt32(0); // End marker. Asm->OutStreamer->EmitLabel(EndLabel); } /// Emit .debug_pubnames for \p Unit. void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) { emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(), "names", Unit, Unit.getPubnames()); } /// Emit .debug_pubtypes for \p Unit. void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) { emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(), "types", Unit, Unit.getPubtypes()); } /// Emit a CIE into the debug_frame section. void DwarfStreamer::emitCIE(StringRef CIEBytes) { MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection()); MS->EmitBytes(CIEBytes); FrameSectionSize += CIEBytes.size(); } /// Emit a FDE into the debug_frame section. \p FDEBytes /// contains the FDE data without the length, CIE offset and address /// which will be replaced with the parameter values. void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize, uint32_t Address, StringRef FDEBytes) { MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection()); MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4); MS->EmitIntValue(CIEOffset, 4); MS->EmitIntValue(Address, AddrSize); MS->EmitBytes(FDEBytes); FrameSectionSize += FDEBytes.size() + 8 + AddrSize; } } // namespace dsymutil } // namespace llvm
apple/swift-llvm
tools/dsymutil/DwarfStreamer.cpp
C++
apache-2.0
28,781
/* * Copyright (c) 2011. The Apache Software Foundation * * 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.hbase.hbql; import jline.ArgumentCompletor; import jline.ConsoleReader; import jline.SimpleCompletor; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.hbql.client.ExecutionResults; import org.apache.hadoop.hbase.hbql.client.HBqlException; import org.apache.hadoop.hbase.hbql.client.HConnectionManager; import org.apache.hadoop.hbase.hbql.impl.HConnectionImpl; import org.apache.hadoop.hbase.hbql.impl.Utils; import org.apache.hadoop.hbase.hbql.statement.ImportStatement; import org.apache.hadoop.hbase.hbql.statement.VersionStatement; import org.apache.hadoop.hbase.hbql.util.Lists; import org.apache.hadoop.hbase.hbql.util.Maps; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Map; public class Console { private static HConnectionImpl conn = null; private static boolean processCommandLine = true; private static Configuration config = null; public static void main(String[] args) throws HBqlException, IOException { if (args != null && args.length > 0) { final List<String> argList = new LinkedList<String>(); argList.addAll(Arrays.asList(args)); while (argList.size() > 0) { if (!processArg(argList)) break; } } if (processCommandLine) processCommandLineInput(); } private static void usage() { System.out.println("Usage: java " + Console.class.getName() + " [-options]"); System.out.println("\t\t(comand line usage"); System.out.println(" or java " + Console.class.getName() + " [-options] [file_names]"); System.out.println("\t\t(executes the statements in the space-separated file names)"); System.out.println("\nwhere options include:"); System.out.println("\t-usage print this message"); System.out.println("\t-version print version info and exit"); System.out.println("\t-" + HConnectionImpl.MASTER + "=value set " + HConnectionImpl.MASTER + " value"); } private static boolean processArg(final List<String> argList) throws HBqlException { final String option = argList.remove(0); if (option.equals("-usage")) { processCommandLine = false; usage(); return true; } if (option.equals("-version")) { processCommandLine = false; final VersionStatement version = new VersionStatement(); final ExecutionResults results = version.execute(); System.out.print(results); return true; } if (option.startsWith("-" + HConnectionImpl.MASTER)) { final String[] vals = option.split("="); if (vals.length != 2) { processCommandLine = false; System.out.println("Incorrect syntax: " + option); usage(); return false; } else { config = HConnectionImpl.getConfiguration(vals[1]); return true; } } if (option.startsWith("-")) { processCommandLine = false; System.out.println("Unknown option: " + option); usage(); return false; } else { // Assume that an arg without "-" prefix is a filename processCommandLine = false; final ImportStatement importStmt = new ImportStatement(option); final ExecutionResults results = importStmt.evaluatePredicateAndExecute(getConnection()); System.out.print(results); return results.hadSuccess(); } } private synchronized static HConnectionImpl getConnection() throws HBqlException { if (conn == null) conn = (HConnectionImpl)HConnectionManager.newConnection(config); return conn; } private static void processCommandLineInput() throws IOException, HBqlException { final List<SimpleCompletor> completors = Lists.newArrayList(); completors.add(new SimpleCompletor(new String[]{"select", "insert", "create", "table", "mapping", "describe", "drop", "enable", "disable", "show", "executor", "pool"})); final ConsoleReader reader = new ConsoleReader(); reader.setBellEnabled(false); reader.setUseHistory(true); //reader.setDebug(new PrintWriter(new FileWriter("writer.debug", true))); reader.addCompletor(new ArgumentCompletor(completors)); final PrintWriter out = new PrintWriter(System.out); StringBuilder stmtBuffer = new StringBuilder(); boolean continuation = false; final Map<Boolean, String> prompts = Maps.newHashMap(); prompts.put(Boolean.FALSE, "HBql> "); prompts.put(Boolean.TRUE, "> "); while (true) { final String line = reader.readLine(prompts.get(continuation)); if (line == null || line.toLowerCase().startsWith("quit") || line.toLowerCase().startsWith("exit")) break; if (Utils.isValidString(line)) { stmtBuffer.append(line); continuation = !line.trim().endsWith(";"); if (!continuation) { final String sql = stmtBuffer.toString(); stmtBuffer = new StringBuilder(); ImportStatement.processInput(out, getConnection(), sql); } } } } }
pambrose/HBql
src/main/java/org/apache/hadoop/hbase/hbql/Console.java
Java
apache-2.0
6,629
package rectangles; import org.assertj.core.api.AbstractBooleanAssert; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebElement; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static rectangles.TestAssumptions.*; public class ToleranceOnNegativeAssumptionsTest { private final int x = 100; private final int y = 1000; private final int width = 200; private final int height = 300; private WebElement root; @Before public void setUp() { root = createElement(x, y); } public WebElement createElement(int x, int y) { return DummyWebElement.createElement(x, y, x + width, y + height); } @Test public void isNotOverlappingWithTolerance() { assertThatNotOverlappingWithTolerance(x+width, y).isTrue(); assertThatNotOverlappingWithTolerance(x+width-1, y).isTrue(); assertThatNotOverlappingWithTolerance(x+width-2, y).isFalse(); assertThatNotOverlappingWithTolerance(x-width, y).isTrue(); assertThatNotOverlappingWithTolerance(x-width+1, y).isTrue(); assertThatNotOverlappingWithTolerance(x-width+2, y).isFalse(); assertThatNotOverlappingWithTolerance(x, y+height).isTrue(); assertThatNotOverlappingWithTolerance(x, y+height-1).isTrue(); assertThatNotOverlappingWithTolerance(x, y+height-2).isFalse(); assertThatNotOverlappingWithTolerance(x, y-height).isTrue(); assertThatNotOverlappingWithTolerance(x, y-height+1).isTrue(); assertThatNotOverlappingWithTolerance(x, y-height+2).isFalse(); } @Test public void hasDifferentSizeAsWithTolerance() { assertThatHasDifferentSizeWithTolerance(-2, 0).isTrue(); assertThatHasDifferentSizeWithTolerance(-1, 0).isFalse(); assertThatHasDifferentSizeWithTolerance( 0, 0).isFalse(); assertThatHasDifferentSizeWithTolerance(+1, 0).isFalse(); assertThatHasDifferentSizeWithTolerance(+2, 0).isTrue(); assertThatHasDifferentWidthWithTolerance(-2).isTrue(); assertThatHasDifferentWidthWithTolerance(-1).isFalse(); assertThatHasDifferentWidthWithTolerance( 0).isFalse(); assertThatHasDifferentWidthWithTolerance(+1).isFalse(); assertThatHasDifferentWidthWithTolerance(+2).isTrue(); assertThatHasDifferentSizeWithTolerance(0, -2).isTrue(); assertThatHasDifferentSizeWithTolerance(0, -1).isFalse(); assertThatHasDifferentSizeWithTolerance(0, 0).isFalse(); assertThatHasDifferentSizeWithTolerance(0, +1).isFalse(); assertThatHasDifferentSizeWithTolerance(0, +2).isTrue(); assertThatHasDifferentHeightWithTolerance(-2).isTrue(); assertThatHasDifferentHeightWithTolerance(-1).isFalse(); assertThatHasDifferentHeightWithTolerance( 0).isFalse(); assertThatHasDifferentHeightWithTolerance(+1).isFalse(); assertThatHasDifferentHeightWithTolerance(+2).isTrue(); } public AbstractBooleanAssert<?> assertThatHasDifferentSizeWithTolerance(int deltaWidth, int deltaHeight) { WebElement element = DummyWebElement.createElement(x, y, x + width + deltaWidth, y + height + deltaHeight); return assertThat(hasDifferentSizeAs(root, element, 1) && hasDifferentSizeAs(root, asList(element), 1) && haveDifferentSizes(asList(root, element), 1)); } public AbstractBooleanAssert<?> assertThatHasDifferentHeightWithTolerance(int deltaHeight) { WebElement element = DummyWebElement.createElement(x, y, x + width, y + height + deltaHeight); return assertThat(haveDifferentHeights(asList(root, element), 1)); } public AbstractBooleanAssert<?> assertThatHasDifferentWidthWithTolerance(int deltaWidth) { WebElement element = DummyWebElement.createElement(x, y, x + width + deltaWidth, y + height); return assertThat(haveDifferentWidths(asList(root, element), 1)); } private AbstractBooleanAssert<?> assertThatNotOverlappingWithTolerance(int x, int y) { WebElement element = createElement(x, y); return assertThat(isNotOverlapping(root, element, 1) && doNotOverlap(asList(root, element), 1) && isNotOverlapping(root, asList(element), 1)); } }
dzaiats/java.automation.library
src/test/java/rectangles/ToleranceOnNegativeAssumptionsTest.java
Java
apache-2.0
4,327
/* * 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. */ /** * @author Alexander V. Esin, Stepan M. Mishura * @version $Revision$ */ package org.apache.harmony.security.x509; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.harmony.security.x501.AttributeTypeAndValue; import org.apache.harmony.security.x501.AttributeValue; /** * Distinguished Name Parser. * * Parses a distinguished name(DN) string according BNF syntax specified in RFC * 2253 and RFC 1779 * * RFC 2253: Lightweight Directory Access Protocol (v3): UTF-8 String * Representation of Distinguished Names http://www.ietf.org/rfc/rfc2253.txt * * RFC 1779: A String Representation of Distinguished Names * http://www.ietf.org/rfc/rfc1779.txt */ public class DNParser { // length of distinguished name string protected final int length; protected int pos, beg, end; // tmp vars to store positions of the currently parsed item protected int cur; // distinguished name chars protected char[] chars; // raw string contains '"' or '\' protected boolean hasQE; // DER encoding of currently parsed item protected byte[] encoded; /** * Constructs DN parser * * @param dn * - distinguished name string to be parsed */ public DNParser(String dn) throws IOException { this.length = dn.length(); chars = dn.toCharArray(); } // gets next attribute type: (ALPHA 1*keychar) / oid protected String nextAT() throws IOException { hasQE = false; // reset // skip preceding space chars, they can present after // comma or semicolon (compatibility with RFC 1779) for (; pos < length && chars[pos] == ' '; pos++) { } if (pos == length) { return null; // reached the end of DN } // mark the beginning of attribute type beg = pos; // attribute type chars pos++; for (; pos < length && chars[pos] != '=' && chars[pos] != ' '; pos++) { // we don't follow exact BNF syntax here: // accept any char except space and '=' } if (pos >= length) { // unexpected end of DN throw new IOException("Invalid distinguished name string"); } // mark the end of attribute type end = pos; // skip trailing space chars between attribute type and '=' // (compatibility with RFC 1779) if (chars[pos] == ' ') { for (; pos < length && chars[pos] != '=' && chars[pos] == ' '; pos++) { } if (chars[pos] != '=' || pos == length) { // unexpected end of DN throw new IOException("Invalid distinguished name string"); } } pos++; // skip '=' char // skip space chars between '=' and attribute value // (compatibility with RFC 1779) for (; pos < length && chars[pos] == ' '; pos++) { } // in case of oid attribute type skip its prefix: "oid." or "OID." // (compatibility with RFC 1779) if ((end - beg > 4) && (chars[beg + 3] == '.') && (chars[beg] == 'O' || chars[beg] == 'o') && (chars[beg + 1] == 'I' || chars[beg + 1] == 'i') && (chars[beg + 2] == 'D' || chars[beg + 2] == 'd')) { beg += 4; } return new String(chars, beg, end - beg); } // gets quoted attribute value: QUOTATION *( quotechar / pair ) QUOTATION protected String quotedAV() throws IOException { pos++; beg = pos; end = beg; while (true) { if (pos == length) { // unexpected end of DN throw new IOException("Invalid distinguished name string"); } if (chars[pos] == '"') { // enclosing quotation was found pos++; break; } else if (chars[pos] == '\\') { chars[end] = getEscaped(); } else { // shift char: required for string with escaped chars chars[end] = chars[pos]; } pos++; end++; } // skip trailing space chars before comma or semicolon. // (compatibility with RFC 1779) for (; pos < length && chars[pos] == ' '; pos++) { } return new String(chars, beg, end - beg); } // gets hex string attribute value: "#" hexstring private String hexAV() throws IOException { if (pos + 4 >= length) { // encoded byte array must be not less then 4 c throw new IOException("Invalid distinguished name string"); } beg = pos; // store '#' position pos++; while (true) { // check for end of attribute value // looks for space and component separators if (pos == length || chars[pos] == '+' || chars[pos] == ',' || chars[pos] == ';') { end = pos; break; } if (chars[pos] == ' ') { end = pos; pos++; // skip trailing space chars before comma or semicolon. // (compatibility with RFC 1779) for (; pos < length && chars[pos] == ' '; pos++) { } break; } else if (chars[pos] >= 'A' && chars[pos] <= 'F') { chars[pos] += 32; // to low case } pos++; } // verify length of hex string // encoded byte array must be not less then 4 and must be even number int hexLen = end - beg; // skip first '#' char if (hexLen < 5 || (hexLen & 1) == 0) { throw new IOException("Invalid distinguished name string"); } // get byte encoding from string representation encoded = new byte[hexLen / 2]; for (int i = 0, p = beg + 1; i < encoded.length; p += 2, i++) { encoded[i] = (byte) getByte(p); } return new String(chars, beg, hexLen); } // gets string attribute value: *( stringchar / pair ) protected String escapedAV() throws IOException { beg = pos; end = pos; while (true) { if (pos >= length) { // the end of DN has been found return new String(chars, beg, end - beg); } switch (chars[pos]) { case '+': case ',': case ';': // separator char has beed found return new String(chars, beg, end - beg); case '\\': // escaped char chars[end++] = getEscaped(); pos++; break; case ' ': // need to figure out whether space defines // the end of attribute value or not cur = end; pos++; chars[end++] = ' '; for (; pos < length && chars[pos] == ' '; pos++) { chars[end++] = ' '; } if (pos == length || chars[pos] == ',' || chars[pos] == '+' || chars[pos] == ';') { // separator char or the end of DN has beed found return new String(chars, beg, cur - beg); } break; default: chars[end++] = chars[pos]; pos++; } } } // returns escaped char private char getEscaped() throws IOException { pos++; if (pos == length) { throw new IOException("Invalid distinguished name string"); } switch (chars[pos]) { case '"': case '\\': hasQE = true; case ',': case '=': case '+': case '<': case '>': case '#': case ';': case ' ': case '*': case '%': case '_': // FIXME: escaping is allowed only for leading or trailing space // char return chars[pos]; default: // RFC doesn't explicitly say that escaped hex pair is // interpreted as UTF-8 char. It only contains an example of such // DN. return getUTF8(); } } // decodes UTF-8 char // see http://www.unicode.org for UTF-8 bit distribution table protected char getUTF8() throws IOException { int res = getByte(pos); pos++; // FIXME tmp if (res < 128) { // one byte: 0-7F return (char) res; } else if (res >= 192 && res <= 247) { int count; if (res <= 223) { // two bytes: C0-DF count = 1; res = res & 0x1F; } else if (res <= 239) { // three bytes: E0-EF count = 2; res = res & 0x0F; } else { // four bytes: F0-F7 count = 3; res = res & 0x07; } int b; for (int i = 0; i < count; i++) { pos++; if (pos == length || chars[pos] != '\\') { return 0x3F; // FIXME failed to decode UTF-8 char - return // '?' } pos++; b = getByte(pos); pos++; // FIXME tmp if ((b & 0xC0) != 0x80) { return 0x3F; // FIXME failed to decode UTF-8 char - return // '?' } res = (res << 6) + (b & 0x3F); } return (char) res; } else { return 0x3F; // FIXME failed to decode UTF-8 char - return '?' } } // Returns byte representation of a char pair // The char pair is composed of DN char in // specified 'position' and the next char // According to BNF syntax: // hexchar = DIGIT / "A" / "B" / "C" / "D" / "E" / "F" // / "a" / "b" / "c" / "d" / "e" / "f" protected int getByte(int position) throws IOException { if ((position + 1) >= length) { // to avoid ArrayIndexOutOfBoundsException throw new IOException("Invalid distinguished name string"); } int b1, b2; b1 = chars[position]; if (b1 >= '0' && b1 <= '9') { b1 = b1 - '0'; } else if (b1 >= 'a' && b1 <= 'f') { b1 = b1 - 87; // 87 = 'a' - 10 } else if (b1 >= 'A' && b1 <= 'F') { b1 = b1 - 55; // 55 = 'A' - 10 } else { throw new IOException("Invalid distinguished name string"); } b2 = chars[position + 1]; if (b2 >= '0' && b2 <= '9') { b2 = b2 - '0'; } else if (b2 >= 'a' && b2 <= 'f') { b2 = b2 - 87; // 87 = 'a' - 10 } else if (b2 >= 'A' && b2 <= 'F') { b2 = b2 - 55; // 55 = 'A' - 10 } else { throw new IOException("Invalid distinguished name string"); } return (b1 << 4) + b2; } /** * Parses DN * * @return a list of Relative Distinguished Names(RND), each RDN is * represented as a list of AttributeTypeAndValue objects */ public List parse() throws IOException { List list = new ArrayList(); String attValue; String attType = nextAT(); if (attType == null) { return list; // empty list of RDNs } List atav = new ArrayList(); while (true) { if (pos == length) { // empty Attribute Value atav.add(new AttributeTypeAndValue(attType, new AttributeValue( "", false))); list.add(0, atav); return list; } switch (chars[pos]) { case '"': attValue = quotedAV(); atav.add(new AttributeTypeAndValue(attType, new AttributeValue( attValue, hasQE))); break; case '#': attValue = hexAV(); atav.add(new AttributeTypeAndValue(attType, new AttributeValue( attValue, encoded))); break; case '+': case ',': case ';': // compatibility with RFC 1779: semicolon can separate // RDNs // empty attribute value atav.add(new AttributeTypeAndValue(attType, new AttributeValue( "", false))); break; default: attValue = escapedAV(); atav.add(new AttributeTypeAndValue(attType, new AttributeValue( attValue, hasQE))); } if (pos >= length) { list.add(0, atav); return list; } if (chars[pos] == ',' || chars[pos] == ';') { list.add(0, atav); atav = new ArrayList(); } else if (chars[pos] != '+') { throw new IOException("Invalid distinguished name string"); } pos++; attType = nextAT(); if (attType == null) { throw new IOException("Invalid distinguished name string"); } } } }
webos21/xi
java/jcl/src/java/org/apache/harmony/security/x509/DNParser.java
Java
apache-2.0
11,512
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include <algorithm> #include <deque> #include <set> #include <unordered_set> #include <utility> #include "tensorflow/compiler/xla/layout_util.h" #include "tensorflow/compiler/xla/literal_util.h" #include "tensorflow/compiler/xla/map_util.h" #include "tensorflow/compiler/xla/protobuf_util.h" #include "tensorflow/compiler/xla/ptr_util.h" #include "tensorflow/compiler/xla/service/dfs_hlo_visitor_with_default.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/compiler/xla/window_util.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/gtl/flatmap.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "tensorflow/core/platform/logging.h" namespace xla { /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateParameter( int64 parameter_number, const Shape& shape, const string& name) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kParameter, shape)); instruction->parameter_number_ = parameter_number; instruction->parameter_name_ = name; instruction->name_ = "%" + name; return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateTrace( const string& tag, HloInstruction* operand) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kTrace, ShapeUtil::MakeNil())); instruction->operands_.push_back(operand); instruction->literal_.reset(new Literal); *instruction->literal_->mutable_u8s() += tag; return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConstant( std::unique_ptr<Literal> literal) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kConstant, literal->shape())); instruction->literal_ = std::move(literal); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateGetTupleElement(const Shape& shape, HloInstruction* operand, int64 index) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kGetTupleElement, shape)); instruction->tuple_index_ = index; instruction->AppendOperand(operand); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateRng( const Shape& shape, RandomDistribution distribution, tensorflow::gtl::ArraySlice<HloInstruction*> parameters) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kRng, shape)); instruction->distribution_ = distribution; instruction->shape_ = shape; for (HloInstruction* param : parameters) { instruction->AppendOperand(param); } return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateNary( const Shape& shape, HloOpcode opcode, tensorflow::gtl::ArraySlice<HloInstruction*> operands) { if (opcode == HloOpcode::kCopy) { // It is impossible to copy an opaque shape, we don't know how big it is. CHECK(!ShapeUtil::IsOpaque(shape)); } auto instruction = WrapUnique(new HloInstruction(opcode, shape)); for (auto operand : operands) { instruction->AppendOperand(operand); } return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateUnary( const Shape& shape, HloOpcode opcode, HloInstruction* operand) { // Only certain opcodes are supported with CreateUnary: opcodes of unary // instructions with no auxiliary fields. switch (opcode) { case HloOpcode::kAbs: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kCopy: case HloOpcode::kExp: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLogicalNot: case HloOpcode::kNegate: case HloOpcode::kSign: case HloOpcode::kSort: case HloOpcode::kTanh: break; default: LOG(FATAL) << "Invalid unary instruction opcode " << HloOpcodeString(opcode); } return CreateNary(shape, opcode, {operand}); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateBinary( const Shape& shape, HloOpcode opcode, HloInstruction* lhs, HloInstruction* rhs) { // Only certain opcodes are supported with CreateBinary: opcodes of binary // instructions with no auxiliary fields. switch (opcode) { case (HloOpcode::kAdd): case (HloOpcode::kDivide): case (HloOpcode::kDot): case (HloOpcode::kEq): case (HloOpcode::kGe): case (HloOpcode::kGt): case (HloOpcode::kLe): case (HloOpcode::kLt): case (HloOpcode::kMaximum): case (HloOpcode::kMinimum): case (HloOpcode::kMultiply): case (HloOpcode::kNe): case (HloOpcode::kPower): case (HloOpcode::kRemainder): case (HloOpcode::kSubtract): case (HloOpcode::kLogicalAnd): case (HloOpcode::kLogicalOr): break; default: LOG(FATAL) << "Invalid binary instruction opcode " << HloOpcodeString(opcode); } return CreateNary(shape, opcode, {lhs, rhs}); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateTernary( const Shape& shape, HloOpcode opcode, HloInstruction* lhs, HloInstruction* rhs, HloInstruction* ehs) { // Only certain opcodes are supported with CreateTernary: opcodes of ternary // instructions with no auxiliary fields. switch (opcode) { case (HloOpcode::kClamp): case (HloOpcode::kSelect): break; default: LOG(FATAL) << "Invalid ternary instruction opcode " << HloOpcodeString(opcode); } return CreateNary(shape, opcode, {lhs, rhs, ehs}); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateVariadic( const Shape& shape, HloOpcode opcode, tensorflow::gtl::ArraySlice<HloInstruction*> operands) { CHECK_EQ(HloOpcode::kTuple, opcode); return CreateNary(shape, opcode, operands); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateMap( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> operands, HloComputation* map_computation, tensorflow::gtl::ArraySlice<HloInstruction*> static_operands) { CHECK(static_operands.empty()) << "static_operands not yet supported"; auto instruction = WrapUnique(new HloInstruction(HloOpcode::kMap, shape)); for (auto operand : operands) { instruction->AppendOperand(operand); } instruction->to_apply_ = map_computation; return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConvolve( const Shape& shape, HloInstruction* lhs, HloInstruction* rhs, const Window& window, const ConvolutionDimensionNumbers& dimension_numbers) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kConvolution, shape)); if (window_util::HasBaseDilation(window)) { instruction->set_name(instruction->name() + "-base-dilated"); } if (window_util::HasWindowDilation(window)) { instruction->set_name(instruction->name() + "-window-dilated"); } instruction->AppendOperand(lhs); instruction->AppendOperand(rhs); instruction->window_ = MakeUnique<Window>(window); instruction->convolution_dimension_numbers_ = MakeUnique<ConvolutionDimensionNumbers>(dimension_numbers); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateCrossReplicaSum(const Shape& shape, HloInstruction* operand) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kCrossReplicaSum, shape)); instruction->AppendOperand(operand); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateInfeed( const Shape& shape, const string& config) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kInfeed, shape)); instruction->set_infeed_config(config); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateOutfeed( HloInstruction* operand, tensorflow::StringPiece outfeed_config) { std::unique_ptr<HloInstruction> instruction = WrapUnique(new HloInstruction(HloOpcode::kOutfeed, ShapeUtil::MakeNil())); instruction->AppendOperand(operand); instruction->outfeed_config_ = outfeed_config.ToString(); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateSend( HloInstruction* operand, int64 channel_id) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kSend, ShapeUtil::MakeNil())); instruction->AppendOperand(operand); instruction->channel_id_ = channel_id; return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateRecv( const Shape& shape, int64 channel_id) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kRecv, shape)); instruction->channel_id_ = channel_id; return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReverse( const Shape& shape, HloInstruction* operand, tensorflow::gtl::ArraySlice<int64> dimensions) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kReverse, shape)); instruction->AppendOperand(operand); instruction->dimensions_.assign(dimensions.begin(), dimensions.end()); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateWhile( const Shape& shape, HloComputation* condition, HloComputation* body, HloInstruction* init) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kWhile, shape)); instruction->AppendOperand(init); instruction->condition_ = condition; instruction->body_ = body; return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateSlice( const Shape& shape, HloInstruction* operand, tensorflow::gtl::ArraySlice<int64> start_indices, tensorflow::gtl::ArraySlice<int64> limit_indices) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kSlice, shape)); instruction->AppendOperand(operand); instruction->slice_starts_.assign(start_indices.begin(), start_indices.end()); instruction->slice_limits_.assign(limit_indices.begin(), limit_indices.end()); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateDynamicSlice( const Shape& shape, HloInstruction* operand, HloInstruction* start_indices, tensorflow::gtl::ArraySlice<int64> slice_sizes) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kDynamicSlice, shape)); instruction->AppendOperand(operand); instruction->AppendOperand(start_indices); instruction->dynamic_slice_sizes_.assign(slice_sizes.begin(), slice_sizes.end()); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateDynamicUpdateSlice(const Shape& shape, HloInstruction* operand, HloInstruction* update, HloInstruction* start_indices) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kDynamicUpdateSlice, shape)); instruction->AppendOperand(operand); instruction->AppendOperand(update); instruction->AppendOperand(start_indices); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConcatenate( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> operands, int64 dimension) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kConcatenate, shape)); for (auto operand : operands) { instruction->AppendOperand(operand); } instruction->dimensions_.push_back(dimension); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConvert( const Shape& shape, HloInstruction* operand) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kConvert, shape)); instruction->AppendOperand(operand); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReduce( const Shape& shape, HloInstruction* arg, HloInstruction* init_value, tensorflow::gtl::ArraySlice<int64> dimensions_to_reduce, HloComputation* reduce_computation) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kReduce, shape)); instruction->AppendOperand(arg); instruction->AppendOperand(init_value); instruction->dimensions_.assign(dimensions_to_reduce.begin(), dimensions_to_reduce.end()); instruction->to_apply_ = reduce_computation; return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReduceWindow( const Shape& shape, HloInstruction* operand, HloInstruction* init_value, const Window& window, HloComputation* reduce_computation) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kReduceWindow, shape)); instruction->AppendOperand(operand); instruction->AppendOperand(init_value); instruction->to_apply_ = reduce_computation; instruction->window_ = MakeUnique<Window>(window); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateSelectAndScatter( const Shape& shape, HloInstruction* operand, HloComputation* select, const Window& window, HloInstruction* source, HloInstruction* init_value, HloComputation* scatter) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kSelectAndScatter, shape)); instruction->AppendOperand(operand); instruction->AppendOperand(source); instruction->AppendOperand(init_value); instruction->select_ = select; instruction->scatter_ = scatter; instruction->window_ = MakeUnique<Window>(window); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateBroadcast( const Shape& shape, HloInstruction* operand, tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kBroadcast, shape)); instruction->AppendOperand(operand); instruction->dimensions_.assign(broadcast_dimensions.begin(), broadcast_dimensions.end()); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreatePad( const Shape& shape, HloInstruction* operand, HloInstruction* padding_value, const PaddingConfig& padding_config) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kPad, shape)); instruction->AppendOperand(operand); instruction->AppendOperand(padding_value); instruction->padding_config_ = MakeUnique<PaddingConfig>(padding_config); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReshape( const Shape& shape, HloInstruction* operand) { CHECK_EQ(ShapeUtil::ElementsIn(shape), ShapeUtil::ElementsIn(operand->shape())); auto instruction = WrapUnique(new HloInstruction(HloOpcode::kReshape, shape)); instruction->AppendOperand(operand); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateTranspose( const Shape& shape, HloInstruction* operand, tensorflow::gtl::ArraySlice<int64> dimensions) { CHECK_EQ(shape.dimensions().size(), dimensions.size()); CHECK_EQ(shape.dimensions().size(), operand->shape().dimensions().size()); CHECK(std::equal(operand->shape().dimensions().begin(), operand->shape().dimensions().end(), Permute(dimensions, shape.dimensions()).begin())); auto instruction = WrapUnique(new HloInstruction(HloOpcode::kTranspose, shape)); instruction->AppendOperand(operand); instruction->dimensions_.assign(dimensions.begin(), dimensions.end()); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateFusion( const Shape& shape, FusionKind fusion_kind, HloInstruction* fused_root) { auto instruction = WrapUnique(new HloInstruction(HloOpcode::kFusion, shape)); instruction->fusion_kind_ = fusion_kind; instruction->CloneAndFuseInternal(fused_root); instruction->CheckFusionInstruction(); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateFusionForBackwardConvolution( const Shape& shape, FusionKind fusion_kind, const Window& window, const ConvolutionDimensionNumbers& conv_dnums, HloInstruction* fused_root) { std::unique_ptr<HloInstruction> fusion = CreateFusion(shape, fusion_kind, fused_root); fusion->window_ = MakeUnique<Window>(window); fusion->convolution_dimension_numbers_ = MakeUnique<ConvolutionDimensionNumbers>(conv_dnums); return fusion; } void HloInstruction::MergeFusionInstruction( HloInstruction* instruction_to_merge) { CHECK_EQ(opcode_, HloOpcode::kFusion); CHECK_EQ(instruction_to_merge->opcode(), HloOpcode::kFusion); // Clone the instruction from which to merge fused instructions. std::unique_ptr<HloInstruction> clone = instruction_to_merge->Clone(); // Replace uses of fused parameters with the corresponding operand of the // fusion. // Add all non-parameter fused instructions to 'unfused_instructions' to be // merged into 'this'. std::vector<HloInstruction*> unfused_instructions; for (auto& fused_instruction : clone->fused_instructions()) { if (fused_instruction->opcode() == HloOpcode::kParameter) { TF_CHECK_OK(fused_instruction->ReplaceAllUsesWith( clone->mutable_operand(fused_instruction->parameter_number()))); } else { unfused_instructions.push_back(fused_instruction.get()); } } CHECK(unfused_instructions.front() == clone->fused_expression_root()); // Replace instruction_to_merge use of 'this' with unfused_root. TF_CHECK_OK( instruction_to_merge->ReplaceUseWith(this, unfused_instructions.front())); // Fuse 'unfused_instructions' into 'this'. for (auto& instruction : unfused_instructions) { FuseInstruction(instruction); instruction->DetachFromOperands(); } CHECK_EQ(0, clone->user_count()); clone->DetachFromOperands(); } HloInstruction* HloInstruction::FuseInstruction( HloInstruction* instruction_to_fuse) { CHECK_EQ(opcode_, HloOpcode::kFusion); // This fusion instruction must be a user of instruction_to_fuse. CHECK_NE(0, instruction_to_fuse->users().count(this)); HloInstruction* fused_instruction = CloneAndFuseInternal(instruction_to_fuse); CheckFusionInstruction(); return fused_instruction; } HloInstruction* HloInstruction::CloneAndFuseInternal( HloInstruction* instruction_to_fuse) { CHECK_EQ(opcode_, HloOpcode::kFusion); CHECK(instruction_to_fuse->IsFusable()); bool new_fusion_instruction = fused_instructions_.empty(); fused_instructions_.emplace_back(instruction_to_fuse->Clone()); HloInstruction* clone = fused_instructions_.back().get(); clone->parent_fusion_instruction_ = this; if (new_fusion_instruction) { fused_root_ = clone; } else { // instruction_to_fuse is necessarily an operand of the fusion instruction. // After fusion this will no longer be the case. Remove the operand from the // operand list and remove its corresponding fused parameter // instruction. Renumber parameters as necessary to make parameter numbers // consistent with their index in the fused_parameter_ vector. CHECK(std::find(operands_.begin(), operands_.end(), instruction_to_fuse) != operands_.end()); for (int64 operand_num = 0; operand_num < operand_count(); ++operand_num) { if (instruction_to_fuse == operands_[operand_num]) { // replace the fused parameter instruction's uses with the clone. HloInstruction* fused_parameter = fused_parameters_[operand_num]; TF_CHECK_OK(fused_parameter->ReplaceAllUsesWith(clone)); // Remove the corresponding fused parameter and operand from their // respective vectors. fused_parameters_.erase(fused_parameters_.begin() + operand_num); operands_.erase(operands_.begin() + operand_num); // Renumber fused parameter numbers to match the vector index. while (operand_num < fused_parameters_.size()) { fused_parameters_[operand_num]->parameter_number_ = operand_num; operand_num++; } // Throw removed fused parameter instruction away. auto inst_it = std::find_if(fused_instructions_.begin(), fused_instructions_.end(), [=](const std::unique_ptr<HloInstruction>& inst) { return inst.get() == fused_parameter; }); CHECK(inst_it != fused_instructions_.end()); fused_instructions_.erase(inst_it); break; } } // We've cloned instruction_to_fuse into this fusion instruction, so this // fusion instruction is no longer a use of instruction_to_fuse. instruction_to_fuse->RemoveUser(this); } // Add each operand of the clone as an operand of the fusion instruction. A // complication is that some clone operands may already be operands of the // fusion instruction. for (int64 operand_num = 0; operand_num < clone->operand_count(); ++operand_num) { HloInstruction* operand = clone->mutable_operand(operand_num); // See if this operand is already an operand of the fusion node. CHECK_EQ(operands_.size(), fused_parameters_.size()); HloInstruction* fused_param = nullptr; for (int64 i = 0; i < operands_.size(); ++i) { if (operands_[i] == operand) { fused_param = fused_parameters_[i]; break; } } if (fused_param == nullptr) { // Clone's operand was not already an operand of the fusion // instruction. Add it as an operand and add a corresponding fused // parameter instruction. int64 param_no = fused_parameters_.size(); std::unique_ptr<HloInstruction> param_instruction = CreateParameter(param_no, operand->shape(), "fusion_param"); param_instruction->parent_fusion_instruction_ = this; fused_parameters_.push_back(param_instruction.get()); fused_instructions_.push_back(std::move(param_instruction)); AppendOperand(operand); fused_param = fused_instructions_.back().get(); } TF_CHECK_OK(clone->ReplaceOperandWith(operand_num, fused_param)); } return clone; } RandomDistribution HloInstruction::random_distribution() const { CHECK_EQ(opcode_, HloOpcode::kRng); return distribution_; } namespace { // Adds any HloComputations this instruction calls directly to the given set. void CalledComputationsInternal( const HloInstruction& instruction, std::set<HloComputation*>* called_computations) { switch (instruction.opcode()) { case HloOpcode::kCall: case HloOpcode::kMap: case HloOpcode::kReduce: case HloOpcode::kReduceWindow: called_computations->insert(instruction.to_apply()); break; case HloOpcode::kSelectAndScatter: called_computations->insert(instruction.select()); called_computations->insert(instruction.scatter()); break; case HloOpcode::kWhile: called_computations->insert(instruction.while_condition()); called_computations->insert(instruction.while_body()); break; case HloOpcode::kFusion: for (const auto& fused_instruction : instruction.fused_instructions()) { CalledComputationsInternal(*fused_instruction, called_computations); } break; default: break; } } } // namespace std::set<HloComputation*> HloInstruction::MakeCalledComputationsSet() const { std::set<HloComputation*> called_computations; CalledComputationsInternal(*this, &called_computations); return called_computations; } void HloInstruction::CheckFusionInstruction() const { CHECK_EQ(opcode_, HloOpcode::kFusion); // All instructions owned by this fusion instruction must be fused, and the // parent fusion instruction of the fused instructions must be 'this'. for (auto& instruction : fused_instructions_) { CHECK(instruction->IsFused()); CHECK_EQ(this, instruction->fusion_instruction()); } // Fused root instruction and fused parameters must all be owned by the fusion // instruction. bool root_owned = false; std::vector<bool> parameter_owned(fused_parameters_.size(), false); for (auto& instruction : fused_instructions_) { if (fused_root_ == instruction.get()) { CHECK(!root_owned); root_owned = true; } for (int i = 0; i < fused_parameters_.size(); ++i) { if (fused_parameters_[i] == instruction.get()) { CHECK(!parameter_owned[i]); parameter_owned[i] = true; } } } CHECK(root_owned); // Make sure all the parameter_owned entries are set for (int i = 0; i < parameter_owned.size(); i++) { CHECK(parameter_owned[i]); } // Fused root must have no users. CHECK_EQ(0, fused_root_->user_count()); // All uses of fused instructions must be in the fusion instruction, and every // non-root instruction must have at least one use. for (auto& instruction : fused_instructions_) { if (instruction.get() != fused_root_) { CHECK_GT(instruction->user_count(), 0); for (auto& user : instruction->users()) { CHECK(user->IsFused()); CHECK_EQ(this, user->fusion_instruction()); } } } // Fused parameter instructions must be numbered contiguously and match up // (shapes compatible) with their respective operand. CHECK_EQ(operands_.size(), fused_parameters_.size()); std::vector<bool> parameter_numbers(fused_parameters_.size(), false); for (auto fused_param : fused_parameters_) { int64 param_no = fused_param->parameter_number(); CHECK_GE(param_no, 0); CHECK_LT(param_no, fused_parameters_.size()); CHECK(!parameter_numbers[param_no]); parameter_numbers[param_no] = true; CHECK(ShapeUtil::Compatible(fused_param->shape(), operands_[param_no]->shape())); } // Make sure all the parameter_numbers entries were seen for (int i = 0; i < parameter_numbers.size(); i++) { CHECK(parameter_numbers[i]); } // Operands must be distinct. std::set<HloInstruction*> operand_set(operands_.begin(), operands_.end()); CHECK_EQ(operand_set.size(), operands_.size()); } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateCall( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> operands, HloComputation* computation) { std::unique_ptr<HloInstruction> instruction = WrapUnique(new HloInstruction(HloOpcode::kCall, shape)); for (auto operand : operands) { instruction->AppendOperand(operand); } instruction->to_apply_ = computation; return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateCustomCall( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> operands, tensorflow::StringPiece custom_call_target) { std::unique_ptr<HloInstruction> instruction = WrapUnique(new HloInstruction(HloOpcode::kCustomCall, shape)); for (auto operand : operands) { instruction->AppendOperand(operand); } instruction->custom_call_target_ = custom_call_target.ToString(); return instruction; } /* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateTuple( tensorflow::gtl::ArraySlice<HloInstruction*> elements) { std::vector<Shape> element_shapes; for (auto element : elements) { element_shapes.push_back(element->shape()); } Shape tuple_shape = ShapeUtil::MakeTupleShape(element_shapes); return CreateVariadic(tuple_shape, HloOpcode::kTuple, elements); } std::unique_ptr<HloInstruction> HloInstruction::CloneWithNewOperands( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> operands) { // Explicitly call the factory for the instruction type. This is more robust // in the face of code changes than copying fields explicitly. This also // properly sets the user fields of the operands. switch (opcode_) { // Unary ops. case HloOpcode::kAbs: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kCopy: case HloOpcode::kExp: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLogicalNot: case HloOpcode::kNegate: case HloOpcode::kSign: case HloOpcode::kSort: case HloOpcode::kTanh: CHECK_EQ(operands.size(), 1); return CreateUnary(shape, opcode_, operands[0]); // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kEq: case HloOpcode::kGe: case HloOpcode::kGt: case HloOpcode::kLe: case HloOpcode::kLt: case HloOpcode::kNe: case HloOpcode::kDot: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kLogicalAnd: case HloOpcode::kLogicalOr: CHECK_EQ(operands.size(), 2); return CreateBinary(shape, opcode_, operands[0], operands[1]); // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: CHECK_EQ(operands.size(), 3); return CreateTernary(shape, opcode_, operands[0], operands[1], operands[2]); // Other supported ops. case HloOpcode::kBroadcast: CHECK_EQ(operands.size(), 1); return CreateBroadcast(shape, operands[0], dimensions_); case HloOpcode::kCall: return CreateCall(shape, operands, to_apply_); case HloOpcode::kCustomCall: return CreateCustomCall(shape, operands, custom_call_target_); case HloOpcode::kConcatenate: return CreateConcatenate(shape, operands, dimensions(0)); case HloOpcode::kConvert: CHECK_EQ(operands.size(), 1); return CreateConvert(shape, operands[0]); case HloOpcode::kConvolution: CHECK_EQ(operands.size(), 2); return CreateConvolve(shape, operands[0], operands[1], *window_, *convolution_dimension_numbers_); case HloOpcode::kCrossReplicaSum: CHECK_EQ(operands.size(), 1); return CreateCrossReplicaSum(shape, operands[0]); case HloOpcode::kGetTupleElement: CHECK_EQ(operands.size(), 1); return CreateGetTupleElement(shape, operands[0], tuple_index()); case HloOpcode::kMap: return CreateMap(shape, operands, to_apply_); case HloOpcode::kPad: CHECK_EQ(operands.size(), 2); return CreatePad(shape, operands[0], operands[1], *padding_config_); case HloOpcode::kReduce: CHECK_EQ(operands.size(), 2); return CreateReduce(shape, operands[0], operands[1], dimensions_, to_apply_); case HloOpcode::kReduceWindow: CHECK_EQ(operands.size(), 2); return CreateReduceWindow(shape, operands[0], operands[1], *window_, to_apply_); case HloOpcode::kSelectAndScatter: CHECK_EQ(operands.size(), 3); return CreateSelectAndScatter(shape, operands[0], select_, *window_, operands[1], operands[2], scatter_); case HloOpcode::kRecv: CHECK_EQ(operands.size(), 0); return CreateRecv(shape, channel_id_); case HloOpcode::kReverse: CHECK_EQ(operands.size(), 1); return CreateReverse(shape, operands[0], dimensions_); case HloOpcode::kRng: return CreateRng(shape, distribution_, operands); case HloOpcode::kReshape: CHECK_EQ(operands.size(), 1); return CreateReshape(shape, operands[0]); case HloOpcode::kSend: CHECK_EQ(operands.size(), 1); return CreateSend(operands[0], channel_id_); case HloOpcode::kSlice: CHECK_EQ(operands.size(), 1); return CreateSlice(shape, operands[0], slice_starts_, slice_limits_); case HloOpcode::kDynamicSlice: return CreateDynamicSlice(shape, operands[0], operands[1], dynamic_slice_sizes_); case HloOpcode::kDynamicUpdateSlice: CHECK_EQ(operands.size(), 3); return CreateDynamicUpdateSlice(shape, operands[0], operands[1], operands[2]); case HloOpcode::kTranspose: CHECK_EQ(operands.size(), 1); return CreateTranspose(shape, operands[0], dimensions_); case HloOpcode::kTuple: return CreateTuple(operands_); case HloOpcode::kWhile: CHECK_EQ(operands.size(), 1); return CreateWhile(shape, condition_, body_, operands[0]); case HloOpcode::kConstant: return CreateConstant(LiteralUtil::CloneToUnique(*literal_)); case HloOpcode::kFusion: return CloneFusionWithNewOperands(shape, operands); case HloOpcode::kParameter: return CreateParameter(parameter_number_, shape, parameter_name_); // Unsupported ops for cloning. case HloOpcode::kUpdate: case HloOpcode::kIndex: case HloOpcode::kInfeed: case HloOpcode::kOutfeed: case HloOpcode::kTrace: LOG(FATAL) << "Not yet implemented, clone: " << HloOpcodeString(opcode_); } } std::unique_ptr<HloInstruction> HloInstruction::Clone() { std::unique_ptr<HloInstruction> clone = CloneWithNewOperands(shape_, operands_); clone->name_ = name() + ".clone"; return clone; } std::unique_ptr<HloInstruction> HloInstruction::CloneFusionWithNewOperands( const Shape& shape, tensorflow::gtl::ArraySlice<HloInstruction*> operands) { CHECK_EQ(opcode_, HloOpcode::kFusion); auto new_instruction = WrapUnique(new HloInstruction(HloOpcode::kFusion, shape)); // Add the operands to our new fusion instruction. for (HloInstruction* new_operand : operands) { new_instruction->AppendOperand(new_operand); } // Clone all the fused instructions for the new fusion instruction. std::map<HloInstruction*, HloInstruction*> old_to_new; std::list<std::unique_ptr<HloInstruction>> new_fused_instructions; // Create the list of fused parameters by mapping through the cloned, // fused instructions. std::vector<HloInstruction*> new_fused_parameters; for (HloInstruction* old_fused_parameter : fused_parameters_) { new_fused_instructions.push_back(old_fused_parameter->Clone()); HloInstruction* new_fusion_parameter = new_fused_instructions.back().get(); new_fusion_parameter->parent_fusion_instruction_ = new_instruction.get(); new_fused_parameters.push_back(new_fusion_parameter); InsertOrDie(&old_to_new, old_fused_parameter, new_fusion_parameter); } for (auto old_fused_instruction_iter = fused_instructions_.rbegin(); old_fused_instruction_iter != fused_instructions_.rend(); ++old_fused_instruction_iter) { HloInstruction* old_fused_instruction = old_fused_instruction_iter->get(); if (old_fused_instruction->opcode() == HloOpcode::kParameter) { FindOrDie(old_to_new, old_fused_instruction); continue; } std::vector<HloInstruction*> new_operands; for (int64 operand_idx = 0; operand_idx < old_fused_instruction->operand_count(); ++operand_idx) { HloInstruction* old_operand = old_fused_instruction->mutable_operand(operand_idx); new_operands.push_back(FindOrDie(old_to_new, old_operand)); } new_fused_instructions.push_back( old_fused_instruction->CloneWithNewOperands( old_fused_instruction->shape(), new_operands)); HloInstruction* new_fused_instruction = new_fused_instructions.back().get(); new_fused_instruction->parent_fusion_instruction_ = new_instruction.get(); InsertOrDie(&old_to_new, old_fused_instruction, new_fused_instruction); } // We iterated the fusion instructions in reverse post order which means // that we must reverse our new list of fusion instructions. std::reverse(new_fused_instructions.begin(), new_fused_instructions.end()); new_instruction->fusion_kind_ = fusion_kind_; new_instruction->fused_instructions_ = std::move(new_fused_instructions); new_instruction->fused_parameters_ = std::move(new_fused_parameters); new_instruction->fused_root_ = FindOrDie(old_to_new, fused_root_); new_instruction->CheckFusionInstruction(); return new_instruction; } const Literal& HloInstruction::literal() const { CHECK_EQ(HloOpcode::kConstant, opcode_); return *literal_; } bool HloInstruction::CanHaveDimensionsField() const { return (opcode() == HloOpcode::kReverse || opcode() == HloOpcode::kConcatenate || opcode() == HloOpcode::kReduce || opcode() == HloOpcode::kBroadcast || opcode() == HloOpcode::kTranspose); } const std::vector<int64>& HloInstruction::dimensions() const { CHECK(CanHaveDimensionsField()); return dimensions_; } int64 HloInstruction::dimensions(int64 index) const { return dimensions()[index]; } int64 HloInstruction::concatenate_dimension() const { CHECK(opcode() == HloOpcode::kConcatenate); CHECK_EQ(1, dimensions_.size()); return dimensions(0); } int64 HloInstruction::tuple_index() const { CHECK_EQ(HloOpcode::kGetTupleElement, opcode_); return tuple_index_; } const HloInstruction* HloInstruction::operand(int64 i) const { return operands_[i]; } HloInstruction* HloInstruction::mutable_operand(int64 i) { CHECK(operands_[i] != nullptr); return operands_[i]; } int64 HloInstruction::operand_index(const HloInstruction* target) const { for (int64 i = 0; i < operand_count(); ++i) { if (target == operand(i)) { return i; } } LOG(FATAL) << "target was not an operand"; } void HloInstruction::AppendOperand(HloInstruction* operand) { operands_.push_back(operand); operand->AddUser(this); } void HloInstruction::AddUser(HloInstruction* user) { users_.insert(user); } bool HloInstruction::IsConstant() const { return opcode_ == HloOpcode::kConstant; } bool HloInstruction::HasConstantOperand() const { for (const HloInstruction* operand : operands_) { if (operand->IsConstant()) { return true; } } return false; } void HloInstruction::AddControlPredecessor(HloInstruction* instruction) { control_predecessors_.insert(instruction); } void HloInstruction::AddControlSuccessor(HloInstruction* instruction) { control_successors_.insert(instruction); } bool HloInstruction::Identical( const HloInstruction& other, std::function<bool(const HloInstruction*, const HloInstruction*)> eq_operands, std::function<bool(const HloComputation*, const HloComputation*)> eq_computations) const { // An instruction is always identical to itself. if (this == &other) { return true; } // Identical instruction must have the same opcode and identical operands. In // general, there is no need to check shape because shape is inferred from the // shape of the operands. if (opcode() != other.opcode() || !ContainersEqual(operands(), other.operands(), eq_operands)) { return false; } // Perform opcode specific checks. switch (opcode()) { // The result of these instructions only depend upon their opcode and // operands. case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kCeil: case HloOpcode::kClamp: case HloOpcode::kCopy: case HloOpcode::kCrossReplicaSum: case HloOpcode::kDivide: case HloOpcode::kDot: case HloOpcode::kEq: case HloOpcode::kExp: case HloOpcode::kFloor: case HloOpcode::kGe: case HloOpcode::kGt: case HloOpcode::kLe: case HloOpcode::kLog: case HloOpcode::kLogicalAnd: case HloOpcode::kLogicalNot: case HloOpcode::kLogicalOr: case HloOpcode::kLt: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNe: case HloOpcode::kNegate: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kSelect: case HloOpcode::kSign: case HloOpcode::kSubtract: case HloOpcode::kTanh: case HloOpcode::kTuple: return true; // These opcodes have complex or special behavior so just return false. case HloOpcode::kFusion: case HloOpcode::kRng: case HloOpcode::kTrace: case HloOpcode::kWhile: return false; case HloOpcode::kParameter: return parameter_number() == other.parameter_number() && // Check the shape too because `this` and `other` may be in // different HloComputations. ShapeUtil::Compatible(shape(), other.shape()); // A constant is defined by the value in the literal. case HloOpcode::kConstant: return LiteralUtil::Equal(literal(), other.literal()); // A convert result is determined by the primitive type that the operand is // converted into. case HloOpcode::kConvert: return shape().element_type() == other.shape().element_type(); // Convolution has a window and dimensions. case HloOpcode::kConvolution: return protobuf_util::ProtobufEquals(window(), other.window()) && protobuf_util::ProtobufEquals( convolution_dimension_numbers(), other.convolution_dimension_numbers()); // Reduction results are determined by the reduction dimension and the // reduction computation. case HloOpcode::kReduce: return dimensions() == other.dimensions() && eq_computations(to_apply(), other.to_apply()); case HloOpcode::kReduceWindow: return eq_computations(to_apply(), other.to_apply()) && protobuf_util::ProtobufEquals(window(), other.window()); // SelectAndScatter is determined by both select and scatter // computation as well as the window configuration. case HloOpcode::kSelectAndScatter: return eq_computations(select(), other.select()) && eq_computations(scatter(), other.scatter()) && protobuf_util::ProtobufEquals(window(), other.window()); case HloOpcode::kReshape: return ShapeUtil::Compatible(shape(), other.shape()); // Transpose result is determined by the final shape and the permutation. case HloOpcode::kTranspose: return ShapeUtil::Compatible(shape(), other.shape()) && dimensions() == other.dimensions(); // Remaining instructions with special values. case HloOpcode::kBitcast: return ShapeUtil::Equal(shape(), other.shape()); case HloOpcode::kBroadcast: return ShapeUtil::Compatible(shape(), other.shape()) && dimensions() == other.dimensions(); case HloOpcode::kConcatenate: return dimensions() == other.dimensions(); case HloOpcode::kGetTupleElement: return tuple_index() == other.tuple_index(); case HloOpcode::kPad: return protobuf_util::ProtobufEquals(padding_config(), other.padding_config()); case HloOpcode::kSlice: return slice_starts_ == other.slice_starts_ && slice_limits_ == other.slice_limits_; case HloOpcode::kDynamicSlice: return ShapeUtil::Compatible(shape(), other.shape()) && dynamic_slice_sizes_ == other.dynamic_slice_sizes_; case HloOpcode::kDynamicUpdateSlice: return ShapeUtil::Compatible(shape(), other.shape()); case HloOpcode::kCall: case HloOpcode::kMap: return eq_computations(to_apply(), other.to_apply()); case HloOpcode::kCustomCall: return custom_call_target_ == other.custom_call_target_; case HloOpcode::kReverse: return dimensions() == other.dimensions(); // These opcodes are not yet supported. case HloOpcode::kIndex: case HloOpcode::kInfeed: case HloOpcode::kOutfeed: case HloOpcode::kSort: case HloOpcode::kUpdate: case HloOpcode::kSend: case HloOpcode::kRecv: return false; } } bool HloInstruction::IsRank2Transpose() const { return (opcode_ == HloOpcode::kTranspose) && dimensions_ == std::vector<int64>({1, 0}) && shape_.dimensions_size() == 2 && std::equal(shape_.dimensions().begin(), shape_.dimensions().end(), operands_[0]->shape_.dimensions().rbegin()); } void HloInstruction::RemoveUser(HloInstruction* user) { auto user_it = users_.find(user); CHECK(user_it != users_.end()); users_.erase(user_it); } Status HloInstruction::ReplaceUseWith(HloInstruction* user, HloInstruction* new_producer) { TF_RET_CHECK(ShapeUtil::Compatible(shape(), new_producer->shape())) << "this shape: " << ShapeUtil::HumanString(shape()) << ", replacement shape: " << ShapeUtil::HumanString(new_producer->shape()); auto user_it = std::find(users_.begin(), users_.end(), user); TF_RET_CHECK(user_it != users_.end()) << "Instruction " << user->name() << " not a use of instruction " << name(); users_.erase(user_it); VLOG(3) << "Replacing uses of " << name() << " in " << user->name() << " with " << new_producer->name(); TF_RET_CHECK( std::count(user->operands_.begin(), user->operands_.end(), this) >= 0); std::replace(user->operands_.begin(), user->operands_.end(), this, new_producer); new_producer->AddUser(user); return Status::OK(); } Status HloInstruction::ReplaceOperandWith(int64 operand_num, HloInstruction* new_operand) { TF_RET_CHECK(operand_num >= 0); TF_RET_CHECK(operand_num < operand_count()); HloInstruction* old_operand = mutable_operand(operand_num); TF_RET_CHECK( ShapeUtil::Compatible(old_operand->shape(), new_operand->shape())) << old_operand->shape().ShortDebugString() << " is not compatible with " << new_operand->shape().ShortDebugString(); operands_[operand_num] = new_operand; VLOG(3) << "Replacing operand " << operand_num << " of " << name() << " with " << new_operand->name() << ", was " << old_operand->name(); if (std::find(operands_.begin(), operands_.end(), old_operand) == operands_.end()) { old_operand->RemoveUser(this); } new_operand->AddUser(this); return Status::OK(); } Status HloInstruction::ReplaceAllUsesWith(HloInstruction* new_producer) { // We can't use range-based loop because the iterator is invalidated by call // to ReplaceUseWith. for (auto user = users_.begin(); user != users_.end();) { auto this_user = user; user++; // It's possible that new_producer is a user of this instruction as might // be the case when replacing an instruction with a kCopy of itself. In // this case, don't do the replacement to avoid creating a cycle in the // graph. if (*this_user != new_producer) { TF_RETURN_IF_ERROR(ReplaceUseWith(*this_user, new_producer)); } } return Status::OK(); } void HloInstruction::DetachFromOperands() { CHECK_EQ(0, user_count()); // An intruction may be repeated as an operand. To avoid calling RemoveUser // twice on the same operand, keep a set of already detached operands. std::set<HloInstruction*> detached_operands; for (int64 operand_num = 0; operand_num < operand_count(); ++operand_num) { HloInstruction* operand = operands_[operand_num]; if (detached_operands.count(operand) == 0) { operand->RemoveUser(this); detached_operands.insert(operand); } operands_[operand_num] = nullptr; } } HloComputation* HloInstruction::to_apply() const { switch (opcode_) { case HloOpcode::kCall: case HloOpcode::kMap: case HloOpcode::kReduceWindow: case HloOpcode::kReduce: return to_apply_; default: LOG(FATAL) << "Invalid instruction for to_apply(): " << ToString(); } } void HloInstruction::set_to_apply(HloComputation* computation) { switch (opcode_) { case HloOpcode::kCall: case HloOpcode::kMap: case HloOpcode::kReduceWindow: case HloOpcode::kReduce: to_apply_ = computation; break; default: LOG(FATAL) << "Invalid instruction for to_apply(): " << ToString(); } } const string& HloInstruction::custom_call_target() const { CHECK_EQ(opcode_, HloOpcode::kCustomCall); return custom_call_target_; } const string& HloInstruction::outfeed_config() const { CHECK_EQ(opcode_, HloOpcode::kOutfeed); return outfeed_config_; } HloComputation* HloInstruction::while_condition() const { CHECK_EQ(HloOpcode::kWhile, opcode_); return condition_; } HloComputation* HloInstruction::while_body() const { CHECK_EQ(HloOpcode::kWhile, opcode_); return body_; } void HloInstruction::set_while_condition(HloComputation* computation) { CHECK_EQ(HloOpcode::kWhile, opcode_); condition_ = computation; } void HloInstruction::set_while_body(HloComputation* computation) { CHECK_EQ(HloOpcode::kWhile, opcode_); body_ = computation; } HloComputation* HloInstruction::select() const { CHECK_EQ(HloOpcode::kSelectAndScatter, opcode_); return select_; } HloComputation* HloInstruction::scatter() const { CHECK_EQ(HloOpcode::kSelectAndScatter, opcode_); return scatter_; } void HloInstruction::set_select(HloComputation* computation) { CHECK_EQ(HloOpcode::kSelectAndScatter, opcode_); select_ = computation; } void HloInstruction::set_scatter(HloComputation* computation) { CHECK_EQ(HloOpcode::kSelectAndScatter, opcode_); scatter_ = computation; } string HloInstruction::SignatureString() const { string operands = tensorflow::str_util::Join( operands_, ", ", [](string* out, HloInstruction* operand) { tensorflow::strings::StrAppend( out, ShapeUtil::HumanString(operand->shape())); }); return tensorflow::strings::StrCat("(", operands, ") -> ", ShapeUtil::HumanString(shape())); } string HloInstruction::ToString(bool compact_operands) const { string operands; if (opcode() == HloOpcode::kConstant) { // For constants, show the actual value in place of an empty operand list. if (ShapeUtil::ElementsIn(shape()) <= 10) { // LiteralUtil::ToString emits multidimensional arrays over multiple // lines. Compact this into one line by stripping out white space. string tmp = LiteralUtil::ToString(literal()); std::replace(tmp.begin(), tmp.end(), '\n', ' '); std::vector<string> v = tensorflow::str_util::Split(tmp, ' '); bool first = true; // Concatenate elements in "v" with spaces separating them, but ignoring // empty entries. for (const auto& s : v) { if (s.empty()) continue; tensorflow::strings::StrAppend(&operands, (first ? "" : " "), s); first = false; } } else { // Do not show large constants. operands = "{...}"; } } else { tensorflow::gtl::ArraySlice<HloInstruction*> slice(operands_); const int64 kMaxOperandsToShowIfCompact = 4; if (compact_operands && slice.size() > kMaxOperandsToShowIfCompact) { slice.remove_suffix(slice.size() - kMaxOperandsToShowIfCompact); } operands = tensorflow::str_util::Join( slice, ", ", [&](string* out, HloInstruction* operand) { *out += ShapeUtil::HumanStringWithLayout(operand->shape()); if (!compact_operands) { tensorflow::strings::StrAppend(out, " ", operand->name()); } }); const int64 remaining = operands_.size() - slice.size(); if (slice.size() != operands_.size()) { tensorflow::strings::StrAppend(&operands, ", ...(+", remaining, ")"); } } string extra; if (CanHaveDimensionsField()) { tensorflow::strings::StrAppend( &extra, ", dimensions={", tensorflow::str_util::Join(dimensions(), ","), "}"); } if (window_ != nullptr) { tensorflow::strings::StrAppend(&extra, ", ", window_util::ToString(*window_)); } if (padding_config_ != nullptr) { tensorflow::strings::StrAppend( &extra, ", padding=", padding_config_->ShortDebugString()); } if (!slice_starts_.empty() && !slice_limits_.empty()) { std::vector<string> bounds; for (int i = 0; i < slice_starts_.size(); ++i) { bounds.push_back(tensorflow::strings::StrCat("[", slice_starts_[i], ":", slice_limits_[i], "]")); } tensorflow::strings::StrAppend( &extra, ", slice={", tensorflow::str_util::Join(bounds, ", "), "}"); } if (convolution_dimension_numbers_ != nullptr) { const auto& dnums = *convolution_dimension_numbers_; // Show the given dimension labels in order of major to minor based on the // shape's layout. const auto append_dims = [&](const std::vector<string>& dims, const Shape& shape) { CHECK_EQ(dims.size(), ShapeUtil::Rank(shape)); for (int64 logical = 0; logical < dims.size(); ++logical) { int64 physical = logical; if (!shape.layout().minor_to_major().empty()) { physical = LayoutUtil::Major(shape.layout(), logical); } extra += dims[physical]; } }; // lhs_dims[i] is the symbol of the logical dimension i for the lhs // operand. E.g. if batch has dimension number 2, then lhs_dims[2] == "b". std::vector<string> lhs_dims(2 + dnums.spatial_dimensions().size()); lhs_dims[dnums.batch_dimension()] = 'b'; lhs_dims[dnums.feature_dimension()] = 'f'; for (int64 i = 0; i < dnums.spatial_dimensions().size(); ++i) { lhs_dims[dnums.spatial_dimensions(i)] = tensorflow::strings::StrCat(i); } std::vector<string> rhs_dims(2 + dnums.kernel_spatial_dimensions().size()); rhs_dims[dnums.kernel_input_feature_dimension()] = "i"; rhs_dims[dnums.kernel_output_feature_dimension()] = "o"; for (int64 i = 0; i < dnums.spatial_dimensions().size(); ++i) { rhs_dims[dnums.kernel_spatial_dimensions(i)] = tensorflow::strings::StrCat(i); } extra += " dims: "; append_dims(lhs_dims, operands_.at(0)->shape()); extra += "_"; append_dims(rhs_dims, operands_.at(1)->shape()); extra += "->"; append_dims(lhs_dims, shape()); } if (to_apply_ != nullptr) { tensorflow::strings::StrAppend(&extra, ", computation=", to_apply_->name()); } if (opcode() == HloOpcode::kWhile) { tensorflow::strings::StrAppend(&extra, ", condition=", while_condition()->name()); tensorflow::strings::StrAppend(&extra, ", body=", while_body()->name()); } if (opcode() == HloOpcode::kGetTupleElement) { tensorflow::strings::StrAppend(&extra, ", index=", tuple_index()); } return tensorflow::strings::Printf( "%s = %s %s(%s)%s", name().c_str(), ShapeUtil::HumanStringWithLayout(shape()).c_str(), HloOpcodeString(opcode()).c_str(), operands.c_str(), extra.c_str()); } string HloInstruction::ToShortString() const { return tensorflow::strings::Printf( "%s = %s(%s)", name().c_str(), HloOpcodeString(opcode()).c_str(), tensorflow::str_util::Join(operands_, ", ", [](string* out, HloInstruction* operand) { tensorflow::strings::StrAppend( out, operand->name()); }) .c_str()); } string HloInstruction::ToCategory() const { if (opcode() == HloOpcode::kTranspose || opcode() == HloOpcode::kCopy || opcode() == HloOpcode::kReshape) { return "data formatting"; } if (opcode() == HloOpcode::kConvolution) { string category = "convolution"; if (window_util::HasBaseDilation(window())) { category += " base-dilated"; } if (window_util::HasWindowDilation(window())) { category += " window-dilated"; } return category; } if (opcode() == HloOpcode::kFusion) { if (operands().size() == 2) { bool saw_rank_1 = false; bool saw_higher_rank = false; for (const auto* operand : operands()) { saw_rank_1 |= ShapeUtil::Rank(operand->shape()) == 1; saw_higher_rank |= ShapeUtil::Rank(operand->shape()) > 1; } if (saw_rank_1 && saw_higher_rank) { return "rank-1-broadcast binary fusion"; } } if (IsElementwise()) { return "elementwise fusion"; } else { return "non-elementwise fusion"; } } if (IsElementwise() && opcode() != HloOpcode::kFusion) { return "non-fusion elementwise"; } return HloOpcodeString(opcode()); } string HloInstruction::FullyQualifiedName() const { if (IsFused()) { return tensorflow::strings::StrCat(fusion_instruction()->parent()->name(), "::", fusion_instruction()->name(), "::", name_); } return tensorflow::strings::StrCat(parent_->name(), "::", name_); } HloInstruction* HloInstruction::tracing() const { return trace_instruction_; } void HloInstruction::set_tracing(HloInstruction* trace_instruction) { trace_instruction_ = trace_instruction; } const string& HloInstruction::tracing_tag() const { CHECK_EQ(HloOpcode::kTrace, opcode()); CHECK(literal_ != nullptr); return literal_->u8s(); } bool HloInstruction::IsFused() const { return parent_fusion_instruction_ != nullptr; } bool HloInstruction::IsFusable() const { // Instructions which are traced should not be fused. if (tracing()) { return false; } // Some kinds of instructions don't make sense to fuse. switch (opcode_) { case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kTrace: case HloOpcode::kSend: case HloOpcode::kRecv: return false; // Only fuse Rng if it is used once, otherwise the random numbers generated // will be different in each fusion. case HloOpcode::kRng: return users_.size() == 1; default: return true; } } HloInstruction* HloInstruction::fusion_instruction() const { CHECK(IsFused()); return parent_fusion_instruction_; } HloInstruction* HloInstruction::fused_expression_root() const { CHECK_EQ(opcode_, HloOpcode::kFusion); return fused_root_; } HloInstruction* HloInstruction::fused_parameter(int64 parameter_number) const { CHECK_EQ(opcode_, HloOpcode::kFusion); CHECK_GE(parameter_number, 0); CHECK_LT(parameter_number, fused_parameters_.size()); return fused_parameters_[parameter_number]; } const std::list<std::unique_ptr<HloInstruction>>& HloInstruction::fused_instructions() const { CHECK_EQ(opcode_, HloOpcode::kFusion); return fused_instructions_; } HloInstruction::HloInstruction(HloOpcode opcode, const Shape& shape) : shape_(shape), opcode_(opcode), name_("%" + HloOpcodeString(opcode)) { TF_DCHECK_OK(ShapeUtil::ValidateShapeWithOptionalLayout(shape_)); } Status HloInstruction::Visit(DfsHloVisitor* visitor) { switch (opcode_) { case HloOpcode::kAbs: return visitor->HandleAbs(this, operands_[0]); case HloOpcode::kSign: return visitor->HandleSign(this, operands_[0]); case HloOpcode::kConstant: return visitor->HandleConstant(this, *literal_); case HloOpcode::kGetTupleElement: return visitor->HandleGetTupleElement(this, operands_[0]); case HloOpcode::kParameter: return visitor->HandleParameter(this); case HloOpcode::kEq: case HloOpcode::kGe: case HloOpcode::kGt: case HloOpcode::kLe: case HloOpcode::kLt: case HloOpcode::kNe: return visitor->HandleCompare(this, opcode_, operands_[0], operands_[1]); case HloOpcode::kAdd: return visitor->HandleAdd(this, operands_[0], operands_[1]); case HloOpcode::kDivide: return visitor->HandleDivide(this, operands_[0], operands_[1]); case HloOpcode::kSubtract: return visitor->HandleSubtract(this, operands_[0], operands_[1]); case HloOpcode::kMaximum: return visitor->HandleMaximum(this, operands_[0], operands_[1]); case HloOpcode::kMinimum: return visitor->HandleMinimum(this, operands_[0], operands_[1]); case HloOpcode::kLogicalAnd: return visitor->HandleLogicalAnd(this, operands_[0], operands_[1]); case HloOpcode::kLogicalOr: return visitor->HandleLogicalOr(this, operands_[0], operands_[1]); case HloOpcode::kConcatenate: return visitor->HandleConcatenate(this, operands_); case HloOpcode::kConvert: return visitor->HandleConvert(this, operands_[0]); case HloOpcode::kCopy: return visitor->HandleCopy(this, operands_[0]); case HloOpcode::kMultiply: return visitor->HandleMultiply(this, operands_[0], operands_[1]); case HloOpcode::kDot: return visitor->HandleDot(this, operands_[0], operands_[1]); case HloOpcode::kPower: return visitor->HandlePower(this, operands_[0], operands_[1]); case HloOpcode::kRemainder: return visitor->HandleRemainder(this, operands_[0], operands_[1]); case HloOpcode::kSelect: return visitor->HandleSelect(this, operands_[0], operands_[1], operands_[2]); case HloOpcode::kConvolution: return visitor->HandleConvolution(this, operands_[0], operands_[1], window()); case HloOpcode::kCrossReplicaSum: return visitor->HandleCrossReplicaSum(this); case HloOpcode::kTuple: return visitor->HandleTuple(this, operands_); case HloOpcode::kMap: return visitor->HandleMap(this, operands_, to_apply_, {}); case HloOpcode::kClamp: return visitor->HandleClamp(this, operands_[0], operands_[1], operands_[2]); case HloOpcode::kReduce: return visitor->HandleReduce(this, operands_[0], operands_[1], dimensions_, to_apply_); case HloOpcode::kReduceWindow: return visitor->HandleReduceWindow(this, operands_[0], window(), to_apply_); case HloOpcode::kSelectAndScatter: return visitor->HandleSelectAndScatter(this); case HloOpcode::kNegate: return visitor->HandleNegate(this, operands_[0]); case HloOpcode::kExp: return visitor->HandleExp(this, operands_[0]); case HloOpcode::kFloor: return visitor->HandleFloor(this, operands_[0]); case HloOpcode::kCeil: return visitor->HandleCeil(this, operands_[0]); case HloOpcode::kLog: return visitor->HandleLog(this, operands_[0]); case HloOpcode::kTanh: return visitor->HandleTanh(this, operands_[0]); case HloOpcode::kLogicalNot: return visitor->HandleLogicalNot(this, operands_[0]); case HloOpcode::kBitcast: return visitor->HandleBitcast(this); case HloOpcode::kBroadcast: return visitor->HandleBroadcast(this); case HloOpcode::kPad: return visitor->HandlePad(this); case HloOpcode::kReshape: return visitor->HandleReshape(this); case HloOpcode::kTranspose: return visitor->HandleTranspose(this); case HloOpcode::kReverse: return visitor->HandleReverse(this, operands_[0]); case HloOpcode::kSlice: return visitor->HandleSlice(this, operands_[0]); case HloOpcode::kDynamicSlice: return visitor->HandleDynamicSlice(this, operands_); case HloOpcode::kDynamicUpdateSlice: return visitor->HandleDynamicUpdateSlice(this, operands_[0], operands_[1], operands_[2]); case HloOpcode::kSort: return visitor->HandleSort(this, operands_[0]); case HloOpcode::kInfeed: return visitor->HandleInfeed(this); case HloOpcode::kOutfeed: return visitor->HandleOutfeed(this); case HloOpcode::kRng: return visitor->HandleRng(this, distribution_); case HloOpcode::kWhile: return visitor->HandleWhile(this, operands_[0], condition_, body_); case HloOpcode::kFusion: return visitor->HandleFusion(this); case HloOpcode::kCall: return visitor->HandleCall(this, operands_, to_apply_); case HloOpcode::kCustomCall: return visitor->HandleCustomCall(this, operands_, custom_call_target_); case HloOpcode::kSend: return visitor->HandleSend(this); case HloOpcode::kRecv: return visitor->HandleRecv(this); // These opcodes are not handled here. case HloOpcode::kIndex: case HloOpcode::kTrace: case HloOpcode::kUpdate: break; } return Unimplemented("unhandled HloOpcode for DfsHloVisitor: %s", HloOpcodeString(opcode_).c_str()); } Status HloInstruction::AcceptInternal(DfsHloVisitor* visitor) { // Do not visit this HLO node again if it is already visited. if (visitor->DidVisit(*this)) { VLOG(3) << "Not visiting HLO " << name() << " as it was already visited."; return Status::OK(); } // If the instruction is in the visiting state, it means a cycle. if (visitor->IsVisiting(*this)) { return FailedPrecondition( "A cycle is detected while visiting instruction %s", ToString().c_str()); } visitor->SetVisiting(*this); for (auto operand : operands_) { VLOG(3) << "Going to visit HLO " << operand->name() << " as operand of HLO " << name(); TF_RETURN_IF_ERROR(operand->AcceptInternal(visitor)); } for (auto control_predecessor : control_predecessors_) { VLOG(3) << "Going to visit HLO " << control_predecessor->name() << " as a control predecessor of HLO " << name(); TF_RETURN_IF_ERROR(control_predecessor->AcceptInternal(visitor)); } TF_RETURN_IF_ERROR(visitor->Preprocess(this)); VLOG(2) << "Visiting HLO " << name(); TF_RETURN_IF_ERROR(Visit(visitor)); visitor->SetVisited(*this); return visitor->Postprocess(this); } Status HloInstruction::Accept(DfsHloVisitor* visitor, bool call_finish_visit) { VLOG(2) << "HloInstruction::Accept(" << name() << ")"; auto status = AcceptInternal(visitor); if (!status.ok()) { return status; } if (call_finish_visit) { return visitor->FinishVisit(this); } else { return Status::OK(); } } namespace { // Returns true if the given order is a topological sort of the instructions it // contains. bool OrderIsTopologicalSort(const std::vector<const HloInstruction*>& order) { // Create a map from instruction to its position in 'order'. std::unordered_map<const HloInstruction*, int> order_position; for (int i = 0; i < order.size(); i++) { if (!order_position.insert({order[i], i}).second) { // Instruction order[i] is duplicated in the order. return false; } } // Verify that the operand of each instruction in the order is also in the // order *and* the operand's position is earlier (defs are before uses for all // ops). for (auto* instruction : order) { for (auto* operand : instruction->operands()) { if (order_position.count(operand) == 0 || order_position.at(operand) >= order_position.at(instruction)) { return false; } } } return true; } } // namespace Status HloInstruction::Accept(FunctionVisitor::VisitorFunction visitor_func) { FunctionVisitor visitor(visitor_func); return this->Accept(&visitor); } Status HloInstruction::AcceptOrdered( DfsHloVisitor* visitor, const std::vector<const HloInstruction*>& order) { VLOG(2) << "HloInstruction::AcceptOrdered(" << name() << ")"; TF_RET_CHECK(OrderIsTopologicalSort(order)); // Compute the predecessors of this instruction. std::unordered_set<const HloInstruction*> predecessors; TF_RETURN_IF_ERROR(this->Accept([&predecessors](HloInstruction* instruction) { predecessors.insert(instruction); return Status::OK(); })); for (auto* const_instruction : order) { if (predecessors.count(const_instruction) == 0) { // Instruction is not a predecessors of 'this'. continue; } // The visitor can mark instructions as visited to skip particular // instructions. if (visitor->DidVisit(*const_instruction)) { VLOG(3) << "Not visiting HLO " << const_instruction->name() << " as it was already visited."; continue; } HloInstruction* instruction = const_cast<HloInstruction*>(const_instruction); TF_RETURN_IF_ERROR(visitor->Preprocess(instruction)); VLOG(2) << "Visiting HLO " << instruction->name(); TF_RETURN_IF_ERROR(instruction->Visit(visitor)); visitor->SetVisited(*instruction); TF_RETURN_IF_ERROR(visitor->Postprocess(instruction)); } return visitor->FinishVisit(this); } const Shape& HloInstruction::shape() const { TF_DCHECK_OK(ShapeUtil::ValidateShapeWithOptionalLayout(shape_)); return shape_; } std::vector<int64> HloInstruction::OperandIndices( const HloInstruction* operand) const { std::vector<int64> result; for (int64 i = 0; i < operand_count(); ++i) { if (this->operand(i) == operand) { result.push_back(i); } } return result; } bool HloInstruction::IsElementwise() const { switch (opcode_) { // Nullary elementwise operations. case HloOpcode::kConstant: return true; // Unary elementwise operations. case HloOpcode::kAbs: case HloOpcode::kCeil: case HloOpcode::kConvert: case HloOpcode::kCopy: case HloOpcode::kExp: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLogicalNot: case HloOpcode::kNegate: case HloOpcode::kSign: case HloOpcode::kTanh: return true; // Binary elementwise operations. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kEq: case HloOpcode::kGe: case HloOpcode::kGt: case HloOpcode::kLe: case HloOpcode::kLt: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNe: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kSubtract: case HloOpcode::kLogicalAnd: case HloOpcode::kLogicalOr: return true; // Ternary elementwise operations. case HloOpcode::kSelect: return !ShapeUtil::IsTuple(shape_); case HloOpcode::kClamp: return true; // Other operations. case HloOpcode::kRng: case HloOpcode::kMap: return true; case HloOpcode::kFusion: if (fusion_kind() != FusionKind::kLoop) { return false; } for (auto& fused : fused_instructions()) { if (fused->opcode() != HloOpcode::kParameter && !fused->IsElementwise()) { return false; } } return true; default: return false; } } namespace { bool IsInstructionElementwiseOnOperand(const HloInstruction* instruction, const HloInstruction* operand) { std::vector<int64> operand_indices = instruction->OperandIndices(operand); return std::all_of( operand_indices.begin(), operand_indices.end(), [instruction](int64 operand_index) { return instruction->IsElementwiseOnOperand(operand_index); }); } } // namespace bool HloInstruction::IsElementwiseOnOperand(int64 operand_idx) const { // For all instructions other than kFusion, being elementwise on one of the // operands is equivalent to being elementwise on all the operands. if (opcode() != HloOpcode::kFusion) { return IsElementwise(); } CHECK_EQ(HloOpcode::kFusion, opcode()); if (fusion_kind() != FusionKind::kLoop) { return false; } // A loop-fusion is elementwise on an operand if all operations (computed // using BFS) between the operand and the fused root are elementwise. std::deque<HloInstruction*> worklist; std::unordered_set<const HloInstruction*> visited; worklist.push_back(fused_parameter(operand_idx)); visited.insert(fused_parameter(operand_idx)); while (!worklist.empty()) { HloInstruction* operand = worklist.front(); worklist.pop_front(); for (HloInstruction* user : operand->users()) { if (visited.count(user)) { continue; } if (user->IsElementwise() || IsInstructionElementwiseOnOperand(user, operand)) { worklist.push_back(user); visited.insert(user); } else { return false; } } } return true; } HloInstruction::UseKind HloInstruction::OperandElementUse(int64 i) const { switch (opcode_) { case HloOpcode::kBitcast: case HloOpcode::kConcatenate: case HloOpcode::kReshape: case HloOpcode::kReverse: case HloOpcode::kSlice: case HloOpcode::kTranspose: return UseKind::kUsePermutingElements; case HloOpcode::kPad: case HloOpcode::kReduce: // Pad reuses the padding value but not the padded array elements. // Reduce reuses the init value but not the operand array elements. return i > 0 ? UseKind::kReuse : UseKind::kUsePermutingElements; case HloOpcode::kFusion: { tensorflow::gtl::FlatMap<const HloInstruction*, UseKind> cache; // We could rather iterate backwards thru fused_instructions_ here, as it // is in reverse postorder, and compute whether each fused instruction // reuses the value of this parameter, which would save stack space but // not allow us to finish early if we find a reuse. std::function<UseKind(const HloInstruction&)> reuses_parameter_elements = [i, &cache, &reuses_parameter_elements](const HloInstruction& hlo) { auto plus = [](const UseKind& a, const UseKind& b) { if (a == UseKind::kNoUse) return b; if (b == UseKind::kNoUse) return a; if (a == UseKind::kReuse || b == UseKind::kReuse) { return UseKind::kReuse; } if (a == UseKind::kUsePermutingElements || b == UseKind::kUsePermutingElements) { return UseKind::kReuse; } CHECK(UseKind::kUse == a && UseKind::kUse == b); return UseKind::kUse; }; if (hlo.opcode_ == HloOpcode::kParameter && hlo.parameter_number_ == i) { return UseKind::kUse; } if (cache.count(&hlo) == 0) { for (int64 j = 0; j < hlo.operands_.size(); ++j) { UseKind old = cache[&hlo]; UseKind updated = plus( old, std::min(hlo.OperandElementUse(j), reuses_parameter_elements(*hlo.operand(j)))); cache[&hlo] = updated; } } return cache[&hlo]; }; return reuses_parameter_elements(*fused_root_); } default: return IsElementwise() ? UseKind::kUse : UseKind::kReuse; } } namespace { // Prereq: `order` is a permutation of {0, 1, ..., `dims.size()-1`} void Strip1SizedDimensions(tensorflow::protobuf::RepeatedField<int64>* dims, std::vector<int64>* order) { // We can't merely call StripDegenerateDimensions here as we must also delete // the dimension indices. for (size_t i = 0; i < dims->size(); ++i) { if (1 == dims->Get(i)) { dims->erase(dims->begin() + i); // We must find this, as order must be a permutation of operand // dimensions. order->erase(std::find(order->begin(), order->end(), i)); } } } } // namespace std::tuple<bool, std::vector<int64>, std::vector<int64>> HloInstruction::ReshapeMerelyInsertsOrDeletes1SizedDimensions() const { if (HloOpcode::kReshape != opcode_) { return std::make_tuple(false, std::vector<int64>(), std::vector<int64>()); } return ShapeUtil::InsertedOrDeleted1SizedDimensions(operand(0)->shape_, shape_); } string FusionKindString(HloInstruction::FusionKind kind) { switch (kind) { case HloInstruction::FusionKind::kLoop: return "Loop"; case HloInstruction::FusionKind::kInput: return "Input"; case HloInstruction::FusionKind::kTransposeDot: return "TransposeDot"; case HloInstruction::FusionKind::kConvBackwardFilter: return "ConvBackwardFilter"; case HloInstruction::FusionKind::kConvBackwardInput: return "ConvBackwardInput"; } } bool HloInstruction::CouldBeBitcast() const { switch (opcode_) { case HloOpcode::kTranspose: return true; case HloOpcode::kReshape: return std::get<0>(ReshapeMerelyInsertsOrDeletes1SizedDimensions()); default: return false; } } } // namespace xla
code-sauce/tensorflow
tensorflow/compiler/xla/service/hlo_instruction.cc
C++
apache-2.0
77,051
package net.estinet.gFeatures.Feature.gWarsSuite; import java.io.File; import java.io.IOException; import org.bukkit.configuration.file.YamlConfiguration; import net.estinet.gFeatures.Configuration.Config; import net.estinet.gFeatures.Feature.gWarsSuite.Connection.Enabling; /* * gFeatures * https://github.com/EstiNet/gFeatures * * Copyright 2019 EstiNet * * 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 ConfigHub { Config config = new Config(); Configuration con = new Configuration(true); public void setupConfig(){ File f = new File("plugins/gFeatures/gWarsSuite/Config.yml"); boolean bool = !f.exists(); config.createDirectory("plugins/gFeatures/gWarsSuite", "gWarsSuite plugin directory set!"); config.createFile("plugins/gFeatures/gWarsSuite/Config.yml", "gWarsSuite plugin config set!"); if(bool){ YamlConfiguration yamlFile = YamlConfiguration.loadConfiguration(f); yamlFile.createSection("Config"); yamlFile.createSection("Config.MySQL"); yamlFile.createSection("Config.MySQL.Address"); yamlFile.createSection("Config.MySQL.Port"); yamlFile.createSection("Config.MySQL.TableName"); yamlFile.createSection("Config.MySQL.Username"); yamlFile.createSection("Config.MySQL.Password"); yamlFile.set("Config.MySQL.Port", "3306"); yamlFile.set("Config.MySQL.Address", "localhost"); yamlFile.set("Config.MySQL.TableName", "gwars"); yamlFile.set("Config.MySQL.Username", "root"); yamlFile.set("Config.MySQL.Password", "pass123"); try { yamlFile.save(f); } catch (IOException e) { e.printStackTrace(); } } Enabling en = new Enabling(); en.start(); } }
EstiNet/gFeatures
src/main/java/net/estinet/gFeatures/Feature/gWarsSuite/ConfigHub.java
Java
apache-2.0
2,179
/* * Copyright (c) 2015 Daniel Higuero. * * 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.spark.examples.events; import org.apache.commons.math3.random.MersenneTwister; import java.util.Date; /** * Authorization event */ public class AuthEventGenerator implements IGenerator{ /** * Processes that generate the auth entries. */ private String [] processes = {"sshd", "httpd", "login"}; /** * Number of hosts in the scenario. */ private final int numberHosts; /** * Field separator. */ private final String separator; /** * Random number generator. */ private MersenneTwister twister = null; /** * Log message in case of successful authentication. */ private static final String AUTH_OK = "Authorization OK"; /** * Log message in case of failed authentication. */ private static final String AUTH_FAIL = "Authorization failed"; /** * Generator constructor. * @param numberHosts Number of hosts in the scenario. * @param separator field separator. */ public AuthEventGenerator(int numberHosts, String separator){ //Fixed seed to reproduce patterns. twister = new MersenneTwister(numberHosts); this.numberHosts = numberHosts; this.separator = separator; } /** * Generate a random auth log entry. * @param successful Whether the authorization should be successful or not. * @return A line with the log. */ public String generateRandomEvent(boolean successful){ StringBuilder sb = new StringBuilder(new Date().toString()); sb.append(separator); sb.append("host").append(twister.nextInt(numberHosts)).append(separator); sb.append(processes[twister.nextInt(processes.length)]).append(separator); if(successful){ sb.append(AUTH_OK); }else{ sb.append(AUTH_FAIL); } return sb.toString(); } }
anazamarron/spark-streaming-exercises
src/main/java/org/spark/examples/events/AuthEventGenerator.java
Java
apache-2.0
2,512
package com.jia.imageprocess; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.GridLayout; import android.widget.ImageView; public class MatrixActivity extends Activity { GridLayout gridLayout; ImageView imageView; EditText[]editTexts; private ImageView mImageView; private GridLayout mGroup; private Bitmap bitmap; private int mEtWidth, mEtHeight; private EditText[] mEts = new EditText[20]; private float[] mColorMatrix = new float[20]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_matrix); bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test); mImageView = (ImageView) findViewById(R.id.image1); mGroup = (GridLayout) findViewById(R.id.grid); mImageView.setImageBitmap(bitmap); mGroup.post(new Runnable() { @Override public void run() { mEtWidth = mGroup.getWidth() / 5; mEtHeight = mGroup.getHeight() / 4; addEts(); initMatrix(); } }); } private void getMatrix() { for (int i = 0; i < 20; i++) { mColorMatrix[i] = Float.valueOf(mEts[i].getText().toString()); } } private void setImageMatrix() { Bitmap bmp = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); android.graphics.ColorMatrix colorMatrix = new android.graphics.ColorMatrix(); colorMatrix.set(mColorMatrix); Canvas canvas = new Canvas(bmp); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColorFilter(new ColorMatrixColorFilter(colorMatrix)); canvas.drawBitmap(bitmap, 0, 0, paint); mImageView.setImageBitmap(bmp); } public void btnChange(View view) { getMatrix(); setImageMatrix(); } public void btnReset(View view) { initMatrix(); getMatrix(); setImageMatrix(); } private void addEts() { for (int i = 0; i < 20; i++) { EditText editText = new EditText(this); mEts[i] = editText; mGroup.addView(editText, mEtWidth, mEtHeight); } } private void initMatrix() { for (int i = 0; i < 20; i++) { if (i % 6 == 0) { mEts[i].setText(String.valueOf(1)); } else { mEts[i].setText(String.valueOf(0)); } } } }
LearnJ/ImageProcess
src/com/jia/imageprocess/MatrixActivity.java
Java
apache-2.0
2,568
package db import ( "encoding/binary" "fmt" "sync" "github.com/google/orderedcode" dbm "github.com/tendermint/tm-db" "github.com/tendermint/tendermint/light/store" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/tendermint/tendermint/types" ) const ( prefixLightBlock = int64(11) prefixSize = int64(12) ) type dbs struct { db dbm.DB mtx sync.RWMutex size uint16 } // New returns a Store that wraps any DB // If you want to share one DB across many light clients consider using PrefixDB func New(db dbm.DB) store.Store { lightStore := &dbs{db: db} // retrieve the size of the db size := uint16(0) bz, err := lightStore.db.Get(lightStore.sizeKey()) if err == nil && len(bz) > 0 { size = unmarshalSize(bz) } lightStore.size = size return lightStore } // SaveLightBlock persists LightBlock to the db. // // Safe for concurrent use by multiple goroutines. func (s *dbs) SaveLightBlock(lb *types.LightBlock) error { if lb.Height <= 0 { panic("negative or zero height") } lbpb, err := lb.ToProto() if err != nil { return fmt.Errorf("unable to convert light block to protobuf: %w", err) } lbBz, err := lbpb.Marshal() if err != nil { return fmt.Errorf("marshaling LightBlock: %w", err) } s.mtx.Lock() defer s.mtx.Unlock() b := s.db.NewBatch() defer b.Close() if err = b.Set(s.lbKey(lb.Height), lbBz); err != nil { return err } if err = b.Set(s.sizeKey(), marshalSize(s.size+1)); err != nil { return err } if err = b.WriteSync(); err != nil { return err } s.size++ return nil } // DeleteLightBlockAndValidatorSet deletes the LightBlock from // the db. // // Safe for concurrent use by multiple goroutines. func (s *dbs) DeleteLightBlock(height int64) error { if height <= 0 { panic("negative or zero height") } s.mtx.Lock() defer s.mtx.Unlock() b := s.db.NewBatch() defer b.Close() if err := b.Delete(s.lbKey(height)); err != nil { return err } if err := b.Set(s.sizeKey(), marshalSize(s.size-1)); err != nil { return err } if err := b.WriteSync(); err != nil { return err } s.size-- return nil } // LightBlock retrieves the LightBlock at the given height. // // Safe for concurrent use by multiple goroutines. func (s *dbs) LightBlock(height int64) (*types.LightBlock, error) { if height <= 0 { panic("negative or zero height") } bz, err := s.db.Get(s.lbKey(height)) if err != nil { panic(err) } if len(bz) == 0 { return nil, store.ErrLightBlockNotFound } var lbpb tmproto.LightBlock err = lbpb.Unmarshal(bz) if err != nil { return nil, fmt.Errorf("unmarshal error: %w", err) } lightBlock, err := types.LightBlockFromProto(&lbpb) if err != nil { return nil, fmt.Errorf("proto conversion error: %w", err) } return lightBlock, err } // LastLightBlockHeight returns the last LightBlock height stored. // // Safe for concurrent use by multiple goroutines. func (s *dbs) LastLightBlockHeight() (int64, error) { itr, err := s.db.ReverseIterator( s.lbKey(1), append(s.lbKey(1<<63-1), byte(0x00)), ) if err != nil { panic(err) } defer itr.Close() if itr.Valid() { return s.decodeLbKey(itr.Key()) } return -1, itr.Error() } // FirstLightBlockHeight returns the first LightBlock height stored. // // Safe for concurrent use by multiple goroutines. func (s *dbs) FirstLightBlockHeight() (int64, error) { itr, err := s.db.Iterator( s.lbKey(1), append(s.lbKey(1<<63-1), byte(0x00)), ) if err != nil { panic(err) } defer itr.Close() if itr.Valid() { return s.decodeLbKey(itr.Key()) } return -1, itr.Error() } // LightBlockBefore iterates over light blocks until it finds a block before // the given height. It returns ErrLightBlockNotFound if no such block exists. // // Safe for concurrent use by multiple goroutines. func (s *dbs) LightBlockBefore(height int64) (*types.LightBlock, error) { if height <= 0 { panic("negative or zero height") } itr, err := s.db.ReverseIterator( s.lbKey(1), s.lbKey(height), ) if err != nil { panic(err) } defer itr.Close() if itr.Valid() { var lbpb tmproto.LightBlock err = lbpb.Unmarshal(itr.Value()) if err != nil { return nil, fmt.Errorf("unmarshal error: %w", err) } lightBlock, err := types.LightBlockFromProto(&lbpb) if err != nil { return nil, fmt.Errorf("proto conversion error: %w", err) } return lightBlock, nil } if err = itr.Error(); err != nil { return nil, err } return nil, store.ErrLightBlockNotFound } // Prune prunes header & validator set pairs until there are only size pairs // left. // // Safe for concurrent use by multiple goroutines. func (s *dbs) Prune(size uint16) error { // 1) Check how many we need to prune. s.mtx.Lock() defer s.mtx.Unlock() sSize := s.size if sSize <= size { // nothing to prune return nil } numToPrune := sSize - size b := s.db.NewBatch() defer b.Close() // 2) use an iterator to batch together all the blocks that need to be deleted if err := s.batchDelete(b, numToPrune); err != nil { return err } // 3) // update size s.size = size if err := b.Set(s.sizeKey(), marshalSize(size)); err != nil { return fmt.Errorf("failed to persist size: %w", err) } // 4) write batch deletion to disk return b.WriteSync() } // Size returns the number of header & validator set pairs. // // Safe for concurrent use by multiple goroutines. func (s *dbs) Size() uint16 { s.mtx.RLock() defer s.mtx.RUnlock() return s.size } func (s *dbs) batchDelete(batch dbm.Batch, numToPrune uint16) error { itr, err := s.db.Iterator( s.lbKey(1), append(s.lbKey(1<<63-1), byte(0x00)), ) if err != nil { return err } defer itr.Close() for itr.Valid() && numToPrune > 0 { if err = batch.Delete(itr.Key()); err != nil { return err } itr.Next() numToPrune-- } return itr.Error() } func (s *dbs) sizeKey() []byte { key, err := orderedcode.Append(nil, prefixSize) if err != nil { panic(err) } return key } func (s *dbs) lbKey(height int64) []byte { key, err := orderedcode.Append(nil, prefixLightBlock, height) if err != nil { panic(err) } return key } func (s *dbs) decodeLbKey(key []byte) (height int64, err error) { var lightBlockPrefix int64 remaining, err := orderedcode.Parse(string(key), &lightBlockPrefix, &height) if err != nil { err = fmt.Errorf("failed to parse light block key: %w", err) } if len(remaining) != 0 { err = fmt.Errorf("expected no remainder when parsing light block key but got: %s", remaining) } if lightBlockPrefix != prefixLightBlock { err = fmt.Errorf("expected light block prefix but got: %d", lightBlockPrefix) } return } func marshalSize(size uint16) []byte { bs := make([]byte, 2) binary.LittleEndian.PutUint16(bs, size) return bs } func unmarshalSize(bz []byte) uint16 { return binary.LittleEndian.Uint16(bz) }
tendermint/tendermint
light/store/db/db.go
GO
apache-2.0
6,818
// // 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: 2015.05.01 at 10:44:03 PM CEST // package org.openehealth.ipf.commons.xml.svrl; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" /> * &lt;attribute name="role" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "active-pattern") public class ActivePattern { @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; @XmlAttribute(name = "name") @XmlSchemaType(name = "anySimpleType") protected String name; @XmlAttribute(name = "role") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NMTOKEN") protected String role; /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the role property. * * @return * possible object is * {@link String } * */ public String getRole() { return role; } /** * Sets the value of the role property. * * @param value * allowed object is * {@link String } * */ public void setRole(String value) { this.role = value; } }
oehf/ipf
commons/xml/src/main/java/org/openehealth/ipf/commons/xml/svrl/ActivePattern.java
Java
apache-2.0
3,320
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package fconv // An extFloat represents an extended floating-point number, with more // precision than a float64. It does not try to save bits: the // number represented by the structure is mant*(2^exp), with a negative // sign if neg is true. type extFloat struct { mant uint64 exp int neg bool } // TODO: move elsewhere? type floatInfo struct { mantbits uint expbits uint bias int } var float64info = floatInfo{52, 11, -1023} // Powers of ten taken from double-conversion library. // http://code.google.com/p/double-conversion/ const ( firstPowerOfTen = -348 stepPowerOfTen = 8 ) var smallPowersOfTen = [...]extFloat{ {1 << 63, -63, false}, // 1 {0xa << 60, -60, false}, // 1e1 {0x64 << 57, -57, false}, // 1e2 {0x3e8 << 54, -54, false}, // 1e3 {0x2710 << 50, -50, false}, // 1e4 {0x186a0 << 47, -47, false}, // 1e5 {0xf4240 << 44, -44, false}, // 1e6 {0x989680 << 40, -40, false}, // 1e7 } var powersOfTen = [...]extFloat{ {0xfa8fd5a0081c0288, -1220, false}, // 10^-348 {0xbaaee17fa23ebf76, -1193, false}, // 10^-340 {0x8b16fb203055ac76, -1166, false}, // 10^-332 {0xcf42894a5dce35ea, -1140, false}, // 10^-324 {0x9a6bb0aa55653b2d, -1113, false}, // 10^-316 {0xe61acf033d1a45df, -1087, false}, // 10^-308 {0xab70fe17c79ac6ca, -1060, false}, // 10^-300 {0xff77b1fcbebcdc4f, -1034, false}, // 10^-292 {0xbe5691ef416bd60c, -1007, false}, // 10^-284 {0x8dd01fad907ffc3c, -980, false}, // 10^-276 {0xd3515c2831559a83, -954, false}, // 10^-268 {0x9d71ac8fada6c9b5, -927, false}, // 10^-260 {0xea9c227723ee8bcb, -901, false}, // 10^-252 {0xaecc49914078536d, -874, false}, // 10^-244 {0x823c12795db6ce57, -847, false}, // 10^-236 {0xc21094364dfb5637, -821, false}, // 10^-228 {0x9096ea6f3848984f, -794, false}, // 10^-220 {0xd77485cb25823ac7, -768, false}, // 10^-212 {0xa086cfcd97bf97f4, -741, false}, // 10^-204 {0xef340a98172aace5, -715, false}, // 10^-196 {0xb23867fb2a35b28e, -688, false}, // 10^-188 {0x84c8d4dfd2c63f3b, -661, false}, // 10^-180 {0xc5dd44271ad3cdba, -635, false}, // 10^-172 {0x936b9fcebb25c996, -608, false}, // 10^-164 {0xdbac6c247d62a584, -582, false}, // 10^-156 {0xa3ab66580d5fdaf6, -555, false}, // 10^-148 {0xf3e2f893dec3f126, -529, false}, // 10^-140 {0xb5b5ada8aaff80b8, -502, false}, // 10^-132 {0x87625f056c7c4a8b, -475, false}, // 10^-124 {0xc9bcff6034c13053, -449, false}, // 10^-116 {0x964e858c91ba2655, -422, false}, // 10^-108 {0xdff9772470297ebd, -396, false}, // 10^-100 {0xa6dfbd9fb8e5b88f, -369, false}, // 10^-92 {0xf8a95fcf88747d94, -343, false}, // 10^-84 {0xb94470938fa89bcf, -316, false}, // 10^-76 {0x8a08f0f8bf0f156b, -289, false}, // 10^-68 {0xcdb02555653131b6, -263, false}, // 10^-60 {0x993fe2c6d07b7fac, -236, false}, // 10^-52 {0xe45c10c42a2b3b06, -210, false}, // 10^-44 {0xaa242499697392d3, -183, false}, // 10^-36 {0xfd87b5f28300ca0e, -157, false}, // 10^-28 {0xbce5086492111aeb, -130, false}, // 10^-20 {0x8cbccc096f5088cc, -103, false}, // 10^-12 {0xd1b71758e219652c, -77, false}, // 10^-4 {0x9c40000000000000, -50, false}, // 10^4 {0xe8d4a51000000000, -24, false}, // 10^12 {0xad78ebc5ac620000, 3, false}, // 10^20 {0x813f3978f8940984, 30, false}, // 10^28 {0xc097ce7bc90715b3, 56, false}, // 10^36 {0x8f7e32ce7bea5c70, 83, false}, // 10^44 {0xd5d238a4abe98068, 109, false}, // 10^52 {0x9f4f2726179a2245, 136, false}, // 10^60 {0xed63a231d4c4fb27, 162, false}, // 10^68 {0xb0de65388cc8ada8, 189, false}, // 10^76 {0x83c7088e1aab65db, 216, false}, // 10^84 {0xc45d1df942711d9a, 242, false}, // 10^92 {0x924d692ca61be758, 269, false}, // 10^100 {0xda01ee641a708dea, 295, false}, // 10^108 {0xa26da3999aef774a, 322, false}, // 10^116 {0xf209787bb47d6b85, 348, false}, // 10^124 {0xb454e4a179dd1877, 375, false}, // 10^132 {0x865b86925b9bc5c2, 402, false}, // 10^140 {0xc83553c5c8965d3d, 428, false}, // 10^148 {0x952ab45cfa97a0b3, 455, false}, // 10^156 {0xde469fbd99a05fe3, 481, false}, // 10^164 {0xa59bc234db398c25, 508, false}, // 10^172 {0xf6c69a72a3989f5c, 534, false}, // 10^180 {0xb7dcbf5354e9bece, 561, false}, // 10^188 {0x88fcf317f22241e2, 588, false}, // 10^196 {0xcc20ce9bd35c78a5, 614, false}, // 10^204 {0x98165af37b2153df, 641, false}, // 10^212 {0xe2a0b5dc971f303a, 667, false}, // 10^220 {0xa8d9d1535ce3b396, 694, false}, // 10^228 {0xfb9b7cd9a4a7443c, 720, false}, // 10^236 {0xbb764c4ca7a44410, 747, false}, // 10^244 {0x8bab8eefb6409c1a, 774, false}, // 10^252 {0xd01fef10a657842c, 800, false}, // 10^260 {0x9b10a4e5e9913129, 827, false}, // 10^268 {0xe7109bfba19c0c9d, 853, false}, // 10^276 {0xac2820d9623bf429, 880, false}, // 10^284 {0x80444b5e7aa7cf85, 907, false}, // 10^292 {0xbf21e44003acdd2d, 933, false}, // 10^300 {0x8e679c2f5e44ff8f, 960, false}, // 10^308 {0xd433179d9c8cb841, 986, false}, // 10^316 {0x9e19db92b4e31ba9, 1013, false}, // 10^324 {0xeb96bf6ebadf77d9, 1039, false}, // 10^332 {0xaf87023b9bf0ee6b, 1066, false}, // 10^340 } // floatBits returns the bits of the float64 that best approximates // the extFloat passed as receiver. Overflow is set to true if // the resulting float64 is ±Inf. func (f *extFloat) floatBits(flt *floatInfo) (bits uint64, overflow bool) { f.Normalize() exp := f.exp + 63 // Exponent too small. if exp < flt.bias+1 { n := flt.bias + 1 - exp f.mant >>= uint(n) exp += n } // Extract 1+flt.mantbits bits from the 64-bit mantissa. mant := f.mant >> (63 - flt.mantbits) if f.mant&(1<<(62-flt.mantbits)) != 0 { // Round up. mant += 1 } // Rounding might have added a bit; shift down. if mant == 2<<flt.mantbits { mant >>= 1 exp++ } // Infinities. if exp-flt.bias >= 1<<flt.expbits-1 { // ±Inf mant = 0 exp = 1<<flt.expbits - 1 + flt.bias overflow = true } else if mant&(1<<flt.mantbits) == 0 { // Denormalized? exp = flt.bias } // Assemble bits. bits = mant & (uint64(1)<<flt.mantbits - 1) bits |= uint64((exp-flt.bias)&(1<<flt.expbits-1)) << flt.mantbits if f.neg { bits |= 1 << (flt.mantbits + flt.expbits) } return } // AssignComputeBounds sets f to the floating point value // defined by mant, exp and precision given by flt. It returns // lower, upper such that any number in the closed interval // [lower, upper] is converted back to the same floating point number. func (f *extFloat) AssignComputeBounds(mant uint64, exp int, neg bool, flt *floatInfo) (lower, upper extFloat) { f.mant = mant f.exp = exp - int(flt.mantbits) f.neg = neg if f.exp <= 0 && mant == (mant>>uint(-f.exp))<<uint(-f.exp) { // An exact integer f.mant >>= uint(-f.exp) f.exp = 0 return *f, *f } expBiased := exp - flt.bias upper = extFloat{mant: 2*f.mant + 1, exp: f.exp - 1, neg: f.neg} if mant != 1<<flt.mantbits || expBiased == 1 { lower = extFloat{mant: 2*f.mant - 1, exp: f.exp - 1, neg: f.neg} } else { lower = extFloat{mant: 4*f.mant - 1, exp: f.exp - 2, neg: f.neg} } return } // Normalize normalizes f so that the highest bit of the mantissa is // set, and returns the number by which the mantissa was left-shifted. func (f *extFloat) Normalize() (shift uint) { mant, exp := f.mant, f.exp if mant == 0 { return 0 } if mant>>(64-32) == 0 { mant <<= 32 exp -= 32 } if mant>>(64-16) == 0 { mant <<= 16 exp -= 16 } if mant>>(64-8) == 0 { mant <<= 8 exp -= 8 } if mant>>(64-4) == 0 { mant <<= 4 exp -= 4 } if mant>>(64-2) == 0 { mant <<= 2 exp -= 2 } if mant>>(64-1) == 0 { mant <<= 1 exp -= 1 } shift = uint(f.exp - exp) f.mant, f.exp = mant, exp return } // Multiply sets f to the product f*g: the result is correctly rounded, // but not normalized. func (f *extFloat) Multiply(g extFloat) { fhi, flo := f.mant>>32, uint64(uint32(f.mant)) ghi, glo := g.mant>>32, uint64(uint32(g.mant)) // Cross products. cross1 := fhi * glo cross2 := flo * ghi // f.mant*g.mant is fhi*ghi << 64 + (cross1+cross2) << 32 + flo*glo f.mant = fhi*ghi + (cross1 >> 32) + (cross2 >> 32) rem := uint64(uint32(cross1)) + uint64(uint32(cross2)) + ((flo * glo) >> 32) // Round up. rem += (1 << 31) f.mant += (rem >> 32) f.exp = f.exp + g.exp + 64 } var uint64pow10 = [...]uint64{ 1, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, } // AssignDecimal sets f to an approximate value mantissa*10^exp. It // reports whether the value represented by f is guaranteed to be the // best approximation of d after being rounded to a float64 or // float32 depending on flt. func (f *extFloat) AssignDecimal(mantissa uint64, exp10 int, neg bool, trunc bool, flt *floatInfo) (ok bool) { const uint64digits = 19 const errorscale = 8 errors := 0 // An upper bound for error, computed in errorscale*ulp. if trunc { // the decimal number was truncated. errors += errorscale / 2 } f.mant = mantissa f.exp = 0 f.neg = neg // Multiply by powers of ten. i := (exp10 - firstPowerOfTen) / stepPowerOfTen if exp10 < firstPowerOfTen || i >= len(powersOfTen) { return false } adjExp := (exp10 - firstPowerOfTen) % stepPowerOfTen // We multiply by exp%step if adjExp < uint64digits && mantissa < uint64pow10[uint64digits-adjExp] { // We can multiply the mantissa exactly. f.mant *= uint64pow10[adjExp] f.Normalize() } else { f.Normalize() f.Multiply(smallPowersOfTen[adjExp]) errors += errorscale / 2 } // We multiply by 10 to the exp - exp%step. f.Multiply(powersOfTen[i]) if errors > 0 { errors += 1 } errors += errorscale / 2 // Normalize shift := f.Normalize() errors <<= shift // Now f is a good approximation of the decimal. // Check whether the error is too large: that is, if the mantissa // is perturbated by the error, the resulting float64 will change. // The 64 bits mantissa is 1 + 52 bits for float64 + 11 extra bits. // // In many cases the approximation will be good enough. denormalExp := flt.bias - 63 var extrabits uint if f.exp <= denormalExp { // f.mant * 2^f.exp is smaller than 2^(flt.bias+1). extrabits = 63 - flt.mantbits + 1 + uint(denormalExp-f.exp) } else { extrabits = 63 - flt.mantbits } halfway := uint64(1) << (extrabits - 1) mant_extra := f.mant & (1<<extrabits - 1) // Do a signed comparison here! If the error estimate could make // the mantissa round differently for the conversion to double, // then we can't give a definite answer. if int64(halfway)-int64(errors) < int64(mant_extra) && int64(mant_extra) < int64(halfway)+int64(errors) { return false } return true } // Frexp10 is an analogue of math.Frexp for decimal powers. It scales // f by an approximate power of ten 10^-exp, and returns exp10, so // that f*10^exp10 has the same value as the old f, up to an ulp, // as well as the index of 10^-exp in the powersOfTen table. func (f *extFloat) frexp10() (exp10, index int) { // The constants expMin and expMax constrain the final value of the // binary exponent of f. We want a small integral part in the result // because finding digits of an integer requires divisions, whereas // digits of the fractional part can be found by repeatedly multiplying // by 10. const expMin = -60 const expMax = -32 // Find power of ten such that x * 10^n has a binary exponent // between expMin and expMax. approxExp10 := ((expMin+expMax)/2 - f.exp) * 28 / 93 // log(10)/log(2) is close to 93/28. i := (approxExp10 - firstPowerOfTen) / stepPowerOfTen Loop: for { exp := f.exp + powersOfTen[i].exp + 64 switch { case exp < expMin: i++ case exp > expMax: i-- default: break Loop } } // Apply the desired decimal shift on f. It will have exponent // in the desired range. This is multiplication by 10^-exp10. f.Multiply(powersOfTen[i]) return -(firstPowerOfTen + i*stepPowerOfTen), i } // frexp10Many applies a common shift by a power of ten to a, b, c. func frexp10Many(a, b, c *extFloat) (exp10 int) { exp10, i := c.frexp10() a.Multiply(powersOfTen[i]) b.Multiply(powersOfTen[i]) return }
connectordb/duck
quack/fconv/extfloats.go
GO
apache-2.0
12,225
// Author: Charles var ResultMessage = require('./ResultMessage'); var Ladder = require('./Ladder'); var RandomUtil = require('./RandomUtil'); var util = require('util'); var ladderTime = require('../model/LadderTime.json'); var schedule = require('node-schedule'); var ladderManager = null; function LadderManager() { var games = {}; this.getRandomTime = function(time) { var randomDay = RandomUtil.randomFromRange(time.dayofweek); var hour = RandomUtil.randomFromRange(time.hour); var minute = RandomUtil.randomFromRange(time.minute); return util.format('%s %s * * %s', minute, hour, randomDay); } this.run = function(ladderRunner) { var resultMessage = new ResultMessage(); resultMessage.message = '랜덤 사다리 알람 설정 완료!!'; resultMessage.result = true; var jobs = {}; for(var key in ladderTime) { var timeStr = this.getRandomTime(ladderTime[key]); console.log(key + ': ' + timeStr); schedule.scheduleJob(key, this.getRandomTime(ladderTime[key]), function () { pushMessage(); }); } var weeklyTime = util.format('0 0 * * 0'); var weeklyLadderManageJob = schedule.scheduleJob(weeklyTime, function () { schedule.rescheduleJob(ladderJob, this.getRandomTime()); }); return resultMessage; } } function getLadderManager() { if(!ladderManager) { ladderManager = new LadderManager(); } return ladderManager; } function LadderRunner() { this.ladderManager = getLadderManager(); } LadderRunner.prototype.run = function() { return this.ladderManager.run(this); } LadderRunner.prototype.setChannelAccessToken = function(_token) { this.token = _token; } LadderRunner.prototype.getChannelAccessToken = function() { return this.token; } LadderRunner.prototype.setId = function(_id) { this.id = _id; } LadderRunner.prototype.getId = function() { return this.id; } LadderRunner.prototype.getQuery = function() { return this.query; } LadderRunner.prototype.getResult = function() { return this.result; } module.exports = LadderRunner;
Charleslee522/8ctci
server/MasterOfTime/controller/LadderRunner.js
JavaScript
apache-2.0
2,122
/* * 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.psi.impl.compiled; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.impl.ResolveScopeManager; import com.intellij.psi.impl.cache.TypeAnnotationContainer; import com.intellij.psi.impl.cache.TypeInfo; import com.intellij.psi.impl.source.resolve.ResolveCache; import com.intellij.psi.impl.source.tree.JavaElementType; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.psi.infos.CandidateInfo; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.IncorrectOperationException; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class ClsJavaCodeReferenceElementImpl extends ClsElementImpl implements PsiAnnotatedJavaCodeReferenceElement { private final PsiElement myParent; private final String myCanonicalText; private final String myQualifiedName; private final PsiReferenceParameterList myRefParameterList; private final TypeAnnotationContainer myAnnotations; private final ClsJavaCodeReferenceElementImpl myQualifier; public ClsJavaCodeReferenceElementImpl(@Nonnull PsiElement parent, @Nonnull String canonicalText) { this(parent, canonicalText, TypeAnnotationContainer.EMPTY); } public ClsJavaCodeReferenceElementImpl(@Nonnull PsiElement parent, @Nonnull String canonicalText, @Nonnull TypeAnnotationContainer annotations) { myParent = parent; String canonical = TypeInfo.internFrequentType(canonicalText); myCanonicalText = canonical; String qName = TypeInfo.internFrequentType(PsiNameHelper.getQualifiedClassName(myCanonicalText, false)); myQualifiedName = qName.equals(canonical) ? canonical : qName; String[] classParameters = PsiNameHelper.getClassParametersText(canonicalText); myRefParameterList = classParameters.length == 0 ? null : new ClsReferenceParameterListImpl(this, classParameters, annotations); myAnnotations = annotations; String prefix = PsiNameHelper.getOuterClassReference(canonicalText); TypeAnnotationContainer container = prefix.isEmpty() ? TypeAnnotationContainer.EMPTY : annotations.forEnclosingClass(); myQualifier = container.isEmpty() ? null : new ClsJavaCodeReferenceElementImpl(this, prefix, container); } @Override @Nonnull public PsiElement[] getChildren() { if(myQualifier != null) { return myRefParameterList != null ? new PsiElement[]{ myQualifier, myRefParameterList } : new PsiElement[]{myQualifier}; } return myRefParameterList != null ? new PsiElement[]{myRefParameterList} : PsiElement.EMPTY_ARRAY; } @Override public PsiElement getParent() { return myParent; } @Override public String getText() { return PsiNameHelper.getPresentableText(this); } @Override public int getTextLength() { return getText().length(); } @Override public PsiReference getReference() { return this; } @Override @Nonnull public String getCanonicalText() { return myCanonicalText; } @Nonnull @Override public String getCanonicalText(boolean annotated, @Nullable PsiAnnotation[] annotations) { String text = getCanonicalText(); if(!annotated || annotations == null) { return text; } StringBuilder sb = new StringBuilder(); String prefix = PsiNameHelper.getOuterClassReference(text); int simpleNamePos = 0; if(!StringUtil.isEmpty(prefix)) { if(myQualifier != null) { sb.append(myQualifier.getCanonicalText(true, myQualifier.myAnnotations.getProvider(myQualifier).getAnnotations())); } else { sb.append(prefix); } sb.append('.'); simpleNamePos = prefix.length() + 1; } PsiNameHelper.appendAnnotations(sb, Arrays.asList(annotations), true); int typeArgPos = text.indexOf('<', simpleNamePos); if(typeArgPos == -1) { sb.append(text, simpleNamePos, text.length()); } else { sb.append(text, simpleNamePos, typeArgPos); PsiNameHelper.appendTypeArgs(sb, getTypeParameters(), true, true); } return sb.toString(); } private static class Resolver implements ResolveCache.PolyVariantContextResolver<ClsJavaCodeReferenceElementImpl> { public static final Resolver INSTANCE = new Resolver(); @Override @Nonnull public JavaResolveResult[] resolve(@Nonnull ClsJavaCodeReferenceElementImpl ref, @Nonnull PsiFile containingFile, boolean incompleteCode) { final JavaResolveResult resolveResult = ref.advancedResolveImpl(containingFile); return resolveResult == null ? JavaResolveResult.EMPTY_ARRAY : new JavaResolveResult[]{resolveResult}; } } private JavaResolveResult advancedResolveImpl(@Nonnull PsiFile containingFile) { PsiTypeElement[] typeElements = myRefParameterList == null ? PsiTypeElement.EMPTY_ARRAY : myRefParameterList.getTypeParameterElements(); PsiElement resolve = resolveElement(containingFile); if(resolve == null) { return null; } if(resolve instanceof PsiClass) { Map<PsiTypeParameter, PsiType> substitutionMap = new HashMap<>(); int index = 0; for(PsiTypeParameter parameter : PsiUtil.typeParametersIterable((PsiClass) resolve)) { if(index >= typeElements.length) { substitutionMap.put(parameter, null); } else { substitutionMap.put(parameter, typeElements[index].getType()); } index++; } collectOuterClassTypeArgs((PsiClass) resolve, myCanonicalText, substitutionMap); return new CandidateInfo(resolve, PsiSubstitutor.createSubstitutor(substitutionMap)); } else { return new CandidateInfo(resolve, PsiSubstitutor.EMPTY); } } private void collectOuterClassTypeArgs(@Nonnull PsiClass psiClass, final String canonicalText, final Map<PsiTypeParameter, PsiType> substitutionMap) { final PsiClass containingClass = psiClass.getContainingClass(); if(containingClass != null) { final String outerClassRef = PsiNameHelper.getOuterClassReference(canonicalText); final String[] classParameters = PsiNameHelper.getClassParametersText(outerClassRef); final PsiType[] args = classParameters.length == 0 ? null : new ClsReferenceParameterListImpl(this, classParameters, TypeAnnotationContainer.EMPTY).getTypeArguments(); final PsiTypeParameter[] typeParameters = containingClass.getTypeParameters(); for(int i = 0; i < typeParameters.length; i++) { if(args != null) { if(i < args.length) { substitutionMap.put(typeParameters[i], args[i]); } } else { substitutionMap.put(typeParameters[i], null); } } if(!containingClass.hasModifierProperty(PsiModifier.STATIC)) { collectOuterClassTypeArgs(containingClass, outerClassRef, substitutionMap); } } } @Override @Nonnull public JavaResolveResult advancedResolve(boolean incompleteCode) { final JavaResolveResult[] results = multiResolve(incompleteCode); if(results.length == 1) { return results[0]; } return JavaResolveResult.EMPTY; } @Override @Nonnull public JavaResolveResult[] multiResolve(boolean incompleteCode) { PsiFile file = getContainingFile(); if(file == null) { return diagnoseNoFile(); } final ResolveCache resolveCache = ResolveCache.getInstance(file.getProject()); ResolveResult[] results = resolveCache.resolveWithCaching(this, Resolver.INSTANCE, true, incompleteCode, file); if(results.length == 0) { return JavaResolveResult.EMPTY_ARRAY; } return (JavaResolveResult[]) results; } @Nonnull private JavaResolveResult[] diagnoseNoFile() { PsiElement root = SyntaxTraverser.psiApi().parents(this).last(); PsiUtilCore.ensureValid(Objects.requireNonNull(root)); throw new PsiInvalidElementAccessException(this, "parent=" + myParent + ", root=" + root + ", canonicalText=" + myCanonicalText); } @Override public PsiElement resolve() { return advancedResolve(false).getElement(); } @Nullable private PsiElement resolveElement(@Nonnull PsiFile containingFile) { PsiElement element = getParent(); while(element != null && !(element instanceof PsiFile)) { if(element instanceof PsiMethod) { for(PsiTypeParameter parameter : PsiUtil.typeParametersIterable((PsiMethod) element)) { if(myQualifiedName.equals(parameter.getName())) { return parameter; } } } else if(element instanceof PsiClass && !(element instanceof PsiTypeParameter)) { PsiClass psiClass = (PsiClass) element; if(myQualifiedName.equals(psiClass.getQualifiedName())) { return element; } for(PsiTypeParameter parameter : PsiUtil.typeParametersIterable(psiClass)) { if(myQualifiedName.equals(parameter.getName())) { return parameter; } } for(PsiClass innerClass : psiClass.getInnerClasses()) { if(myQualifiedName.equals(innerClass.getQualifiedName())) { return innerClass; } } } element = element.getParent(); } Project project = containingFile.getProject(); GlobalSearchScope scope = ResolveScopeManager.getInstance(project).getResolveScope(this); return JavaPsiFacade.getInstance(project).findClass(myQualifiedName, scope); } @Override public void processVariants(@Nonnull PsiScopeProcessor processor) { throw new RuntimeException("Variants are not available for light references"); } @Override public PsiElement getReferenceNameElement() { return null; } @Override public PsiReferenceParameterList getParameterList() { return myRefParameterList; } @Override public String getQualifiedName() { return getCanonicalText(); } @Override public String getReferenceName() { return PsiNameHelper.getShortClassName(myCanonicalText); } @Override public PsiElement handleElementRename(@Nonnull String newElementName) throws IncorrectOperationException { throw cannotModifyException(this); } @Override public PsiElement bindToElement(@Nonnull PsiElement element) throws IncorrectOperationException { throw cannotModifyException(this); } @Override public boolean isReferenceTo(@Nonnull PsiElement element) { if(!(element instanceof PsiClass)) { return false; } PsiClass aClass = (PsiClass) element; return myCanonicalText.equals(aClass.getQualifiedName()) || getManager().areElementsEquivalent(resolve(), element); } @Override @Nonnull public Object[] getVariants() { throw new RuntimeException("Variants are not available for references to compiled code"); } @Override public boolean isSoft() { return false; } @Override public void appendMirrorText(final int indentLevel, @Nonnull final StringBuilder buffer) { buffer.append(getCanonicalText()); } @Override public void setMirror(@Nonnull TreeElement element) throws InvalidMirrorException { setMirrorCheckingType(element, JavaElementType.JAVA_CODE_REFERENCE); } @Override public void accept(@Nonnull PsiElementVisitor visitor) { if(visitor instanceof JavaElementVisitor) { ((JavaElementVisitor) visitor).visitReferenceElement(this); } else { visitor.visitElement(this); } } @Nonnull @Override public TextRange getRangeInElement() { return new TextRange(0, getTextLength()); } @Nonnull @Override public PsiElement getElement() { return this; } @Override @Nonnull public PsiType[] getTypeParameters() { return myRefParameterList == null ? PsiType.EMPTY_ARRAY : myRefParameterList.getTypeArguments(); } @Override public boolean isQualified() { return false; } @Override public PsiElement getQualifier() { return null; } @Override public String toString() { return "PsiJavaCodeReferenceElement:" + getText(); } }
consulo/consulo-java
java-psi-impl/src/main/java/com/intellij/psi/impl/compiled/ClsJavaCodeReferenceElementImpl.java
Java
apache-2.0
12,490
import requests import pytest import subprocess import os from settings import TEST_DATA from suite.custom_resources_utils import ( create_dos_logconf_from_yaml, create_dos_policy_from_yaml, create_dos_protected_from_yaml, delete_dos_policy, delete_dos_logconf, delete_dos_protected, ) from suite.dos_utils import find_in_log, log_content_to_dic from suite.resources_utils import ( wait_before_test, create_example_app, wait_until_all_pods_are_ready, create_items_from_yaml, delete_items_from_yaml, delete_common_app, ensure_connection_to_public_endpoint, create_ingress_with_dos_annotations, ensure_response_from_backend, get_ingress_nginx_template_conf, get_file_contents, get_test_file_name, write_to_json, replace_configmap_from_yaml, scale_deployment, nginx_reload, get_pods_amount, get_pods_amount_with_name, clear_file_contents, ) from suite.yaml_utils import get_first_ingress_host_from_yaml from datetime import datetime src_ing_yaml = f"{TEST_DATA}/dos/dos-ingress.yaml" valid_resp_addr = "Server address:" valid_resp_name = "Server name:" invalid_resp_title = "Request Rejected" invalid_resp_body = "The requested URL was rejected. Please consult with your administrator." reload_times = {} class DosSetup: """ Encapsulate the example details. Attributes: req_url (str): pol_name (str): log_name (str): """ def __init__(self, req_url, pol_name, log_name): self.req_url = req_url self.pol_name = pol_name self.log_name = log_name @pytest.fixture(scope="class") def dos_setup( request, kube_apis, ingress_controller_endpoint, ingress_controller_prerequisites, test_namespace ) -> DosSetup: """ Deploy simple application and all the DOS resources under test in one namespace. :param request: pytest fixture :param kube_apis: client apis :param ingress_controller_endpoint: public endpoint :param ingress_controller_prerequisites: IC pre-requisites :param test_namespace: :return: DosSetup """ print(f"------------- Replace ConfigMap --------------") replace_configmap_from_yaml( kube_apis.v1, ingress_controller_prerequisites.config_map["metadata"]["name"], ingress_controller_prerequisites.namespace, f"{TEST_DATA}/dos/nginx-config.yaml" ) print("------------------------- Deploy Dos backend application -------------------------") create_example_app(kube_apis, "dos", test_namespace) req_url = f"http://{ingress_controller_endpoint.public_ip}:{ingress_controller_endpoint.port}/" wait_until_all_pods_are_ready(kube_apis.v1, test_namespace) ensure_connection_to_public_endpoint( ingress_controller_endpoint.public_ip, ingress_controller_endpoint.port, ingress_controller_endpoint.port_ssl, ) print("------------------------- Deploy Secret -----------------------------") src_sec_yaml = f"{TEST_DATA}/dos/dos-secret.yaml" create_items_from_yaml(kube_apis, src_sec_yaml, test_namespace) print("------------------------- Deploy logconf -----------------------------") src_log_yaml = f"{TEST_DATA}/dos/dos-logconf.yaml" log_name = create_dos_logconf_from_yaml(kube_apis.custom_objects, src_log_yaml, test_namespace) print(f"------------------------- Deploy dospolicy ---------------------------") src_pol_yaml = f"{TEST_DATA}/dos/dos-policy.yaml" pol_name = create_dos_policy_from_yaml(kube_apis.custom_objects, src_pol_yaml, test_namespace) print(f"------------------------- Deploy protected resource ---------------------------") src_protected_yaml = f"{TEST_DATA}/dos/dos-protected.yaml" protected_name = create_dos_protected_from_yaml(kube_apis.custom_objects, src_protected_yaml, test_namespace, ingress_controller_prerequisites.namespace) for item in kube_apis.v1.list_namespaced_pod(ingress_controller_prerequisites.namespace).items: if "nginx-ingress" in item.metadata.name: nginx_reload(kube_apis.v1, item.metadata.name, ingress_controller_prerequisites.namespace) def fin(): print("Clean up:") delete_dos_policy(kube_apis.custom_objects, pol_name, test_namespace) delete_dos_logconf(kube_apis.custom_objects, log_name, test_namespace) delete_dos_protected(kube_apis.custom_objects, protected_name, test_namespace) delete_common_app(kube_apis, "dos", test_namespace) delete_items_from_yaml(kube_apis, src_sec_yaml, test_namespace) write_to_json(f"reload-{get_test_file_name(request.node.fspath)}.json", reload_times) request.addfinalizer(fin) return DosSetup(req_url, pol_name, log_name) @pytest.mark.dos @pytest.mark.parametrize( "crd_ingress_controller_with_dos", [ { "extra_args": [ f"-enable-custom-resources", f"-enable-app-protect-dos", f"-v=3", ] } ], indirect=["crd_ingress_controller_with_dos"], ) class TestDos: def getPodNameThatContains(self, kube_apis, namespace, contains_string): for item in kube_apis.v1.list_namespaced_pod(namespace).items: if contains_string in item.metadata.name: return item.metadata.name return "" def test_ap_nginx_config_entries( self, kube_apis, ingress_controller_prerequisites, crd_ingress_controller_with_dos, dos_setup, test_namespace ): """ Test to verify Dos directive in nginx config """ conf_directive = [ f"app_protect_dos_enable on;", f"app_protect_dos_security_log_enable on;", f"app_protect_dos_monitor uri=dos.example.com protocol=http1 timeout=5;", f"app_protect_dos_name \"{test_namespace}/dos-protected/name\";", f"app_protect_dos_policy_file /etc/nginx/dos/policies/{test_namespace}_{dos_setup.pol_name}.json;", f"app_protect_dos_security_log_enable on;", f"app_protect_dos_security_log /etc/nginx/dos/logconfs/{test_namespace}_{dos_setup.log_name}.json syslog:server=syslog-svc.{ingress_controller_prerequisites.namespace}.svc.cluster.local:514;", ] create_ingress_with_dos_annotations( kube_apis, src_ing_yaml, test_namespace, test_namespace + "/dos-protected", ) ingress_host = get_first_ingress_host_from_yaml(src_ing_yaml) ensure_response_from_backend(dos_setup.req_url, ingress_host, check404=True) pod_name = self.getPodNameThatContains(kube_apis, ingress_controller_prerequisites.namespace, "nginx-ingress") result_conf = get_ingress_nginx_template_conf( kube_apis.v1, test_namespace, "dos-ingress", pod_name, "nginx-ingress" ) delete_items_from_yaml(kube_apis, src_ing_yaml, test_namespace) for _ in conf_directive: assert _ in result_conf def test_dos_sec_logs_on( self, kube_apis, ingress_controller_prerequisites, crd_ingress_controller_with_dos, dos_setup, test_namespace, ): """ Test corresponding log entries with correct policy (includes setting up a syslog server as defined in syslog.yaml) """ print("----------------------- Get syslog pod name ----------------------") syslog_pod = self.getPodNameThatContains(kube_apis, ingress_controller_prerequisites.namespace, "syslog") assert "syslog" in syslog_pod log_loc = f"/var/log/messages" clear_file_contents(kube_apis.v1, log_loc, syslog_pod, ingress_controller_prerequisites.namespace) create_ingress_with_dos_annotations( kube_apis, src_ing_yaml, test_namespace, test_namespace+"/dos-protected" ) ingress_host = get_first_ingress_host_from_yaml(src_ing_yaml) print("--------- Run test while DOS module is enabled with correct policy ---------") ensure_response_from_backend(dos_setup.req_url, ingress_host, check404=True) pod_name = self.getPodNameThatContains(kube_apis, ingress_controller_prerequisites.namespace, "nginx-ingress") get_ingress_nginx_template_conf( kube_apis.v1, test_namespace, "dos-ingress", pod_name, "nginx-ingress" ) print("----------------------- Send request ----------------------") response = requests.get( dos_setup.req_url, headers={"host": "dos.example.com"}, verify=False ) print(response.text) wait_before_test(10) print(f'log_loc {log_loc} syslog_pod {syslog_pod} namespace {ingress_controller_prerequisites.namespace}') log_contents = get_file_contents(kube_apis.v1, log_loc, syslog_pod, ingress_controller_prerequisites.namespace) delete_items_from_yaml(kube_apis, src_ing_yaml, test_namespace) print(log_contents) assert 'product="app-protect-dos"' in log_contents assert f'vs_name="{test_namespace}/dos-protected/name"' in log_contents assert 'bad_actor' in log_contents @pytest.mark.skip def test_dos_under_attack_no_learning( self, kube_apis, ingress_controller_prerequisites, crd_ingress_controller_with_dos, dos_setup, test_namespace ): """ Test App Protect Dos: Block bad clients attack """ log_loc = f"/var/log/messages" print("----------------------- Get syslog pod name ----------------------") syslog_pod = self.getPodNameThatContains(kube_apis, ingress_controller_prerequisites.namespace, "syslog") assert "syslog" in syslog_pod clear_file_contents(kube_apis.v1, log_loc, syslog_pod, ingress_controller_prerequisites.namespace) print("------------------------- Deploy ingress -----------------------------") create_ingress_with_dos_annotations( kube_apis, src_ing_yaml, test_namespace, test_namespace+"/dos-protected" ) ingress_host = get_first_ingress_host_from_yaml(src_ing_yaml) print("------------------------- Attack -----------------------------") wait_before_test(10) print("start bad clients requests") p_attack = subprocess.Popen( [f"exec {TEST_DATA}/dos/bad_clients_xff.sh {ingress_host} {dos_setup.req_url}"], shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) print("Attack for 30 seconds") wait_before_test(30) print("Stop Attack") p_attack.terminate() print("wait max 140 seconds after attack stop, to get attack ended") find_in_log(kube_apis, log_loc, syslog_pod, ingress_controller_prerequisites.namespace, 140, "attack_event=\"Attack ended\"") log_contents = get_file_contents(kube_apis.v1, log_loc, syslog_pod, ingress_controller_prerequisites.namespace) log_info_dic = log_content_to_dic(log_contents) # Analyze the log no_attack = False attack_started = False under_attack = False attack_ended = False for log in log_info_dic: # Start with no attack if log['attack_event'] == "No Attack" and int(log['dos_attack_id']) == 0 and not no_attack: no_attack = True # Attack started elif log['attack_event'] == "Attack started" and int(log['dos_attack_id']) > 0 and not attack_started: attack_started = True # Under attack elif log['attack_event'] == "Under Attack" and int(log['dos_attack_id']) > 0 and not under_attack: under_attack = True # Attack ended elif log['attack_event'] == "Attack ended" and int(log['dos_attack_id']) > 0 and not attack_ended: attack_ended = True delete_items_from_yaml(kube_apis, src_ing_yaml, test_namespace) assert ( no_attack and attack_started and under_attack and attack_ended ) @pytest.mark.skip def test_dos_under_attack_with_learning( self, kube_apis, ingress_controller_prerequisites, crd_ingress_controller_with_dos, dos_setup, test_namespace ): """ Test App Protect Dos: Block bad clients attack with learning """ log_loc = f"/var/log/messages" print("----------------------- Get syslog pod name ----------------------") syslog_pod = self.getPodNameThatContains(kube_apis, ingress_controller_prerequisites.namespace, "syslog") assert "syslog" in syslog_pod clear_file_contents(kube_apis.v1, log_loc, syslog_pod, ingress_controller_prerequisites.namespace) print("------------------------- Deploy ingress -----------------------------") create_ingress_with_dos_annotations( kube_apis, src_ing_yaml, test_namespace, test_namespace+"/dos-protected" ) ingress_host = get_first_ingress_host_from_yaml(src_ing_yaml) print("------------------------- Learning Phase -----------------------------") print("start good clients requests") p_good_client = subprocess.Popen( [f"exec {TEST_DATA}/dos/good_clients_xff.sh {ingress_host} {dos_setup.req_url}"], preexec_fn=os.setsid, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) print("Learning for max 10 minutes") find_in_log(kube_apis, log_loc, syslog_pod, ingress_controller_prerequisites.namespace, 600, "learning_confidence=\"Ready\"") print("------------------------- Attack -----------------------------") print("start bad clients requests") p_attack = subprocess.Popen( [f"exec {TEST_DATA}/dos/bad_clients_xff.sh {ingress_host} {dos_setup.req_url}"], preexec_fn=os.setsid, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) print("Attack for 300 seconds") wait_before_test(300) print("Stop Attack") p_attack.terminate() print("wait max 140 seconds after attack stop, to get attack ended") find_in_log(kube_apis, log_loc, syslog_pod, ingress_controller_prerequisites.namespace, 140, "attack_event=\"Attack ended\"") print("Stop Good Client") p_good_client.terminate() log_contents = get_file_contents(kube_apis.v1, log_loc, syslog_pod, ingress_controller_prerequisites.namespace) log_info_dic = log_content_to_dic(log_contents) # Analyze the log no_attack = False attack_started = False under_attack = False attack_ended = False bad_actor_detected = False signature_detected = False health_ok = False bad_ip = ['1.1.1.1', '1.1.1.2', '1.1.1.3'] fmt = '%b %d %Y %H:%M:%S' for log in log_info_dic: if log['attack_event'] == 'No Attack': if int(log['dos_attack_id']) == 0 and not no_attack: no_attack = True elif log['attack_event'] == 'Attack started': if int(log['dos_attack_id']) > 0 and not attack_started: attack_started = True start_attack_time = datetime.strptime(log['date_time'], fmt) elif log['attack_event'] == 'Under Attack': under_attack = True if not health_ok and float(log['stress_level']) < 0.6: health_ok = True health_ok_time = datetime.strptime(log['date_time'], fmt) elif log['attack_event'] == 'Attack signature detected': signature_detected = True elif log['attack_event'] == 'Bad actors detected': if under_attack: bad_actor_detected = True elif log['attack_event'] == 'Bad actor detection': if under_attack and log['source_ip'] in bad_ip: bad_ip.remove(log['source_ip']) elif log['attack_event'] == 'Attack ended': attack_ended = True delete_items_from_yaml(kube_apis, src_ing_yaml, test_namespace) assert ( no_attack and attack_started and under_attack and attack_ended and health_ok and (health_ok_time - start_attack_time).total_seconds() < 150 and signature_detected and bad_actor_detected and len(bad_ip) == 0 ) @pytest.mark.skip def test_dos_arbitrator( self, kube_apis, ingress_controller_prerequisites, crd_ingress_controller_with_dos, dos_setup, test_namespace ): """ Test App Protect Dos: Check new IC pod get learning info """ print("----------------------- Get syslog pod name ----------------------") syslog_pod = self.getPodNameThatContains(kube_apis, ingress_controller_prerequisites.namespace, "syslog") assert "syslog" in syslog_pod log_loc = f"/var/log/messages" clear_file_contents(kube_apis.v1, log_loc, syslog_pod, ingress_controller_prerequisites.namespace) print("------------------------- Deploy ingress -----------------------------") create_ingress_with_dos_annotations( kube_apis, src_ing_yaml, test_namespace, test_namespace+"/dos-protected" ) ingress_host = get_first_ingress_host_from_yaml(src_ing_yaml) # print("------------------------- Learning Phase -----------------------------") print("start good clients requests") p_good_client = subprocess.Popen( [f"exec {TEST_DATA}/dos/good_clients_xff.sh {ingress_host} {dos_setup.req_url}"], preexec_fn=os.setsid, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) print("Learning for max 10 minutes") find_in_log(kube_apis, log_loc, syslog_pod, ingress_controller_prerequisites.namespace, 600, "learning_confidence=\"Ready\"") print("------------------------- Check new IC pod get info from arbitrator -----------------------------") ic_ns = ingress_controller_prerequisites.namespace scale_deployment(kube_apis.v1, kube_apis.apps_v1_api, "nginx-ingress", ic_ns, 2) while get_pods_amount_with_name(kube_apis.v1, "nginx-ingress", "nginx-ingress") is not 2: print(f"Number of replicas is not 2, retrying...") wait_before_test() print("------------------------- Check if new pod receive info from arbitrator -----------------------------") print("Wait for 30 seconds") wait_before_test(30) log_contents = get_file_contents(kube_apis.v1, log_loc, syslog_pod, ingress_controller_prerequisites.namespace) log_info_dic = log_content_to_dic(log_contents) print("Stop Good Client") p_good_client.terminate() learning_units_hostname = [] for log in log_info_dic: if log['unit_hostname'] not in learning_units_hostname and log['learning_confidence'] == "Ready": learning_units_hostname.append(log['unit_hostname']) delete_items_from_yaml(kube_apis, src_ing_yaml, test_namespace) assert ( len(learning_units_hostname) == 2 )
nginxinc/kubernetes-ingress
tests/suite/test_dos.py
Python
apache-2.0
19,400
var q = {a:5}; q.a++; dumpValue(q.a); assert(q.a == 6); var x = {a:6} x.a ^= 42; assert(x.a == 44);
keil/TbDA
test/micro/test84.js
JavaScript
apache-2.0
109
// Package rabbitmq provides a RabbitMQ broker package rabbitmq import ( "github.com/micro/go-micro/broker" "github.com/micro/go-micro/cmd" "github.com/streadway/amqp" ) type rbroker struct { conn *rabbitMQConn addrs []string opts broker.Options } type subscriber struct { opts broker.SubscribeOptions topic string ch *rabbitMQChannel } type publication struct { d amqp.Delivery m *broker.Message t string } func init() { cmd.DefaultBrokers["rabbitmq"] = NewBroker } func (p *publication) Ack() error { return p.d.Ack(false) } func (p *publication) Topic() string { return p.t } func (p *publication) Message() *broker.Message { return p.m } func (s *subscriber) Options() broker.SubscribeOptions { return s.opts } func (s *subscriber) Topic() string { return s.topic } func (s *subscriber) Unsubscribe() error { return s.ch.Close() } func (r *rbroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error { m := amqp.Publishing{ Body: msg.Body, Headers: amqp.Table{}, } for k, v := range msg.Header { m.Headers[k] = v } return r.conn.Publish(r.conn.exchange, topic, m) } func (r *rbroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) { opt := broker.SubscribeOptions{ AutoAck: true, } for _, o := range opts { o(&opt) } durableQueue := false if opt.Context != nil { durableQueue, _ = opt.Context.Value(durableQueueKey{}).(bool) } ch, sub, err := r.conn.Consume( opt.Queue, topic, opt.AutoAck, durableQueue, ) if err != nil { return nil, err } fn := func(msg amqp.Delivery) { header := make(map[string]string) for k, v := range msg.Headers { header[k], _ = v.(string) } m := &broker.Message{ Header: header, Body: msg.Body, } handler(&publication{d: msg, m: m, t: msg.RoutingKey}) } go func() { for d := range sub { go fn(d) } }() return &subscriber{ch: ch, topic: topic, opts: opt}, nil } func (r *rbroker) Options() broker.Options { return r.opts } func (r *rbroker) String() string { return "rabbitmq" } func (r *rbroker) Address() string { if len(r.addrs) > 0 { return r.addrs[0] } return "" } func (r *rbroker) Init(opts ...broker.Option) error { for _, o := range opts { o(&r.opts) } return nil } func (r *rbroker) Connect() error { <-r.conn.Init(r.opts.Secure, r.opts.TLSConfig) return nil } func (r *rbroker) Disconnect() error { r.conn.Close() return nil } func NewBroker(opts ...broker.Option) broker.Broker { var options broker.Options for _, o := range opts { o(&options) } return &rbroker{ conn: newRabbitMQConn("", options.Addrs), addrs: options.Addrs, opts: options, } }
yzprofile/go-plugins
broker/rabbitmq/rabbitmq.go
GO
apache-2.0
2,735
<?php /** * Author: Abel Halo <zxz054321@163.com> */ use App\Foundation\Application; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; /** * Throw an Http Exception with the given data. * * @param int $code * @param string $message * @return void */ function abort($code, $message = '') { app()->abort($code, $message); } /** * Get the available container instance. * * @param string $make * @return Application|mixed */ function app($make = null) { $app = Application::getInstance(); if (is_null($make)) { return $app; } return $app[ $make ]; } /** * Generate an asset path for the application. * * @param string $path * @return string */ function asset($path) { /** @var Request $request */ $request = app('request'); return $request->getBasePath().'/'.$path; } /** * Generate a url based on base url. * * @param string $relative * @return string */ function base_url($relative = null) { $url = request()->getBaseUrl(); if ($relative) { $url = $url.'/'.$relative; } return $url; } /** * Get / set the specified configuration value. * * If an array is passed as the key, we will assume you want to set an array of values. * * @param array|string $key * @param mixed $default * @return mixed */ function config($key = null, $default = null) { if (is_null($key)) { return app('config'); } if (is_array($key)) { return app('config')->set($key); } return app('config')->get($key, $default); } /** * @return Request */ function request() { return app('request'); } /** * Generates an absolute URL from the given parameters. * * @param string $route The name of the route * @param mixed $parameters An array of parameters * @param $type * * @return string The generated URL */ function route($route, $parameters = [], $type = UrlGeneratorInterface::ABSOLUTE_URL) { return app('url_generator')->generate($route, $parameters, $type); } /** * Get / set the specified session value. * * If an array is passed as the key, we will assume you want to set an array of values. * * @param array|string $key * @param mixed $default * @return Session|mixed|null */ function session($key = null, $default = null) { /** @var Session $session */ $session = app('session'); if (is_null($key)) { return $session; } if (is_array($key)) { $session->set(key($key), current($key)); /** @noinspection PhpInconsistentReturnPointsInspection */ return; } return $session->get($key, $default); } /** * Get the evaluated view contents for the given view. * * @param string $name * @param array $data * @return Twig_Environment */ function view($name = null, array $data = []) { /** @var Twig_Environment $twig */ $twig = app('twig'); if (func_num_args() === 0) { return $twig; } return $twig->render($name.'.twig', $data); }
zxz054321/glass
app/helpers.php
PHP
apache-2.0
3,092
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Evaluate the common logarithm (base ten). * * @module @stdlib/math/base/special/log10 * * @example * var log10 = require( '@stdlib/math/base/special/log10' ); * * var v = log10( 100.0 ); * // returns ~0.602 * * v = log10( 8.0 ); * // returns ~0.903 * * v = log10( 0.0 ); * // returns -Infinity * * v = log10( Infinity ); * // returns Infinity * * v = log10( NaN ); * // returns NaN * * v = log10( -4.0 ); * // returns NaN */ // MODULES // var log10 = require( './log10.js' ); // EXPORTS // module.exports = log10;
stdlib-js/stdlib
lib/node_modules/@stdlib/math/base/special/log10/lib/index.js
JavaScript
apache-2.0
1,158
var newick_tree = function () { var tree = biojs.vis.tree.tree(); var theme = function(ta,div) { var newick = '((A,B),C);'; ta.data(biojs.io.newick.newick(newick)); ta.width = 600; ta.scale = false; //tree.layout (tree.layout.vertical()); ta(div); } return theme; }
rajido/biojs2
biojs-vis-tree/newick-tree.js
JavaScript
apache-2.0
292
/** * Copyright 2013 Oak Ridge National Laboratory * Author: James Horey <horeyjl@ornl.gov> * * 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 gov.ornl.keva.node; /** * Java libs. **/ import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Iterator; /** * Keva libs. **/ import gov.ornl.keva.table.TableKey; import gov.ornl.keva.table.TableValue; import gov.ornl.keva.core.WriteOptions; /** * Batch operations list write operations that * must be applied atomically. The writes are applied * in order for a single key, but are not ordered across * different keys. * * @author James Horey **/ public class WriteBatch { private Map<TableKey, List<TableWrite>> writes; public WriteBatch() { writes = new HashMap<>(); } /** * Add a write operation to the batch. * * @param key The key of the value. * @param value The value to place into the database. * @param option Write options that define how the */ public void addWrite(final TableKey key, final TableValue value, final WriteOptions option) { synchronized (this) { List<TableWrite> values = writes.get(key); if(values == null) { values = new ArrayList<>(); writes.put(key, values); } values.add(new TableWrite(value, option)); } } /** * Get the list of keys in the write batch. * * @return Iterator over the keys. */ public Iterator<TableKey> iterator() { return writes.keySet().iterator(); } /** * Get the value and write options associated with the key. * * @param key The table key * @return List of (TableValue,WriteOption) pairs */ public List<TableWrite> getValues(TableKey key) { return writes.get(key); } /** * Organize the value and option togethers. */ static class TableWrite { public TableWrite(TableValue value, WriteOptions options) { this.value = value; this.options = options; } public TableValue value = null; public WriteOptions options = null; } }
jhorey/KevaDB
src/gov/ornl/keva/node/WriteBatch.java
Java
apache-2.0
2,628
package org.cucina.cluster; import java.util.Map; /** * JAVADOC Interface Level * * @author $Author: $ * @version $Revision: $ */ public interface ActiveClusterNodeService { /** * JAVADOC Method Level Comments * * @param eventName JAVADOC. * @param nodeId JAVADOC. */ void executeActive(String eventName, String nodeId, Map<Object, Object> properties); }
cucina/opencucina
loader/src/main/java/org/cucina/cluster/ActiveClusterNodeService.java
Java
apache-2.0
378
package org.jboss.wolf.validator.impl.distribution; import static org.apache.commons.io.filefilter.FileFilterUtils.trueFileFilter; import static org.jboss.wolf.validator.impl.TestUtil.pom; import static org.jboss.wolf.validator.impl.suspicious.TestSuspiciousFileValidator.touch; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.maven.model.Model; import org.jboss.wolf.validator.impl.AbstractTest; import org.junit.Test; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; @ContextConfiguration public class DistributionValidatorTest extends AbstractTest { @Configuration public static class TestConfiguration { @Bean public IOFileFilter distributionValidatorFilter() { return trueFileFilter(); } } private final File distFooJar = new File(distributionDir, "foo-1.0.jar"); private final File distBarJar = new File(distributionDir, "bar-1.0.jar"); private final File distBazJar = new File(distributionDir, "baz-1.0.jar"); @Test public void shouldSkipValidationIfDirectoryDontExists() throws IOException { FileUtils.deleteDirectory(distributionDir); validationExecutor.execute(ctx); assertSuccess(); } @Test public void shouldSuccess() throws IOException { pom().artifactId("foo").create(repoFooDir); touch("com/acme/foo/1.0/foo-1.0-sources.jar"); touch("com/acme/foo/1.0/foo-1.0-javadoc.jar"); touch("com/acme/foo/1.0/foo-1.0-tests.jar"); touch("com/acme/foo/1.0/foo-1.0-test-sources.jar"); FileUtils.copyFile(new File(repoFooDir + "/com/acme/foo/1.0/foo-1.0.jar"), distFooJar); validationExecutor.execute(ctx); assertSuccess(); } @Test public void shouldFindCorruptedFiles() throws IOException { pom().artifactId("foo").create(repoFooDir); FileUtils.copyFile(new File("target/test-classes/empty-signed-damaged.jar"), distFooJar); validationExecutor.execute(ctx); assertExpectedException(DistributionCorruptedFileException.class, "File in distribution foo-1.0.jar has same name like file in repository com/acme/foo/1.0/foo-1.0.jar, but has different content"); } @Test public void shouldFindDuplicatedFiles() throws IOException { pom().artifactId("foo").create(repoFooDir); FileUtils.copyFile(new File(repoFooDir + "/com/acme/foo/1.0/foo-1.0.jar"), distFooJar); FileUtils.copyFile(new File(repoFooDir + "/com/acme/foo/1.0/foo-1.0.jar"), distBarJar); FileUtils.copyFile(new File(repoFooDir + "/com/acme/foo/1.0/foo-1.0.jar"), distBazJar); validationExecutor.execute(ctx); assertExpectedException(DistributionDuplicateFilesException.class, "Duplicate files in distribution: bar-1.0.jar, baz-1.0.jar, foo-1.0.jar"); } @Test public void shouldFindMisnomerFiles() throws IOException { pom().artifactId("foo").create(repoFooDir); FileUtils.copyFile(new File(repoFooDir + "/com/acme/foo/1.0/foo-1.0.jar"), distBarJar); validationExecutor.execute(ctx); assertExpectedException(DistributionMisnomerFileException.class, "File in distribution bar-1.0.jar has same content like file in repository com/acme/foo/1.0/foo-1.0.jar, but has different name"); } @Test public void shouldFindMissingFiles() throws IOException { pom().artifactId("foo").create(repoFooDir); validationExecutor.execute(ctx); assertExpectedException(DistributionMissingFileException.class, "Distribution doesn't contain file from repository: com/acme/foo/1.0/foo-1.0.jar"); } @Test public void shouldFindRedundantFiles() throws IOException { pom().artifactId("foo").create(repoFooDir); FileUtils.copyFile(new File(repoFooDir + "/com/acme/foo/1.0/foo-1.0.jar"), distFooJar); FileUtils.deleteQuietly(new File(repoFooDir + "/com/acme/foo/1.0/foo-1.0.jar")); validationExecutor.execute(ctx); assertExpectedException(DistributionRedundantFileException.class, "Distribution contains file, which is not in repository: foo-1.0.jar"); } @Test public void shouldNotFindRedundantFilesIfTheyComeFromRemoteRepositoriesDueTransitiveDependencies() throws IOException { Model barPom = pom().artifactId("bar").create(repoBarDir, "target/test-classes/empty-signed.jar"); pom().artifactId("foo").dependency(barPom).create(repoFooDir); FileUtils.copyFile(new File(repoFooDir + "/com/acme/foo/1.0/foo-1.0.jar"), distFooJar); FileUtils.copyFile(new File(repoBarDir + "/com/acme/bar/1.0/bar-1.0.jar"), distBarJar); FileUtils.copyDirectory(repoFooDir, repoLocalDir); FileUtils.copyDirectory(repoBarDir, repoLocalDir); validationExecutor.execute(ctx); assertSuccess(); } }
kpiwko/wolf-validator
src/test/java/org/jboss/wolf/validator/impl/distribution/DistributionValidatorTest.java
Java
apache-2.0
5,084
import { FC, memo } from 'react' import Link from 'next/link' import type { TArticle } from '@/spec' import { ICON, GITHUB, ABOUT_LINK } from '@/config' import { METRIC, ROUTE } from '@/constant' import { joinUS } from '@/utils/helper' import TopInfo from './TopInfo' import BottomInfo from './BottomInfo' import { Wrapper, InnerWrapper, MainInfos, BaseInfo, Item, NoLinkItem, HeartCrabIcon, } from '../styles/desktop_view/works_article_layout' type TProps = { viewingArticle: TArticle } const WorksArticleLayout: FC<TProps> = ({ viewingArticle }) => { return ( <Wrapper> <InnerWrapper> <TopInfo metric={METRIC.WORKS_ARTICLE} article={viewingArticle} noBottomBorder /> <MainInfos> <BaseInfo> <Link href={`${ABOUT_LINK}`} passHref> <Item>关于</Item> </Link> <Link href={`/${ROUTE.APPLY_COMMUNITY}`} passHref> <Item>创建社区</Item> </Link> <NoLinkItem onClick={() => joinUS()}>加入群聊</NoLinkItem> <Item href={`${GITHUB}`} rel="noopener noreferrer" target="_blank"> Github </Item> <Link href="/feedback" passHref> <Item>反馈建议</Item> </Link> <Link href={`/${ROUTE.SPONSOR}`} passHref> <Item> <HeartCrabIcon src={`${ICON}/emotion/heart.png`} noLazy /> 特别感谢 </Item> </Link> <Link href={`/${ROUTE.FRIENDS}`} passHref> <Item>友链</Item> </Link> </BaseInfo> </MainInfos> </InnerWrapper> <BottomInfo metric={METRIC.WORKS_ARTICLE} /> </Wrapper> ) } export default memo(WorksArticleLayout)
mydearxym/mastani
src/containers/unit/Footer/DesktopView/WorksArticleLayout.tsx
TypeScript
apache-2.0
1,827