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 (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Roslyn.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A struct that combines a single type with annotations
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
internal readonly struct TypeWithAnnotations : IFormattable
{
/// <summary>
/// A builder for lazy instances of TypeWithAnnotations.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
internal struct Builder
{
private TypeSymbol _defaultType;
private NullableAnnotation _nullableAnnotation;
private Extensions _extensions;
/// <summary>
/// The underlying type, unless overridden by _extensions.
/// </summary>
internal TypeSymbol DefaultType => _defaultType;
/// <summary>
/// True if the fields of the builder are unset.
/// </summary>
internal bool IsDefault => _defaultType is null && _nullableAnnotation == 0 && (_extensions == null || _extensions == Extensions.Default);
/// <summary>
/// Set the fields of the builder.
/// </summary>
/// <remarks>
/// This method guarantees: fields will be set once; exactly one caller is
/// returned true; and IsNull will return true until all fields are initialized.
/// This method does not guarantee that all fields will be set by the same
/// caller. Instead, the expectation is that all callers will attempt to initialize
/// the builder with equivalent TypeWithAnnotations instances where
/// different fields of the builder may be assigned from different instances.
/// </remarks>
internal bool InterlockedInitialize(TypeWithAnnotations type)
{
if ((object)_defaultType != null)
{
return false;
}
_nullableAnnotation = type.NullableAnnotation;
Interlocked.CompareExchange(ref _extensions, type._extensions, null);
return (object)Interlocked.CompareExchange(ref _defaultType, type._defaultType, null) == null;
}
/// <summary>
/// Create immutable TypeWithAnnotations instance.
/// </summary>
internal TypeWithAnnotations ToType()
{
return IsDefault ?
default :
new TypeWithAnnotations(_defaultType, _nullableAnnotation, _extensions);
}
internal string GetDebuggerDisplay() => ToType().GetDebuggerDisplay();
}
/// <summary>
/// The underlying type, unless overridden by _extensions.
/// </summary>
private readonly TypeSymbol _defaultType;
/// <summary>
/// Additional data or behavior. Such cases should be
/// uncommon to minimize allocations.
/// </summary>
private readonly Extensions _extensions;
public readonly NullableAnnotation NullableAnnotation;
private TypeWithAnnotations(TypeSymbol defaultType, NullableAnnotation nullableAnnotation, Extensions extensions)
{
Debug.Assert(defaultType?.IsNullableType() != true || (nullableAnnotation != NullableAnnotation.Oblivious && nullableAnnotation != NullableAnnotation.NotAnnotated));
Debug.Assert(extensions != null);
_defaultType = defaultType;
NullableAnnotation = nullableAnnotation;
_extensions = extensions;
}
public override string ToString() => Type.ToString();
internal static readonly SymbolDisplayFormat DebuggerDisplayFormat = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier);
internal static readonly SymbolDisplayFormat TestDisplayFormat = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier,
compilerInternalOptions: SymbolDisplayCompilerInternalOptions.IncludeNonNullableTypeModifier);
internal static TypeWithAnnotations Create(bool isNullableEnabled, TypeSymbol typeSymbol, bool isAnnotated = false, ImmutableArray<CustomModifier> customModifiers = default)
{
if (typeSymbol is null)
{
return default;
}
return Create(typeSymbol, nullableAnnotation: isAnnotated ? NullableAnnotation.Annotated : isNullableEnabled ? NullableAnnotation.NotAnnotated : NullableAnnotation.Oblivious,
customModifiers.NullToEmpty());
}
internal static TypeWithAnnotations Create(TypeSymbol typeSymbol, NullableAnnotation nullableAnnotation = NullableAnnotation.Oblivious, ImmutableArray<CustomModifier> customModifiers = default)
{
if (typeSymbol is null && nullableAnnotation == 0)
{
return default;
}
switch (nullableAnnotation)
{
case NullableAnnotation.Oblivious:
case NullableAnnotation.NotAnnotated:
if (typeSymbol?.IsNullableType() == true)
{
// int?, T? where T : struct (add annotation)
nullableAnnotation = NullableAnnotation.Annotated;
}
break;
}
return CreateNonLazyType(typeSymbol, nullableAnnotation, customModifiers.NullToEmpty());
}
internal bool IsPossiblyNullableTypeTypeParameter()
{
return NullableAnnotation.IsNotAnnotated() &&
(Type?.IsPossiblyNullableReferenceTypeTypeParameter() == true ||
Type?.IsNullableTypeOrTypeParameter() == true);
}
internal NullableAnnotation GetValueNullableAnnotation()
{
if (IsPossiblyNullableTypeTypeParameter())
{
return NullableAnnotation.Annotated;
}
// https://github.com/dotnet/roslyn/issues/31675: Is a similar case needed in ValueCanBeNull?
if (NullableAnnotation != NullableAnnotation.NotAnnotated && Type.IsNullableTypeOrTypeParameter())
{
return NullableAnnotation.Annotated;
}
return NullableAnnotation;
}
internal bool CanBeAssignedNull
{
get
{
switch (NullableAnnotation)
{
case NullableAnnotation.Oblivious:
case NullableAnnotation.Annotated:
return true;
case NullableAnnotation.NotAnnotated:
return Type.IsNullableTypeOrTypeParameter();
default:
throw ExceptionUtilities.UnexpectedValue(NullableAnnotation);
}
}
}
private static bool IsIndexedTypeParameter(TypeSymbol typeSymbol)
{
return typeSymbol is IndexedTypeParameterSymbol ||
typeSymbol is IndexedTypeParameterSymbolForOverriding;
}
private static TypeWithAnnotations CreateNonLazyType(TypeSymbol typeSymbol, NullableAnnotation nullableAnnotation, ImmutableArray<CustomModifier> customModifiers)
{
return new TypeWithAnnotations(typeSymbol, nullableAnnotation, Extensions.Create(customModifiers));
}
private static TypeWithAnnotations CreateLazyNullableType(CSharpCompilation compilation, TypeWithAnnotations underlying)
{
return new TypeWithAnnotations(defaultType: underlying._defaultType, nullableAnnotation: NullableAnnotation.Annotated, Extensions.CreateLazy(compilation, underlying));
}
/// <summary>
/// True if the fields are unset. Appropriate when detecting if a lazily-initialized variable has been initialized.
/// </summary>
internal bool IsDefault => _defaultType is null && this.NullableAnnotation == 0 && (_extensions == null || _extensions == Extensions.Default);
/// <summary>
/// True if the type is not null.
/// </summary>
internal bool HasType => !(_defaultType is null);
public TypeWithAnnotations SetIsAnnotated(CSharpCompilation compilation)
{
Debug.Assert(CustomModifiers.IsEmpty);
var typeSymbol = this.Type;
if (typeSymbol.TypeKind != TypeKind.TypeParameter)
{
if (!typeSymbol.IsValueType && !typeSymbol.IsErrorType())
{
return CreateNonLazyType(typeSymbol, NullableAnnotation.Annotated, this.CustomModifiers);
}
else
{
return makeNullableT();
}
}
if (((TypeParameterSymbol)typeSymbol).TypeParameterKind == TypeParameterKind.Cref)
{
// We always bind annotated type parameters in cref as `Nullable<T>`
return makeNullableT();
}
// It is not safe to check if a type parameter is a reference type right away, this can send us into a cycle.
// In this case we delay asking this question as long as possible.
return CreateLazyNullableType(compilation, this);
TypeWithAnnotations makeNullableT()
=> Create(compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(ImmutableArray.Create(typeSymbol)));
}
private TypeWithAnnotations AsNullableReferenceType() => _extensions.AsNullableReferenceType(this);
public TypeWithAnnotations AsNotNullableReferenceType() => _extensions.AsNotNullableReferenceType(this);
/// <summary>
/// Merges top-level and nested nullability from an otherwise identical type.
/// </summary>
internal TypeWithAnnotations MergeNullability(TypeWithAnnotations other, VarianceKind variance)
{
TypeSymbol typeSymbol = other.Type;
NullableAnnotation nullableAnnotation = this.NullableAnnotation.MergeNullableAnnotation(other.NullableAnnotation, variance);
TypeSymbol type = Type.MergeNullability(typeSymbol, variance);
Debug.Assert((object)type != null);
return Create(type, nullableAnnotation, CustomModifiers);
}
public TypeWithAnnotations WithModifiers(ImmutableArray<CustomModifier> customModifiers) =>
_extensions.WithModifiers(this, customModifiers);
public TypeSymbol Type => _extensions?.GetResolvedType(_defaultType);
public TypeSymbol NullableUnderlyingTypeOrSelf => _extensions.GetNullableUnderlyingTypeOrSelf(_defaultType);
/// <summary>
/// Is this System.Nullable`1 type, or its substitution.
/// </summary>
public bool IsNullableType() => Type.IsNullableType();
/// <summary>
/// The list of custom modifiers, if any, associated with the <see cref="Type"/>.
/// </summary>
public ImmutableArray<CustomModifier> CustomModifiers => _extensions.CustomModifiers;
public TypeKind TypeKind => Type.TypeKind;
public SpecialType SpecialType => _extensions.GetSpecialType(_defaultType);
public Cci.PrimitiveTypeCode PrimitiveTypeCode => Type.PrimitiveTypeCode;
public bool IsVoid =>
_extensions.IsVoid(_defaultType);
public bool IsSZArray() =>
_extensions.IsSZArray(_defaultType);
public bool IsStatic =>
_extensions.IsStatic(_defaultType);
public bool IsRestrictedType(bool ignoreSpanLikeTypes = false) =>
_extensions.IsRestrictedType(_defaultType, ignoreSpanLikeTypes);
internal bool GetIsReferenceType(ConsList<TypeParameterSymbol> inProgress) =>
_extensions.GetIsReferenceType(_defaultType, inProgress);
internal bool GetIsValueType(ConsList<TypeParameterSymbol> inProgress) =>
_extensions.GetIsValueType(_defaultType, inProgress);
public string ToDisplayString(SymbolDisplayFormat format = null)
{
var str = !HasType ? "<null>" : Type.ToDisplayString(format);
if (format != null)
{
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier) &&
!IsNullableType() && !Type.IsValueType &&
NullableAnnotation.IsAnnotated())
{
return str + "?";
}
else if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.IncludeNonNullableTypeModifier) &&
!Type.IsValueType &&
NullableAnnotation.IsNotAnnotated() &&
!Type.IsTypeParameterDisallowingAnnotation())
{
return str + "!";
}
}
return str;
}
internal string GetDebuggerDisplay() => !this.HasType ? "<null>" : ToDisplayString(DebuggerDisplayFormat);
string IFormattable.ToString(string format, IFormatProvider formatProvider)
{
return ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat);
}
public bool Equals(TypeWithAnnotations other, TypeCompareKind comparison)
{
if (this.IsSameAs(other))
{
return true;
}
if (!HasType)
{
if (other.HasType || NullableAnnotation != other.NullableAnnotation)
return false;
}
else if (!other.HasType || !TypeSymbolEquals(other, comparison))
{
return false;
}
// Make sure custom modifiers are the same.
if ((comparison & TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) == 0 &&
!this.CustomModifiers.SequenceEqual(other.CustomModifiers))
{
return false;
}
var thisAnnotation = NullableAnnotation;
var otherAnnotation = other.NullableAnnotation;
if (!HasType)
{
return thisAnnotation == otherAnnotation;
}
else if ((comparison & TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) == 0)
{
if (otherAnnotation != thisAnnotation && (!Type.IsValueType || Type.IsNullableType()))
{
if (thisAnnotation.IsOblivious() || otherAnnotation.IsOblivious())
{
if ((comparison & TypeCompareKind.UnknownNullableModifierMatchesAny) == 0)
{
return false;
}
}
else
{
return false;
}
}
}
return true;
}
internal sealed class EqualsComparer : EqualityComparer<TypeWithAnnotations>
{
internal static readonly EqualsComparer Instance = new EqualsComparer();
private EqualsComparer()
{
}
public override int GetHashCode(TypeWithAnnotations obj)
{
if (!obj.HasType)
{
return 0;
}
return obj.Type.GetHashCode();
}
public override bool Equals(TypeWithAnnotations x, TypeWithAnnotations y)
{
if (!x.HasType)
{
return !y.HasType;
}
return x.Equals(y, TypeCompareKind.ConsiderEverything);
}
}
internal bool TypeSymbolEquals(TypeWithAnnotations other, TypeCompareKind comparison) =>
_extensions.TypeSymbolEquals(this, other, comparison);
public bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes)
{
return Type.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes) ||
Symbol.GetUnificationUseSiteDiagnosticRecursive(ref result, this.CustomModifiers, owner, ref checkedTypes);
}
public bool IsAtLeastAsVisibleAs(Symbol sym, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
// System.Nullable is public, so it is safe to delegate to the underlying.
return NullableUnderlyingTypeOrSelf.IsAtLeastAsVisibleAs(sym, ref useSiteDiagnostics);
}
public TypeWithAnnotations SubstituteType(AbstractTypeMap typeMap) =>
_extensions.SubstituteType(this, typeMap, withTupleUnification: false);
public TypeWithAnnotations SubstituteTypeWithTupleUnification(AbstractTypeMap typeMap) =>
_extensions.SubstituteType(this, typeMap, withTupleUnification: true);
internal TypeWithAnnotations TransformToTupleIfCompatible() => _extensions.TransformToTupleIfCompatible(this);
internal TypeWithAnnotations SubstituteTypeCore(AbstractTypeMap typeMap, bool withTupleUnification)
{
var newCustomModifiers = typeMap.SubstituteCustomModifiers(this.CustomModifiers);
TypeSymbol typeSymbol = this.Type;
var newTypeWithModifiers = typeMap.SubstituteType(typeSymbol, withTupleUnification);
if (!typeSymbol.IsTypeParameter())
{
Debug.Assert(newTypeWithModifiers.NullableAnnotation.IsOblivious() || (typeSymbol.IsNullableType() && newTypeWithModifiers.NullableAnnotation.IsAnnotated()));
Debug.Assert(newTypeWithModifiers.CustomModifiers.IsEmpty);
if (typeSymbol.Equals(newTypeWithModifiers.Type, TypeCompareKind.ConsiderEverything) &&
newCustomModifiers == CustomModifiers)
{
return this; // substitution had no effect on the type or modifiers
}
else if ((NullableAnnotation.IsOblivious() || (typeSymbol.IsNullableType() && NullableAnnotation.IsAnnotated())) &&
newCustomModifiers.IsEmpty)
{
return newTypeWithModifiers;
}
return Create(newTypeWithModifiers.Type, NullableAnnotation, newCustomModifiers);
}
if (newTypeWithModifiers.Is((TypeParameterSymbol)typeSymbol) &&
newCustomModifiers == CustomModifiers)
{
return this; // substitution had no effect on the type or modifiers
}
else if (Is((TypeParameterSymbol)typeSymbol))
{
return newTypeWithModifiers;
}
NullableAnnotation newAnnotation;
Debug.Assert(!IsIndexedTypeParameter(newTypeWithModifiers.Type) || newTypeWithModifiers.NullableAnnotation.IsOblivious());
if (NullableAnnotation.IsAnnotated() || newTypeWithModifiers.NullableAnnotation.IsAnnotated())
{
newAnnotation = NullableAnnotation.IsAnnotated() || newTypeWithModifiers.NullableAnnotation.IsAnnotated() ?
NullableAnnotation.Annotated : NullableAnnotation.Annotated;
}
else if (IsIndexedTypeParameter(newTypeWithModifiers.Type))
{
newAnnotation = NullableAnnotation;
}
else if (NullableAnnotation != NullableAnnotation.Oblivious)
{
if (!typeSymbol.IsTypeParameterDisallowingAnnotation())
{
newAnnotation = NullableAnnotation;
}
else
{
newAnnotation = newTypeWithModifiers.NullableAnnotation;
}
}
else if (newTypeWithModifiers.NullableAnnotation != NullableAnnotation.Oblivious)
{
newAnnotation = newTypeWithModifiers.NullableAnnotation;
}
else
{
Debug.Assert(NullableAnnotation.IsOblivious());
Debug.Assert(newTypeWithModifiers.NullableAnnotation.IsOblivious());
newAnnotation = NullableAnnotation;
}
return CreateNonLazyType(
newTypeWithModifiers.Type,
newAnnotation,
newCustomModifiers.Concat(newTypeWithModifiers.CustomModifiers));
}
public void ReportDiagnosticsIfObsolete(Binder binder, SyntaxNode syntax, DiagnosticBag diagnostics) =>
_extensions.ReportDiagnosticsIfObsolete(this, binder, syntax, diagnostics);
private bool TypeSymbolEqualsCore(TypeWithAnnotations other, TypeCompareKind comparison)
{
return Type.Equals(other.Type, comparison);
}
private void ReportDiagnosticsIfObsoleteCore(Binder binder, SyntaxNode syntax, DiagnosticBag diagnostics)
{
binder.ReportDiagnosticsIfObsolete(diagnostics, Type, syntax, hasBaseReceiver: false);
}
/// <summary>
/// Extract type under assumption that there should be no custom modifiers or annotations.
/// The method asserts otherwise.
/// </summary>
public TypeSymbol AsTypeSymbolOnly() => _extensions.AsTypeSymbolOnly(_defaultType);
/// <summary>
/// Is this the given type parameter?
/// </summary>
public bool Is(TypeParameterSymbol other)
{
return NullableAnnotation.IsOblivious() && ((object)_defaultType == other) &&
CustomModifiers.IsEmpty;
}
public TypeWithAnnotations WithTypeAndModifiers(TypeSymbol typeSymbol, ImmutableArray<CustomModifier> customModifiers) =>
_extensions.WithTypeAndModifiers(this, typeSymbol, customModifiers);
public bool NeedsNullableAttribute()
{
return NeedsNullableAttribute(this, typeOpt: null);
}
public static bool NeedsNullableAttribute(
TypeWithAnnotations typeWithAnnotationsOpt,
TypeSymbol typeOpt)
{
var type = TypeSymbolExtensions.VisitType(
typeWithAnnotationsOpt,
typeOpt,
typeWithAnnotationsPredicateOpt: (t, a, b) => t.NullableAnnotation != NullableAnnotation.Oblivious && !t.Type.IsErrorType() && !t.Type.IsValueType,
typePredicateOpt: null,
arg: (object)null);
return (object)type != null;
}
public void AddNullableTransforms(ArrayBuilder<byte> transforms)
{
var typeSymbol = Type;
byte flag;
if (NullableAnnotation.IsOblivious() || typeSymbol.IsValueType)
{
flag = (byte)NullableAnnotation.Oblivious;
}
else if (NullableAnnotation.IsAnnotated())
{
flag = (byte)NullableAnnotation.Annotated;
}
else
{
flag = (byte)NullableAnnotation.NotAnnotated;
}
transforms.Add(flag);
typeSymbol.AddNullableTransforms(transforms);
}
public bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeWithAnnotations result)
{
result = this;
byte transformFlag;
if (transforms.IsDefault)
{
transformFlag = defaultTransformFlag;
}
else if (position < transforms.Length)
{
transformFlag = transforms[position++];
}
else
{
return false;
}
TypeSymbol oldTypeSymbol = Type;
TypeSymbol newTypeSymbol;
if (!oldTypeSymbol.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out newTypeSymbol))
{
return false;
}
if ((object)oldTypeSymbol != newTypeSymbol)
{
result = result.WithTypeAndModifiers(newTypeSymbol, result.CustomModifiers);
}
switch ((NullableAnnotation)transformFlag)
{
case NullableAnnotation.Annotated:
result = result.AsNullableReferenceType();
break;
case NullableAnnotation.NotAnnotated:
result = result.AsNotNullableReferenceType();
break;
case NullableAnnotation.Oblivious:
if (result.NullableAnnotation != NullableAnnotation.Oblivious &&
!(result.NullableAnnotation.IsAnnotated() && oldTypeSymbol.IsNullableType())) // Preserve nullable annotation on Nullable<T>.
{
result = CreateNonLazyType(newTypeSymbol, NullableAnnotation.Oblivious, result.CustomModifiers);
}
break;
default:
result = this;
return false;
}
return true;
}
public TypeWithAnnotations WithTopLevelNonNullability()
{
var typeSymbol = Type;
if (NullableAnnotation.IsNotAnnotated() || (typeSymbol.IsValueType && !typeSymbol.IsNullableType()))
{
return this;
}
return CreateNonLazyType(typeSymbol, NullableAnnotation.NotAnnotated, CustomModifiers);
}
public TypeWithAnnotations SetUnknownNullabilityForReferenceTypes()
{
var typeSymbol = Type;
if (NullableAnnotation != NullableAnnotation.Oblivious)
{
if (!typeSymbol.IsValueType)
{
typeSymbol = typeSymbol.SetUnknownNullabilityForReferenceTypes();
return CreateNonLazyType(typeSymbol, NullableAnnotation.Oblivious, CustomModifiers);
}
}
var newTypeSymbol = typeSymbol.SetUnknownNullabilityForReferenceTypes();
if ((object)newTypeSymbol != typeSymbol)
{
return WithTypeAndModifiers(newTypeSymbol, CustomModifiers);
}
return this;
}
#pragma warning disable CS0809
[Obsolete("Unsupported", error: true)]
public override bool Equals(object other)
#pragma warning restore CS0809
{
throw ExceptionUtilities.Unreachable;
}
#pragma warning disable CS0809
[Obsolete("Unsupported", error: true)]
public override int GetHashCode()
#pragma warning restore CS0809
{
if (!HasType)
{
return 0;
}
return Type.GetHashCode();
}
#pragma warning disable CS0809
[Obsolete("Unsupported", error: true)]
public static bool operator ==(TypeWithAnnotations? x, TypeWithAnnotations? y)
#pragma warning restore CS0809
{
throw ExceptionUtilities.Unreachable;
}
#pragma warning disable CS0809
[Obsolete("Unsupported", error: true)]
public static bool operator !=(TypeWithAnnotations? x, TypeWithAnnotations? y)
#pragma warning restore CS0809
{
throw ExceptionUtilities.Unreachable;
}
// Field-wise ReferenceEquals.
internal bool IsSameAs(TypeWithAnnotations other)
{
return ReferenceEquals(_defaultType, other._defaultType) &&
NullableAnnotation == other.NullableAnnotation &&
ReferenceEquals(_extensions, other._extensions);
}
/// <summary>
/// Compute the flow state resulting from reading from an lvalue.
/// </summary>
internal TypeWithState ToTypeWithState()
{
// This operation reflects reading from an lvalue, which produces an rvalue.
// Reading from a variable of a type parameter (that could be substituted with a nullable type), but which
// cannot itself be annotated (because it isn't known to be a reference type), may yield a null value
// even though the type parameter isn't annotated.
return new TypeWithState(
Type,
IsPossiblyNullableTypeTypeParameter() || NullableAnnotation.IsAnnotated() ? NullableFlowState.MaybeNull : NullableFlowState.NotNull);
}
/// <summary>
/// Additional data or behavior beyond the core TypeWithAnnotations.
/// </summary>
private abstract class Extensions
{
internal static readonly Extensions Default = new NonLazyType(ImmutableArray<CustomModifier>.Empty);
internal static Extensions Create(ImmutableArray<CustomModifier> customModifiers)
{
if (customModifiers.IsEmpty)
{
return Default;
}
return new NonLazyType(customModifiers);
}
internal static Extensions CreateLazy(CSharpCompilation compilation, TypeWithAnnotations underlying)
{
return new LazyNullableTypeParameter(compilation, underlying);
}
internal abstract TypeSymbol GetResolvedType(TypeSymbol defaultType);
internal abstract ImmutableArray<CustomModifier> CustomModifiers { get; }
internal abstract TypeWithAnnotations AsNullableReferenceType(TypeWithAnnotations type);
internal abstract TypeWithAnnotations AsNotNullableReferenceType(TypeWithAnnotations type);
internal abstract TypeWithAnnotations WithModifiers(TypeWithAnnotations type, ImmutableArray<CustomModifier> customModifiers);
internal abstract TypeSymbol GetNullableUnderlyingTypeOrSelf(TypeSymbol typeSymbol);
internal abstract bool GetIsReferenceType(TypeSymbol typeSymbol, ConsList<TypeParameterSymbol> inProgress);
internal abstract bool GetIsValueType(TypeSymbol typeSymbol, ConsList<TypeParameterSymbol> inProgress);
internal abstract TypeSymbol AsTypeSymbolOnly(TypeSymbol typeSymbol);
internal abstract SpecialType GetSpecialType(TypeSymbol typeSymbol);
internal abstract bool IsRestrictedType(TypeSymbol typeSymbol, bool ignoreSpanLikeTypes);
internal abstract bool IsStatic(TypeSymbol typeSymbol);
internal abstract bool IsVoid(TypeSymbol typeSymbol);
internal abstract bool IsSZArray(TypeSymbol typeSymbol);
internal abstract TypeWithAnnotations WithTypeAndModifiers(TypeWithAnnotations type, TypeSymbol typeSymbol, ImmutableArray<CustomModifier> customModifiers);
internal abstract bool TypeSymbolEquals(TypeWithAnnotations type, TypeWithAnnotations other, TypeCompareKind comparison);
internal abstract TypeWithAnnotations SubstituteType(TypeWithAnnotations type, AbstractTypeMap typeMap, bool withTupleUnification);
internal abstract TypeWithAnnotations TransformToTupleIfCompatible(TypeWithAnnotations type);
internal abstract void ReportDiagnosticsIfObsolete(TypeWithAnnotations type, Binder binder, SyntaxNode syntax, DiagnosticBag diagnostics);
}
private sealed class NonLazyType : Extensions
{
private readonly ImmutableArray<CustomModifier> _customModifiers;
public NonLazyType(ImmutableArray<CustomModifier> customModifiers)
{
Debug.Assert(!customModifiers.IsDefault);
_customModifiers = customModifiers;
}
internal override TypeSymbol GetResolvedType(TypeSymbol defaultType) => defaultType;
internal override ImmutableArray<CustomModifier> CustomModifiers => _customModifiers;
internal override SpecialType GetSpecialType(TypeSymbol typeSymbol) => typeSymbol.SpecialType;
internal override bool IsRestrictedType(TypeSymbol typeSymbol, bool ignoreSpanLikeTypes) => typeSymbol.IsRestrictedType(ignoreSpanLikeTypes);
internal override bool IsStatic(TypeSymbol typeSymbol) => typeSymbol.IsStatic;
internal override bool IsVoid(TypeSymbol typeSymbol) => typeSymbol.SpecialType == SpecialType.System_Void;
internal override bool IsSZArray(TypeSymbol typeSymbol) => typeSymbol.IsSZArray();
internal override TypeSymbol GetNullableUnderlyingTypeOrSelf(TypeSymbol typeSymbol) => typeSymbol.StrippedType();
internal override bool GetIsReferenceType(TypeSymbol typeSymbol, ConsList<TypeParameterSymbol> inProgress)
{
if (typeSymbol.TypeKind == TypeKind.TypeParameter)
{
return ((TypeParameterSymbol)typeSymbol).GetIsReferenceType(inProgress);
}
return typeSymbol.IsReferenceType;
}
internal override bool GetIsValueType(TypeSymbol typeSymbol, ConsList<TypeParameterSymbol> inProgress)
{
if (typeSymbol.TypeKind == TypeKind.TypeParameter)
{
return ((TypeParameterSymbol)typeSymbol).GetIsValueType(inProgress);
}
return typeSymbol.IsValueType;
}
internal override TypeWithAnnotations WithModifiers(TypeWithAnnotations type, ImmutableArray<CustomModifier> customModifiers)
{
return CreateNonLazyType(type._defaultType, type.NullableAnnotation, customModifiers);
}
internal override TypeSymbol AsTypeSymbolOnly(TypeSymbol typeSymbol) => typeSymbol;
internal override TypeWithAnnotations WithTypeAndModifiers(TypeWithAnnotations type, TypeSymbol typeSymbol, ImmutableArray<CustomModifier> customModifiers)
{
return CreateNonLazyType(typeSymbol, type.NullableAnnotation, customModifiers);
}
internal override TypeWithAnnotations AsNullableReferenceType(TypeWithAnnotations type)
{
return CreateNonLazyType(type._defaultType, NullableAnnotation.Annotated, _customModifiers);
}
internal override TypeWithAnnotations AsNotNullableReferenceType(TypeWithAnnotations type)
{
var defaultType = type._defaultType;
return CreateNonLazyType(defaultType, defaultType.IsNullableType() ? type.NullableAnnotation : NullableAnnotation.NotAnnotated, _customModifiers);
}
internal override bool TypeSymbolEquals(TypeWithAnnotations type, TypeWithAnnotations other, TypeCompareKind comparison)
{
return type.TypeSymbolEqualsCore(other, comparison);
}
internal override TypeWithAnnotations SubstituteType(TypeWithAnnotations type, AbstractTypeMap typeMap, bool withTupleUnification)
{
return type.SubstituteTypeCore(typeMap, withTupleUnification);
}
internal override TypeWithAnnotations TransformToTupleIfCompatible(TypeWithAnnotations type)
{
var defaultType = type._defaultType;
var transformedType = TupleTypeSymbol.TransformToTupleIfCompatible(defaultType);
if ((object)defaultType != transformedType)
{
return TypeWithAnnotations.Create(transformedType, type.NullableAnnotation, _customModifiers);
}
return type;
}
internal override void ReportDiagnosticsIfObsolete(TypeWithAnnotations type, Binder binder, SyntaxNode syntax, DiagnosticBag diagnostics)
{
type.ReportDiagnosticsIfObsoleteCore(binder, syntax, diagnostics);
}
}
/// <summary>
/// Nullable type parameter. The underlying TypeSymbol is resolved
/// lazily to avoid cycles when binding declarations.
/// </summary>
private sealed class LazyNullableTypeParameter : Extensions
{
private readonly CSharpCompilation _compilation;
private readonly TypeWithAnnotations _underlying;
private TypeSymbol _resolved;
public LazyNullableTypeParameter(CSharpCompilation compilation, TypeWithAnnotations underlying)
{
Debug.Assert(!underlying.NullableAnnotation.IsAnnotated());
Debug.Assert(underlying.TypeKind == TypeKind.TypeParameter);
Debug.Assert(underlying.CustomModifiers.IsEmpty);
_compilation = compilation;
_underlying = underlying;
}
internal override bool IsVoid(TypeSymbol typeSymbol) => false;
internal override bool IsSZArray(TypeSymbol typeSymbol) => false;
internal override bool IsStatic(TypeSymbol typeSymbol) => false;
private TypeSymbol GetResolvedType()
{
if ((object)_resolved == null)
{
if (!_underlying.Type.IsValueType)
{
_resolved = _underlying.Type;
}
else
{
Interlocked.CompareExchange(ref _resolved,
_compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(ImmutableArray.Create(_underlying)),
null);
}
}
return _resolved;
}
internal override bool GetIsReferenceType(TypeSymbol typeSymbol, ConsList<TypeParameterSymbol> inProgress)
{
return _underlying.GetIsReferenceType(inProgress);
}
internal override bool GetIsValueType(TypeSymbol typeSymbol, ConsList<TypeParameterSymbol> inProgress)
{
return _underlying.GetIsValueType(inProgress);
}
internal override TypeSymbol GetNullableUnderlyingTypeOrSelf(TypeSymbol typeSymbol) => _underlying.Type;
internal override SpecialType GetSpecialType(TypeSymbol typeSymbol)
{
var specialType = _underlying.SpecialType;
return specialType.IsValueType() ? SpecialType.None : specialType;
}
internal override bool IsRestrictedType(TypeSymbol typeSymbol, bool ignoreSpanLikeTypes) => _underlying.IsRestrictedType(ignoreSpanLikeTypes);
internal override TypeSymbol AsTypeSymbolOnly(TypeSymbol typeSymbol)
{
var resolvedType = GetResolvedType();
Debug.Assert(resolvedType.IsNullableType() && CustomModifiers.IsEmpty);
return resolvedType;
}
internal override TypeSymbol GetResolvedType(TypeSymbol defaultType) => GetResolvedType();
internal override ImmutableArray<CustomModifier> CustomModifiers => ImmutableArray<CustomModifier>.Empty;
internal override TypeWithAnnotations WithModifiers(TypeWithAnnotations type, ImmutableArray<CustomModifier> customModifiers)
{
if (customModifiers.IsEmpty)
{
return type;
}
var resolvedType = GetResolvedType();
if (resolvedType.IsNullableType())
{
return TypeWithAnnotations.Create(resolvedType, type.NullableAnnotation, customModifiers: customModifiers);
}
return CreateNonLazyType(resolvedType, type.NullableAnnotation, customModifiers);
}
internal override TypeWithAnnotations WithTypeAndModifiers(TypeWithAnnotations type, TypeSymbol typeSymbol, ImmutableArray<CustomModifier> customModifiers)
{
if (typeSymbol.IsNullableType())
{
return TypeWithAnnotations.Create(typeSymbol, type.NullableAnnotation, customModifiers: customModifiers);
}
return CreateNonLazyType(typeSymbol, type.NullableAnnotation, customModifiers);
}
internal override TypeWithAnnotations AsNullableReferenceType(TypeWithAnnotations type)
{
return type;
}
internal override TypeWithAnnotations AsNotNullableReferenceType(TypeWithAnnotations type)
{
if (!_underlying.Type.IsValueType)
{
return _underlying;
}
return type;
}
internal override TypeWithAnnotations SubstituteType(TypeWithAnnotations type, AbstractTypeMap typeMap, bool withTupleUnification)
{
if ((object)_resolved != null)
{
return type.SubstituteTypeCore(typeMap, withTupleUnification);
}
var newUnderlying = _underlying.SubstituteTypeCore(typeMap, withTupleUnification);
if (!newUnderlying.IsSameAs(this._underlying))
{
if ((newUnderlying.Type.Equals(this._underlying.Type, TypeCompareKind.ConsiderEverything) ||
newUnderlying.Type is IndexedTypeParameterSymbolForOverriding) &&
newUnderlying.CustomModifiers.IsEmpty)
{
return CreateLazyNullableType(_compilation, newUnderlying);
}
return type.SubstituteTypeCore(typeMap, withTupleUnification);
}
else
{
return type; // substitution had no effect on the type or modifiers
}
}
internal override TypeWithAnnotations TransformToTupleIfCompatible(TypeWithAnnotations type)
{
return type;
}
internal override void ReportDiagnosticsIfObsolete(TypeWithAnnotations type, Binder binder, SyntaxNode syntax, DiagnosticBag diagnostics)
{
if ((object)_resolved != null)
{
type.ReportDiagnosticsIfObsoleteCore(binder, syntax, diagnostics);
}
else
{
diagnostics.Add(new LazyObsoleteDiagnosticInfo(type, binder.ContainingMemberOrLambda, binder.Flags), syntax.GetLocation());
}
}
internal override bool TypeSymbolEquals(TypeWithAnnotations type, TypeWithAnnotations other, TypeCompareKind comparison)
{
var otherLazy = other._extensions as LazyNullableTypeParameter;
if ((object)otherLazy != null)
{
return _underlying.TypeSymbolEquals(otherLazy._underlying, comparison);
}
return type.TypeSymbolEqualsCore(other, comparison);
}
}
}
}
| MichalStrehovsky/roslyn | src/Compilers/CSharp/Portable/Symbols/TypeWithAnnotations.cs | C# | apache-2.0 | 44,331 |
/*
* 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
*
* 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 eu.solidcraft.starter.examples.example2.repository.springdatajpa;
import eu.solidcraft.starter.examples.example2.model.Visit;
import eu.solidcraft.starter.examples.example2.repository.VisitRepository;
import org.springframework.data.repository.Repository;
/**
* Spring Data JPA specialization of the {@link VisitRepository} interface
*
* @author Michael Isvy
* @since 15.1.2013
*/
public interface SpringDataVisitRepository extends VisitRepository, Repository<Visit, Integer> {
}
| jakubnabrdalik/spring-workshops | src/main/groovy/eu/solidcraft/starter/examples/example2/repository/springdatajpa/SpringDataVisitRepository.java | Java | apache-2.0 | 1,116 |
require 'rails_helper'
RSpec.describe "customers/index", :type => :view do
before(:each) do
assign(:customers, [
Customer.create!(
:name => "Name",
:kana => "Kana",
:email => "Email",
:sex => 1,
:age => 2,
:marriage => 3,
:pref => "Pref",
:carrier => "Carrier",
:curry => "Curry"
),
Customer.create!(
:name => "Name",
:kana => "Kana",
:email => "Email",
:sex => 1,
:age => 2,
:marriage => 3,
:pref => "Pref",
:carrier => "Carrier",
:curry => "Curry"
)
])
end
it "renders a list of customers" do
render
assert_select "tr>td", :text => "Name".to_s, :count => 2
assert_select "tr>td", :text => "Kana".to_s, :count => 2
assert_select "tr>td", :text => "Email".to_s, :count => 2
assert_select "tr>td", :text => 1.to_s, :count => 2
assert_select "tr>td", :text => 2.to_s, :count => 2
assert_select "tr>td", :text => 3.to_s, :count => 2
assert_select "tr>td", :text => "Pref".to_s, :count => 2
assert_select "tr>td", :text => "Carrier".to_s, :count => 2
assert_select "tr>td", :text => "Curry".to_s, :count => 2
end
end
| otsutomesan/mid | spec/views/customers/index.html.erb_spec.rb | Ruby | apache-2.0 | 1,239 |
/*
* Copyright 2014 Ranjan Kumar
*
* 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.restfeel.entity;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.mongodb.core.mapping.DBRef;
public class RfRequest extends NamedEntity {
private static final long serialVersionUID = 1L;
private String apiUrl;
private String methodType;
private String apiBody;
private List<RfHeader> rfHeaders = new ArrayList<RfHeader>();
private List<RfCookie> rfCookies;
private List<UrlParam> urlParams;
private List<FormParam> formParams;
private BasicAuth basicAuth;
private DigestAuth digestAuth;
private OAuth2 oAuth2;
private String conversationId;
private String evaluatedApiUrl;
@DBRef
private Assertion assertion;
public String getMethodType() {
return methodType;
}
public void setMethodType(String methodType) {
this.methodType = methodType;
}
public List<RfHeader> getRfHeaders() {
return rfHeaders;
}
public void setRfHeaders(List<RfHeader> rfHeaders) {
this.rfHeaders = rfHeaders;
}
public List<RfCookie> getRfCookies() {
return rfCookies;
}
public void setRfCookies(List<RfCookie> rfCookies) {
this.rfCookies = rfCookies;
}
public List<UrlParam> getUrlParams() {
return urlParams;
}
public void setUrlParams(List<UrlParam> urlParams) {
this.urlParams = urlParams;
}
public List<FormParam> getFormParams() {
return formParams;
}
public void setFormParams(List<FormParam> formParams) {
this.formParams = formParams;
}
public BasicAuth getBasicAuth() {
return basicAuth;
}
public void setBasicAuth(BasicAuth basicAuth) {
this.basicAuth = basicAuth;
}
public DigestAuth getDigestAuth() {
return digestAuth;
}
public void setDigestAuth(DigestAuth digestAuth) {
this.digestAuth = digestAuth;
}
public OAuth2 getoAuth2() {
return oAuth2;
}
public void setoAuth2(OAuth2 oAuth2) {
this.oAuth2 = oAuth2;
}
public Assertion getAssertion() {
return assertion;
}
public void setAssertion(Assertion assertion) {
this.assertion = assertion;
}
public String getConversationId() {
return conversationId;
}
public void setConversationId(String conversationId) {
this.conversationId = conversationId;
}
public String getApiUrl() {
return apiUrl;
}
public void setApiUrl(String apiUrl) {
this.apiUrl = apiUrl;
}
public String getApiBody() {
return apiBody;
}
public void setApiBody(String apiBody) {
this.apiBody = apiBody;
}
public String getEvaluatedApiUrl() {
return evaluatedApiUrl;
}
public void setEvaluatedApiUrl(String evaluatedApiUrl) {
this.evaluatedApiUrl = evaluatedApiUrl;
}
}
| Jason-Chen-2017/restfeel | src/main/java/com/restfeel/entity/RfRequest.java | Java | apache-2.0 | 3,393 |
// Copyright 2015 Garrett D'Amore
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use file except in compliance with the License.
// You may obtain a copy of the license at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"math/rand"
"time"
"github.com/gdamore/tcell"
"github.com/gdamore/tcell/views"
)
type Level struct {
name string
title string
width int
height int
startx int
starty int
game *Game
layer int
maxlayer int
view *views.ViewPort
maxtime time.Duration
begin time.Time
expired bool
gravity float64
clock AlarmClock
stopped bool
manager *SpriteManager
terrain *Sprite
data *LevelData
win bool
started bool
}
func NewLevelFromData(d *LevelData) *Level {
lvl := &Level{data: d}
lvl.name = d.Name
lvl.title = d.Properties.PropString("title", lvl.name)
timer := d.Properties.PropInt("timer", 300)
lvl.gravity = d.Properties.PropFloat64("gravity", 0.0)
lvl.width = d.Properties.PropInt("width", 0)
lvl.height = d.Properties.PropInt("height", 0)
if lvl.width == 0 || lvl.height == 0 {
panic("level has no dimensions!")
}
lvl.maxtime = time.Duration(timer) * time.Second
lvl.manager = NewSpriteManager(lvl.width, lvl.height)
lvl.clock = NewAlarmClock()
return lvl
}
func (l *Level) Name() string {
return l.name
}
func (l *Level) Title() string {
return l.title
}
func (l *Level) randomViewXY() (int, int) {
x1, y1, x2, y2 := l.view.GetVisible()
return rand.Intn(x2-x1+1) + x1, rand.Intn(y2-y1+1) + y1
}
func (l *Level) Update(now time.Time) {
l.clock.Tick(now)
l.manager.Update(now)
if l.gravity != 0 {
l.HandleEvent(&EventGravity{when: now, accel: l.gravity})
}
if l.GetTimer() == 0 && !l.expired && !l.win && l.started {
l.HandleEvent(&EventTimesUp{})
l.expired = true
}
}
func (l *Level) SetView(v *views.ViewPort) {
l.view = v
v.SetContentSize(l.width, l.height, true)
l.manager.SetView(v)
}
func (l *Level) Draw(v *views.ViewPort) {
l.manager.Draw(v)
}
func (l *Level) Reset() {
l.manager.Reset()
l.clock.Reset()
for name, plist := range l.data.Objects {
props := GameObjectProps{}
props["label"] = name
for k, v := range plist {
props[k] = v
}
MakeGameObject(l, props["class"], props)
}
l.begin = time.Now()
l.stopped = false
l.started = false
l.win = false
l.expired = false
}
func (l *Level) GetTimer() time.Duration {
if l.win || !l.started {
return l.maxtime
}
d := time.Now().Sub(l.begin)
d = l.maxtime - d
if d < 0 {
d = 0
}
return d
}
func (l *Level) SetGame(g *Game) {
l.game = g
}
func (l *Level) Layer() int {
return LayerTerrain
}
func (l *Level) Size() (int, int) {
return l.width, l.height
}
func (l *Level) MakeVisible(x, y int) {
if l.view != nil {
l.view.MakeVisible(x, y)
}
}
func (l *Level) Center(x, y int) {
if l.view != nil {
l.view.Center(x, y)
}
}
func (l *Level) Start() {
l.started = true
l.begin = time.Now()
l.HandleEvent(&EventLevelStart{})
}
func (l *Level) ShowPress() {
x1, y1, x2, y2 := l.view.GetVisible()
sprite := GetSprite("PressSpace")
sprite.SetLayer(LayerDialog)
sprite.SetFrame("F0")
sprite.SetPosition(x1+(x2-x1)/2, y1+(y2-y1)/2+2)
l.manager.AddSprite(sprite)
}
func (l *Level) ShowComplete() {
x1, y1, x2, y2 := l.view.GetVisible()
sprite := GetSprite("LevelComplete")
sprite.SetLayer(LayerDialog)
sprite.SetFrame("F0")
sprite.SetPosition(x1+(x2-x1)/2, y1+(y2-y1)/2)
l.manager.AddSprite(sprite)
}
func (l *Level) HandleEvent(ev tcell.Event) bool {
switch ev := ev.(type) {
case *tcell.EventKey:
switch ev.Key() {
case tcell.KeyCtrlR:
// secret reset button
l.Reset()
}
case *tcell.EventMouse:
offx, offy, _, _ := l.view.GetVisible()
px1, py1, px2, py2 := l.view.GetPhysical()
mx, my := ev.Position()
if mx < px1 || mx > px2 || my < py1 || my > py2 {
// outside our view
return false
}
if ev.Buttons()&tcell.Button1 != 0 {
l.stopped = true
l.view.Center(offx+mx-px1, offy+my-py1)
} else if ev.Buttons()&tcell.Button2 != 0 {
l.Reset()
} else if ev.Buttons()&tcell.Button3 != 0 {
l.Reset()
}
return true
case *EventPlayerDeath:
l.game.HandleEvent(ev)
l.ShowPress()
return true
case *EventLevelComplete:
l.win = true
l.game.HandleEvent(ev)
l.ShowComplete()
l.ShowPress()
return true
case *EventGameOver:
x1, y1, x2, y2 := l.view.GetVisible()
sprite := GetSprite("GameOver")
sprite.SetLayer(LayerDialog)
sprite.SetFrame("F0")
sprite.SetPosition(x1+(x2-x1)/2, y1+(y2-y1)/2)
l.manager.AddSprite(sprite)
case *EventTimesUp:
bw := GetSprite("Blastwave")
bw.Resize(l.width, l.height)
bw.ScheduleFrame("0", time.Now().Add(2*time.Second))
l.AddSprite(bw)
dur := time.Duration(0)
for i := 0; i < 100; i++ {
x, y := l.randomViewXY()
sprite := GetSprite("Explosion")
sprite.ScheduleFrame("0", time.Now().Add(dur))
sprite.SetPosition(x, y)
l.AddSprite(sprite)
dur += time.Millisecond * 5
for j := 0; j < 4; j++ {
x, y = l.randomViewXY()
sprite = GetSprite("SmallExplosion")
sprite.SetPosition(x, y)
sprite.ScheduleFrame("0", time.Now().Add(dur))
l.AddSprite(sprite)
dur += time.Millisecond * 50
}
}
}
if l.stopped {
return false
}
return l.manager.HandleEvent(ev)
}
func (l *Level) AddSprite(sprite *Sprite) {
l.manager.AddSprite(sprite)
}
func (l *Level) RemoveSprite(sprite *Sprite) {
l.manager.RemoveSprite(sprite)
}
func (l *Level) AddAlarm(d time.Duration, h EventHandler) *Alarm {
return l.clock.Schedule(d, h)
}
func (l *Level) RemoveAlarm(a *Alarm) {
l.clock.Cancel(a)
}
| gdamore/proxima5 | level.go | GO | apache-2.0 | 5,973 |
# -*- coding: utf-8 -*-
"""Class representing the mapper for the parser init files."""
from plasoscaffolder.bll.mappings import base_mapping_helper
from plasoscaffolder.bll.mappings import base_sqliteplugin_mapping
from plasoscaffolder.model import init_data_model
class ParserInitMapping(
base_sqliteplugin_mapping.BaseSQLitePluginMapper):
"""Class representing the parser mapper."""
_PARSER_INIT_TEMPLATE = 'parser_init_template.jinja2'
def __init__(self, mapping_helper: base_mapping_helper.BaseMappingHelper):
"""Initializing the init mapper class.
Args:
mapping_helper (base_mapping_helper.BaseMappingHelper): the helper class
for the mapping
"""
super().__init__()
self._helper = mapping_helper
def GetRenderedTemplate(
self,
data: init_data_model.InitDataModel) -> str:
"""Retrieves the parser init file.
Args:
data (init_data_model.InitDataModel): the data for init file
Returns:
str: the rendered template
"""
context = {'plugin_name': data.plugin_name,
'is_create_template': data.is_create_template}
rendered = self._helper.RenderTemplate(
self._PARSER_INIT_TEMPLATE, context)
return rendered
| ClaudiaSaxer/PlasoScaffolder | src/plasoscaffolder/bll/mappings/parser_init_mapping.py | Python | apache-2.0 | 1,234 |
#include <iostream>
#include <zmf/AbstractModule.hpp>
#include "zsdn/StartupHelper.h"
#include "LinkDiscoveryModule.hpp"
#include <google/protobuf/stubs/common.h>
int main(int argc, char* argv[]) {
int returnCode;
if (zsdn::StartupHelper::paramsOkay(argc, argv)) {
zmf::logging::ZmfLogging::initializeLogging("LinkDiscoveryModule", argv[1]);
returnCode = zsdn::StartupHelper::startInConsole(new LinkDiscoveryModule(0), argv[1]);
} else {
returnCode = 1;
}
google::protobuf::ShutdownProtobufLibrary();
return returnCode;
} | zeroSDN/ZSDN-Controller | modules/cpp/LinkDiscoveryModule/main.cpp | C++ | apache-2.0 | 570 |
/**
* Copyright 2015-2016 GetSocial 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.
*/
#if ENABLE_GETSOCIAL_CHAT
#if UNITY_IOS
using System;
using GetSocialSdk.Core;
namespace GetSocialSdk.Chat
{
class PublicChatRoomIOSImpl : ChatRoomIOSImpl, IPublicChatRoom
{
internal PublicChatRoomIOSImpl(string roomTopic) : base(roomTopic)
{
}
public string Name
{
get
{
return ChatRoomIOSImpl._getRoomName(roomTopic);
}
}
public bool IsSubscribed
{
get
{
return ChatRoomIOSImpl._isSubscribedToPublicRoom(roomTopic);
}
}
public void Subscribe(Action onSuccess, Action<string> onFailure)
{
ChatRoomIOSImpl._subscribeToPublicRoom(roomTopic, onSuccess.GetPointer(), onFailure.GetPointer(),
GetSocialNativeBridgeIOS.CompleteCallback, GetSocialNativeBridgeIOS.FailureCallback);
}
public void Unsubscribe(Action onSuccess, Action<string> onFailure)
{
ChatRoomIOSImpl._unsubscribeFromPublicRoom(roomTopic, onSuccess.GetPointer(), onFailure.GetPointer(),
GetSocialNativeBridgeIOS.CompleteCallback, GetSocialNativeBridgeIOS.FailureCallback);
}
public override string ToString()
{
return string.Format("[PublicChatRoomIOSImpl: IsSubscribed={0}, Name={1}, Base={2}]", IsSubscribed, Name, base.ToString());
}
}
}
#endif
#endif | getsocial-im/getsocial-unity-kakao-demo | Assets/GetSocial/Scripts/Chat/Platforms/IOS/Room/PublicChatRoomIOSImpl.cs | C# | apache-2.0 | 2,066 |
'use strict';
angular.module('Home').controller('ModalDeleteAssetCtrl',
function ($scope, $modalInstance, parentScope, HomeService,
asset, name, token, typeId, menuId) {
$scope.name = name;
$scope.message = "Are you sure you want to delete this asset ?";
$scope.ok = function () {
HomeService.deleteAsset(
token,
menuId,
asset,
function (response) {
if (response) {
if (response.error_description) {
$scope.error = response.error_description + ". Please logout!";
} else {
if (response.success) {
parentScope.removeAssetFromTemplate(typeId, asset);
} else {
$scope.message = response.message;
}
}
} else {
$scope.error = "Invalid server response";
}
}
);
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}); | fixxit/MoknJ-WebUI | modules/templatetypes/asset/delete/controllers.js | JavaScript | apache-2.0 | 1,480 |
/*
Copyright 2016 ParticleNET
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace Particle.Common.Controls
{
public sealed partial class TinkerControl : UserControl
{
public TinkerControl()
{
this.InitializeComponent();
}
}
}
| ParticleNET/Particle-Windows-app | Particle-Win8/Particle-Win8.Shared/Controls/TinkerControl.xaml.cs | C# | apache-2.0 | 1,272 |
/*
* Copyright 2000-2017 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.ui.speedSearch;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.codeStyle.AllOccurrencesMatcher;
import com.intellij.psi.codeStyle.FixingLayoutMatcher;
import com.intellij.psi.codeStyle.MinusculeMatcher;
import com.intellij.psi.codeStyle.NameUtil;
import com.intellij.util.text.Matcher;
import com.intellij.util.ui.UIUtil;
import kava.beans.PropertyChangeListener;
import kava.beans.PropertyChangeSupport;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class SpeedSearch extends SpeedSearchSupply implements KeyListener {
public static final String PUNCTUATION_MARKS = "*_-\"'/.#$>: ,;?!@%^&";
private final PropertyChangeSupport myChangeSupport = new PropertyChangeSupport(this);
private final boolean myMatchAllOccurrences;
private String myString = "";
private boolean myEnabled;
private Matcher myMatcher;
public SpeedSearch() {
this(false);
}
public SpeedSearch(boolean matchAllOccurrences) {
myMatchAllOccurrences = matchAllOccurrences;
}
public void type(String letter) {
updatePattern(myString + letter);
}
public void backspace() {
if (myString.length() > 0) {
updatePattern(myString.substring(0, myString.length() - 1));
}
}
public boolean shouldBeShowing(String string) {
return string == null || myString.length() == 0 || (myMatcher != null && myMatcher.matches(string));
}
public void processKeyEvent(KeyEvent e) {
if (e.isConsumed() || !myEnabled) return;
String old = myString;
if (e.getID() == KeyEvent.KEY_PRESSED) {
if (KeymapUtil.isEventForAction(e, "EditorDeleteToWordStart")) {
if (isHoldingFilter()) {
while (!myString.isEmpty() && !Character.isWhitespace(myString.charAt(myString.length() - 1))) {
backspace();
}
e.consume();
}
}
else if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
backspace();
e.consume();
}
else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
if (isHoldingFilter()) {
updatePattern("");
e.consume();
}
}
}
else if (e.getID() == KeyEvent.KEY_TYPED) {
if (!UIUtil.isReallyTypedEvent(e)) return;
// key-char is good only on KEY_TYPED
// for example: key-char on ctrl-J PRESSED is \n
// see https://en.wikipedia.org/wiki/Control_character
char ch = e.getKeyChar();
if (Character.isLetterOrDigit(ch) || !startedWithWhitespace(ch) && PUNCTUATION_MARKS.indexOf(ch) != -1) {
type(Character.toString(ch));
e.consume();
}
}
if (!old.equalsIgnoreCase(myString)) {
update();
}
}
private boolean startedWithWhitespace(char ch) {
return !isHoldingFilter() && Character.isWhitespace(ch);
}
public void update() {
}
public void noHits() {
}
public boolean isHoldingFilter() {
return myEnabled && myString.length() > 0;
}
public void setEnabled(boolean enabled) {
myEnabled = enabled;
}
public void reset() {
if (isHoldingFilter()) {
updatePattern("");
}
if (myEnabled) {
update();
}
}
public String getFilter() {
return myString;
}
public void updatePattern(final String string) {
String prevString = myString;
myString = string;
try {
String pattern = "*" + string;
NameUtil.MatchingCaseSensitivity caseSensitivity = NameUtil.MatchingCaseSensitivity.NONE;
String separators = "";
myMatcher = myMatchAllOccurrences ? AllOccurrencesMatcher.create(pattern, caseSensitivity, separators) : new FixingLayoutMatcher(pattern, caseSensitivity, separators);
}
catch (Exception e) {
myMatcher = null;
}
fireStateChanged(prevString);
}
@Nullable
public Matcher getMatcher() {
return myMatcher;
}
@Nullable
@Override
public Iterable<TextRange> matchingFragments(@Nonnull String text) {
if (myMatcher instanceof MinusculeMatcher) {
return ((MinusculeMatcher)myMatcher).matchingFragments(text);
}
return null;
}
@Override
public void refreshSelection() {
}
@Override
public boolean isPopupActive() {
return isHoldingFilter();
}
@Nullable
@Override
public String getEnteredPrefix() {
return myString;
}
@Override
public void addChangeListener(@Nonnull PropertyChangeListener listener) {
myChangeSupport.addPropertyChangeListener(listener);
}
@Override
public void removeChangeListener(@Nonnull PropertyChangeListener listener) {
myChangeSupport.removePropertyChangeListener(listener);
}
private void fireStateChanged(String prevString) {
myChangeSupport.firePropertyChange(SpeedSearchSupply.ENTERED_PREFIX_PROPERTY_NAME, prevString, getEnteredPrefix());
}
@Override
public void findAndSelectElement(@Nonnull String searchQuery) {
}
@Override
public void keyTyped(KeyEvent e) {
processKeyEvent(e);
}
@Override
public void keyPressed(KeyEvent e) {
processKeyEvent(e);
}
@Override
public void keyReleased(KeyEvent e) {
processKeyEvent(e);
}
}
| consulo/consulo | modules/base/platform-api/src/main/java/com/intellij/ui/speedSearch/SpeedSearch.java | Java | apache-2.0 | 5,838 |
/*
* Copyright 2012 International Business Machines Corp.
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ibm.jbatch.container.jsl.impl;
import com.ibm.jbatch.container.jsl.TransitionElement;
import com.ibm.jbatch.container.jsl.ExecutionElement;
import com.ibm.jbatch.container.jsl.Transition;
public class TransitionImpl implements Transition {
private TransitionElement transitionElement;
private ExecutionElement executionElement;
boolean finishedTransitioning = false;
boolean noTransitionElementMatchedAfterException = false;
public TransitionImpl() {
super();
}
@Override
public TransitionElement getTransitionElement() {
return transitionElement;
}
@Override
public ExecutionElement getNextExecutionElement() {
return executionElement;
}
@Override
public void setTransitionElement(TransitionElement transitionElement) {
this.transitionElement = transitionElement;
}
@Override
public void setNextExecutionElement(ExecutionElement executionElement) {
this.executionElement = executionElement;
}
@Override
public boolean isFinishedTransitioning() {
return finishedTransitioning;
}
@Override
public void setFinishedTransitioning() {
this.finishedTransitioning = true;
}
@Override
public void setNoTransitionElementMatchAfterException() {
this.noTransitionElementMatchedAfterException = true;
}
@Override
public boolean noTransitionElementMatchedAfterException() {
return noTransitionElementMatchedAfterException;
}
}
| WASdev/standards.jsr352.jbatch | com.ibm.jbatch.container/src/main/java/com/ibm/jbatch/container/jsl/impl/TransitionImpl.java | Java | apache-2.0 | 2,254 |
/**
* guy
* 异步树
* @class BI.TreeView
* @extends BI.Pane
*/
BI.TreeView = BI.inherit(BI.Pane, {
_defaultConfig: function () {
return BI.extend(BI.TreeView.superclass._defaultConfig.apply(this, arguments), {
_baseCls: "bi-tree",
paras: {
selectedValues: {}
},
itemsCreator: BI.emptyFn
});
},
_init: function () {
BI.TreeView.superclass._init.apply(this, arguments);
var o = this.options;
this._stop = false;
this._createTree();
this.tip = BI.createWidget({
type: "bi.loading_bar",
invisible: true,
handler: BI.bind(this._loadMore, this)
});
BI.createWidget({
type: "bi.vertical",
scrollable: true,
scrolly: false,
element: this,
items: [this.tip]
});
if(BI.isNotNull(o.value)) {
this.setSelectedValue(o.value);
}
if (BI.isIE9Below && BI.isIE9Below()) {
this.element.addClass("hack");
}
},
_createTree: function () {
this.id = "bi-tree" + BI.UUID();
if (this.nodes) {
this.nodes.destroy();
}
if (this.tree) {
this.tree.destroy();
}
this.tree = BI.createWidget({
type: "bi.layout",
element: "<ul id='" + this.id + "' class='ztree'></ul>"
});
BI.createWidget({
type: "bi.default",
element: this.element,
items: [this.tree]
});
},
// 选择节点触发方法
_selectTreeNode: function (treeId, treeNode) {
this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.CLICK, treeNode, this);
this.fireEvent(BI.TreeView.EVENT_CHANGE, treeNode, this);
},
// 配置属性
_configSetting: function () {
var paras = this.options.paras;
var self = this;
var setting = {
async: {
enable: true,
url: getUrl,
autoParam: ["id", "name"], // 节点展开异步请求自动提交id和name
otherParam: BI.cjkEncodeDO(paras) // 静态参数
},
check: {
enable: true
},
data: {
key: {
title: "title",
name: "text" // 节点的name属性替换成text
},
simpleData: {
enable: true // 可以穿id,pid属性的对象数组
}
},
view: {
showIcon: false,
expandSpeed: "",
nameIsHTML: true, // 节点可以用html标签代替
dblClickExpand: false
},
callback: {
beforeExpand: beforeExpand,
onAsyncSuccess: onAsyncSuccess,
onAsyncError: onAsyncError,
beforeCheck: beforeCheck,
onCheck: onCheck,
onExpand: onExpand,
onCollapse: onCollapse,
onClick: onClick
}
};
var className = "dark", perTime = 100;
function onClick (event, treeId, treeNode) {
// 当前点击节点的状态是半选,且为true_part, 则将其改为false_part,使得点击半选后切换到的是全选
var checked = treeNode.checked;
var status = treeNode.getCheckStatus();
if(status.half === true && status.checked === true) {
checked = false;
}
// 更新此node的check状态, 影响父子关联,并调用beforeCheck和onCheck回调
self.nodes.checkNode(treeNode, !checked, true, true);
}
function getUrl (treeId, treeNode) {
var parentNode = self._getParentValues(treeNode);
treeNode.times = treeNode.times || 1;
var param = "id=" + treeNode.id
+ "×=" + (treeNode.times++)
+ "&parentValues= " + _global.encodeURIComponent(BI.jsonEncode(parentNode))
+ "&checkState=" + _global.encodeURIComponent(BI.jsonEncode(treeNode.getCheckStatus()));
return "&" + param;
}
function beforeExpand (treeId, treeNode) {
if (!treeNode.isAjaxing) {
if (!treeNode.children) {
treeNode.times = 1;
ajaxGetNodes(treeNode, "refresh");
}
return true;
}
BI.Msg.toast("Please Wait。", "warning"); // 不展开节点,也不触发onExpand事件
return false;
}
function onAsyncSuccess (event, treeId, treeNode, msg) {
treeNode.halfCheck = false;
if (!msg || msg.length === 0 || /^<html>[\s,\S]*<\/html>$/gi.test(msg) || self._stop) {
return;
}
var zTree = self.nodes;
var totalCount = treeNode.count || 0;
// 尝试去获取下一组节点,若获取值为空数组,表示获取完成
// TODO by GUY
if (treeNode.children.length > totalCount) {
treeNode.count = treeNode.children.length;
BI.delay(function () {
ajaxGetNodes(treeNode);
}, perTime);
} else {
// treeNode.icon = "";
zTree.updateNode(treeNode);
zTree.selectNode(treeNode.children[0]);
// className = (className === "dark" ? "":"dark");
}
}
function onAsyncError (event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
var zTree = self.nodes;
BI.Msg.toast("Error!", "warning");
// treeNode.icon = "";
// zTree.updateNode(treeNode);
}
function ajaxGetNodes (treeNode, reloadType) {
var zTree = self.nodes;
if (reloadType == "refresh") {
zTree.updateNode(treeNode); // 刷新一下当前节点,如果treeNode.xxx被改了的话
}
zTree.reAsyncChildNodes(treeNode, reloadType, true); // 强制加载子节点,reloadType === refresh为先清空再加载,否则为追加到现有子节点之后
}
function beforeCheck (treeId, treeNode) {
treeNode.halfCheck = false;
if (treeNode.checked === true) {
// 将展开的节点halfCheck设为false,解决展开节点存在halfCheck=true的情况 guy
// 所有的半选状态都需要取消halfCheck=true的情况
function track (children) {
BI.each(children, function (i, ch) {
if (ch.halfCheck === true) {
ch.halfCheck = false;
track(ch.children);
}
});
}
track(treeNode.children);
var treeObj = self.nodes;
var nodes = treeObj.getSelectedNodes();
BI.$.each(nodes, function (index, node) {
node.halfCheck = false;
});
}
var status = treeNode.getCheckStatus();
// 当前点击节点的状态是半选,且为true_part, 则将其改为false_part,使得点击半选后切换到的是全选
if(status.half === true && status.checked === true) {
treeNode.checked = false;
}
}
function onCheck (event, treeId, treeNode) {
self._selectTreeNode(treeId, treeNode);
}
function onExpand (event, treeId, treeNode) {
treeNode.halfCheck = false;
}
function onCollapse (event, treeId, treeNode) {
}
return setting;
},
_getParentValues: function (treeNode) {
if (!treeNode.getParentNode()) {
return [];
}
var parentNode = treeNode.getParentNode();
var result = this._getParentValues(parentNode);
result = result.concat([this._getNodeValue(parentNode)]);
return result;
},
_getNodeValue: function (node) {
// 去除标红
return node.value == null ? BI.replaceAll(node.text.replace(/<[^>]+>/g, ""), " ", " ") : node.value;
},
// 获取半选框值
_getHalfSelectedValues: function (map, node) {
var self = this;
var checkState = node.getCheckStatus();
// 将未选的去掉
if (checkState.checked === false && checkState.half === false) {
return;
}
// 如果节点已展开,并且是半选
if (BI.isNotEmptyArray(node.children) && checkState.half === true) {
var children = node.children;
BI.each(children, function (i, ch) {
self._getHalfSelectedValues(map, ch);
});
return;
}
var parent = node.parentValues || self._getParentValues(node);
var path = parent.concat(this._getNodeValue(node));
// 当前节点是全选的,因为上面的判断已经排除了不选和半选
if (BI.isNotEmptyArray(node.children) || checkState.half === false) {
this._buildTree(map, path);
return;
}
// 剩下的就是半选不展开的节点,因为不知道里面是什么情况,所以借助selectedValues(这个是完整的选中情况)
var storeValues = BI.deepClone(this.options.paras.selectedValues);
var treeNode = this._getTree(storeValues, path);
this._addTreeNode(map, parent, this._getNodeValue(node), treeNode);
},
// 获取的是以values最后一个节点为根的子树
_getTree: function (map, values) {
var cur = map;
BI.any(values, function (i, value) {
if (cur[value] == null) {
return true;
}
cur = cur[value];
});
return cur;
},
// 以values为path一路向里补充map, 并在末尾节点添加key: value节点
_addTreeNode: function (map, values, key, value) {
var cur = map;
BI.each(values, function (i, value) {
if (cur[value] == null) {
cur[value] = {};
}
cur = cur[value];
});
cur[key] = value;
},
// 构造树节点
_buildTree: function (map, values) {
var cur = map;
BI.each(values, function (i, value) {
if (cur[value] == null) {
cur[value] = {};
}
cur = cur[value];
});
},
// 获取选中的值
_getSelectedValues: function () {
var self = this;
var hashMap = {};
var rootNoots = this.nodes.getNodes();
track(rootNoots); // 可以看到这个方法没有递归调用,所以在_getHalfSelectedValues中需要关心全选的节点
function track (nodes) {
BI.each(nodes, function (i, node) {
var checkState = node.getCheckStatus();
if (checkState.checked === true || checkState.half === true) {
if (checkState.half === true) {
self._getHalfSelectedValues(hashMap, node);
} else {
var parentValues = node.parentValues || self._getParentValues(node);
var values = parentValues.concat([self._getNodeValue(node)]);
self._buildTree(hashMap, values);
}
}
});
}
return hashMap;
},
// 处理节点
_dealWidthNodes: function (nodes) {
var self = this, o = this.options;
var ns = BI.Tree.arrayFormat(nodes);
BI.each(ns, function (i, n) {
n.title = n.title || n.text || n.value;
n.isParent = n.isParent || n.parent;
// 处理标红
if (BI.isKey(o.paras.keyword)) {
n.text = BI.$("<div>").__textKeywordMarked__(n.text, o.paras.keyword, n.py).html();
} else {
n.text = BI.htmlEncode(n.text + "");
}
});
return nodes;
},
_loadMore: function () {
var self = this, o = this.options;
this.tip.setLoading();
var op = BI.extend({}, o.paras, {
times: ++this.times
});
o.itemsCreator(op, function (res) {
if (self._stop === true) {
return;
}
var hasNext = !!res.hasNext, nodes = res.items || [];
if (!hasNext) {
self.tip.setEnd();
} else {
self.tip.setLoaded();
}
if (nodes.length > 0) {
self.nodes.addNodes(null, self._dealWidthNodes(nodes));
}
});
},
// 生成树内部方法
_initTree: function (setting) {
var self = this, o = this.options;
self.fireEvent(BI.Events.INIT);
this.times = 1;
var tree = this.tree;
tree.empty();
this.loading();
this.tip.setVisible(false);
var callback = function (nodes) {
if (self._stop === true) {
return;
}
self.nodes = BI.$.fn.zTree.init(tree.element, setting, nodes);
};
var op = BI.extend({}, o.paras, {
times: 1
});
o.itemsCreator(op, function (res) {
if (self._stop === true) {
return;
}
var hasNext = !!res.hasNext, nodes = res.items || [];
if (nodes.length > 0) {
callback(self._dealWidthNodes(nodes));
}
self.setTipVisible(nodes.length <= 0);
self.loaded();
if (!hasNext) {
self.tip.invisible();
} else {
self.tip.setLoaded();
}
op.times === 1 && self.fireEvent(BI.Events.AFTERINIT);
});
},
// 构造树结构,
initTree: function (nodes, setting) {
var setting = setting || {
async: {
enable: false
},
check: {
enable: false
},
data: {
key: {
title: "title",
name: "text"
},
simpleData: {
enable: true
}
},
view: {
showIcon: false,
expandSpeed: "",
nameIsHTML: true
},
callback: {}
};
this.nodes = BI.$.fn.zTree.init(this.tree.element, setting, nodes);
},
start: function () {
this._stop = false;
},
stop: function () {
this._stop = true;
},
// 生成树方法
stroke: function (config) {
delete this.options.keyword;
BI.extend(this.options.paras, config);
var setting = this._configSetting();
this._createTree();
this.start();
this._initTree(setting);
},
populate: function () {
this.stroke.apply(this, arguments);
},
hasChecked: function () {
var treeObj = this.nodes;
return treeObj.getCheckedNodes(true).length > 0;
},
checkAll: function (checked) {
function setNode (children) {
BI.each(children, function (i, child) {
child.halfCheck = false;
setNode(child.children);
});
}
if (!this.nodes) {
return;
}
BI.each(this.nodes.getNodes(), function (i, node) {
node.halfCheck = false;
setNode(node.children);
});
this.nodes.checkAllNodes(checked);
},
expandAll: function (flag) {
this.nodes && this.nodes.expandAll(flag);
},
// 设置树节点的状态
setValue: function (value, param) {
this.checkAll(false);
this.updateValue(value, param);
this.refresh();
},
setSelectedValue: function (value) {
this.options.paras.selectedValues = BI.deepClone(value || {});
},
updateValue: function (values, param) {
if (!this.nodes) {
return;
}
param || (param = "value");
var treeObj = this.nodes;
BI.each(values, function (v, op) {
var nodes = treeObj.getNodesByParam(param, v, null);
BI.each(nodes, function (j, node) {
BI.extend(node, {checked: true}, op);
treeObj.updateNode(node);
});
});
},
refresh: function () {
this.nodes && this.nodes.refresh();
},
getValue: function () {
if (!this.nodes) {
return null;
}
return this._getSelectedValues();
},
destroyed: function () {
this.stop();
this.nodes && this.nodes.destroy();
}
});
BI.extend(BI.TreeView, {
REQ_TYPE_INIT_DATA: 1,
REQ_TYPE_ADJUST_DATA: 2,
REQ_TYPE_SELECT_DATA: 3,
REQ_TYPE_GET_SELECTED_DATA: 4
});
BI.TreeView.EVENT_CHANGE = "EVENT_CHANGE";
BI.TreeView.EVENT_INIT = BI.Events.INIT;
BI.TreeView.EVENT_AFTERINIT = BI.Events.AFTERINIT;
BI.shortcut("bi.tree_view", BI.TreeView); | fanruan/fineui | src/base/tree/ztree/treeview.js | JavaScript | apache-2.0 | 17,478 |
/* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.coap;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.camel.spi.EndpointUriFactory;
/**
* Generated by camel build tools - do NOT edit this file!
*/
public class CoAPEndpointUriFactory extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory {
private static final String BASE = "coaps+tcp:uri";
private static final String[] SCHEMES = new String[]{"coap", "coaps", "coap+tcp", "coaps+tcp"};
private static final Set<String> PROPERTY_NAMES;
static {
Set<String> set = new HashSet<>(17);
set.add("uri");
set.add("alias");
set.add("cipherSuites");
set.add("clientAuthentication");
set.add("privateKey");
set.add("pskStore");
set.add("publicKey");
set.add("recommendedCipherSuitesOnly");
set.add("sslContextParameters");
set.add("trustedRpkStore");
set.add("bridgeErrorHandler");
set.add("coapMethodRestrict");
set.add("exceptionHandler");
set.add("exchangePattern");
set.add("lazyStartProducer");
set.add("basicPropertyBinding");
set.add("synchronous");
PROPERTY_NAMES = set;
}
@Override
public boolean isEnabled(String scheme) {
for (String s : SCHEMES) {
if (s.equals(scheme)) {
return true;
}
}
return false;
}
@Override
public String buildUri(String scheme, Map<String, Object> properties) throws URISyntaxException {
String syntax = scheme + BASE;
String uri = syntax;
Map<String, Object> copy = new HashMap<>(properties);
uri = buildPathParameter(syntax, uri, "uri", null, false, copy);
uri = buildQueryParameters(uri, copy);
return uri;
}
@Override
public Set<String> propertyNames() {
return PROPERTY_NAMES;
}
@Override
public boolean isLenientProperties() {
return false;
}
}
| alvinkwekel/camel | components/camel-coap/src/generated/java/org/apache/camel/coap/CoAPEndpointUriFactory.java | Java | apache-2.0 | 2,176 |
/*
* Copyright (c) 2015-2016 LoiLo 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 tv.loilo.promise;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Parameters that are passed to {@link UntilCallback}.
*/
public final class UntilParams<T> extends ResultParams<T> {
private final AtomicInteger mIndex;
public UntilParams(AtomicInteger index, Result<T> result, CloseableStack scope, Object tag) {
super(result, scope, tag);
mIndex = index;
}
public AtomicInteger getIndex() {
return mIndex;
}
}
| loilo-inc/loilo-promise | promise/src/main/java/tv/loilo/promise/UntilParams.java | Java | apache-2.0 | 1,081 |
/*
* 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
*
* 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 com.google.events.cloud.cloudbuild.v1;
import java.io.IOException;
public enum MachineTypeEnum {
N1_HIGHCPU_32, N1_HIGHCPU_8, UNSPECIFIED;
public String toValue() {
switch (this) {
case N1_HIGHCPU_32: return "N1_HIGHCPU_32";
case N1_HIGHCPU_8: return "N1_HIGHCPU_8";
case UNSPECIFIED: return "UNSPECIFIED";
}
return null;
}
public static MachineTypeEnum forValue(String value) throws IOException {
if (value.equals("N1_HIGHCPU_32")) return N1_HIGHCPU_32;
if (value.equals("N1_HIGHCPU_8")) return N1_HIGHCPU_8;
if (value.equals("UNSPECIFIED")) return UNSPECIFIED;
throw new IOException("Cannot deserialize MachineTypeEnum");
}
}
| googleapis/google-cloudevents-java | src/main/java/com/google/events/cloud/cloudbuild/v1/MachineTypeEnum.java | Java | apache-2.0 | 1,348 |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudformation-2010-05-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CloudFormation.Model
{
/// <summary>
/// Container for the parameters to the CreateStack operation.
/// Creates a stack as specified in the template. After the call completes successfully,
/// the stack creation starts. You can check the status of the stack via the <a>DescribeStacks</a>
/// API.
/// </summary>
public partial class CreateStackRequest : AmazonCloudFormationRequest
{
private List<string> _capabilities = new List<string>();
private bool? _disableRollback;
private List<string> _notificationARNs = new List<string>();
private OnFailure _onFailure;
private List<Parameter> _parameters = new List<Parameter>();
private List<string> _resourceTypes = new List<string>();
private string _stackName;
private string _stackPolicyBody;
private string _stackPolicyURL;
private List<Tag> _tags = new List<Tag>();
private string _templateBody;
private string _templateURL;
private int? _timeoutInMinutes;
/// <summary>
/// Gets and sets the property Capabilities.
/// <para>
/// A list of capabilities that you must specify before AWS CloudFormation can create
/// or update certain stacks. Some stack templates might include resources that can affect
/// permissions in your AWS account. For those stacks, you must explicitly acknowledge
/// their capabilities by specifying this parameter.
/// </para>
///
/// <para>
/// Currently, the only valid value is <code>CAPABILITY_IAM</code>, which is required
/// for the following resources: <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-accesskey.html">
/// AWS::IAM::AccessKey</a>, <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-group.html">
/// AWS::IAM::Group</a>, <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-instanceprofile.html">
/// AWS::IAM::InstanceProfile</a>, <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html">
/// AWS::IAM::Policy</a>, <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html">
/// AWS::IAM::Role</a>, <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html">
/// AWS::IAM::User</a>, and <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-addusertogroup.html">
/// AWS::IAM::UserToGroupAddition</a>. If your stack template contains these resources,
/// we recommend that you review any permissions associated with them. If you don't specify
/// this parameter, this action returns an <code>InsufficientCapabilities</code> error.
/// </para>
/// </summary>
public List<string> Capabilities
{
get { return this._capabilities; }
set { this._capabilities = value; }
}
// Check to see if Capabilities property is set
internal bool IsSetCapabilities()
{
return this._capabilities != null && this._capabilities.Count > 0;
}
/// <summary>
/// Gets and sets the property DisableRollback.
/// <para>
/// Set to <code>true</code> to disable rollback of the stack if stack creation failed.
/// You can specify either <code>DisableRollback</code> or <code>OnFailure</code>, but
/// not both.
/// </para>
///
/// <para>
/// Default: <code>false</code>
/// </para>
/// </summary>
public bool DisableRollback
{
get { return this._disableRollback.GetValueOrDefault(); }
set { this._disableRollback = value; }
}
// Check to see if DisableRollback property is set
internal bool IsSetDisableRollback()
{
return this._disableRollback.HasValue;
}
/// <summary>
/// Gets and sets the property NotificationARNs.
/// <para>
/// The Simple Notification Service (SNS) topic ARNs to publish stack related events.
/// You can find your SNS topic ARNs using the <a href="http://console.aws.amazon.com/sns">SNS
/// console</a> or your Command Line Interface (CLI).
/// </para>
/// </summary>
public List<string> NotificationARNs
{
get { return this._notificationARNs; }
set { this._notificationARNs = value; }
}
// Check to see if NotificationARNs property is set
internal bool IsSetNotificationARNs()
{
return this._notificationARNs != null && this._notificationARNs.Count > 0;
}
/// <summary>
/// Gets and sets the property OnFailure.
/// <para>
/// Determines what action will be taken if stack creation fails. This must be one of:
/// DO_NOTHING, ROLLBACK, or DELETE. You can specify either <code>OnFailure</code> or
/// <code>DisableRollback</code>, but not both.
/// </para>
///
/// <para>
/// Default: <code>ROLLBACK</code>
/// </para>
/// </summary>
public OnFailure OnFailure
{
get { return this._onFailure; }
set { this._onFailure = value; }
}
// Check to see if OnFailure property is set
internal bool IsSetOnFailure()
{
return this._onFailure != null;
}
/// <summary>
/// Gets and sets the property Parameters.
/// <para>
/// A list of <code>Parameter</code> structures that specify input parameters for the
/// stack.
/// </para>
/// </summary>
public List<Parameter> Parameters
{
get { return this._parameters; }
set { this._parameters = value; }
}
// Check to see if Parameters property is set
internal bool IsSetParameters()
{
return this._parameters != null && this._parameters.Count > 0;
}
/// <summary>
/// Gets and sets the property ResourceTypes.
/// <para>
/// The template resource types that you have permissions to work with for this create
/// stack action, such as <code>AWS::EC2::Instance</code>, <code>AWS::EC2::*</code>, or
/// <code>Custom::MyCustomInstance</code>. Use the following syntax to describe template
/// resource types: <code>AWS::*</code> (for all AWS resource), <code>Custom::*</code>
/// (for all custom resources), <code>Custom::<i>logical_ID</i></code> (for a specific
/// custom resource), <code>AWS::<i>service_name</i>::*</code> (for all resources of a
/// particular AWS service), and <code>AWS::<i>service_name</i>::<i>resource_logical_ID</i></code>
/// (for a specific AWS resource).
/// </para>
///
/// <para>
/// If the list of resource types doesn't include a resource that you're creating, the
/// stack creation fails. By default, AWS CloudFormation grants permissions to all resource
/// types. AWS Identity and Access Management (IAM) uses this parameter for AWS CloudFormation-specific
/// condition keys in IAM policies. For more information, see <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html">Controlling
/// Access with AWS Identity and Access Management</a>.
/// </para>
/// </summary>
public List<string> ResourceTypes
{
get { return this._resourceTypes; }
set { this._resourceTypes = value; }
}
// Check to see if ResourceTypes property is set
internal bool IsSetResourceTypes()
{
return this._resourceTypes != null && this._resourceTypes.Count > 0;
}
/// <summary>
/// Gets and sets the property StackName.
/// <para>
/// The name that is associated with the stack. The name must be unique in the region
/// in which you are creating the stack.
/// </para>
/// <note>A stack name can contain only alphanumeric characters (case sensitive) and
/// hyphens. It must start with an alphabetic character and cannot be longer than 255
/// characters.</note>
/// </summary>
public string StackName
{
get { return this._stackName; }
set { this._stackName = value; }
}
// Check to see if StackName property is set
internal bool IsSetStackName()
{
return this._stackName != null;
}
/// <summary>
/// Gets and sets the property StackPolicyBody.
/// <para>
/// Structure containing the stack policy body. For more information, go to <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html">
/// Prevent Updates to Stack Resources</a> in the AWS CloudFormation User Guide. You can
/// specify either the <code>StackPolicyBody</code> or the <code>StackPolicyURL</code>
/// parameter, but not both.
/// </para>
/// </summary>
public string StackPolicyBody
{
get { return this._stackPolicyBody; }
set { this._stackPolicyBody = value; }
}
// Check to see if StackPolicyBody property is set
internal bool IsSetStackPolicyBody()
{
return this._stackPolicyBody != null;
}
/// <summary>
/// Gets and sets the property StackPolicyURL.
/// <para>
/// Location of a file containing the stack policy. The URL must point to a policy (max
/// size: 16KB) located in an S3 bucket in the same region as the stack. You can specify
/// either the <code>StackPolicyBody</code> or the <code>StackPolicyURL</code> parameter,
/// but not both.
/// </para>
/// </summary>
public string StackPolicyURL
{
get { return this._stackPolicyURL; }
set { this._stackPolicyURL = value; }
}
// Check to see if StackPolicyURL property is set
internal bool IsSetStackPolicyURL()
{
return this._stackPolicyURL != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// A set of user-defined <code>Tags</code> to associate with this stack, represented
/// by key/value pairs. Tags defined for the stack are propagated to EC2 resources that
/// are created as part of the stack. A maximum number of 10 tags can be specified.
/// </para>
/// </summary>
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property TemplateBody.
/// <para>
/// Structure containing the template body with a minimum length of 1 byte and a maximum
/// length of 51,200 bytes. For more information, go to <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html">Template
/// Anatomy</a> in the AWS CloudFormation User Guide.
/// </para>
///
/// <para>
/// Conditional: You must specify either the <code>TemplateBody</code> or the <code>TemplateURL</code>
/// parameter, but not both.
/// </para>
/// </summary>
public string TemplateBody
{
get { return this._templateBody; }
set { this._templateBody = value; }
}
// Check to see if TemplateBody property is set
internal bool IsSetTemplateBody()
{
return this._templateBody != null;
}
/// <summary>
/// Gets and sets the property TemplateURL.
/// <para>
/// Location of file containing the template body. The URL must point to a template (max
/// size: 460,800 bytes) that is located in an Amazon S3 bucket. For more information,
/// go to the <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html">Template
/// Anatomy</a> in the AWS CloudFormation User Guide.
/// </para>
///
/// <para>
/// Conditional: You must specify either the <code>TemplateBody</code> or the <code>TemplateURL</code>
/// parameter, but not both.
/// </para>
/// </summary>
public string TemplateURL
{
get { return this._templateURL; }
set { this._templateURL = value; }
}
// Check to see if TemplateURL property is set
internal bool IsSetTemplateURL()
{
return this._templateURL != null;
}
/// <summary>
/// Gets and sets the property TimeoutInMinutes.
/// <para>
/// The amount of time that can pass before the stack status becomes CREATE_FAILED; if
/// <code>DisableRollback</code> is not set or is set to <code>false</code>, the stack
/// will be rolled back.
/// </para>
/// </summary>
public int TimeoutInMinutes
{
get { return this._timeoutInMinutes.GetValueOrDefault(); }
set { this._timeoutInMinutes = value; }
}
// Check to see if TimeoutInMinutes property is set
internal bool IsSetTimeoutInMinutes()
{
return this._timeoutInMinutes.HasValue;
}
}
} | rafd123/aws-sdk-net | sdk/src/Services/CloudFormation/Generated/Model/CreateStackRequest.cs | C# | apache-2.0 | 14,931 |
package cn.oftenporter.servlet;
/**
* 实现了该接口的对象,被输出时设置内容类型为{@linkplain ContentType#APP_JSON}。
*/
public interface JSONHeader
{
}
| CLovinr/OftenPorter | Porter-Bridge-Servlet/src/main/java/cn/oftenporter/servlet/JSONHeader.java | Java | apache-2.0 | 176 |
<?php defined('BASEPATH') or exit('No direct script access allowed');
$lang['streams:textarea.name'] = 'Textarea';
$lang['streams:textarea.default_text'] = 'Default Text';
$lang['streams:textarea.allow_tags'] = 'Allow Lex Tags';
$lang['streams:textarea.content_type'] = 'Content Type';
$lang['streams:textarea_limited.character_limit'] = 'character limit';
$lang['streams:textarea_limited.info_characters'] = 'Characters';
$lang['streams:textarea_limited.info_characters_left'] = 'Characters limit';
$lang['streams:textarea_limited.info_words'] = 'words';
/* End of file textarea_lang.php */ | WeDreamPro/PyroCMS-Textarea-limited-FieldType | language/english/textarea_limited_lang.php | PHP | apache-2.0 | 598 |
package com.simonbrunner.msnswitchctrl.network;
/**
* Created by simon on 03/01/16.
*/
public class SwitchStatus {
private Boolean plug1;
private Boolean plug2;
public Boolean getPlug1() {
return plug1;
}
public void setPlug1(Boolean plug1) {
this.plug1 = plug1;
}
public Boolean getPlug2() {
return plug2;
}
public void setPlug2(Boolean plug2) {
this.plug2 = plug2;
}
}
| simonbrunner/msnswitch-control | src/main/java/com/simonbrunner/msnswitchctrl/network/SwitchStatus.java | Java | apache-2.0 | 451 |
/*
* 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.geode.internal.cache.tier;
import java.io.IOException;
import org.apache.geode.internal.Version;
import org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier;
/**
* Defines the message listener/acceptor interface which is the GemFire Bridge Server. Multiple
* communication stacks may provide implementations for the interfaces defined in this package
*
* @since GemFire 2.0.2
*/
public interface Acceptor {
/**
* The GFE version of the server.
*
* @since GemFire 5.7
*/
Version VERSION = Version.CURRENT.getGemFireVersion();
/**
* Listens for a client to connect and establishes a connection to that client.
*/
void accept() throws Exception;
/**
* Starts this acceptor thread
*/
void start() throws IOException;
/**
* Returns the port on which this acceptor listens for connections from clients.
*/
int getPort();
/**
* returns the server's name string, including the inet address and port that the server is
* listening on
*/
String getServerName();
/**
* Closes this acceptor thread
*/
void close();
/**
* Is this acceptor running (handling connections)?
*/
boolean isRunning();
/**
* Returns the CacheClientNotifier used by this Acceptor.
*/
CacheClientNotifier getCacheClientNotifier();
}
| smanvi-pivotal/geode | geode-core/src/main/java/org/apache/geode/internal/cache/tier/Acceptor.java | Java | apache-2.0 | 2,120 |
/*
* Copyright 2010-2017 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.
*/
#include <aws/robomaker/model/DescribeFleetResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::RoboMaker::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
DescribeFleetResult::DescribeFleetResult() :
m_lastDeploymentStatus(DeploymentStatus::NOT_SET)
{
}
DescribeFleetResult::DescribeFleetResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
m_lastDeploymentStatus(DeploymentStatus::NOT_SET)
{
*this = result;
}
DescribeFleetResult& DescribeFleetResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("name"))
{
m_name = jsonValue.GetString("name");
}
if(jsonValue.ValueExists("arn"))
{
m_arn = jsonValue.GetString("arn");
}
if(jsonValue.ValueExists("robots"))
{
Array<JsonView> robotsJsonList = jsonValue.GetArray("robots");
for(unsigned robotsIndex = 0; robotsIndex < robotsJsonList.GetLength(); ++robotsIndex)
{
m_robots.push_back(robotsJsonList[robotsIndex].AsObject());
}
}
if(jsonValue.ValueExists("createdAt"))
{
m_createdAt = jsonValue.GetDouble("createdAt");
}
if(jsonValue.ValueExists("lastDeploymentStatus"))
{
m_lastDeploymentStatus = DeploymentStatusMapper::GetDeploymentStatusForName(jsonValue.GetString("lastDeploymentStatus"));
}
if(jsonValue.ValueExists("lastDeploymentJob"))
{
m_lastDeploymentJob = jsonValue.GetString("lastDeploymentJob");
}
if(jsonValue.ValueExists("lastDeploymentTime"))
{
m_lastDeploymentTime = jsonValue.GetDouble("lastDeploymentTime");
}
if(jsonValue.ValueExists("tags"))
{
Aws::Map<Aws::String, JsonView> tagsJsonMap = jsonValue.GetObject("tags").GetAllObjects();
for(auto& tagsItem : tagsJsonMap)
{
m_tags[tagsItem.first] = tagsItem.second.AsString();
}
}
return *this;
}
| cedral/aws-sdk-cpp | aws-cpp-sdk-robomaker/source/model/DescribeFleetResult.cpp | C++ | apache-2.0 | 2,665 |
/*
* Copyright 2014 OSBI 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.
*/
/**
* OLAP Totals.
*
*/
package org.saiku.service.olap.totals;
| witcxc/saiku | saiku-core/saiku-service/src/main/java/org/saiku/service/olap/totals/package-info.java | Java | apache-2.0 | 655 |
package ru.job4j.model.dao;
import org.slf4j.LoggerFactory;
import ru.job4j.model.entities.Carbody;
import java.util.List;
/**
* class DCarbody.
*
* @author ifedorenko
* @since 19.12.2018
*/
public class DCarbody extends DAOAbstract<Carbody> {
private static final DCarbody INSTANCE = new DCarbody();
/**
* Private Constructor
*/
private DCarbody() {
this.logger = LoggerFactory.getLogger(DCarbody.class);
}
@Override
public Carbody getById(int id) {
return this.tx(session -> session.get(Carbody.class, id));
}
@Override
public List<Carbody> getAll() {
return this.tx(session -> session.createQuery("from ru.job4j.model.entities.Carbody").getResultList());
}
/**
* Method getInstance.
* @return INSTANCE
*/
public static DCarbody getInstance() {
return INSTANCE;
}
}
| fr3anthe/ifedorenko | 3.1-Hibernate/3.1.2.2-CarSell/src/main/java/ru/job4j/model/dao/DCarbody.java | Java | apache-2.0 | 888 |
package com.xjt.crazypic.edit.pipeline;
public interface RenderingRequestCaller {
public void available(RenderingRequest request);
}
| jituo666/CrazyPic | src/com/xjt/crazypic/edit/pipeline/RenderingRequestCaller.java | Java | apache-2.0 | 138 |
package com.orionplatform.data.data_structures.array;
import java.util.Arrays;
import java.util.Comparator;
import com.orionplatform.core.abstraction.OrionService;
public class ArraySortService<T> extends OrionService
{
public static synchronized void sort(byte[] array)
{
Arrays.sort(array);
}
public static synchronized void sort(short[] array)
{
Arrays.sort(array);
}
public static synchronized void sort(int[] array)
{
Arrays.sort(array);
}
public static synchronized void sort(long[] array)
{
Arrays.sort(array);
}
public static synchronized void sort(float[] array)
{
Arrays.sort(array);
}
public static synchronized void sort(double[] array)
{
Arrays.sort(array);
}
public static synchronized void sort(char[] array)
{
Arrays.sort(array);
}
public static synchronized <T> void sort(T[] array)
{
Arrays.sort(array);
}
public static synchronized <T> void sort(T[] array, Comparator<T> comparator)
{
Arrays.sort(array, comparator);
}
} | orioncode/orionplatform | orion_data/orion_data_structures/src/main/java/com/orionplatform/data/data_structures/array/ArraySortService.java | Java | apache-2.0 | 1,201 |
cmapi.channel["map.view.clicked"].examples = [
{
"title": "Map Clicked",
"description": "Report that the map was clicked at a location",
"valid": true,
"payload": {
"lat": 40.195659093364654,
"lon": -74.28955078125,
"button": "right",
"type": "single",
"keys": ["shift", "ctrl"]
}
},
{
"title": "Map Clicked",
"description": "Report that the map was clicked at a location",
"valid": true,
"payload": {
"lat": 40.195659093364654,
"lon": -74.28955078125,
"button": "middle",
"type": "double",
"keys": ["none"]
}
},
{
"title": "Map Clicked",
"description": "Report that the map was clicked at a location",
"valid": false,
"payload": {
"lat": 40.195659093364654,
"lon": -74.28955078125,
"button": "taco",
"type": "single",
"keys": ["shift", "ctrl"]
}
},
{
"title": "Map Clicked",
"description": "Report that the map was clicked at a location",
"valid": false,
"payload": {
"lat": 40.195659093364654,
"lon": -74.28955078125,
"type": "single",
"keys": ["shift", "ctrl"]
}
}
]; | CMAPI/cmapi | channels/map.view.clicked.examples.js | JavaScript | apache-2.0 | 1,202 |
/*
* 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.activemq.artemis.core.server;
/**
* Logger Code 22
*
* each message id must be 6 digits long starting with 10, the 3rd digit donates the level so
*
* INF0 1
* WARN 2
* DEBUG 3
* ERROR 4
* TRACE 5
* FATAL 6
*
* so an INFO message would be 101000 to 101999
*/
import javax.transaction.xa.Xid;
import java.io.File;
import java.net.SocketAddress;
import java.net.URI;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import io.netty.channel.Channel;
import org.apache.activemq.artemis.api.core.ActiveMQExceptionType;
import org.apache.activemq.artemis.api.core.Pair;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.client.impl.ServerLocatorInternal;
import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.io.IOCallback;
import org.apache.activemq.artemis.core.io.SequentialFile;
import org.apache.activemq.artemis.core.paging.cursor.PagePosition;
import org.apache.activemq.artemis.core.paging.cursor.PageSubscription;
import org.apache.activemq.artemis.core.persistence.OperationContext;
import org.apache.activemq.artemis.core.protocol.core.Packet;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.BackupReplicationStartFailedMessage;
import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
import org.apache.activemq.artemis.core.server.cluster.Bridge;
import org.apache.activemq.artemis.core.server.cluster.impl.BridgeImpl;
import org.apache.activemq.artemis.core.server.cluster.impl.ClusterConnectionImpl;
import org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl;
import org.apache.activemq.artemis.core.server.impl.ServerSessionImpl;
import org.apache.activemq.artemis.core.server.management.Notification;
import org.apache.activemq.artemis.utils.FutureLatch;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.w3c.dom.Node;
@MessageLogger(projectCode = "AMQ")
public interface ActiveMQServerLogger extends BasicLogger {
/**
* The default logger.
*/
ActiveMQServerLogger LOGGER = Logger.getMessageLogger(ActiveMQServerLogger.class, ActiveMQServerLogger.class.getPackage().getName());
@LogMessage(level = Logger.Level.DEBUG)
@Message(id = 223000, value = "Received Interrupt Exception whilst waiting for component to shutdown: {0}", format = Message.Format.MESSAGE_FORMAT)
void interruptWhilstStoppingComponent(String componentClassName);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221000, value = "{0} Message Broker is starting with configuration {1}", format = Message.Format.MESSAGE_FORMAT)
void serverStarting(String type, Configuration configuration);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221001, value = "Apache ActiveMQ Artemis Message Broker version {0} [{1}, nodeID={2}] {3}", format = Message.Format.MESSAGE_FORMAT)
void serverStarted(String fullVersion, String name, SimpleString nodeId, String identity);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221002, value = "Apache ActiveMQ Artemis Message Broker version {0} [{1}] stopped, uptime {2}", format = Message.Format.MESSAGE_FORMAT)
void serverStopped(String version, SimpleString nodeId, String uptime);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221003, value = "Deploying queue {0}", format = Message.Format.MESSAGE_FORMAT)
void deployQueue(SimpleString queueName);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221004, value = "{0}", format = Message.Format.MESSAGE_FORMAT)
void dumpServerInfo(String serverInfo);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221005, value = "Deleting pending large message as it was not completed: {0}",
format = Message.Format.MESSAGE_FORMAT)
void deletingPendingMessage(Pair<Long, Long> msgToDelete);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221006, value = "Waiting to obtain live lock", format = Message.Format.MESSAGE_FORMAT)
void awaitingLiveLock();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221007, value = "Server is now live", format = Message.Format.MESSAGE_FORMAT)
void serverIsLive();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221008, value = "live server wants to restart, restarting server in backup", format = Message.Format.MESSAGE_FORMAT)
void awaitFailBack();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221109, value = "Apache ActiveMQ Artemis Backup Server version {0} [{1}] started, waiting live to fail before it gets active",
format = Message.Format.MESSAGE_FORMAT)
void backupServerStarted(String version, SimpleString nodeID);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221010, value = "Backup Server is now live", format = Message.Format.MESSAGE_FORMAT)
void backupServerIsLive();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221011, value = "Server {0} is now live", format = Message.Format.MESSAGE_FORMAT)
void serverIsLive(String identity);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221012, value = "Using AIO Journal", format = Message.Format.MESSAGE_FORMAT)
void journalUseAIO();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221013, value = "Using NIO Journal", format = Message.Format.MESSAGE_FORMAT)
void journalUseNIO();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221014, value = "{0}% loaded", format = Message.Format.MESSAGE_FORMAT)
void percentLoaded(Long percent);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221015, value = "Can not find queue {0} while reloading ACKNOWLEDGE_CURSOR, deleting record now",
format = Message.Format.MESSAGE_FORMAT)
void journalCannotFindQueueReloading(Long queueID);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221016,
value = "Can not find queue {0} while reloading PAGE_CURSOR_COUNTER_VALUE, deleting record now",
format = Message.Format.MESSAGE_FORMAT)
void journalCannotFindQueueReloadingPage(Long queueID);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221017, value = "Can not find queue {0} while reloading PAGE_CURSOR_COUNTER_INC, deleting record now",
format = Message.Format.MESSAGE_FORMAT)
void journalCannotFindQueueReloadingPageCursor(Long queueID);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221018, value = "Large message: {0} did not have any associated reference, file will be deleted",
format = Message.Format.MESSAGE_FORMAT)
void largeMessageWithNoRef(Long messageID);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221019, value = "Deleting unreferenced message id={0} from the journal", format = Message.Format.MESSAGE_FORMAT)
void journalUnreferencedMessage(Long messageID);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221020, value = "Started {0} Acceptor at {1}:{2,number,#} for protocols [{3}]", format = Message.Format.MESSAGE_FORMAT)
void startedAcceptor(String acceptorType, String host, Integer port, String enabledProtocols);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221021, value = "failed to remove connection", format = Message.Format.MESSAGE_FORMAT)
void errorRemovingConnection();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221022, value = "unable to start connector service: {0}", format = Message.Format.MESSAGE_FORMAT)
void errorStartingConnectorService(@Cause Throwable e, String name);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221023, value = "unable to stop connector service: {0}", format = Message.Format.MESSAGE_FORMAT)
void errorStoppingConnectorService(@Cause Throwable e, String name);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221024, value = "Backup server {0} is synchronized with live-server.", format = Message.Format.MESSAGE_FORMAT)
void backupServerSynched(ActiveMQServerImpl server);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221025, value = "Replication: sending {0} (size={1}) to replica.", format = Message.Format.MESSAGE_FORMAT)
void replicaSyncFile(SequentialFile jf, Long size);
@LogMessage(level = Logger.Level.INFO)
@Message(
id = 221026,
value = "Bridge {0} connected to forwardingAddress={1}. {2} does not have any bindings. Messages will be ignored until a binding is created.",
format = Message.Format.MESSAGE_FORMAT)
void bridgeNoBindings(SimpleString name, SimpleString forwardingAddress, SimpleString address);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221027, value = "Bridge {0} is connected", format = Message.Format.MESSAGE_FORMAT)
void bridgeConnected(BridgeImpl name);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221028, value = "Bridge is stopping, will not retry", format = Message.Format.MESSAGE_FORMAT)
void bridgeStopping();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221029, value = "stopped bridge {0}", format = Message.Format.MESSAGE_FORMAT)
void bridgeStopped(SimpleString name);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221030, value = "paused bridge {0}", format = Message.Format.MESSAGE_FORMAT)
void bridgePaused(SimpleString name);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221031, value = "backup announced", format = Message.Format.MESSAGE_FORMAT)
void backupAnnounced();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221032, value = "Waiting to become backup node", format = Message.Format.MESSAGE_FORMAT)
void waitingToBecomeBackup();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221033, value = "** got backup lock", format = Message.Format.MESSAGE_FORMAT)
void gotBackupLock();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221034, value = "Waiting {0} to obtain live lock", format = Message.Format.MESSAGE_FORMAT)
void waitingToObtainLiveLock(String timeoutMessage);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221035, value = "Live Server Obtained live lock", format = Message.Format.MESSAGE_FORMAT)
void obtainedLiveLock();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221036, value = "Message with duplicate ID {0} was already set at {1}. Move from {2} being ignored and message removed from {3}",
format = Message.Format.MESSAGE_FORMAT)
void messageWithDuplicateID(Object duplicateProperty,
SimpleString toAddress,
SimpleString address,
SimpleString simpleString);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221037, value = "{0} to become ''live''", format = Message.Format.MESSAGE_FORMAT)
void becomingLive(ActiveMQServer server);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221038, value = "Configuration option ''{0}'' is deprecated. Consult the manual for details.",
format = Message.Format.MESSAGE_FORMAT)
void deprecatedConfigurationOption(String deprecatedOption);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221039, value = "Restarting as Replicating backup server after live restart",
format = Message.Format.MESSAGE_FORMAT)
void restartingReplicatedBackupAfterFailback();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221040, value = "Remote group coordinators has not started.", format = Message.Format.MESSAGE_FORMAT)
void remoteGroupCoordinatorsNotStarted();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221041, value = "Cannot find queue {0} while reloading PAGE_CURSOR_COMPLETE, deleting record now",
format = Message.Format.MESSAGE_FORMAT)
void cantFindQueueOnPageComplete(long queueID);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221042,
value = "Bridge {0} timed out waiting for the completion of {1} messages, we will just shutdown the bridge after 10 seconds wait",
format = Message.Format.MESSAGE_FORMAT)
void timedOutWaitingCompletions(String bridgeName, long numberOfMessages);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221043, value = "Protocol module found: [{1}]. Adding protocol support for: {0}", format = Message.Format.MESSAGE_FORMAT)
void addingProtocolSupport(String protocolKey, String moduleName);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221045, value = "libaio is not available, switching the configuration into NIO", format = Message.Format.MESSAGE_FORMAT)
void switchingNIO();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221046, value = "Unblocking message production on address ''{0}''; size is currently: {1} bytes; max-size-bytes: {2}", format = Message.Format.MESSAGE_FORMAT)
void unblockingMessageProduction(SimpleString addressName, long currentSize, long maxSize);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221047, value = "Backup Server has scaled down to live server", format = Message.Format.MESSAGE_FORMAT)
void backupServerScaledDown();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221048, value = "Consumer {0}:{1} attached to queue ''{2}'' from {3} identified as ''slow.'' Expected consumption rate: {4} msgs/second; actual consumption rate: {5} msgs/second.", format = Message.Format.MESSAGE_FORMAT)
void slowConsumerDetected(String sessionID,
long consumerID,
String queueName,
String remoteAddress,
float slowConsumerThreshold,
float consumerRate);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221049, value = "Activating Replica for node: {0}", format = Message.Format.MESSAGE_FORMAT)
void activatingReplica(SimpleString nodeID);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221050, value = "Activating Shared Store Slave", format = Message.Format.MESSAGE_FORMAT)
void activatingSharedStoreSlave();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221051, value = "Populating security roles from LDAP at: {0}", format = Message.Format.MESSAGE_FORMAT)
void populatingSecurityRolesFromLDAP(String url);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221052, value = "Deploying topic {0}", format = Message.Format.MESSAGE_FORMAT)
void deployTopic(SimpleString topicName);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221053,
value = "Disallowing use of vulnerable protocol ''{0}'' on acceptor ''{1}''. See http://www.oracle.com/technetwork/topics/security/poodlecve-2014-3566-2339408.html for more details.",
format = Message.Format.MESSAGE_FORMAT)
void disallowedProtocol(String protocol, String acceptorName);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221054, value = "libaio was found but the filesystem does not support AIO. Switching the configuration into NIO. Journal path: {0}", format = Message.Format.MESSAGE_FORMAT)
void switchingNIOonPath(String journalPath);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221055, value = "There were too many old replicated folders upon startup, removing {0}",
format = Message.Format.MESSAGE_FORMAT)
void removingBackupData(String path);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221056, value = "Reloading configuration ...{0}",
format = Message.Format.MESSAGE_FORMAT)
void reloadingConfiguration(String module);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221057, value = "Global Max Size is being adjusted to 1/2 of the JVM max size (-Xmx). being defined as {0}",
format = Message.Format.MESSAGE_FORMAT)
void usingDefaultPaging(long bytes);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221058, value = "resetting Journal File size from {0} to {1} to fit with alignment of {2}", format = Message.Format.MESSAGE_FORMAT)
void invalidJournalFileSize(int journalFileSize, int fileSize, int alignment);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221059, value = "Deleting old data directory {0} as the max folders is set to 0", format = Message.Format.MESSAGE_FORMAT)
void backupDeletingData(String oldPath);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221060, value = "Sending quorum vote request to {0}: {1}", format = Message.Format.MESSAGE_FORMAT)
void sendingQuorumVoteRequest(String remoteAddress, String vote);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221061, value = "Received quorum vote response from {0}: {1}", format = Message.Format.MESSAGE_FORMAT)
void receivedQuorumVoteResponse(String remoteAddress, String vote);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221062, value = "Received quorum vote request: {0}", format = Message.Format.MESSAGE_FORMAT)
void receivedQuorumVoteRequest(String vote);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221063, value = "Sending quorum vote response: {0}", format = Message.Format.MESSAGE_FORMAT)
void sendingQuorumVoteResponse(String vote);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221064, value = "Node {0} found in cluster topology", format = Message.Format.MESSAGE_FORMAT)
void nodeFoundInClusterTopology(String nodeId);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221065, value = "Node {0} not found in cluster topology", format = Message.Format.MESSAGE_FORMAT)
void nodeNotFoundInClusterTopology(String nodeId);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221066, value = "Initiating quorum vote: {0}", format = Message.Format.MESSAGE_FORMAT)
void initiatingQuorumVote(SimpleString vote);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221067, value = "Waiting {0} {1} for quorum vote results.", format = Message.Format.MESSAGE_FORMAT)
void waitingForQuorumVoteResults(int timeout, String unit);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221068, value = "Received all quorum votes.", format = Message.Format.MESSAGE_FORMAT)
void receivedAllQuorumVotes();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221069, value = "Timeout waiting for quorum vote responses.", format = Message.Format.MESSAGE_FORMAT)
void timeoutWaitingForQuorumVoteResponses();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221070, value = "Restarting as backup based on quorum vote results.", format = Message.Format.MESSAGE_FORMAT)
void restartingAsBackupBasedOnQuorumVoteResults();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 221071, value = "Failing over based on quorum vote results.", format = Message.Format.MESSAGE_FORMAT)
void failingOverBasedOnQuorumVoteResults();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222000, value = "ActiveMQServer is being finalized and has not been stopped. Please remember to stop the server before letting it go out of scope",
format = Message.Format.MESSAGE_FORMAT)
void serverFinalisedWIthoutBeingSTopped();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222001, value = "Error closing sessions while stopping server", format = Message.Format.MESSAGE_FORMAT)
void errorClosingSessionsWhileStoppingServer(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222002, value = "Timed out waiting for pool to terminate {0}. Interrupting all its threads!", format = Message.Format.MESSAGE_FORMAT)
void timedOutStoppingThreadpool(ExecutorService service);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222004, value = "Must specify an address for each divert. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT)
void divertWithNoAddress();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222005, value = "Must specify a forwarding address for each divert. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT)
void divertWithNoForwardingAddress();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222006, value = "Binding already exists with name {0}, divert will not be deployed", format = Message.Format.MESSAGE_FORMAT)
void divertBindingAlreadyExists(SimpleString bindingName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222007, value = "Security risk! Apache ActiveMQ Artemis is running with the default cluster admin user and default password. Please see the cluster chapter in the ActiveMQ Artemis User Guide for instructions on how to change this.", format = Message.Format.MESSAGE_FORMAT)
void clusterSecurityRisk();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222008, value = "unable to restart server, please kill and restart manually", format = Message.Format.MESSAGE_FORMAT)
void serverRestartWarning();
@LogMessage(level = Logger.Level.WARN)
void serverRestartWarning(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222009, value = "Unable to announce backup for replication. Trying to stop the server.", format = Message.Format.MESSAGE_FORMAT)
void replicationStartProblem(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222010, value = "Critical IO Error, shutting down the server. file={1}, message={0}", format = Message.Format.MESSAGE_FORMAT)
void ioCriticalIOError(String message, String file, @Cause Throwable code);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222011, value = "Error stopping server", format = Message.Format.MESSAGE_FORMAT)
void errorStoppingServer(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222012, value = "Timed out waiting for backup activation to exit", format = Message.Format.MESSAGE_FORMAT)
void backupActivationProblem();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222013, value = "Error when trying to start replication", format = Message.Format.MESSAGE_FORMAT)
void errorStartingReplication(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222014, value = "Error when trying to stop replication", format = Message.Format.MESSAGE_FORMAT)
void errorStoppingReplication(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222016, value = "Cannot deploy a connector with no name specified.", format = Message.Format.MESSAGE_FORMAT)
void connectorWithNoName();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222017, value = "There is already a connector with name {0} deployed. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT)
void connectorAlreadyDeployed(String name);
@LogMessage(level = Logger.Level.WARN)
@Message(
id = 222018,
value = "AIO was not located on this platform, it will fall back to using pure Java NIO. If your platform is Linux, install LibAIO to enable the AIO journal",
format = Message.Format.MESSAGE_FORMAT)
void AIONotFound();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222019, value = "There is already a discovery group with name {0} deployed. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT)
void discoveryGroupAlreadyDeployed(String name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222020, value = "error scanning for URL''s", format = Message.Format.MESSAGE_FORMAT)
void errorScanningURLs(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222021, value = "problem undeploying {0}", format = Message.Format.MESSAGE_FORMAT)
void problemUndeployingNode(@Cause Exception e, Node node);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222022, value = "Timed out waiting for paging cursor to stop {0} {1}", format = Message.Format.MESSAGE_FORMAT)
void timedOutStoppingPagingCursor(FutureLatch future, Executor executor);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222023, value = "problem cleaning page address {0}", format = Message.Format.MESSAGE_FORMAT)
void problemCleaningPageAddress(@Cause Exception e, SimpleString address);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222024, value = "Could not complete operations on IO context {0}",
format = Message.Format.MESSAGE_FORMAT)
void problemCompletingOperations(OperationContext e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222025, value = "Problem cleaning page subscription counter", format = Message.Format.MESSAGE_FORMAT)
void problemCleaningPagesubscriptionCounter(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222026, value = "Error on cleaning up cursor pages", format = Message.Format.MESSAGE_FORMAT)
void problemCleaningCursorPages(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222027, value = "Timed out flushing executors for paging cursor to stop {0}", format = Message.Format.MESSAGE_FORMAT)
void timedOutFlushingExecutorsPagingCursor(PageSubscription pageSubscription);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222028, value = "Could not find page cache for page {0} removing it from the journal",
format = Message.Format.MESSAGE_FORMAT)
void pageNotFound(PagePosition pos);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222029,
value = "Could not locate page transaction {0}, ignoring message on position {1} on address={2} queue={3}",
format = Message.Format.MESSAGE_FORMAT)
void pageSubscriptionCouldntLoad(long transactionID, PagePosition position, SimpleString address, SimpleString name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222030, value = "File {0} being renamed to {1}.invalidPage as it was loaded partially. Please verify your data.", format = Message.Format.MESSAGE_FORMAT)
void pageInvalid(String fileName, String name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222031, value = "Error while deleting page file", format = Message.Format.MESSAGE_FORMAT)
void pageDeleteError(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222032, value = "page finalise error", format = Message.Format.MESSAGE_FORMAT)
void pageFinaliseError(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222033, value = "Page file {0} had incomplete records at position {1} at record number {2}", format = Message.Format.MESSAGE_FORMAT)
void pageSuspectFile(String fileName, int position, int msgNumber);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222034, value = "Can not delete page transaction id={0}", format = Message.Format.MESSAGE_FORMAT)
void pageTxDeleteError(@Cause Exception e, long recordID);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222035, value = "Directory {0} did not have an identification file {1}",
format = Message.Format.MESSAGE_FORMAT)
void pageStoreFactoryNoIdFile(String s, String addressFile);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222036, value = "Timed out on waiting PagingStore {0} to shutdown", format = Message.Format.MESSAGE_FORMAT)
void pageStoreTimeout(SimpleString address);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222037, value = "IO Error, impossible to start paging", format = Message.Format.MESSAGE_FORMAT)
void pageStoreStartIOError(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222038, value = "Starting paging on address ''{0}''; size is currently: {1} bytes; max-size-bytes: {2}", format = Message.Format.MESSAGE_FORMAT)
void pageStoreStart(SimpleString storeName, long addressSize, long maxSize);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222039, value = "Messages sent to address ''{0}'' are being dropped; size is currently: {1} bytes; max-size-bytes: {2}", format = Message.Format.MESSAGE_FORMAT)
void pageStoreDropMessages(SimpleString storeName, long addressSize, long maxSize);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222040, value = "Server is stopped", format = Message.Format.MESSAGE_FORMAT)
void serverIsStopped();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222041, value = "Cannot find queue {0} to update delivery count", format = Message.Format.MESSAGE_FORMAT)
void journalCannotFindQueueDelCount(Long queueID);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222042, value = "Cannot find message {0} to update delivery count", format = Message.Format.MESSAGE_FORMAT)
void journalCannotFindMessageDelCount(Long msg);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222043, value = "Message for queue {0} which does not exist. This message will be ignored.", format = Message.Format.MESSAGE_FORMAT)
void journalCannotFindQueueForMessage(Long queueID);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222044, value = "It was not possible to delete message {0}", format = Message.Format.MESSAGE_FORMAT)
void journalErrorDeletingMessage(@Cause Exception e, Long messageID);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222045, value = "Message in prepared tx for queue {0} which does not exist. This message will be ignored.", format = Message.Format.MESSAGE_FORMAT)
void journalMessageInPreparedTX(Long queueID);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222046, value = "Failed to remove reference for {0}", format = Message.Format.MESSAGE_FORMAT)
void journalErrorRemovingRef(Long messageID);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222047, value = "Can not find queue {0} while reloading ACKNOWLEDGE_CURSOR",
format = Message.Format.MESSAGE_FORMAT)
void journalCannotFindQueueReloadingACK(Long queueID);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222048, value = "PAGE_CURSOR_COUNTER_VALUE record used on a prepared statement, invalid state", format = Message.Format.MESSAGE_FORMAT)
void journalPAGEOnPrepared();
@LogMessage(level = Logger.Level.WARN)
@Message(
id = 222049,
value = "InternalError: Record type {0} not recognized. Maybe you are using journal files created on a different version",
format = Message.Format.MESSAGE_FORMAT)
void journalInvalidRecordType(Byte recordType);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222050, value = "Can not locate recordType={0} on loadPreparedTransaction//deleteRecords",
format = Message.Format.MESSAGE_FORMAT)
void journalInvalidRecordTypeOnPreparedTX(Byte recordType);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222051, value = "Journal Error", format = Message.Format.MESSAGE_FORMAT)
void journalError(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222052, value = "error incrementing delay detection", format = Message.Format.MESSAGE_FORMAT)
void errorIncrementDelayDeletionCount(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222053, value = "Error on copying large message {0} for DLA or Expiry", format = Message.Format.MESSAGE_FORMAT)
void lareMessageErrorCopying(@Cause Exception e, LargeServerMessage largeServerMessage);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222054, value = "Error on executing IOCallback", format = Message.Format.MESSAGE_FORMAT)
void errorExecutingAIOCallback(@Cause Throwable t);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222055, value = "Error on deleting duplicate cache", format = Message.Format.MESSAGE_FORMAT)
void errorDeletingDuplicateCache(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222056, value = "Did not route to any bindings for address {0} and sendToDLAOnNoRoute is true but there is no DLA configured for the address, the message will be ignored.",
format = Message.Format.MESSAGE_FORMAT)
void noDLA(SimpleString address);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222057, value = "It was not possible to add references due to an IO error code {0} message = {1}",
format = Message.Format.MESSAGE_FORMAT)
void ioErrorAddingReferences(Integer errorCode, String errorMessage);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222059, value = "Duplicate message detected - message will not be routed. Message information:\n{0}", format = Message.Format.MESSAGE_FORMAT)
void duplicateMessageDetected(org.apache.activemq.artemis.api.core.Message message);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222060, value = "Error while confirming large message completion on rollback for recordID={0}", format = Message.Format.MESSAGE_FORMAT)
void journalErrorConfirmingLargeMessage(@Cause Throwable e, Long messageID);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222061, value = "Client connection failed, clearing up resources for session {0}", format = Message.Format.MESSAGE_FORMAT)
void clientConnectionFailed(String name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222062, value = "Cleared up resources for session {0}", format = Message.Format.MESSAGE_FORMAT)
void clearingUpSession(String name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222063, value = "Error processing IOCallback code = {0} message = {1}", format = Message.Format.MESSAGE_FORMAT)
void errorProcessingIOCallback(Integer errorCode, String errorMessage);
@LogMessage(level = Logger.Level.DEBUG)
@Message(id = 222065, value = "Client is not being consistent on the request versioning. It just sent a version id={0} while it informed {1} previously", format = Message.Format.MESSAGE_FORMAT)
void incompatibleVersionAfterConnect(int version, int clientVersion);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222066, value = "Reattach request from {0} failed as there is no confirmationWindowSize configured, which may be ok for your system", format = Message.Format.MESSAGE_FORMAT)
void reattachRequestFailed(String remoteAddress);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222067, value = "Connection failure has been detected: {0} [code={1}]", format = Message.Format.MESSAGE_FORMAT)
void connectionFailureDetected(String message, ActiveMQExceptionType type);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222069, value = "error cleaning up stomp connection", format = Message.Format.MESSAGE_FORMAT)
void errorCleaningStompConn(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222070, value = "Stomp Transactional acknowledgement is not supported", format = Message.Format.MESSAGE_FORMAT)
void stompTXAckNorSupported();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222071, value = "Interrupted while waiting for stomp heartbeat to die", format = Message.Format.MESSAGE_FORMAT)
void errorOnStompHeartBeat(@Cause InterruptedException e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222072, value = "Timed out flushing channel on InVMConnection", format = Message.Format.MESSAGE_FORMAT)
void timedOutFlushingInvmChannel();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 212074, value = "channel group did not completely close", format = Message.Format.MESSAGE_FORMAT)
void nettyChannelGroupError();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222075, value = "{0} is still connected to {1}", format = Message.Format.MESSAGE_FORMAT)
void nettyChannelStillOpen(Channel channel, SocketAddress remoteAddress);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222076, value = "channel group did not completely unbind", format = Message.Format.MESSAGE_FORMAT)
void nettyChannelGroupBindError();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222077, value = "{0} is still bound to {1}", format = Message.Format.MESSAGE_FORMAT)
void nettyChannelStillBound(Channel channel, SocketAddress remoteAddress);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222078, value = "Error instantiating remoting interceptor {0}", format = Message.Format.MESSAGE_FORMAT)
void errorCreatingRemotingInterceptor(@Cause Exception e, String interceptorClass);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222079, value = "The following keys are invalid for configuring the acceptor: {0} the acceptor will not be started.",
format = Message.Format.MESSAGE_FORMAT)
void invalidAcceptorKeys(String s);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222080, value = "Error instantiating remoting acceptor {0}", format = Message.Format.MESSAGE_FORMAT)
void errorCreatingAcceptor(@Cause Exception e, String factoryClassName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222081, value = "Timed out waiting for remoting thread pool to terminate", format = Message.Format.MESSAGE_FORMAT)
void timeoutRemotingThreadPool();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222082, value = "error on connection failure check", format = Message.Format.MESSAGE_FORMAT)
void errorOnFailureCheck(@Cause Throwable e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222083, value = "The following keys are invalid for configuring the connector service: {0} the connector will not be started.",
format = Message.Format.MESSAGE_FORMAT)
void connectorKeysInvalid(String s);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222084, value = "The following keys are required for configuring the connector service: {0} the connector will not be started.",
format = Message.Format.MESSAGE_FORMAT)
void connectorKeysMissing(String s);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222085, value = "Packet {0} can not be processed by the ReplicationEndpoint",
format = Message.Format.MESSAGE_FORMAT)
void invalidPacketForReplication(Packet packet);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222086, value = "error handling packet {0} for replication", format = Message.Format.MESSAGE_FORMAT)
void errorHandlingReplicationPacket(@Cause Exception e, Packet packet);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222087, value = "Replication Error while closing the page on backup", format = Message.Format.MESSAGE_FORMAT)
void errorClosingPageOnReplication(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222088, value = "Journal comparison mismatch:\n{0}", format = Message.Format.MESSAGE_FORMAT)
void journalcomparisonMismatch(String s);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222089, value = "Replication Error deleting large message ID = {0}", format = Message.Format.MESSAGE_FORMAT)
void errorDeletingLargeMessage(@Cause Exception e, long messageId);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222090, value = "Replication Large MessageID {0} is not available on backup server. Ignoring replication message", format = Message.Format.MESSAGE_FORMAT)
void largeMessageNotAvailable(long messageId);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222091, value = "The backup node has been shut-down, replication will now stop", format = Message.Format.MESSAGE_FORMAT)
void replicationStopOnBackupShutdown();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222092, value = "Connection to the backup node failed, removing replication now", format = Message.Format.MESSAGE_FORMAT)
void replicationStopOnBackupFail(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222093, value = "Timed out waiting to stop Bridge", format = Message.Format.MESSAGE_FORMAT)
void timedOutWaitingToStopBridge();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222094, value = "Bridge unable to send message {0}, will try again once bridge reconnects", format = Message.Format.MESSAGE_FORMAT)
void bridgeUnableToSendMessage(@Cause Exception e, MessageReference ref);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222095, value = "Connection failed with failedOver={0}", format = Message.Format.MESSAGE_FORMAT)
void bridgeConnectionFailed(Boolean failedOver);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222096, value = "Error on querying binding on bridge {0}. Retrying in 100 milliseconds", format = Message.Format.MESSAGE_FORMAT)
void errorQueryingBridge(@Cause Throwable t, SimpleString name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222097, value = "Address {0} does not have any bindings, retry #({1})",
format = Message.Format.MESSAGE_FORMAT)
void errorQueryingBridge(SimpleString address, Integer retryCount);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222098, value = "Server is starting, retry to create the session for bridge {0}", format = Message.Format.MESSAGE_FORMAT)
void errorStartingBridge(SimpleString name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222099, value = "Bridge {0} is unable to connect to destination. It will be disabled.", format = Message.Format.MESSAGE_FORMAT)
void errorConnectingBridge(@Cause Exception e, Bridge bridge);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222100, value = "ServerLocator was shutdown, can not retry on opening connection for bridge",
format = Message.Format.MESSAGE_FORMAT)
void bridgeLocatorShutdown();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222101, value = "Bridge {0} achieved {1} maxattempts={2} it will stop retrying to reconnect", format = Message.Format.MESSAGE_FORMAT)
void bridgeAbortStart(SimpleString name, Integer retryCount, Integer reconnectAttempts);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222102, value = "Unexpected exception while trying to reconnect", format = Message.Format.MESSAGE_FORMAT)
void errorReConnecting(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222103, value = "transaction with xid {0} timed out", format = Message.Format.MESSAGE_FORMAT)
void timedOutXID(Xid xid);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222104, value = "IO Error completing the transaction, code = {0}, message = {1}", format = Message.Format.MESSAGE_FORMAT)
void ioErrorOnTX(Integer errorCode, String errorMessage);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222105, value = "Could not finish context execution in 10 seconds",
format = Message.Format.MESSAGE_FORMAT)
void errorCompletingContext(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222106, value = "Replacing incomplete LargeMessage with ID={0}", format = Message.Format.MESSAGE_FORMAT)
void replacingIncompleteLargeMessage(Long messageID);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222107, value = "Cleared up resources for session {0}", format = Message.Format.MESSAGE_FORMAT)
void clientConnectionFailedClearingSession(String name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222108, value = "unable to send notification when broadcast group is stopped",
format = Message.Format.MESSAGE_FORMAT)
void broadcastGroupClosed(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222109, value = "Timed out waiting for write lock on consumer. Check the Thread dump", format = Message.Format.MESSAGE_FORMAT)
void timeoutLockingConsumer();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222110, value = "no queue IDs defined!, originalMessage = {0}, copiedMessage = {1}, props={2}",
format = Message.Format.MESSAGE_FORMAT)
void noQueueIdDefined(org.apache.activemq.artemis.api.core.Message message, org.apache.activemq.artemis.api.core.Message messageCopy, SimpleString idsHeaderName);
@LogMessage(level = Logger.Level.TRACE)
@Message(id = 222111, value = "exception while invoking {0} on {1}",
format = Message.Format.MESSAGE_FORMAT)
void managementOperationError(@Cause Exception e, String op, String resourceName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222112, value = "exception while retrieving attribute {0} on {1}",
format = Message.Format.MESSAGE_FORMAT)
void managementAttributeError(@Cause Exception e, String att, String resourceName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222113, value = "On ManagementService stop, there are {0} unexpected registered MBeans: {1}",
format = Message.Format.MESSAGE_FORMAT)
void managementStopError(Integer size, List<String> unexpectedResourceNames);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222114, value = "Unable to delete group binding info {0}",
format = Message.Format.MESSAGE_FORMAT)
void unableToDeleteGroupBindings(@Cause Exception e, SimpleString groupId);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222115, value = "Error closing serverLocator={0}",
format = Message.Format.MESSAGE_FORMAT)
void errorClosingServerLocator(@Cause Exception e, ServerLocatorInternal clusterLocator);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222116, value = "unable to start broadcast group {0}", format = Message.Format.MESSAGE_FORMAT)
void unableToStartBroadcastGroup(@Cause Exception e, String name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222117, value = "unable to start cluster connection {0}", format = Message.Format.MESSAGE_FORMAT)
void unableToStartClusterConnection(@Cause Exception e, SimpleString name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222118, value = "unable to start Bridge {0}", format = Message.Format.MESSAGE_FORMAT)
void unableToStartBridge(@Cause Exception e, SimpleString name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222119, value = "No connector with name {0}. backup cannot be announced.",
format = Message.Format.MESSAGE_FORMAT)
void announceBackupNoConnector(String connectorName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222120, value = "no cluster connections defined, unable to announce backup", format = Message.Format.MESSAGE_FORMAT)
void announceBackupNoClusterConnections();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222121, value = "Must specify a unique name for each bridge. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT)
void bridgeNotUnique();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222122, value = "Must specify a queue name for each bridge. This one {0} will not be deployed.", format = Message.Format.MESSAGE_FORMAT)
void bridgeNoQueue(String name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222123, value = "Forward address is not specified on bridge {0}. Will use original message address instead", format = Message.Format.MESSAGE_FORMAT)
void bridgeNoForwardAddress(String bridgeName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222124, value = "There is already a bridge with name {0} deployed. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT)
void bridgeAlreadyDeployed(String name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222125, value = "No queue found with name {0} bridge {1} will not be deployed.", format = Message.Format.MESSAGE_FORMAT)
void bridgeQueueNotFound(String queueName, String bridgeName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222126, value = "No discovery group found with name {0} bridge will not be deployed.", format = Message.Format.MESSAGE_FORMAT)
void bridgeNoDiscoveryGroup(String name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222127, value = "Must specify a unique name for each cluster connection. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT)
void clusterConnectionNotUnique();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222128, value = "Must specify an address for each cluster connection. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT)
void clusterConnectionNoForwardAddress();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222129, value = "No connector with name {0}. The cluster connection will not be deployed.",
format = Message.Format.MESSAGE_FORMAT)
void clusterConnectionNoConnector(String connectorName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222130,
value = "Cluster Configuration {0} already exists. The cluster connection will not be deployed.",
format = Message.Format.MESSAGE_FORMAT)
void clusterConnectionAlreadyExists(String connectorName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222131, value = "No discovery group with name {0}. The cluster connection will not be deployed.",
format = Message.Format.MESSAGE_FORMAT)
void clusterConnectionNoDiscoveryGroup(String discoveryGroupName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222132, value = "There is already a broadcast-group with name {0} deployed. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT)
void broadcastGroupAlreadyExists(String name);
@LogMessage(level = Logger.Level.WARN)
@Message(
id = 222133,
value = "There is no connector deployed with name {0}. The broadcast group with name {1} will not be deployed.",
format = Message.Format.MESSAGE_FORMAT)
void broadcastGroupNoConnector(String connectorName, String bgName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222134, value = "No connector defined with name {0}. The bridge will not be deployed.",
format = Message.Format.MESSAGE_FORMAT)
void noConnector(String name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222135, value = "Stopping Redistributor, Timed out waiting for tasks to complete", format = Message.Format.MESSAGE_FORMAT)
void errorStoppingRedistributor();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222136, value = "IO Error during redistribution, errorCode = {0} message = {1}", format = Message.Format.MESSAGE_FORMAT)
void ioErrorRedistributing(Integer errorCode, String errorMessage);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222137, value = "Unable to announce backup, retrying", format = Message.Format.MESSAGE_FORMAT)
void errorAnnouncingBackup(@Cause Throwable e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222138, value = "Local Member is not set at on ClusterConnection {0}", format = Message.Format.MESSAGE_FORMAT)
void noLocalMemborOnClusterConnection(ClusterConnectionImpl clusterConnection);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222139, value = "{0}::Remote queue binding {1} has already been bound in the post office. Most likely cause for this is you have a loop in your cluster due to cluster max-hops being too large or you have multiple cluster connections to the same nodes using overlapping addresses",
format = Message.Format.MESSAGE_FORMAT)
void remoteQueueAlreadyBoundOnClusterConnection(Object messageFlowRecord, SimpleString clusterName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222141, value = "Node Manager can not open file {0}", format = Message.Format.MESSAGE_FORMAT)
void nodeManagerCantOpenFile(@Cause Exception e, File file);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222142, value = "Error on resetting large message deliver - {0}", format = Message.Format.MESSAGE_FORMAT)
void errorResttingLargeMessage(@Cause Throwable e, Object deliverer);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222143, value = "Timed out waiting for executor to complete", format = Message.Format.MESSAGE_FORMAT)
void errorTransferringConsumer();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222144, value = "Queue could not finish waiting executors. Try increasing the thread pool size",
format = Message.Format.MESSAGE_FORMAT)
void errorFlushingExecutorsOnQueue();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222145, value = "Error expiring reference {0} 0n queue", format = Message.Format.MESSAGE_FORMAT)
void errorExpiringReferencesOnQueue(@Cause Exception e, MessageReference ref);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222146, value = "Message has expired. No bindings for Expiry Address {0} so dropping it", format = Message.Format.MESSAGE_FORMAT)
void errorExpiringReferencesNoBindings(SimpleString expiryAddress);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222147, value = "Messages are being expired on queue{0}. However there is no expiry queue configured, hence messages will be dropped.", format = Message.Format.MESSAGE_FORMAT)
void errorExpiringReferencesNoQueue(SimpleString name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222148, value = "Message {0} has exceeded max delivery attempts. No bindings for Dead Letter Address {1} so dropping it",
format = Message.Format.MESSAGE_FORMAT)
void messageExceededMaxDelivery(MessageReference ref, SimpleString name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222149, value = "Message {0} has reached maximum delivery attempts, sending it to Dead Letter Address {1} from {2}",
format = Message.Format.MESSAGE_FORMAT)
void messageExceededMaxDeliverySendtoDLA(MessageReference ref, SimpleString name, SimpleString simpleString);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222150, value = "Message {0} has exceeded max delivery attempts. No Dead Letter Address configured for queue {1} so dropping it",
format = Message.Format.MESSAGE_FORMAT)
void messageExceededMaxDeliveryNoDLA(MessageReference ref, SimpleString name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222151, value = "removing consumer which did not handle a message, consumer={0}, message={1}",
format = Message.Format.MESSAGE_FORMAT)
void removingBadConsumer(@Cause Throwable e, Consumer consumer, MessageReference reference);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222152, value = "Unable to decrement reference counting on queue",
format = Message.Format.MESSAGE_FORMAT)
void errorDecrementingRefCount(@Cause Throwable e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222153, value = "Unable to remove message id = {0} please remove manually",
format = Message.Format.MESSAGE_FORMAT)
void errorRemovingMessage(@Cause Throwable e, Long messageID);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222154, value = "Error checking DLQ",
format = Message.Format.MESSAGE_FORMAT)
void errorCheckingDLQ(@Cause Throwable e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222155, value = "Failed to register as backup. Stopping the server.",
format = Message.Format.MESSAGE_FORMAT)
void errorRegisteringBackup();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222156, value = "Less than {0}%\n{1}\nYou are in danger of running out of RAM. Have you set paging parameters on your addresses? (See user manual \"Paging\" chapter)",
format = Message.Format.MESSAGE_FORMAT)
void memoryError(Integer memoryWarningThreshold, String info);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222157, value = "Error completing callback on replication manager",
format = Message.Format.MESSAGE_FORMAT)
void errorCompletingCallbackOnReplicationManager(@Cause Throwable e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222158, value = "{0} activation thread did not finish.", format = Message.Format.MESSAGE_FORMAT)
void activationDidntFinish(ActiveMQServer server);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222159, value = "unable to send notification when broadcast group is stopped", format = Message.Format.MESSAGE_FORMAT)
void broadcastBridgeStoppedError(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222160, value = "unable to send notification when broadcast group is stopped", format = Message.Format.MESSAGE_FORMAT)
void notificationBridgeStoppedError(@Cause Exception e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222161, value = "Group Handler timed-out waiting for sendCondition", format = Message.Format.MESSAGE_FORMAT)
void groupHandlerSendTimeout();
@LogMessage(level = Logger.Level.INFO)
@Message(id = 222162, value = "Moving data directory {0} to {1}", format = Message.Format.MESSAGE_FORMAT)
void backupMovingDataAway(String oldPath, String newPath);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222163, value = "Server is being completely stopped, since this was a replicated backup there may be journal files that need cleaning up. The Apache ActiveMQ Artemis broker will have to be manually restarted.",
format = Message.Format.MESSAGE_FORMAT)
void stopReplicatedBackupAfterFailback();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222164, value = "Error when trying to start replication {0}", format = Message.Format.MESSAGE_FORMAT)
void errorStartingReplication(BackupReplicationStartFailedMessage.BackupRegistrationProblem problem);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222165, value = "No Dead Letter Address configured for queue {0} in AddressSettings",
format = Message.Format.MESSAGE_FORMAT)
void AddressSettingsNoDLA(SimpleString name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222166, value = "No Expiry Address configured for queue {0} in AddressSettings",
format = Message.Format.MESSAGE_FORMAT)
void AddressSettingsNoExpiryAddress(SimpleString name);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222167, value = "Group Binding not available so deleting {0} groups from {1}, groups will be bound to another node",
format = Message.Format.MESSAGE_FORMAT)
void groupingQueueRemoved(int size, SimpleString clusterName);
@SuppressWarnings("deprecation")
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222168, value = "The ''" + TransportConstants.PROTOCOL_PROP_NAME + "'' property is deprecated. If you want this Acceptor to support multiple protocols, use the ''" + TransportConstants.PROTOCOLS_PROP_NAME + "'' property, e.g. with value ''CORE,AMQP,STOMP''",
format = Message.Format.MESSAGE_FORMAT)
void warnDeprecatedProtocol();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222169, value = "You have old legacy clients connected to the queue {0} and we can''t disconnect them, these clients may just hang",
format = Message.Format.MESSAGE_FORMAT)
void warnDisconnectOldClient(String queueName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222170, value = "Bridge {0} forwarding address {1} has confirmation-window-size ({2}) greater than address'' max-size-bytes'' ({3})",
format = Message.Format.MESSAGE_FORMAT)
void bridgeConfirmationWindowTooSmall(String bridgeName, String address, int windowConfirmation, long maxSizeBytes);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222171, value = "Bridge {0} forwarding address {1} could not be resolved on address-settings configuration",
format = Message.Format.MESSAGE_FORMAT)
void bridgeCantFindAddressConfig(String bridgeName, String forwardingAddress);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222172, value = "Queue {0} was busy for more than {1} milliseconds. There are possibly consumers hanging on a network operation",
format = Message.Format.MESSAGE_FORMAT)
void queueBusy(String name, long timeout);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222173, value = "Queue {0} is duplicated during reload. This queue will be renamed as {1}", format = Message.Format.MESSAGE_FORMAT)
void queueDuplicatedRenaming(String name, String newName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222174, value = "Queue {0}, on address={1}, is taking too long to flush deliveries. Watch out for frozen clients.", format = Message.Format.MESSAGE_FORMAT)
void timeoutFlushInTransit(String queueName, String addressName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222175, value = "Bridge {0} could not find configured connectors", format = Message.Format.MESSAGE_FORMAT)
void bridgeCantFindConnectors(String bridgeName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222176,
value = "A session that was already doing XA work on {0} is replacing the xid by {1} " + ". This was most likely caused from a previous communication timeout",
format = Message.Format.MESSAGE_FORMAT)
void xidReplacedOnXStart(String xidOriginalToString, String xidReplacedToString);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222177, value = "Wrong configuration for role, {0} is not a valid permission",
format = Message.Format.MESSAGE_FORMAT)
void rolePermissionConfigurationError(String permission);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222178, value = "Error during recovery of page counters",
format = Message.Format.MESSAGE_FORMAT)
void errorRecoveringPageCounter(@Cause Throwable error);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222181, value = "Unable to scaleDown messages", format = Message.Format.MESSAGE_FORMAT)
void failedToScaleDown(@Cause Throwable e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222182, value = "Missing cluster-configuration for scale-down-clustername {0}", format = Message.Format.MESSAGE_FORMAT)
void missingClusterConfigForScaleDown(String scaleDownCluster);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222183, value = "Blocking message production on address ''{0}''; size is currently: {1} bytes; max-size-bytes on address: {2}, global-max-size is {3}", format = Message.Format.MESSAGE_FORMAT)
void blockingMessageProduction(SimpleString addressName, long currentSize, long maxSize, long globalMaxSize);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222184,
value = "Unable to recover group bindings in SCALE_DOWN mode, only FULL backup server can do this",
format = Message.Format.MESSAGE_FORMAT)
void groupBindingsOnRecovery();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222185,
value = "no cluster connection for specified replication cluster",
format = Message.Format.MESSAGE_FORMAT)
void noClusterConnectionForReplicationCluster();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222186,
value = "unable to authorise cluster control",
format = Message.Format.MESSAGE_FORMAT)
void clusterControlAuthfailure();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222187,
value = "Failed to activate replicated backup",
format = Message.Format.MESSAGE_FORMAT)
void activateReplicatedBackupFailed(@Cause Throwable e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222188,
value = "Unable to find target queue for node {0}",
format = Message.Format.MESSAGE_FORMAT)
void unableToFindTargetQueue(String targetNodeID);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222189,
value = "Failed to activate shared store slave",
format = Message.Format.MESSAGE_FORMAT)
void activateSharedStoreSlaveFailed(@Cause Throwable e);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222191,
value = "Could not find any configured role for user {0}.",
format = Message.Format.MESSAGE_FORMAT)
void cannotFindRoleForUser(String user);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222192,
value = "Could not delete: {0}",
format = Message.Format.MESSAGE_FORMAT)
void couldNotDeleteTempFile(String tempFileName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222193,
value = "Memory Limit reached. Producer ({0}) stopped to prevent flooding {1} (blocking for {2}s). See http://activemq.apache.org/producer-flow-control.html for more info.",
format = Message.Format.MESSAGE_FORMAT)
void memoryLimitReached(String producerID, String address, long duration);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222194,
value = "PageCursorInfo == null on address {0}, pos = {1}, queue = {2}.",
format = Message.Format.MESSAGE_FORMAT)
void nullPageCursorInfo(String address, String position, long id);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222195,
value = "Large message {0} wasn''t found when dealing with add pending large message",
format = Message.Format.MESSAGE_FORMAT)
void largeMessageNotFound(long id);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222196,
value = "Could not find binding with id={0} on routeFromCluster for message={1} binding = {2}",
format = Message.Format.MESSAGE_FORMAT)
void bindingNotFound(long id, String message, String binding);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222197,
value = "Internal error! Delivery logic has identified a non delivery and still handled a consumer!",
format = Message.Format.MESSAGE_FORMAT)
void nonDeliveryHandled();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222198,
value = "Could not flush ClusterManager executor ({0}) in 10 seconds, verify your thread pool size",
format = Message.Format.MESSAGE_FORMAT)
void couldNotFlushClusterManager(String manager);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222199,
value = "Thread dump: {0}",
format = Message.Format.MESSAGE_FORMAT)
void threadDump(String manager);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222200,
value = "Could not finish executor on {0}",
format = Message.Format.MESSAGE_FORMAT)
void couldNotFinishExecutor(String clusterConnection);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222201,
value = "Timed out waiting for activation to exit",
format = Message.Format.MESSAGE_FORMAT)
void activationTimeout();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222202,
value = "{0}: <{1}> should not be set to the same value as <{2}>. " +
"If a system is under high load, or there is a minor network delay, " +
"there is a high probability of a cluster split/failure due to connection timeout.",
format = Message.Format.MESSAGE_FORMAT)
void connectionTTLEqualsCheckPeriod(String connectionName, String ttl, String checkPeriod);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222203, value = "Classpath lacks a protocol-manager for protocol {0}, Protocol being ignored on acceptor {1}",
format = Message.Format.MESSAGE_FORMAT)
void noProtocolManagerFound(String protocol, String host);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222204, value = "Duplicated Acceptor {0} with parameters {1} classFactory={2} duplicated on the configuration", format = Message.Format.MESSAGE_FORMAT)
void duplicatedAcceptor(String name, String parameters, String classFactory);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222205, value = "OutOfMemoryError possible! There are currently {0} addresses with a total max-size-bytes of {1} bytes, but the maximum memory available is {2} bytes.", format = Message.Format.MESSAGE_FORMAT)
void potentialOOME(long addressCount, long totalMaxSizeBytes, long maxMemory);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222206, value = "Connection limit of {0} reached. Refusing connection from {1}.", format = Message.Format.MESSAGE_FORMAT)
void connectionLimitReached(long connectionsAllowed, String address);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222207, value = "The backup server is not responding promptly introducing latency beyond the limit. Replication server being disconnected now.",
format = Message.Format.MESSAGE_FORMAT)
void slowReplicationResponse();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222208, value = "SSL handshake failed for client from {0}: {1}.",
format = Message.Format.MESSAGE_FORMAT)
void sslHandshakeFailed(String clientAddress, String cause);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222209, value = "Could not contact group handler coordinator after 10 retries, message being routed without grouping information",
format = Message.Format.MESSAGE_FORMAT)
void impossibleToRouteGrouped();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222210, value = "Storage usage is beyond max-disk-usage. System will start blocking producers.",
format = Message.Format.MESSAGE_FORMAT)
void diskBeyondCapacity();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222211, value = "Storage is back to stable now, under max-disk-usage.",
format = Message.Format.MESSAGE_FORMAT)
void diskCapacityRestored();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222212, value = "Disk Full! Blocking message production on address ''{0}''. Clients will report blocked.", format = Message.Format.MESSAGE_FORMAT)
void blockingDiskFull(SimpleString addressName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222213,
value = "There was an issue on the network, server is isolated!",
format = Message.Format.MESSAGE_FORMAT)
void serverIsolatedOnNetwork();
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222214,
value = "Destination {1} has an inconsistent and negative address size={0}.",
format = Message.Format.MESSAGE_FORMAT)
void negativeAddressSize(long size, String destination);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222215,
value = "Global Address Size has negative and inconsistent value as {0}",
format = Message.Format.MESSAGE_FORMAT)
void negativeGlobalAddressSize(long size);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222216, value = "Security problem while creating session: {0}", format = Message.Format.MESSAGE_FORMAT)
void securityProblemWhileCreatingSession(String message);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222217, value = "Cannot find connector-ref {0}. The cluster-connection {1} will not be deployed.", format = Message.Format.MESSAGE_FORMAT)
void connectorRefNotFound(String connectorRef, String clusterConnection);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 222218, value = "Server disconnecting: {0}", format = Message.Format.MESSAGE_FORMAT)
void disconnectCritical(String reason, @Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224000, value = "Failure in initialisation", format = Message.Format.MESSAGE_FORMAT)
void initializationError(@Cause Throwable e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224001, value = "Error deploying URI {0}", format = Message.Format.MESSAGE_FORMAT)
void errorDeployingURI(@Cause Throwable e, URI uri);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224002, value = "Error deploying URI", format = Message.Format.MESSAGE_FORMAT)
void errorDeployingURI(@Cause Throwable e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224003, value = "Error undeploying URI {0}", format = Message.Format.MESSAGE_FORMAT)
void errorUnDeployingURI(@Cause Throwable e, URI a);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224005, value = "Unable to deploy node {0}", format = Message.Format.MESSAGE_FORMAT)
void unableToDeployNode(@Cause Exception e, Node node);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224006, value = "Invalid filter: {0}", format = Message.Format.MESSAGE_FORMAT)
void invalidFilter(SimpleString filter, @Cause Throwable cause);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224007, value = "page subscription = {0} error={1}", format = Message.Format.MESSAGE_FORMAT)
void pageSubscriptionError(IOCallback IOCallback, String error);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224008, value = "Failed to store id", format = Message.Format.MESSAGE_FORMAT)
void batchingIdError(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224009, value = "Cannot find message {0}", format = Message.Format.MESSAGE_FORMAT)
void cannotFindMessage(Long id);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224010, value = "Cannot find queue messages for queueID={0} on ack for messageID={1}", format = Message.Format.MESSAGE_FORMAT)
void journalCannotFindQueue(Long queue, Long id);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224011, value = "Cannot find queue messages {0} for message {1} while processing scheduled messages", format = Message.Format.MESSAGE_FORMAT)
void journalCannotFindQueueScheduled(Long queue, Long id);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224012, value = "error releasing resources", format = Message.Format.MESSAGE_FORMAT)
void largeMessageErrorReleasingResources(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224013, value = "failed to expire messages for queue", format = Message.Format.MESSAGE_FORMAT)
void errorExpiringMessages(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224014, value = "Failed to close session", format = Message.Format.MESSAGE_FORMAT)
void errorClosingSession(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224015, value = "Caught XA exception", format = Message.Format.MESSAGE_FORMAT)
void caughtXaException(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224016, value = "Caught exception", format = Message.Format.MESSAGE_FORMAT)
void caughtException(@Cause Throwable e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224017, value = "Invalid packet {0}", format = Message.Format.MESSAGE_FORMAT)
void invalidPacket(Packet packet);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224018, value = "Failed to create session", format = Message.Format.MESSAGE_FORMAT)
void failedToCreateSession(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224019, value = "Failed to reattach session", format = Message.Format.MESSAGE_FORMAT)
void failedToReattachSession(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224020, value = "Failed to handle create queue", format = Message.Format.MESSAGE_FORMAT)
void failedToHandleCreateQueue(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224021, value = "Failed to decode packet", format = Message.Format.MESSAGE_FORMAT)
void errorDecodingPacket(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224022, value = "Failed to execute failure listener", format = Message.Format.MESSAGE_FORMAT)
void errorCallingFailureListener(@Cause Throwable e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224024, value = "Stomp Error, tx already exist! {0}", format = Message.Format.MESSAGE_FORMAT)
void stompErrorTXExists(String txID);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224027, value = "Failed to write to handler on invm connector {0}", format = Message.Format.MESSAGE_FORMAT)
void errorWritingToInvmConnector(@Cause Exception e, Runnable runnable);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224028, value = "Failed to stop acceptor {0}", format = Message.Format.MESSAGE_FORMAT)
void errorStoppingAcceptor(String name);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224029, value = "large message sync: largeMessage instance is incompatible with it, ignoring data", format = Message.Format.MESSAGE_FORMAT)
void largeMessageIncompatible();
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224030, value = "Could not cancel reference {0}", format = Message.Format.MESSAGE_FORMAT)
void errorCancellingRefOnBridge(@Cause Exception e, MessageReference ref2);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224031, value = "-------------------------------Stomp begin tx: {0}", format = Message.Format.MESSAGE_FORMAT)
void stompBeginTX(String txID);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224032, value = "Failed to pause bridge", format = Message.Format.MESSAGE_FORMAT)
void errorPausingBridge(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224033, value = "Failed to broadcast connector configs", format = Message.Format.MESSAGE_FORMAT)
void errorBroadcastingConnectorConfigs(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224034, value = "Failed to close consumer", format = Message.Format.MESSAGE_FORMAT)
void errorClosingConsumer(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224035, value = "Failed to close cluster connection flow record", format = Message.Format.MESSAGE_FORMAT)
void errorClosingFlowRecord(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224036, value = "Failed to update cluster connection topology", format = Message.Format.MESSAGE_FORMAT)
void errorUpdatingTopology(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224037, value = "cluster connection Failed to handle message", format = Message.Format.MESSAGE_FORMAT)
void errorHandlingMessage(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224038, value = "Failed to ack old reference", format = Message.Format.MESSAGE_FORMAT)
void errorAckingOldReference(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224039, value = "Failed to expire message reference", format = Message.Format.MESSAGE_FORMAT)
void errorExpiringRef(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224040, value = "Failed to remove consumer", format = Message.Format.MESSAGE_FORMAT)
void errorRemovingConsumer(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224041, value = "Failed to deliver", format = Message.Format.MESSAGE_FORMAT)
void errorDelivering(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224042, value = "Error while restarting the backup server: {0}", format = Message.Format.MESSAGE_FORMAT)
void errorRestartingBackupServer(@Cause Exception e, ActiveMQServer backup);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224043, value = "Failed to send forced delivery message", format = Message.Format.MESSAGE_FORMAT)
void errorSendingForcedDelivery(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224044, value = "error acknowledging message", format = Message.Format.MESSAGE_FORMAT)
void errorAckingMessage(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224045, value = "Failed to run large message deliverer", format = Message.Format.MESSAGE_FORMAT)
void errorRunningLargeMessageDeliverer(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224046, value = "Exception while browser handled from {0}", format = Message.Format.MESSAGE_FORMAT)
void errorBrowserHandlingMessage(@Cause Exception e, MessageReference current);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224047, value = "Failed to delete large message file", format = Message.Format.MESSAGE_FORMAT)
void errorDeletingLargeMessageFile(@Cause Throwable e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224048, value = "Failed to remove temporary queue {0}", format = Message.Format.MESSAGE_FORMAT)
void errorRemovingTempQueue(@Cause Exception e, SimpleString bindingName);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224049, value = "Cannot find consumer with id {0}", format = Message.Format.MESSAGE_FORMAT)
void cannotFindConsumer(long consumerID);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224050, value = "Failed to close connection {0}", format = Message.Format.MESSAGE_FORMAT)
void errorClosingConnection(ServerSessionImpl serverSession);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224051, value = "Failed to call notification listener", format = Message.Format.MESSAGE_FORMAT)
void errorCallingNotifListener(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224052, value = "Unable to call Hierarchical Repository Change Listener", format = Message.Format.MESSAGE_FORMAT)
void errorCallingRepoListener(@Cause Throwable e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224053, value = "failed to timeout transaction, xid:{0}", format = Message.Format.MESSAGE_FORMAT)
void errorTimingOutTX(@Cause Exception e, Xid xid);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224054, value = "exception while stopping the replication manager", format = Message.Format.MESSAGE_FORMAT)
void errorStoppingReplicationManager(@Cause Throwable t);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224055, value = "Bridge Failed to ack", format = Message.Format.MESSAGE_FORMAT)
void bridgeFailedToAck(@Cause Throwable t);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224056, value = "Live server will not fail-back automatically", format = Message.Format.MESSAGE_FORMAT)
void autoFailBackDenied();
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224057, value = "Backup server that requested fail-back was not announced. Server will not stop for fail-back.",
format = Message.Format.MESSAGE_FORMAT)
void failbackMissedBackupAnnouncement();
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224058, value = "Stopping ClusterManager. As it failed to authenticate with the cluster: {0}",
format = Message.Format.MESSAGE_FORMAT)
void clusterManagerAuthenticationError(String msg);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224059, value = "Invalid cipher suite specified. Supported cipher suites are: {0}", format = Message.Format.MESSAGE_FORMAT)
void invalidCipherSuite(String validSuites);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224060, value = "Invalid protocol specified. Supported protocols are: {0}", format = Message.Format.MESSAGE_FORMAT)
void invalidProtocol(String validProtocols);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224061, value = "Setting both <{0}> and <ha-policy> is invalid. Please use <ha-policy> exclusively as <{0}> is deprecated. Ignoring <{0}> value.", format = Message.Format.MESSAGE_FORMAT)
void incompatibleWithHAPolicy(String parameter);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224062, value = "Failed to send SLOW_CONSUMER notification: {0}", format = Message.Format.MESSAGE_FORMAT)
void failedToSendSlowConsumerNotification(Notification notification, @Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224063, value = "Failed to close consumer connections for address {0}", format = Message.Format.MESSAGE_FORMAT)
void failedToCloseConsumerConnectionsForAddress(String address, @Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224064, value = "Setting <{0}> is invalid with this HA Policy Configuration. Please use <ha-policy> exclusively or remove. Ignoring <{0}> value.", format = Message.Format.MESSAGE_FORMAT)
void incompatibleWithHAPolicyChosen(String parameter);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224065, value = "Failed to remove auto-created queue {0}", format = Message.Format.MESSAGE_FORMAT)
void errorRemovingAutoCreatedQueue(@Cause Exception e, SimpleString bindingName);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224066, value = "Error opening context for LDAP", format = Message.Format.MESSAGE_FORMAT)
void errorOpeningContextForLDAP(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224067, value = "Error populating security roles from LDAP", format = Message.Format.MESSAGE_FORMAT)
void errorPopulatingSecurityRolesFromLDAP(@Cause Exception e);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224068, value = "Unable to stop component: {0}", format = Message.Format.MESSAGE_FORMAT)
void errorStoppingComponent(@Cause Throwable t, String componentClassName);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224069, value = "Change detected in broker configuration file, but reload failed", format = Message.Format.MESSAGE_FORMAT)
void configurationReloadFailed(@Cause Throwable t);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 224072, value = "Message Counter Sample Period too short: {0}", format = Message.Format.MESSAGE_FORMAT)
void invalidMessageCounterPeriod(long value);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 224073, value = "Using MAPPED Journal", format = Message.Format.MESSAGE_FORMAT)
void journalUseMAPPED();
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224074, value = "Failed to purge queue {0} on no consumers", format = Message.Format.MESSAGE_FORMAT)
void failedToPurgeQueue(@Cause Exception e, SimpleString bindingName);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224075, value = "Cannot find pageTX id = {0}", format = Message.Format.MESSAGE_FORMAT)
void journalCannotFindPageTX(Long id);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224079, value = "The process for the virtual machine will be killed, as component {0} is not responsive", format = Message.Format.MESSAGE_FORMAT)
void criticalSystemHalt(Object component);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 224080, value = "The server process will now be stopped, as component {0} is not responsive", format = Message.Format.MESSAGE_FORMAT)
void criticalSystemShutdown(Object component);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 224081, value = "The component {0} is not responsive", format = Message.Format.MESSAGE_FORMAT)
void criticalSystemLog(Object component);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 224076, value = "UnDeploying address {0}", format = Message.Format.MESSAGE_FORMAT)
void undeployAddress(SimpleString addressName);
@LogMessage(level = Logger.Level.INFO)
@Message(id = 224077, value = "UnDeploying queue {0}", format = Message.Format.MESSAGE_FORMAT)
void undeployQueue(SimpleString queueName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 224078, value = "The size of duplicate cache detection (<id_cache-size/>) appears to be too large {0}. It should be no greater than the number of messages that can be squeezed into conformation buffer (<confirmation-window-size/>) {1}.", format = Message.Format.MESSAGE_FORMAT)
void duplicateCacheSizeWarning(int idCacheSize, int confirmationWindowSize);
}
| pgfox/activemq-artemis | artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServerLogger.java | Java | apache-2.0 | 88,749 |
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Lucene.Net.Odm.Helpers
{
/// <summary>
/// Represents the extension methods for the lambda expression.
/// </summary>
public static class ExpressionHelper
{
/// <summary>
/// Converts the lambda expression to property info.
/// </summary>
/// <typeparam name="TModel">The type of model.</typeparam>
/// <typeparam name="TProperty">The type of model property.</typeparam>
/// <param name="expression">Lambda expression that represents the property of the model.</param>
/// <returns><see cref="System.Reflection.PropertyInfo"/> by specified <paramref name="expression"/>.</returns>
public static PropertyInfo ToProperty<TModel, TProperty>(this Expression<Func<TModel, TProperty>> expression)
{
if (expression == null)
throw new ArgumentNullException();
Expression body = expression.Body;
MemberExpression op = null;
if (body is UnaryExpression)
op = (body as UnaryExpression).Operand as MemberExpression;
else if (body is MemberExpression)
op = body as MemberExpression;
PropertyInfo property = null;
if (op != null)
{
MemberInfo member = op.Member;
property = typeof(TModel).GetProperty(member.Name);
if (property == null)
{
throw new ArgumentException(Properties.Resources.EXC_INVALID_LAMBDA_EXPRESSION);
}
}
return property;
}
/// <summary>
/// Returns the property name by the specified lambda expression.
/// </summary>
/// <typeparam name="TModel">The type of model.</typeparam>
/// <typeparam name="TProperty">The type of model property.</typeparam>
/// <param name="expression">Lambda expression that represents the property of the model.</param>
/// <returns><see cref="System.String"/> represents the property name for the specified <paramref name="expression"/>.</returns>
public static string GetPropertyName<TModel, TProperty>(this Expression<Func<TModel, TProperty>> expression)
{
PropertyInfo info = ToProperty(expression);
return (info != null) ? info.Name : null;
}
}
}
| T-Alex/Flucene | Flucene/Helpers/ExpressionHelper.cs | C# | apache-2.0 | 2,472 |
/**
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
*/
package org.deephacks.confit.internal.core.property.typesafe.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.deephacks.confit.internal.core.property.typesafe.ConfigMergeable;
import org.deephacks.confit.internal.core.property.typesafe.ConfigRenderOptions;
import org.deephacks.confit.internal.core.property.typesafe.ConfigException;
import org.deephacks.confit.internal.core.property.typesafe.ConfigObject;
import org.deephacks.confit.internal.core.property.typesafe.ConfigOrigin;
import org.deephacks.confit.internal.core.property.typesafe.ConfigValue;
/**
*
* Trying very hard to avoid a parent reference in typesafe values; when you have
* a tree like this, the availability of parent() tends to result in a lot of
* improperly-factored and non-modular code. Please don't add parent().
*
*/
abstract class AbstractConfigValue implements ConfigValue, MergeableValue {
final private SimpleConfigOrigin origin;
AbstractConfigValue(ConfigOrigin origin) {
this.origin = (SimpleConfigOrigin) origin;
}
@Override
public SimpleConfigOrigin origin() {
return this.origin;
}
/**
* This exception means that a value is inherently not resolveable, at the
* moment the only known cause is a cycle of substitutions. This is a
* checked exception since it's internal to the library and we want to be
* sure we handle it before passing it out to public API. This is only
* supposed to be thrown by the target of a cyclic reference and it's
* supposed to be caught by the ConfigReference looking up that reference,
* so it should be impossible for an outermost resolve() to throw this.
*
* Contrast with ConfigException.NotResolved which just means nobody called
* resolve().
*/
static class NotPossibleToResolve extends Exception {
private static final long serialVersionUID = 1L;
final private String traceString;
NotPossibleToResolve(ResolveContext context) {
super("was not possible to resolve");
this.traceString = context.traceString();
}
String traceString() {
return traceString;
}
}
/**
* Called only by ResolveContext.resolve().
*
* @param context
* state of the current resolve
* @return a new value if there were changes, or this if no changes
*/
AbstractConfigValue resolveSubstitutions(ResolveContext context)
throws NotPossibleToResolve {
return this;
}
ResolveStatus resolveStatus() {
return ResolveStatus.RESOLVED;
}
/**
* This is used when including one file in another; the included file is
* relativized to the path it's included into in the parent file. The point
* is that if you include a file at foo.bar in the parent, and the included
* file as a substitution ${a.b.c}, the included substitution now needs to
* be ${foo.bar.a.b.c} because we resolve substitutions globally only after
* parsing everything.
*
* @param prefix
* @return value relativized to the given path or the same value if nothing
* to do
*/
AbstractConfigValue relativized(Path prefix) {
return this;
}
protected interface Modifier {
// keyOrNull is null for non-objects
AbstractConfigValue modifyChildMayThrow(String keyOrNull, AbstractConfigValue v)
throws Exception;
}
protected abstract class NoExceptionsModifier implements Modifier {
@Override
public final AbstractConfigValue modifyChildMayThrow(String keyOrNull, AbstractConfigValue v)
throws Exception {
try {
return modifyChild(keyOrNull, v);
} catch (RuntimeException e) {
throw e;
} catch(Exception e) {
throw new ConfigException.BugOrBroken("Unexpected exception", e);
}
}
abstract AbstractConfigValue modifyChild(String keyOrNull, AbstractConfigValue v);
}
@Override
public AbstractConfigValue toFallbackValue() {
return this;
}
protected abstract AbstractConfigValue newCopy(ConfigOrigin origin);
// this is virtualized rather than a field because only some subclasses
// really need to store the boolean, and they may be able to pack it
// with another boolean to save space.
protected boolean ignoresFallbacks() {
// if we are not resolved, then somewhere in this value there's
// a substitution that may need to look at the fallbacks.
return resolveStatus() == ResolveStatus.RESOLVED;
}
protected AbstractConfigValue withFallbacksIgnored() {
if (ignoresFallbacks())
return this;
else
throw new ConfigException.BugOrBroken(
"value class doesn't implement forced fallback-ignoring " + this);
}
// the withFallback() implementation is supposed to avoid calling
// mergedWith* if we're ignoring fallbacks.
protected final void requireNotIgnoringFallbacks() {
if (ignoresFallbacks())
throw new ConfigException.BugOrBroken(
"method should not have been called with ignoresFallbacks=true "
+ getClass().getSimpleName());
}
protected AbstractConfigValue constructDelayedMerge(ConfigOrigin origin,
List<AbstractConfigValue> stack) {
return new ConfigDelayedMerge(origin, stack);
}
protected final AbstractConfigValue mergedWithTheUnmergeable(
Collection<AbstractConfigValue> stack, Unmergeable fallback) {
requireNotIgnoringFallbacks();
// if we turn out to be an object, and the fallback also does,
// then a merge may be required; delay until we resolve.
List<AbstractConfigValue> newStack = new ArrayList<AbstractConfigValue>();
newStack.addAll(stack);
newStack.addAll(fallback.unmergedValues());
return constructDelayedMerge(AbstractConfigObject.mergeOrigins(newStack), newStack);
}
private final AbstractConfigValue delayMerge(Collection<AbstractConfigValue> stack,
AbstractConfigValue fallback) {
// if we turn out to be an object, and the fallback also does,
// then a merge may be required.
// if we contain a substitution, resolving it may need to look
// back to the fallback.
List<AbstractConfigValue> newStack = new ArrayList<AbstractConfigValue>();
newStack.addAll(stack);
newStack.add(fallback);
return constructDelayedMerge(AbstractConfigObject.mergeOrigins(newStack), newStack);
}
protected final AbstractConfigValue mergedWithObject(Collection<AbstractConfigValue> stack,
AbstractConfigObject fallback) {
requireNotIgnoringFallbacks();
if (this instanceof AbstractConfigObject)
throw new ConfigException.BugOrBroken("Objects must reimplement mergedWithObject");
return mergedWithNonObject(stack, fallback);
}
protected final AbstractConfigValue mergedWithNonObject(Collection<AbstractConfigValue> stack,
AbstractConfigValue fallback) {
requireNotIgnoringFallbacks();
if (resolveStatus() == ResolveStatus.RESOLVED) {
// falling back to a non-object doesn't merge anything, and also
// prohibits merging any objects that we fall back to later.
// so we have to switch to ignoresFallbacks mode.
return withFallbacksIgnored();
} else {
// if unresolved, we may have to look back to fallbacks as part of
// the resolution process, so always delay
return delayMerge(stack, fallback);
}
}
protected AbstractConfigValue mergedWithTheUnmergeable(Unmergeable fallback) {
requireNotIgnoringFallbacks();
return mergedWithTheUnmergeable(Collections.singletonList(this), fallback);
}
protected AbstractConfigValue mergedWithObject(AbstractConfigObject fallback) {
requireNotIgnoringFallbacks();
return mergedWithObject(Collections.singletonList(this), fallback);
}
protected AbstractConfigValue mergedWithNonObject(AbstractConfigValue fallback) {
requireNotIgnoringFallbacks();
return mergedWithNonObject(Collections.singletonList(this), fallback);
}
public AbstractConfigValue withOrigin(ConfigOrigin origin) {
if (this.origin == origin)
return this;
else
return newCopy(origin);
}
// this is only overridden to change the return type
@Override
public AbstractConfigValue withFallback(ConfigMergeable mergeable) {
if (ignoresFallbacks()) {
return this;
} else {
ConfigValue other = ((MergeableValue) mergeable).toFallbackValue();
if (other instanceof Unmergeable) {
return mergedWithTheUnmergeable((Unmergeable) other);
} else if (other instanceof AbstractConfigObject) {
return mergedWithObject((AbstractConfigObject) other);
} else {
return mergedWithNonObject((AbstractConfigValue) other);
}
}
}
protected boolean canEqual(Object other) {
return other instanceof ConfigValue;
}
@Override
public boolean equals(Object other) {
// note that "origin" is deliberately NOT part of equality
if (other instanceof ConfigValue) {
return canEqual(other)
&& (this.valueType() ==
((ConfigValue) other).valueType())
&& ConfigImplUtil.equalsHandlingNull(this.unwrapped(),
((ConfigValue) other).unwrapped());
} else {
return false;
}
}
@Override
public int hashCode() {
// note that "origin" is deliberately NOT part of equality
Object o = this.unwrapped();
if (o == null)
return 0;
else
return o.hashCode();
}
@Override
public final String toString() {
StringBuilder sb = new StringBuilder();
render(sb, 0, null /* atKey */, ConfigRenderOptions.concise());
return getClass().getSimpleName() + "(" + sb.toString() + ")";
}
protected static void indent(StringBuilder sb, int indent, ConfigRenderOptions options) {
if (options.getFormatted()) {
int remaining = indent;
while (remaining > 0) {
sb.append(" ");
--remaining;
}
}
}
protected void render(StringBuilder sb, int indent, String atKey, ConfigRenderOptions options) {
if (atKey != null) {
String renderedKey;
if (options.getJson())
renderedKey = ConfigImplUtil.renderJsonString(atKey);
else
renderedKey = ConfigImplUtil.renderStringUnquotedIfPossible(atKey);
sb.append(renderedKey);
if (options.getJson()) {
if (options.getFormatted())
sb.append(" : ");
else
sb.append(":");
} else {
// in non-JSON we can omit the colon or equals before an object
if (this instanceof ConfigObject) {
if (options.getFormatted())
sb.append(' ');
} else {
sb.append("=");
}
}
}
render(sb, indent, options);
}
protected void render(StringBuilder sb, int indent, ConfigRenderOptions options) {
Object u = unwrapped();
sb.append(u.toString());
}
@Override
public final String render() {
return render(ConfigRenderOptions.defaults());
}
@Override
public final String render(ConfigRenderOptions options) {
StringBuilder sb = new StringBuilder();
render(sb, 0, null, options);
return sb.toString();
}
// toString() is a debugging-oriented string but this is defined
// to create a string that would parse back to the value in JSON.
// It only works for primitive values (that would be a single token)
// which are auto-converted to strings when concatenating with
// other strings or by the DefaultTransformer.
String transformToString() {
return null;
}
SimpleConfig atKey(ConfigOrigin origin, String key) {
Map<String, AbstractConfigValue> m = Collections.singletonMap(key, this);
return (new SimpleConfigObject(origin, m)).toConfig();
}
@Override
public SimpleConfig atKey(String key) {
return atKey(SimpleConfigOrigin.newSimple("atKey(" + key + ")"), key);
}
SimpleConfig atPath(ConfigOrigin origin, Path path) {
Path parent = path.parent();
SimpleConfig result = atKey(origin, path.last());
while (parent != null) {
String key = parent.last();
result = result.atKey(origin, key);
parent = parent.parent();
}
return result;
}
@Override
public SimpleConfig atPath(String pathExpression) {
SimpleConfigOrigin origin = SimpleConfigOrigin.newSimple("atPath(" + pathExpression + ")");
return atPath(origin, Path.newPath(pathExpression));
}
}
| deephacks/confit | core/src/main/java/org/deephacks/confit/internal/core/property/typesafe/impl/AbstractConfigValue.java | Java | apache-2.0 | 13,671 |
/***
*Sensap contribution
* @author George
*
*/
package eu.sensap.farEdge.dataRoutingClient.registry;
import java.io.IOException;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import eu.faredge.edgeInfrastructure.registry.messages.RegistrationResult;
import eu.faredge.edgeInfrastructure.registry.messages.RegistrationResultStatusEnum;
import eu.faredge.edgeInfrastructure.registry.models.dsm.DSM;
//import eu.faredge.edgeInfrastructure.registry.models.DataSourceManifest;
import eu.sensap.farEdge.dataRoutingClient.interfaces.DeviceRegisterInterface;
import eu.sensap.farEdge.dataRoutingClient.models.Credentials;
//import eu.sensap.farEdge.dataRoutingClient.models.RegistrationResult;
/***
* This class supports the basic registry operations
* There are three operations:
* 1. Registers a device with a specific UUID, Credentials, and Configuration Environments
* 2. Unregisters e registered device
* 3. Asks if a device is registered
*/
public class RegistryClient implements DeviceRegisterInterface
{
private final Logger log = LoggerFactory.getLogger(this.getClass());
private Credentials credentials; //Credentials for registry connection
private String registryUri; //the end point from registry service
private DSM dsm; //Data source Manifest for the device
//TODO to be deleted
// private ConfigurationEnv configurationEnv; //configuration environmental values for registry and message bus connection
// private String dsd; //Data source definition for the data source
// private String macAddress; // device macAddress
@Override
public void create(String registryUri)
{
this.setRegistryUri(registryUri);
// this.setCredentials(credentials);
}
public RegistryClient(String registryUri)
{
create(registryUri);
}
// The public registration method
@Override
public RegistrationResult registerDevice(DSM dsm, Credentials credentials)
{
log.debug(" +--Request for registration for DSM with URI =" + dsm.getUri());
this.setDsm(dsm);
this.setCredentials(credentials);
//call post Method to connect with registry
RegistrationResult result= this.postResource(this.registryUri, dsm, credentials);
log.debug(" +--Registration returned status " + result.getStatus());
return result;
}
//the public method for unregister
@Override
public RegistrationResult unRegisterDevice(String id, Credentials credentials)
{
log.debug("Request for registration for DSM with id =" + id);
// System.out.println("client:registryclient:unRegisterDevice==>dsmUri=" + uri + " registryUri=" + this.getRegistryUri());
// call post Method
RegistrationResult result = this.deleteResource(this.registryUri, id,credentials);
// System.out.println("Client:RegistryCLient:unregister response=" + result.getResult());
log.debug("Unregister returned status " + result.getStatus());
return result;
}
// public method for returning the registration status (true false)
@Override
public boolean isRegistered(DSM dsm, Credentials credentials)
{
log.debug("check if DSM is registered with id=" + dsm.getId());
// call post Method
RegistrationResult result = this.postResource(this.registryUri, dsm,credentials);
log.debug("Registration status for dsm_id=" + dsm.getId() + " is " + result.getStatus());
if (result.getStatus()==RegistrationResultStatusEnum.SUCCESS)
return true;
else
return false;
}
// postResource posts postData data to the specific Rest (URI)
private <T> RegistrationResult postResource (String uri, T postData, Credentials credentials)
{
log.debug(" +--Request for post to uri=" + uri);
try
{
// create and initialize client for REST call
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter(credentials.getUser(),credentials.getPassword()));
WebResource webResource = client.resource(uri);
// serialize 'postData' Object to String
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
String request = mapper.writeValueAsString(postData);
log.debug(" +--dsm=" + request);
// call resource and get Results
ClientResponse response = webResource.type("application/json").post(ClientResponse.class,request);
//TODO why do I need this?
if (response.getStatus() != 201)
{
log.debug("Response from rest{" + uri + "} has status " + response.getStatus());
client.destroy();
}
//Get results as registration results
RegistrationResult results = this.getRegistrationResults(response);
//destroy client
client.destroy();
log.debug(" +--Response from rest{" + uri + "} has status " + results.getStatus());
return results;
}
catch (Exception e)
{
// TODO only for skipping registry
//e.printStackTrace();
RegistrationResult results = new RegistrationResult();
results.setStatus(RegistrationResultStatusEnum.SUCCESS);
results.setBody(this.getFakeDsmId());
results.setStatusMessage("Get a fake registration");
log.debug(" +--Getting Fake registration");
return results;
}
// catch (Exception e)
// {
// e.printStackTrace();
// RegistrationResult results = new RegistrationResult();
// results.setStatus(RegistrationResultStatusEnum.FAIL);
// results.setStatusMessage("Error creating-initializing-calling resource or parsing the response");
//
// log.debug("Error creating-initializing-calling resource or parsing the response");
//
// return results;
// }
}
private String getFakeDsmId()
{
UUID id = UUID.randomUUID();
return "dsm://"+id.toString();
}
private <T> RegistrationResult deleteResource (String uri, String postData, Credentials credentials)
{
log.debug("Request for delete to uri=" + uri + ". Delete the id:" + postData);
try
{
// create and initialize client for REST call
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter(credentials.getUser(),credentials.getPassword()));
WebResource webResource = client.resource(uri).queryParam("id", postData);
// call resource and get Results
ClientResponse response = webResource.type("application/json").delete(ClientResponse.class);
//TODO why do I need this?
if (response.getStatus() != 200)
{
client.destroy();
//throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
//Get results as registration results
RegistrationResult results = this.getRegistrationResults(response);
//destroy
client.destroy();
log.debug("Response from rest{" + uri + "} has status " + results.getStatus());
return results;
}
catch (Exception e)
{
e.printStackTrace();
RegistrationResult results = new RegistrationResult();
results.setStatus(RegistrationResultStatusEnum.FAIL);
results.setStatusMessage("Error creating-initializing-calling resource or parsing the response");
log.debug("Error creating-initializing-calling resource or parsing the response");
return results;
}
}
private RegistrationResult getRegistrationResults(ClientResponse response)
{
ObjectMapper mapper = new ObjectMapper();
String createresponseString = response.getEntity(String.class);
RegistrationResult res = new RegistrationResult();
try {
res = mapper.readValue(createresponseString, res.getClass());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
// TODO: Transformations from Client Response to Registration Result Class
// RegistrationResult res = new RegistrationResult();
if (response.getStatus()== 400)
{
res.setStatus(RegistrationResultStatusEnum.NOTFOUND);
}
else
{
res.setStatus(RegistrationResultStatusEnum.SUCCESS);
}
res.setStatusMessage(Integer.toString(response.getStatus()));
return res;
}
//
// private void createDsm()
// {
// dsm = new DSM();
// dsm.setDataSourceDefinitionReferenceID(dsd);
// dsm.setMacAddress(macAddress);
// dsm.setUri(configurationEnv.getEdgeUri()+ macAddress);
// dsm.setDataSourceDefinitionInterfaceParameters(createDsdIp());
// }
//
//
// private DataSourceDefinitionInterfaceParameters createDsdIp ()
// {
// DataSourceDefinitionInterfaceParameters dsdip = new DataSourceDefinitionInterfaceParameters();
// Set<Parameter> paramSet = null;
//
// dsdip.setDescr(configurationEnv.getTopic());
//
// Parameter top = new Parameter();
// top.setKey("topic");
// top.setValue(configurationEnv.getTopic());
// paramSet.add(top);
//
// Set<String> keys = configurationEnv.getKafkaProps().stringPropertyNames();
// for (String key : keys) {
// Parameter e = new Parameter();
// e.setKey(key);
// e.setValue(configurationEnv.getKafkaProps().getProperty(key));
// paramSet.add(e);
// System.out.println(key + " : " + configurationEnv.getKafkaProps().getProperty(key));
// }
//
// dsdip.setParameter(paramSet);
//
// return dsdip;
// }
//
// Getters and setters
public Credentials getCredentials() {
return credentials;
}
public void setCredentials(Credentials credentials) {
this.credentials = credentials;
}
public DSM getDsm() {
return dsm;
}
public void setDsm(DSM dsm) {
this.dsm = dsm;
}
public String getRegistryUri() {
return registryUri;
}
public void setRegistryUri(String registryUri) {
this.registryUri = registryUri;
}
// public String getDsd() {
// return dsd;
// }
//
// public void setDsd(String dsd) {
// this.dsd = dsd;
// }
//
// public String getMacAddress() {
// return macAddress;
// }
//
// public void setMacAddress(String macAddress) {
// this.macAddress = macAddress;
// }
//
// public ConfigurationEnv getConfigurationEnv()
// {
// return configurationEnv;
// }
//
// public void setConfigurationEnv(ConfigurationEnv configurationEnv)
// {
// this.configurationEnv = configurationEnv;
// }
}
| far-edge/EdgeInfrastructure | Clients/dataRoutingClient/src/main/java/eu/sensap/farEdge/dataRoutingClient/registry/RegistryClient.java | Java | apache-2.0 | 10,728 |
<?php
defined('C5_EXECUTE') or die("Access Denied.");
$sets = BlockTypeSet::getList();
$types = array();
foreach ($blockTypes as $bt) {
if (!$cp->canAddBlockType($bt)) {
continue;
}
$btsets = $bt->getBlockTypeSets();
foreach ($btsets as $set) {
$types[$set->getBlockTypeSetName()][] = $bt;
}
if (count($btsets) == 0) {
$types['Other'][] = $bt;
}
}
for ($i = 0; $i < count($sets); $i++) {
$set = $sets[$i];
?>
<div class="ccm-ui" id="ccm-add-block-list">
<section>
<legend><?= $set->getBlockTypeSetDisplayName() ?></legend>
<ul class="item-select-list">
<? $blockTypes = $types[$set->getBlockTypeSetName()];
foreach ($blockTypes as $bt) {
$btIcon = $ci->getBlockTypeIconURL($bt);
?>
<li>
<a
data-cID="<?= $c->getCollectionID() ?>"
data-block-type-handle="<?= $bt->getBlockTypeHandle() ?>"
data-dialog-title="<?= t('Add %s', t($bt->getBlockTypeName())) ?>"
data-dialog-width="<?= $bt->getBlockTypeInterfaceWidth() ?>"
data-dialog-height="<?= $bt->getBlockTypeInterfaceHeight() ?>"
data-has-add-template="<?= $bt->hasAddTemplate() ?>"
data-supports-inline-add="<?= $bt->supportsInlineAdd() ?>"
data-btID="<?= $bt->getBlockTypeID() ?>"
title="<?= t($bt->getBlockTypeName()) ?>"
href="javascript:void(0)"><img src="<?=$btIcon?>" /> <?=t($bt->getBlockTypeName())?></a>
</li>
<? } ?>
</ul>
</section>
<? } ?>
<? if (is_array($types['Other'])) { ?>
<section>
<legend><?=t('Other')?></legend>
<ul class="item-select-list">
<? $blockTypes = $types['Other'];
foreach ($blockTypes as $bt) {
$btIcon = $ci->getBlockTypeIconURL($bt);
?>
<li>
<a
data-cID="<?= $c->getCollectionID() ?>"
data-block-type-handle="<?= $bt->getBlockTypeHandle() ?>"
data-dialog-title="<?= t('Add %s', t($bt->getBlockTypeName())) ?>"
data-dialog-width="<?= $bt->getBlockTypeInterfaceWidth() ?>"
data-dialog-height="<?= $bt->getBlockTypeInterfaceHeight() ?>"
data-has-add-template="<?= $bt->hasAddTemplate() ?>"
data-supports-inline-add="<?= $bt->supportsInlineAdd() ?>"
data-btID="<?= $bt->getBlockTypeID() ?>"
title="<?= t($bt->getBlockTypeName()) ?>"
href="javascript:void(0)"><img src="<?=$btIcon?>" /> <?=t($bt->getBlockTypeName())?></a>
</li>
<? } ?>
</ul>
</section>
<? } ?>
</div>
<script type="text/javascript">
$(function() {
$('#ccm-add-block-list').on('click', 'a', function() {
ConcreteEvent.publish('AddBlockListAddBlock', {
$launcher: $(this)
});
return false;
});
});
</script> | baardev/lbtb | concrete/views/dialogs/page/add_block_list.php | PHP | apache-2.0 | 3,188 |
package com.lagnada.demo.cxfrest.rest;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.security.SecurityContext;
import java.security.Principal;
public class MyInterceptor extends AbstractPhaseInterceptor<Message> {
public MyInterceptor() {
super(Phase.PRE_INVOKE);
}
@Override
public void handleMessage(Message message) throws Fault {
SecurityContext securityContext = (SecurityContext) message.get("org.apache.cxf.security.SecurityContext");
Principal userPrincipal = securityContext.getUserPrincipal();
"".toString();
}
}
| nfet/cxf-rest | src/main/java/com/lagnada/demo/cxfrest/rest/MyInterceptor.java | Java | apache-2.0 | 725 |
"""Python Library Boilerplate contains all the boilerplate you need to create a Python package."""
__author__ = 'Michael Joseph'
__email__ = 'michaeljoseph@gmail.com'
__url__ = 'https://github.com/michaeljoseph/sealeyes'
__version__ = '0.0.1'
def sealeyes():
return 'Hello World!'
| michaeljoseph/sealeyes | sealeyes/__init__.py | Python | apache-2.0 | 288 |
// Copyright 2021 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
package attest
import (
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"fmt"
"io"
)
type key interface {
close(tpmBase) error
marshal() ([]byte, error)
certificationParameters() CertificationParameters
sign(tpmBase, []byte, crypto.PublicKey, crypto.SignerOpts) ([]byte, error)
decrypt(tpmBase, []byte) ([]byte, error)
blobs() ([]byte, []byte, error)
}
// Key represents a key which can be used for signing and decrypting
// outside-TPM objects.
type Key struct {
key key
pub crypto.PublicKey
tpm tpmBase
}
// signer implements crypto.Signer returned by Key.Private().
type signer struct {
key key
pub crypto.PublicKey
tpm tpmBase
}
// Sign signs digest with the TPM-stored private signing key.
func (s *signer) Sign(r io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
return s.key.sign(s.tpm, digest, s.pub, opts)
}
// Public returns the public key corresponding to the private signing key.
func (s *signer) Public() crypto.PublicKey {
return s.pub
}
// Algorithm indicates an asymmetric algorithm to be used.
type Algorithm string
// Algorithm types supported.
const (
ECDSA Algorithm = "ECDSA"
RSA Algorithm = "RSA"
)
// KeyConfig encapsulates parameters for minting keys.
type KeyConfig struct {
// Algorithm to be used, either RSA or ECDSA.
Algorithm Algorithm
// Size is used to specify the bit size of the key or elliptic curve. For
// example, '256' is used to specify curve P-256.
Size int
}
// defaultConfig is used when no other configuration is specified.
var defaultConfig = &KeyConfig{
Algorithm: ECDSA,
Size: 256,
}
// Public returns the public key corresponding to the private key.
func (k *Key) Public() crypto.PublicKey {
return k.pub
}
// Private returns an object allowing to use the TPM-backed private key.
// For now it implements only crypto.Signer.
func (k *Key) Private(pub crypto.PublicKey) (crypto.PrivateKey, error) {
switch pub.(type) {
case *rsa.PublicKey:
if _, ok := k.pub.(*rsa.PublicKey); !ok {
return nil, fmt.Errorf("incompatible public key types: %T != %T", pub, k.pub)
}
case *ecdsa.PublicKey:
if _, ok := k.pub.(*ecdsa.PublicKey); !ok {
return nil, fmt.Errorf("incompatible public key types: %T != %T", pub, k.pub)
}
default:
return nil, fmt.Errorf("unsupported public key type: %T", pub)
}
return &signer{k.key, k.pub, k.tpm}, nil
}
// Close unloads the key from the system.
func (k *Key) Close() error {
return k.key.close(k.tpm)
}
// Marshal encodes the key in a format that can be loaded with tpm.LoadKey().
// This method exists to allow consumers to store the key persistently and load
// it as a later time. Users SHOULD NOT attempt to interpret or extract values
// from this blob.
func (k *Key) Marshal() ([]byte, error) {
return k.key.marshal()
}
// CertificationParameters returns information about the key required to
// verify key certification.
func (k *Key) CertificationParameters() CertificationParameters {
return k.key.certificationParameters()
}
// Blobs returns public and private blobs to be used by tpm2.Load().
func (k *Key) Blobs() (pub, priv []byte, err error) {
return k.key.blobs()
}
| google/go-attestation | attest/application_key.go | GO | apache-2.0 | 3,725 |
package com.coreoz.plume.jersey.security.permission;
import java.util.Collection;
import javax.ws.rs.container.ContainerRequestContext;
/**
* Extract permissions from the user corresponding to the current HTTP request
*/
public interface PermissionRequestProvider {
/**
* Fetch user permissions corresponding to the current HTTP request.
* If the user has no permission or if no user is attached to the HTTP request,
* then an empty collection must be returned.
*/
Collection<String> correspondingPermissions(ContainerRequestContext requestContext);
/**
* Fetch user information. It will be used to monitor or debug unauthorized access
*/
String userInformation(ContainerRequestContext requestContext);
}
| Coreoz/Plume | plume-web-jersey/src/main/java/com/coreoz/plume/jersey/security/permission/PermissionRequestProvider.java | Java | apache-2.0 | 729 |
package kikaha.urouting;
import java.util.*;
import java.util.function.Function;
import javax.annotation.PostConstruct;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.*;
import javax.inject.*;
import kikaha.core.util.Lang;
import kikaha.urouting.api.*;
@Singleton
@SuppressWarnings("rawtypes")
public class ConverterFactoryLoader {
@Inject
@Typed( AbstractConverter.class )
Iterable<AbstractConverter> availableConverters;
ConverterFactory factory;
@PostConstruct
public void onStartup() {
factory = new ConverterFactory( loadAllConverters() );
}
@Produces
public ConverterFactory produceFactory(){
return factory;
}
public Map<String, AbstractConverter<?>> loadAllConverters() {
final Map<String, AbstractConverter<?>> converters = loadPrimitiveConverters();
for ( final AbstractConverter converter : availableConverters ){
final String canonicalName = converter.getGenericClass().getCanonicalName();
converters.put(canonicalName, converter);
}
return converters;
}
static private Map<String, AbstractConverter<?>> loadPrimitiveConverters(){
final Map<String, AbstractConverter<?>> primitiveConverters = new HashMap<>();
converterFrom( primitiveConverters, int.class, 0, Integer::parseInt );
converterFrom( primitiveConverters, byte.class, (byte)0, Byte::parseByte );
converterFrom( primitiveConverters, float.class, 0f, Float::parseFloat );
converterFrom( primitiveConverters, double.class, 0.0, Double::parseDouble );
converterFrom( primitiveConverters, long.class, 0L, Long::parseLong );
converterFrom( primitiveConverters, short.class, (short)0, Short::parseShort );
converterFrom( primitiveConverters, boolean.class, Boolean.FALSE, Boolean::parseBoolean );
return primitiveConverters;
}
static private <T> void converterFrom(
Map<String, AbstractConverter<?>> primitiveConverters,
Class<T> primitiveType, T defaultValue, Function<String, T> converter)
{
primitiveConverters.put(
primitiveType.getCanonicalName(),
new AbstractConverter<T>() {
@Override
public T convert(String value) throws ConversionException {
if (Lang.isUndefined(value))
return defaultValue;
return converter.apply(value);
}
@Override
public Class<T> getGenericClass() { return primitiveType; }
}
);
}
}
| Skullabs/kikaha | kikaha-modules/kikaha-urouting/source/kikaha/urouting/ConverterFactoryLoader.java | Java | apache-2.0 | 2,325 |
/*******************************************************************************
* Copyright (c) 2010-2013, Abel Hegedus, Istvan Rath and Daniel Varro
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-v20.html.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package mb.nabl2.util.graph.alg.misc;
import java.util.Deque;
import java.util.Set;
import mb.nabl2.util.graph.igraph.ITcDataSource;
/**
* The path finder provides methods for retrieving paths in a graph between a source node and one or more target nodes.
* Use {@link ITcDataSource#getPathFinder()} for instantiating.
*
* @author Abel Hegedus
*
* @param <V> the node type of the graph
*/
public interface IGraphPathFinder<V> {
/**
* Returns an arbitrary path from the source node to the target node (if such exists). If there is no path
* between them, an empty collection is returned.
*
* @param sourceNode the source node of the path
* @param targetNode the target node of the path
* @return the path from the source to the target, or empty collection if target is not reachable from source.
*/
Deque<V> getPath(V sourceNode, V targetNode);
/**
* Returns the collection of shortest paths from the source node to the target node (if such exists). If there is no path
* between them, an empty collection is returned.
*
* @param sourceNode the source node of the path
* @param targetNode the target node of the path
* @return the collection of shortest paths from the source to the target, or empty collection if target is not reachable from source.
*/
Iterable<Deque<V>> getShortestPaths(V sourceNode, V targetNode);
/**
* Returns the collection of paths from the source node to the target node (if such exists). If there is no path
* between them, an empty collection is returned.
*
* @param sourceNode the source node of the path
* @param targetNode the target node of the path
* @return the collection of paths from the source to the target, or empty collection if target is not reachable from source.
*/
Iterable<Deque<V>> getAllPaths(V sourceNode, V targetNode);
/**
* Returns the collection of paths from the source node to any of the target nodes (if such exists). If there is no path
* between them, an empty collection is returned.
*
* @param sourceNode the source node of the path
* @param targetNodes the set of target nodes of the paths
* @return the collection of paths from the source to any of the targets, or empty collection if neither target is reachable from source.
*/
Iterable<Deque<V>> getAllPathsToTargets(V sourceNode, Set<V> targetNodes);
} | metaborg/nabl | nabl2.terms/src/main/java/mb/nabl2/util/graph/alg/misc/IGraphPathFinder.java | Java | apache-2.0 | 2,933 |
package com.blogspot.ludumdaresforfun;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
public class Enemy extends Image{
final float VELOCITY = 50f;
final float ATTACK_VELOCITY = 130f;
enum State {
Walking, Running, Hurting, BeingInvoked
}
Vector2 desiredPosition = new Vector2();
final Vector2 velocity = new Vector2();
State state = State.Walking;
boolean facesRight = false;
public boolean updateVelocity;
public boolean setToDie = false;
public boolean running = false;
public float attackHereX = 0;
public boolean attackRight = false;
public enum Direction {
Left, Right
}
public Direction dir = Direction.Left;
public Rectangle rect = new Rectangle();
public int diffInitialPos = 0;
public final int RANGE = 100;
public final int ATTACK_DISTANCE = 100;
protected Animation animation = null;
float stateTime = 0;
float offSetX;
public boolean dying = false;
public boolean canMove = false;
public AtlasRegion actualFrame;
public boolean beingInvoked = false;
public Enemy(Animation animation) {
super(animation.getKeyFrame(0));
this.animation = animation;
this.actualFrame = ((AtlasRegion)animation.getKeyFrame(0));
}
public Rectangle getRect() {
this.rect.set(this.getX(), this.getY(),this.actualFrame.packedWidth, this.actualFrame.packedHeight);
return this.rect;
}
public void die(){
// sound and set to die
Assets.playSound("enemyDead");
this.state = State.Hurting;
this.stateTime = 0;
this.dying = true;
this.velocity.x = 0;
}
public void run() {
if (this.state != Enemy.State.Running)
{
Assets.playSound("enemyAttack");
if (this.dir == Direction.Left) {
this.diffInitialPos -= 2;
this.velocity.x = -this.ATTACK_VELOCITY;
}
else {
this.diffInitialPos += 2;
this.velocity.x = this.ATTACK_VELOCITY;
}
this.state = Enemy.State.Running;
this.stateTime = 0;
this.running = true;
}
}
public void walk() {
if (this.dir == Direction.Left) {
this.diffInitialPos -= 1;
this.velocity.x = -this.VELOCITY;
}
else {
this.diffInitialPos += 1;
this.velocity.x = this.VELOCITY;
}
this.state = Enemy.State.Walking;
}
@Override
public void act(float delta) {
((TextureRegionDrawable)this.getDrawable()).setRegion(this.animation.getKeyFrame(this.stateTime+=delta, true));
super.act(delta);
}
} | jjhaggar/ludum30_a_hole_new_world | core/src/com/blogspot/ludumdaresforfun/Enemy.java | Java | apache-2.0 | 2,894 |
/*
* Copyright 2016 TomeOkin
*
* 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 app.receiver;
import app.data.model.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//@Component
public class CollectionReceiver {
private static final Logger logger = LoggerFactory.getLogger(CollectionReceiver.class);
public void receiveMessage(Object message) {
Collection collection = (Collection) message;
logger.info("receive message: {}", collection.toString());
}
}
| TomeOkin/LsPush-Server | src/main/java/app/receiver/CollectionReceiver.java | Java | apache-2.0 | 1,028 |
# 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.
# String literals representing core resources.
ADDRESS_GROUP = 'address_group'
AGENT = 'agent'
FLOATING_IP = 'floatingip'
LOCAL_IP_ASSOCIATION = 'local_ip_association'
NETWORK = 'network'
NETWORKS = 'networks'
PORT = 'port'
PORTS = 'ports'
PORT_BINDING = 'port_binding'
PORT_DEVICE = 'port_device'
PROCESS = 'process'
RBAC_POLICY = 'rbac-policy'
ROUTER = 'router'
ROUTER_CONTROLLER = 'router_controller'
ROUTER_GATEWAY = 'router_gateway'
ROUTER_INTERFACE = 'router_interface'
SECURITY_GROUP = 'security_group'
SECURITY_GROUP_RULE = 'security_group_rule'
SEGMENT = 'segment'
SEGMENT_HOST_MAPPING = 'segment_host_mapping'
SUBNET = 'subnet'
SUBNETS = 'subnets'
SUBNETPOOL_ADDRESS_SCOPE = 'subnetpool_address_scope'
SUBPORTS = 'subports'
TRUNK = 'trunk'
TRUNK_PLUGIN = 'trunk_plugin'
| openstack/neutron-lib | neutron_lib/callbacks/resources.py | Python | apache-2.0 | 1,353 |
package com.jeesms.entity.system;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.jeesms.common.Constants;
import com.jeesms.entity.base.IdEntity;
import javax.persistence.*;
import java.util.Date;
/**
* 登录日志Entity
*
* @author ASHNL
* @time 2014-08-22 15:42:51
*/
@Entity
@Table(name = "T_S_LOGIN_LOG")
@JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler", "fieldHandler"})
public class LoginLog extends IdEntity {
/**
* 登录用户
*/
private User user;
/**
* 登录时间
*/
private Date loginTime;
/**
* 登录IP
*/
private String loginIp;
/**
* 描述
*/
private String remark;
public LoginLog() {
}
public LoginLog(String id) {
this();
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
@JsonIgnore
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
@Column(name = "LOGIN_TIME")
@JsonFormat(pattern = Constants.yyyyMMddHHmmss, locale = Constants.LOCALE_ZH, timezone = Constants.TIMEZONE)
public Date getLoginTime() {
return this.loginTime;
}
public void setLoginTime(Date loginTime) {
this.loginTime = loginTime;
}
@Column(name = "LOGIN_IP", length = 255)
public String getLoginIp() {
return this.loginIp;
}
public void setLoginIp(String loginIp) {
this.loginIp = loginIp;
}
@Column(name = "REMARK", length = 255)
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Transient
public String getLoginName() {
return user == null ? null : user.getName();
}
} | ashnl007/jeesms | src/main/java/com/jeesms/entity/system/LoginLog.java | Java | apache-2.0 | 1,947 |
#!/usr/bin/env python
# Copyright 2017 F5 Networks Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import json
import os
from pprint import pprint as pp
from f5_cccl.resource.ltm.pool import *
from mock import MagicMock
import pytest
bigip_pools_cfg = [
{'description': None,
'partition': 'Common',
'loadBalancingMode': 'round-robin',
'monitor': '/Common/http ',
'membersReference': {
'isSubcollection': True,
'items': [
{'ratio': 1,
'name': '172.16.0.100:8080',
'partition': 'Common',
'session': 'monitor-enabled',
'priorityGroup': 0,
'connectionLimit': 0,
'description': None},
{'ratio': 1,
'name': '172.16.0.101:8080',
'partition': 'Common',
'session': 'monitor-enabled',
'priorityGroup': 0,
'connectionLimit': 0,
'description': None}
]
},
'name': u'pool1'
},
{'description': None,
'partition': 'Common',
'loadBalancingMode': 'round-robin',
'monitor': '/Common/http ',
'name': u'pool1'
}
]
cccl_pools_cfg = [
{ "name": "pool0" },
{ "name": "pool1",
"members": [
{"address": "172.16.0.100", "port": 8080, "routeDomain": {"id": 0}},
{"address": "172.16.0.101", "port": 8080, "routeDomain": {"id": 0}}
],
"monitors": ["/Common/http"]
},
{ "name": "pool2",
"members": [
{"address": "192.168.0.100", "port": 80, "routeDomain": {"id": 2}},
{"address": "192.168.0.101", "port": 80, "routeDomain": {"id": 2}}
],
"monitors": []
},
{ "name": "pool3",
"members": [],
"description": "This is test pool 3",
"monitors": []
},
{ "name": "pool4",
"members": [],
"description": "This is test pool 4",
"monitors": ["/Common/http"]
},
{ "name": "pool1",
"members": [
{"address": "172.16.0.100", "port": 8080, "routeDomain": {"id": 0}},
{"address": "172.16.0.102", "port": 8080, "routeDomain": {"id": 0}}
],
"monitors": ["/Common/http"]
}
]
@pytest.fixture
def bigip():
bigip = MagicMock()
return bigip
@pytest.fixture
def bigip_pool0():
return bigip_pools_cfg[0]
@pytest.fixture
def bigip_pool1():
return bigip_pools_cfg[1]
@pytest.fixture
def cccl_pool0():
return cccl_pools_cfg[0]
@pytest.fixture
def cccl_pool1():
return cccl_pools_cfg[1]
@pytest.fixture
def cccl_pool2():
return cccl_pools_cfg[2]
@pytest.fixture
def cccl_pool3():
return cccl_pools_cfg[3]
@pytest.fixture
def cccl_pool5():
return cccl_pools_cfg[5]
@pytest.fixture
def bigip_members():
members_filename = (
os.path.join(os.path.dirname(os.path.abspath(__file__)),
'./bigip-members.json'))
with open(members_filename) as fp:
json_data = fp.read()
json_data = json.loads(json_data)
members = [m for m in json_data['members']]
pp(json_data)
return members
def test_create_pool_minconfig(cccl_pool0):
pool = ApiPool(partition="Common", **cccl_pool0)
assert pool.name == "pool0"
assert pool.partition == "Common"
assert pool.data['loadBalancingMode'] == "round-robin"
assert not pool.data['description']
assert len(pool) == 0
assert pool.data['monitor'] == "default"
def test_create_pool(cccl_pool1):
pool = ApiPool(partition="Common", **cccl_pool1)
assert pool.name == "pool1"
assert pool.partition == "Common"
assert pool.data['loadBalancingMode'] == "round-robin"
assert not pool.data['description']
assert pool.data['monitor'] == "/Common/http"
assert len(pool) == 2
def test_create_pool_empty_lists(cccl_pool3):
pool = ApiPool(partition="Common", **cccl_pool3)
assert pool.name == "pool3"
assert pool.partition == "Common"
assert pool.data['loadBalancingMode'] == "round-robin"
assert pool.data['description'] == "This is test pool 3"
assert pool.data['monitor'] == "default"
assert len(pool) == 0
def test_compare_equal_pools(cccl_pool0):
p1 = ApiPool(partition="Common", **cccl_pool0)
p2 = ApiPool(partition="Common", **cccl_pool0)
assert id(p1) != id(p2)
assert p1 == p2
def test_compare_pool_and_dict(cccl_pool0):
pool = ApiPool(partition="Common", **cccl_pool0)
assert not pool == cccl_pool0
def test_get_uri_path(bigip, cccl_pool0):
pool = ApiPool(partition="Common", **cccl_pool0)
assert pool._uri_path(bigip) == bigip.tm.ltm.pools.pool
def test_pool_hash(bigip, cccl_pool0):
pool = ApiPool(partition="Common", **cccl_pool0)
assert hash(pool) == hash((pool.name, pool.partition))
def test_compare_bigip_cccl_pools(cccl_pool1, bigip_pool0):
bigip_pool = IcrPool(**bigip_pool0)
cccl_pool = ApiPool(partition="Common", **cccl_pool1)
assert bigip_pool == cccl_pool
def test_create_bigip_pool_no_members(bigip_pool1):
bigip_pool = IcrPool(**bigip_pool1)
assert bigip_pool.data['membersReference']
assert bigip_pool.data['membersReference']['items'] == []
def test_compare_pools_unequal_members(bigip, cccl_pool1, cccl_pool2, cccl_pool5):
pool1 = ApiPool(partition="Common", **cccl_pool1)
pool2 = ApiPool(partition="Common", **cccl_pool2)
pool5 = ApiPool(partition="Common", **cccl_pool5)
pool1_one_member_cfg = { "name": "pool1",
"members": [
{"address": "172.16.0.100", "port": 8080, "routeDomain": {"id": 0}},
],
"monitors": ["/Common/http"]
}
pool1_one_member = ApiPool(partition="Common",
**pool1_one_member_cfg)
pool2_with_monitor = { "name": "pool2",
"members": [
{"address": "192.168.0.100", "port": 80, "routeDomain": {"id": 2}},
{"address": "192.168.0.101", "port": 80, "routeDomain": {"id": 2}}
],
"monitors": ["/Common/http"]
}
pool2_with_monitor = ApiPool(partition="Common",
**pool2_with_monitor)
assert not pool1 == pool2
assert pool1 != pool2
assert not pool1_one_member == pool1
assert not pool2_with_monitor == pool2
assert not pool1 == pool5
assert pool1 != pool5
assert pool5 != pool1
def test_get_monitors(bigip):
pool = ApiPool(name="pool1", partition="Common")
assert pool._get_monitors(None) == "default"
assert pool._get_monitors([]) == "default"
monitors = ["/Common/http", "/Common/my_tcp"]
assert pool._get_monitors(monitors) == "/Common/http and /Common/my_tcp"
monitors = ["", ""]
assert pool._get_monitors(monitors) == " and "
monitors = ["/Common/my_tcp", "/Common/http"]
assert pool._get_monitors(monitors) == "/Common/http and /Common/my_tcp"
| richbrowne/f5-cccl | f5_cccl/resource/ltm/test/test_pool.py | Python | apache-2.0 | 7,378 |
/*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nanoframework.orm.jdbc.config;
import java.util.Properties;
import org.nanoframework.commons.util.Assert;
/**
* @author yanghe
* @since 1.2
*/
public class DruidJdbcConfig extends JdbcConfig {
private static final long serialVersionUID = -565746278164485851L;
@Property("druid.initialSize")
private Integer initialSize;
@Property("druid.maxActive")
private Integer maxActive;
@Property("druid.maxIdle")
private Integer maxIdle;
@Property("druid.minIdle")
private Integer minIdle;
@Property("druid.maxWait")
private Long maxWait;
@Property("druid.removeAbandoned")
private Boolean removeAbandoned;
@Property("druid.removeAbandonedTimeout")
private Integer removeAbandonedTimeout;
@Property("druid.timeBetweenEvictionRunsMillis")
private Long timeBetweenEvictionRunsMillis;
@Property("druid.minEvictableIdleTimeMillis")
private Long minEvictableIdleTimeMillis;
@Property("druid.validationQuery")
private String validationQuery;
@Property("druid.testWhileIdle")
private Boolean testWhileIdle;
@Property("druid.testOnBorrow")
private Boolean testOnBorrow;
@Property("druid.testOnReturn")
private Boolean testOnReturn;
@Property("druid.poolPreparedStatements")
private Boolean poolPreparedStatements;
@Property("druid.maxPoolPreparedStatementPerConnectionSize")
private Integer maxPoolPreparedStatementPerConnectionSize;
@Property("druid.filters")
private String filters;
public DruidJdbcConfig() {
}
public DruidJdbcConfig(Properties properties) {
Assert.notNull(properties);
this.setProperties(properties);
}
public Integer getInitialSize() {
return initialSize;
}
public void setInitialSize(Integer initialSize) {
this.initialSize = initialSize;
}
public Integer getMaxActive() {
return maxActive;
}
public void setMaxActive(Integer maxActive) {
this.maxActive = maxActive;
}
public Integer getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(Integer maxIdle) {
this.maxIdle = maxIdle;
}
public Integer getMinIdle() {
return minIdle;
}
public void setMinIdle(Integer minIdle) {
this.minIdle = minIdle;
}
public Long getMaxWait() {
return maxWait;
}
public void setMaxWait(Long maxWait) {
this.maxWait = maxWait;
}
public Boolean getRemoveAbandoned() {
return removeAbandoned;
}
public void setRemoveAbandoned(Boolean removeAbandoned) {
this.removeAbandoned = removeAbandoned;
}
public Integer getRemoveAbandonedTimeout() {
return removeAbandonedTimeout;
}
public void setRemoveAbandonedTimeout(Integer removeAbandonedTimeout) {
this.removeAbandonedTimeout = removeAbandonedTimeout;
}
public Long getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(Long timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public Long getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(Long minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public Boolean getTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(Boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public Boolean getTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(Boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public Boolean getTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(Boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public Boolean getPoolPreparedStatements() {
return poolPreparedStatements;
}
public void setPoolPreparedStatements(Boolean poolPreparedStatements) {
this.poolPreparedStatements = poolPreparedStatements;
}
public Integer getMaxPoolPreparedStatementPerConnectionSize() {
return maxPoolPreparedStatementPerConnectionSize;
}
public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) {
this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
}
public String getFilters() {
return filters;
}
public void setFilters(String filters) {
this.filters = filters;
}
}
| nano-projects/nano-framework | nano-orm/nano-orm-jdbc/src/main/java/org/nanoframework/orm/jdbc/config/DruidJdbcConfig.java | Java | apache-2.0 | 5,059 |
<?php
namespace DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRBackboneElement\FHIRCodeSystem;
/*!
* This class was generated with the PHPFHIR library (https://github.com/dcarbone/php-fhir) using
* class definitions from HL7 FHIR (https://www.hl7.org/fhir/)
*
* Class creation date: December 26th, 2019 15:43+0000
*
* PHPFHIR Copyright:
*
* Copyright 2016-2019 Daniel Carbone (daniel.p.carbone@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* FHIR Copyright Notice:
*
* Copyright (c) 2011+, HL7, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of HL7 nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* Generated on Wed, Apr 19, 2017 07:44+1000 for FHIR v3.0.1
*
* Note: the schemas & schematrons do not contain all of the rules about what makes resources
* valid. Implementers will still need to be familiar with the content of the specification and with
* any profiles that apply to the resources in order to make a conformant implementation.
*
*/
use DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRBackboneElement;
use DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRCode;
use DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRFilterOperator;
use DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRString;
use DCarbone\PHPFHIRGenerated\STU3\PHPFHIRConstants;
use DCarbone\PHPFHIRGenerated\STU3\PHPFHIRTypeInterface;
/**
* A code system resource specifies a set of codes drawn from one or more code
* systems.
*
* Class FHIRCodeSystemFilter
* @package \DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRBackboneElement\FHIRCodeSystem
*/
class FHIRCodeSystemFilter extends FHIRBackboneElement
{
// name of FHIR type this class describes
const FHIR_TYPE_NAME = PHPFHIRConstants::TYPE_NAME_CODE_SYSTEM_DOT_FILTER;
const FIELD_CODE = 'code';
const FIELD_CODE_EXT = '_code';
const FIELD_DESCRIPTION = 'description';
const FIELD_DESCRIPTION_EXT = '_description';
const FIELD_OPERATOR = 'operator';
const FIELD_OPERATOR_EXT = '_operator';
const FIELD_VALUE = 'value';
const FIELD_VALUE_EXT = '_value';
/** @var string */
private $_xmlns = 'http://hl7.org/fhir';
/**
* A string which has at least one character and no leading or trailing whitespace
* and where there is no whitespace other than single spaces in the contents
* If the element is present, it must have either a \@value, an \@id referenced from
* the Narrative, or extensions
*
* The code that identifies this filter when it is used in the instance.
*
* @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRCode
*/
protected $code = null;
/**
* A sequence of Unicode characters
* Note that FHIR strings may not exceed 1MB in size
* If the element is present, it must have either a \@value, an \@id, or extensions
*
* A description of how or why the filter is used.
*
* @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRString
*/
protected $description = null;
/**
* The kind of operation to perform as a part of a property based filter.
* If the element is present, it must have either a \@value, an \@id, or extensions
*
* A list of operators that can be used with the filter.
*
* @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRFilterOperator[]
*/
protected $operator = [];
/**
* A sequence of Unicode characters
* Note that FHIR strings may not exceed 1MB in size
* If the element is present, it must have either a \@value, an \@id, or extensions
*
* A description of what the value for the filter should be.
*
* @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRString
*/
protected $value = null;
/**
* Validation map for fields in type CodeSystem.Filter
* @var array
*/
private static $_validationRules = [
self::FIELD_OPERATOR => [
PHPFHIRConstants::VALIDATE_MIN_OCCURS => 1,
],
];
/**
* FHIRCodeSystemFilter Constructor
* @param null|array $data
*/
public function __construct($data = null)
{
if (null === $data || [] === $data) {
return;
}
if (!is_array($data)) {
throw new \InvalidArgumentException(sprintf(
'FHIRCodeSystemFilter::_construct - $data expected to be null or array, %s seen',
gettype($data)
));
}
parent::__construct($data);
if (isset($data[self::FIELD_CODE]) || isset($data[self::FIELD_CODE_EXT])) {
if (isset($data[self::FIELD_CODE])) {
$value = $data[self::FIELD_CODE];
} else {
$value = null;
}
if (isset($data[self::FIELD_CODE_EXT]) && is_array($data[self::FIELD_CODE_EXT])) {
$ext = $data[self::FIELD_CODE_EXT];
} else {
$ext = [];
}
if (null !== $value) {
if ($value instanceof FHIRCode) {
$this->setCode($value);
} else if (is_array($value)) {
$this->setCode(new FHIRCode(array_merge($ext, $value)));
} else {
$this->setCode(new FHIRCode([FHIRCode::FIELD_VALUE => $value] + $ext));
}
} else if ([] !== $ext) {
$this->setCode(new FHIRCode($ext));
}
}
if (isset($data[self::FIELD_DESCRIPTION]) || isset($data[self::FIELD_DESCRIPTION_EXT])) {
if (isset($data[self::FIELD_DESCRIPTION])) {
$value = $data[self::FIELD_DESCRIPTION];
} else {
$value = null;
}
if (isset($data[self::FIELD_DESCRIPTION_EXT]) && is_array($data[self::FIELD_DESCRIPTION_EXT])) {
$ext = $data[self::FIELD_DESCRIPTION_EXT];
} else {
$ext = [];
}
if (null !== $value) {
if ($value instanceof FHIRString) {
$this->setDescription($value);
} else if (is_array($value)) {
$this->setDescription(new FHIRString(array_merge($ext, $value)));
} else {
$this->setDescription(new FHIRString([FHIRString::FIELD_VALUE => $value] + $ext));
}
} else if ([] !== $ext) {
$this->setDescription(new FHIRString($ext));
}
}
if (isset($data[self::FIELD_OPERATOR]) || isset($data[self::FIELD_OPERATOR_EXT])) {
if (isset($data[self::FIELD_OPERATOR])) {
$value = $data[self::FIELD_OPERATOR];
} else {
$value = null;
}
if (isset($data[self::FIELD_OPERATOR_EXT]) && is_array($data[self::FIELD_OPERATOR_EXT])) {
$ext = $data[self::FIELD_OPERATOR_EXT];
} else {
$ext = [];
}
if (null !== $value) {
if ($value instanceof FHIRFilterOperator) {
$this->addOperator($value);
} else if (is_array($value)) {
foreach($value as $i => $v) {
if ($v instanceof FHIRFilterOperator) {
$this->addOperator($v);
} else {
$iext = (isset($ext[$i]) && is_array($ext[$i])) ? $ext[$i] : [];
if (is_array($v)) {
$this->addOperator(new FHIRFilterOperator(array_merge($v, $iext)));
} else {
$this->addOperator(new FHIRFilterOperator([FHIRFilterOperator::FIELD_VALUE => $v] + $iext));
}
}
}
} elseif (is_array($value)) {
$this->addOperator(new FHIRFilterOperator(array_merge($ext, $value)));
} else {
$this->addOperator(new FHIRFilterOperator([FHIRFilterOperator::FIELD_VALUE => $value] + $ext));
}
} else if ([] !== $ext) {
foreach($ext as $iext) {
$this->addOperator(new FHIRFilterOperator($iext));
}
}
}
if (isset($data[self::FIELD_VALUE]) || isset($data[self::FIELD_VALUE_EXT])) {
if (isset($data[self::FIELD_VALUE])) {
$value = $data[self::FIELD_VALUE];
} else {
$value = null;
}
if (isset($data[self::FIELD_VALUE_EXT]) && is_array($data[self::FIELD_VALUE_EXT])) {
$ext = $data[self::FIELD_VALUE_EXT];
} else {
$ext = [];
}
if (null !== $value) {
if ($value instanceof FHIRString) {
$this->setValue($value);
} else if (is_array($value)) {
$this->setValue(new FHIRString(array_merge($ext, $value)));
} else {
$this->setValue(new FHIRString([FHIRString::FIELD_VALUE => $value] + $ext));
}
} else if ([] !== $ext) {
$this->setValue(new FHIRString($ext));
}
}
}
/**
* @return string
*/
public function _getFHIRTypeName()
{
return self::FHIR_TYPE_NAME;
}
/**
* @return string
*/
public function _getFHIRXMLElementDefinition()
{
$xmlns = $this->_getFHIRXMLNamespace();
if (null !== $xmlns) {
$xmlns = " xmlns=\"{$xmlns}\"";
}
return "<CodeSystemFilter{$xmlns}></CodeSystemFilter>";
}
/**
* A string which has at least one character and no leading or trailing whitespace
* and where there is no whitespace other than single spaces in the contents
* If the element is present, it must have either a \@value, an \@id referenced from
* the Narrative, or extensions
*
* The code that identifies this filter when it is used in the instance.
*
* @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRCode
*/
public function getCode()
{
return $this->code;
}
/**
* A string which has at least one character and no leading or trailing whitespace
* and where there is no whitespace other than single spaces in the contents
* If the element is present, it must have either a \@value, an \@id referenced from
* the Narrative, or extensions
*
* The code that identifies this filter when it is used in the instance.
*
* @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRCode $code
* @return static
*/
public function setCode($code = null)
{
if (null === $code) {
$this->code = null;
return $this;
}
if ($code instanceof FHIRCode) {
$this->code = $code;
return $this;
}
$this->code = new FHIRCode($code);
return $this;
}
/**
* A sequence of Unicode characters
* Note that FHIR strings may not exceed 1MB in size
* If the element is present, it must have either a \@value, an \@id, or extensions
*
* A description of how or why the filter is used.
*
* @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRString
*/
public function getDescription()
{
return $this->description;
}
/**
* A sequence of Unicode characters
* Note that FHIR strings may not exceed 1MB in size
* If the element is present, it must have either a \@value, an \@id, or extensions
*
* A description of how or why the filter is used.
*
* @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRString $description
* @return static
*/
public function setDescription($description = null)
{
if (null === $description) {
$this->description = null;
return $this;
}
if ($description instanceof FHIRString) {
$this->description = $description;
return $this;
}
$this->description = new FHIRString($description);
return $this;
}
/**
* The kind of operation to perform as a part of a property based filter.
* If the element is present, it must have either a \@value, an \@id, or extensions
*
* A list of operators that can be used with the filter.
*
* @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRFilterOperator[]
*/
public function getOperator()
{
return $this->operator;
}
/**
* The kind of operation to perform as a part of a property based filter.
* If the element is present, it must have either a \@value, an \@id, or extensions
*
* A list of operators that can be used with the filter.
*
* @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRFilterOperator $operator
* @return static
*/
public function addOperator(FHIRFilterOperator $operator = null)
{
$this->operator[] = $operator;
return $this;
}
/**
* The kind of operation to perform as a part of a property based filter.
* If the element is present, it must have either a \@value, an \@id, or extensions
*
* A list of operators that can be used with the filter.
*
* @param \DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRFilterOperator[] $operator
* @return static
*/
public function setOperator(array $operator = [])
{
$this->operator = [];
if ([] === $operator) {
return $this;
}
foreach($operator as $v) {
if ($v instanceof FHIRFilterOperator) {
$this->addOperator($v);
} else {
$this->addOperator(new FHIRFilterOperator($v));
}
}
return $this;
}
/**
* A sequence of Unicode characters
* Note that FHIR strings may not exceed 1MB in size
* If the element is present, it must have either a \@value, an \@id, or extensions
*
* A description of what the value for the filter should be.
*
* @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRString
*/
public function getValue()
{
return $this->value;
}
/**
* A sequence of Unicode characters
* Note that FHIR strings may not exceed 1MB in size
* If the element is present, it must have either a \@value, an \@id, or extensions
*
* A description of what the value for the filter should be.
*
* @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRString $value
* @return static
*/
public function setValue($value = null)
{
if (null === $value) {
$this->value = null;
return $this;
}
if ($value instanceof FHIRString) {
$this->value = $value;
return $this;
}
$this->value = new FHIRString($value);
return $this;
}
/**
* Returns the validation rules that this type's fields must comply with to be considered "valid"
* The returned array is in ["fieldname[.offset]" => ["rule" => {constraint}]]
*
* @return array
*/
public function _getValidationRules()
{
return self::$_validationRules;
}
/**
* Validates that this type conforms to the specifications set forth for it by FHIR. An empty array must be seen as
* passing.
*
* @return array
*/
public function _getValidationErrors()
{
$errs = parent::_getValidationErrors();
$validationRules = $this->_getValidationRules();
if (null !== ($v = $this->getCode())) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[self::FIELD_CODE] = $fieldErrs;
}
}
if (null !== ($v = $this->getDescription())) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[self::FIELD_DESCRIPTION] = $fieldErrs;
}
}
if ([] !== ($vs = $this->getOperator())) {
foreach($vs as $i => $v) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[sprintf('%s.%d', self::FIELD_OPERATOR, $i)] = $fieldErrs;
}
}
}
if (null !== ($v = $this->getValue())) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[self::FIELD_VALUE] = $fieldErrs;
}
}
if (isset($validationRules[self::FIELD_CODE])) {
$v = $this->getCode();
foreach($validationRules[self::FIELD_CODE] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_CODE_SYSTEM_DOT_FILTER, self::FIELD_CODE, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_CODE])) {
$errs[self::FIELD_CODE] = [];
}
$errs[self::FIELD_CODE][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_DESCRIPTION])) {
$v = $this->getDescription();
foreach($validationRules[self::FIELD_DESCRIPTION] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_CODE_SYSTEM_DOT_FILTER, self::FIELD_DESCRIPTION, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_DESCRIPTION])) {
$errs[self::FIELD_DESCRIPTION] = [];
}
$errs[self::FIELD_DESCRIPTION][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_OPERATOR])) {
$v = $this->getOperator();
foreach($validationRules[self::FIELD_OPERATOR] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_CODE_SYSTEM_DOT_FILTER, self::FIELD_OPERATOR, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_OPERATOR])) {
$errs[self::FIELD_OPERATOR] = [];
}
$errs[self::FIELD_OPERATOR][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_VALUE])) {
$v = $this->getValue();
foreach($validationRules[self::FIELD_VALUE] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_CODE_SYSTEM_DOT_FILTER, self::FIELD_VALUE, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_VALUE])) {
$errs[self::FIELD_VALUE] = [];
}
$errs[self::FIELD_VALUE][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_MODIFIER_EXTENSION])) {
$v = $this->getModifierExtension();
foreach($validationRules[self::FIELD_MODIFIER_EXTENSION] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_BACKBONE_ELEMENT, self::FIELD_MODIFIER_EXTENSION, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_MODIFIER_EXTENSION])) {
$errs[self::FIELD_MODIFIER_EXTENSION] = [];
}
$errs[self::FIELD_MODIFIER_EXTENSION][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_EXTENSION])) {
$v = $this->getExtension();
foreach($validationRules[self::FIELD_EXTENSION] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_EXTENSION, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_EXTENSION])) {
$errs[self::FIELD_EXTENSION] = [];
}
$errs[self::FIELD_EXTENSION][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_ID])) {
$v = $this->getId();
foreach($validationRules[self::FIELD_ID] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_ID, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_ID])) {
$errs[self::FIELD_ID] = [];
}
$errs[self::FIELD_ID][$rule] = $err;
}
}
}
return $errs;
}
/**
* @param \SimpleXMLElement|string|null $sxe
* @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRBackboneElement\FHIRCodeSystem\FHIRCodeSystemFilter $type
* @param null|int $libxmlOpts
* @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRBackboneElement\FHIRCodeSystem\FHIRCodeSystemFilter
*/
public static function xmlUnserialize($sxe = null, PHPFHIRTypeInterface $type = null, $libxmlOpts = 591872)
{
if (null === $sxe) {
return null;
}
if (is_string($sxe)) {
libxml_use_internal_errors(true);
$sxe = new \SimpleXMLElement($sxe, $libxmlOpts, false);
if ($sxe === false) {
throw new \DomainException(sprintf('FHIRCodeSystemFilter::xmlUnserialize - String provided is not parseable as XML: %s', implode(', ', array_map(function(\libXMLError $err) { return $err->message; }, libxml_get_errors()))));
}
libxml_use_internal_errors(false);
}
if (!($sxe instanceof \SimpleXMLElement)) {
throw new \InvalidArgumentException(sprintf('FHIRCodeSystemFilter::xmlUnserialize - $sxe value must be null, \\SimpleXMLElement, or valid XML string, %s seen', gettype($sxe)));
}
if (null === $type) {
$type = new FHIRCodeSystemFilter;
} elseif (!is_object($type) || !($type instanceof FHIRCodeSystemFilter)) {
throw new \RuntimeException(sprintf(
'FHIRCodeSystemFilter::xmlUnserialize - $type must be instance of \DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRBackboneElement\FHIRCodeSystem\FHIRCodeSystemFilter or null, %s seen.',
is_object($type) ? get_class($type) : gettype($type)
));
}
FHIRBackboneElement::xmlUnserialize($sxe, $type);
$xmlNamespaces = $sxe->getDocNamespaces(false, false);
if ([] !== $xmlNamespaces) {
$ns = reset($xmlNamespaces);
if (false !== $ns && '' !== $ns) {
$type->_xmlns = $ns;
}
}
$attributes = $sxe->attributes();
$children = $sxe->children();
if (isset($children->code)) {
$type->setCode(FHIRCode::xmlUnserialize($children->code));
}
if (isset($attributes->code)) {
$pt = $type->getCode();
if (null !== $pt) {
$pt->setValue((string)$attributes->code);
} else {
$type->setCode((string)$attributes->code);
}
}
if (isset($children->description)) {
$type->setDescription(FHIRString::xmlUnserialize($children->description));
}
if (isset($attributes->description)) {
$pt = $type->getDescription();
if (null !== $pt) {
$pt->setValue((string)$attributes->description);
} else {
$type->setDescription((string)$attributes->description);
}
}
if (isset($children->operator)) {
foreach($children->operator as $child) {
$type->addOperator(FHIRFilterOperator::xmlUnserialize($child));
}
}
if (isset($children->value)) {
$type->setValue(FHIRString::xmlUnserialize($children->value));
}
if (isset($attributes->value)) {
$pt = $type->getValue();
if (null !== $pt) {
$pt->setValue((string)$attributes->value);
} else {
$type->setValue((string)$attributes->value);
}
}
return $type;
}
/**
* @param null|\SimpleXMLElement $sxe
* @param null|int $libxmlOpts
* @return \SimpleXMLElement
*/
public function xmlSerialize(\SimpleXMLElement $sxe = null, $libxmlOpts = 591872)
{
if (null === $sxe) {
$sxe = new \SimpleXMLElement($this->_getFHIRXMLElementDefinition(), $libxmlOpts, false);
}
parent::xmlSerialize($sxe);
if (null !== ($v = $this->getCode())) {
$v->xmlSerialize($sxe->addChild(self::FIELD_CODE, null, $v->_getFHIRXMLNamespace()));
}
if (null !== ($v = $this->getDescription())) {
$v->xmlSerialize($sxe->addChild(self::FIELD_DESCRIPTION, null, $v->_getFHIRXMLNamespace()));
}
if ([] !== ($vs = $this->getOperator())) {
foreach($vs as $v) {
if (null === $v) {
continue;
}
$v->xmlSerialize($sxe->addChild(self::FIELD_OPERATOR, null, $v->_getFHIRXMLNamespace()));
}
}
if (null !== ($v = $this->getValue())) {
$sxe->addAttribute(self::FIELD_VALUE, (string)$v);
$v->xmlSerialize($sxe->addChild(self::FIELD_VALUE, null, $v->_getFHIRXMLNamespace()));
}
return $sxe;
}
/**
* @return array
*/
public function jsonSerialize()
{
$a = parent::jsonSerialize();
if (null !== ($v = $this->getCode())) {
$a[self::FIELD_CODE] = $v->getValue();
$enc = $v->jsonSerialize();
$cnt = count($enc);
if (0 < $cnt && (1 !== $cnt || (1 === $cnt && !array_key_exists(FHIRCode::FIELD_VALUE, $enc)))) {
unset($enc[FHIRCode::FIELD_VALUE]);
$a[self::FIELD_CODE_EXT] = $enc;
}
}
if (null !== ($v = $this->getDescription())) {
$a[self::FIELD_DESCRIPTION] = $v->getValue();
$enc = $v->jsonSerialize();
$cnt = count($enc);
if (0 < $cnt && (1 !== $cnt || (1 === $cnt && !array_key_exists(FHIRString::FIELD_VALUE, $enc)))) {
unset($enc[FHIRString::FIELD_VALUE]);
$a[self::FIELD_DESCRIPTION_EXT] = $enc;
}
}
if ([] !== ($vs = $this->getOperator())) {
$a[self::FIELD_OPERATOR] = [];
$encs = [];
$encValued = false;
foreach ($vs as $v) {
if (null === $v) {
continue;
}
$a[self::FIELD_OPERATOR][] = $v->getValue();
$enc = $v->jsonSerialize();
$cnt = count($enc);
if (0 === $cnt || (1 === $cnt && (isset($enc[FHIRFilterOperator::FIELD_VALUE]) || array_key_exists(FHIRFilterOperator::FIELD_VALUE, $enc)))) {
$encs[] = null;
} else {
unset($enc[FHIRFilterOperator::FIELD_VALUE]);
$encs[] = $enc;
$encValued = true;
}
}
if ($encValued) {
$a[self::FIELD_OPERATOR_EXT] = $encs;
}
}
if (null !== ($v = $this->getValue())) {
$a[self::FIELD_VALUE] = $v->getValue();
$enc = $v->jsonSerialize();
$cnt = count($enc);
if (0 < $cnt && (1 !== $cnt || (1 === $cnt && !array_key_exists(FHIRString::FIELD_VALUE, $enc)))) {
unset($enc[FHIRString::FIELD_VALUE]);
$a[self::FIELD_VALUE_EXT] = $enc;
}
}
if ([] !== ($vs = $this->_getFHIRComments())) {
$a[PHPFHIRConstants::JSON_FIELD_FHIR_COMMENTS] = $vs;
}
return $a;
}
/**
* @return string
*/
public function __toString()
{
return self::FHIR_TYPE_NAME;
}
} | dcarbone/php-fhir-generated | src/DCarbone/PHPFHIRGenerated/STU3/FHIRElement/FHIRBackboneElement/FHIRCodeSystem/FHIRCodeSystemFilter.php | PHP | apache-2.0 | 30,555 |
package com.lpiem.apps.loupelec.utilities.customUiElement;
import android.content.Context;
import android.preference.ListPreference;
import android.util.AttributeSet;
/**
* CustomListPreference Class
*/
public class CustomListPreference extends ListPreference {
/**
* Constructors
*/
public CustomListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomListPreference(Context context) {
super(context);
}
/**
* getSummary Method (Override)
* @return CharSequence
*/
@Override
public CharSequence getSummary() {
return this.getEntry() != null ? this.getEntry().toString() : "";
}
}
| JeremyJacquemont/SchoolProjects | IUT/Android-Projects/Loupe/Sources/app/src/main/java/com/lpiem/apps/loupelec/utilities/customUiElement/CustomListPreference.java | Java | apache-2.0 | 707 |
<?php
class InstGenera extends Eloquent {
protected $table = 'inst_genera';
} | Xoloitzcuintles/viajesTransparentes | app/models/InstGenera.php | PHP | apache-2.0 | 84 |
/*
* Copyright (c) 2016-present, RxJava Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package io.reactivex.rxjava3.internal.operators.flowable;
import java.util.Objects;
import java.util.concurrent.atomic.*;
import org.reactivestreams.*;
import io.reactivex.rxjava3.core.*;
import io.reactivex.rxjava3.disposables.*;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.internal.disposables.DisposableHelper;
import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper;
import io.reactivex.rxjava3.internal.util.*;
import io.reactivex.rxjava3.operators.SpscLinkedArrayQueue;
/**
* Maps upstream values into SingleSources and merges their signals into one sequence.
* @param <T> the source value type
* @param <R> the result value type
*/
public final class FlowableFlatMapSingle<T, R> extends AbstractFlowableWithUpstream<T, R> {
final Function<? super T, ? extends SingleSource<? extends R>> mapper;
final boolean delayErrors;
final int maxConcurrency;
public FlowableFlatMapSingle(Flowable<T> source, Function<? super T, ? extends SingleSource<? extends R>> mapper,
boolean delayError, int maxConcurrency) {
super(source);
this.mapper = mapper;
this.delayErrors = delayError;
this.maxConcurrency = maxConcurrency;
}
@Override
protected void subscribeActual(Subscriber<? super R> s) {
source.subscribe(new FlatMapSingleSubscriber<>(s, mapper, delayErrors, maxConcurrency));
}
static final class FlatMapSingleSubscriber<T, R>
extends AtomicInteger
implements FlowableSubscriber<T>, Subscription {
private static final long serialVersionUID = 8600231336733376951L;
final Subscriber<? super R> downstream;
final boolean delayErrors;
final int maxConcurrency;
final AtomicLong requested;
final CompositeDisposable set;
final AtomicInteger active;
final AtomicThrowable errors;
final Function<? super T, ? extends SingleSource<? extends R>> mapper;
final AtomicReference<SpscLinkedArrayQueue<R>> queue;
Subscription upstream;
volatile boolean cancelled;
FlatMapSingleSubscriber(Subscriber<? super R> actual,
Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean delayErrors, int maxConcurrency) {
this.downstream = actual;
this.mapper = mapper;
this.delayErrors = delayErrors;
this.maxConcurrency = maxConcurrency;
this.requested = new AtomicLong();
this.set = new CompositeDisposable();
this.errors = new AtomicThrowable();
this.active = new AtomicInteger(1);
this.queue = new AtomicReference<>();
}
@Override
public void onSubscribe(Subscription s) {
if (SubscriptionHelper.validate(this.upstream, s)) {
this.upstream = s;
downstream.onSubscribe(this);
int m = maxConcurrency;
if (m == Integer.MAX_VALUE) {
s.request(Long.MAX_VALUE);
} else {
s.request(maxConcurrency);
}
}
}
@Override
public void onNext(T t) {
SingleSource<? extends R> ms;
try {
ms = Objects.requireNonNull(mapper.apply(t), "The mapper returned a null SingleSource");
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
upstream.cancel();
onError(ex);
return;
}
active.getAndIncrement();
InnerObserver inner = new InnerObserver();
if (!cancelled && set.add(inner)) {
ms.subscribe(inner);
}
}
@Override
public void onError(Throwable t) {
active.decrementAndGet();
if (errors.tryAddThrowableOrReport(t)) {
if (!delayErrors) {
set.dispose();
}
drain();
}
}
@Override
public void onComplete() {
active.decrementAndGet();
drain();
}
@Override
public void cancel() {
cancelled = true;
upstream.cancel();
set.dispose();
errors.tryTerminateAndReport();
}
@Override
public void request(long n) {
if (SubscriptionHelper.validate(n)) {
BackpressureHelper.add(requested, n);
drain();
}
}
void innerSuccess(InnerObserver inner, R value) {
set.delete(inner);
if (get() == 0 && compareAndSet(0, 1)) {
boolean d = active.decrementAndGet() == 0;
if (requested.get() != 0) {
downstream.onNext(value);
SpscLinkedArrayQueue<R> q = queue.get();
if (d && (q == null || q.isEmpty())) {
errors.tryTerminateConsumer(downstream);
return;
}
BackpressureHelper.produced(requested, 1);
if (maxConcurrency != Integer.MAX_VALUE) {
upstream.request(1);
}
} else {
SpscLinkedArrayQueue<R> q = getOrCreateQueue();
synchronized (q) {
q.offer(value);
}
}
if (decrementAndGet() == 0) {
return;
}
} else {
SpscLinkedArrayQueue<R> q = getOrCreateQueue();
synchronized (q) {
q.offer(value);
}
active.decrementAndGet();
if (getAndIncrement() != 0) {
return;
}
}
drainLoop();
}
SpscLinkedArrayQueue<R> getOrCreateQueue() {
SpscLinkedArrayQueue<R> current = queue.get();
if (current != null) {
return current;
}
current = new SpscLinkedArrayQueue<>(Flowable.bufferSize());
if (queue.compareAndSet(null, current)) {
return current;
}
return queue.get();
}
void innerError(InnerObserver inner, Throwable e) {
set.delete(inner);
if (errors.tryAddThrowableOrReport(e)) {
if (!delayErrors) {
upstream.cancel();
set.dispose();
} else {
if (maxConcurrency != Integer.MAX_VALUE) {
upstream.request(1);
}
}
active.decrementAndGet();
drain();
}
}
void drain() {
if (getAndIncrement() == 0) {
drainLoop();
}
}
void clear() {
SpscLinkedArrayQueue<R> q = queue.get();
if (q != null) {
q.clear();
}
}
void drainLoop() {
int missed = 1;
Subscriber<? super R> a = downstream;
AtomicInteger n = active;
AtomicReference<SpscLinkedArrayQueue<R>> qr = queue;
for (;;) {
long r = requested.get();
long e = 0L;
while (e != r) {
if (cancelled) {
clear();
return;
}
if (!delayErrors) {
Throwable ex = errors.get();
if (ex != null) {
clear();
errors.tryTerminateConsumer(downstream);
return;
}
}
boolean d = n.get() == 0;
SpscLinkedArrayQueue<R> q = qr.get();
R v = q != null ? q.poll() : null;
boolean empty = v == null;
if (d && empty) {
errors.tryTerminateConsumer(a);
return;
}
if (empty) {
break;
}
a.onNext(v);
e++;
}
if (e == r) {
if (cancelled) {
clear();
return;
}
if (!delayErrors) {
Throwable ex = errors.get();
if (ex != null) {
clear();
errors.tryTerminateConsumer(a);
return;
}
}
boolean d = n.get() == 0;
SpscLinkedArrayQueue<R> q = qr.get();
boolean empty = q == null || q.isEmpty();
if (d && empty) {
errors.tryTerminateConsumer(a);
return;
}
}
if (e != 0L) {
BackpressureHelper.produced(requested, e);
if (maxConcurrency != Integer.MAX_VALUE) {
upstream.request(e);
}
}
missed = addAndGet(-missed);
if (missed == 0) {
break;
}
}
}
final class InnerObserver extends AtomicReference<Disposable>
implements SingleObserver<R>, Disposable {
private static final long serialVersionUID = -502562646270949838L;
@Override
public void onSubscribe(Disposable d) {
DisposableHelper.setOnce(this, d);
}
@Override
public void onSuccess(R value) {
innerSuccess(this, value);
}
@Override
public void onError(Throwable e) {
innerError(this, e);
}
@Override
public boolean isDisposed() {
return DisposableHelper.isDisposed(get());
}
@Override
public void dispose() {
DisposableHelper.dispose(this);
}
}
}
}
| ReactiveX/RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFlatMapSingle.java | Java | apache-2.0 | 11,229 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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 <folly/Benchmark.h>
#include <thrift/lib/cpp2/frozen/FrozenUtil.h>
#include <thrift/lib/cpp2/frozen/test/gen-cpp2/Example_layouts.h>
#include <thrift/lib/cpp2/frozen/test/gen-cpp2/Example_types.h>
#include <thrift/lib/cpp2/protocol/Serializer.h>
using namespace apache::thrift;
using namespace apache::thrift::frozen;
using namespace apache::thrift::test;
EveryLayout stressValue2 = [] {
EveryLayout x;
*x.aBool_ref() = true;
*x.aInt_ref() = 2;
*x.aList_ref() = {3, 5};
*x.aSet_ref() = {7, 11};
*x.aHashSet_ref() = {13, 17};
*x.aMap_ref() = {{19, 23}, {29, 31}};
*x.aHashMap_ref() = {{37, 41}, {43, 47}};
x.optInt_ref() = 53;
*x.aFloat_ref() = 59.61;
x.optMap_ref() = {{2, 4}, {3, 9}};
return x;
}();
BENCHMARK(CompactSerialize, iters) {
size_t s = 0;
while (iters--) {
std::string out;
CompactSerializer::serialize(stressValue2, &out);
s += out.size();
}
folly::doNotOptimizeAway(s);
}
BENCHMARK_RELATIVE(FrozenFreeze, iters) {
size_t s = 0;
folly::BenchmarkSuspender setup;
Layout<EveryLayout> layout;
LayoutRoot::layout(stressValue2, layout);
setup.dismiss();
while (iters--) {
std::string out = freezeDataToString(stressValue2, layout);
s += out.size();
}
folly::doNotOptimizeAway(s);
}
BENCHMARK_RELATIVE(FrozenFreezePreallocate, iters) {
size_t s = 0;
folly::BenchmarkSuspender setup;
Layout<EveryLayout> layout;
LayoutRoot::layout(stressValue2, layout);
setup.dismiss();
while (iters--) {
std::array<byte, 1024> buffer;
auto write = folly::MutableByteRange(buffer.begin(), buffer.end());
ByteRangeFreezer::freeze(layout, stressValue2, write);
s += buffer.size() - write.size();
}
folly::doNotOptimizeAway(s);
}
BENCHMARK_DRAW_LINE();
BENCHMARK(CompactDeserialize, iters) {
size_t s = 0;
folly::BenchmarkSuspender setup;
std::string out;
CompactSerializer::serialize(stressValue2, &out);
setup.dismiss();
while (iters--) {
EveryLayout copy;
CompactSerializer::deserialize(out, copy);
s += out.size();
}
folly::doNotOptimizeAway(s);
}
BENCHMARK_RELATIVE(FrozenThaw, iters) {
size_t s = 0;
folly::BenchmarkSuspender setup;
Layout<EveryLayout> layout;
LayoutRoot::layout(stressValue2, layout);
std::string out = freezeDataToString(stressValue2, layout);
setup.dismiss();
while (iters--) {
EveryLayout copy;
layout.thaw(ViewPosition{reinterpret_cast<byte*>(&out[0]), 0}, copy);
s += out.size();
}
folly::doNotOptimizeAway(s);
}
#if 0
============================================================================
relative time/iter iters/s
============================================================================
CompactSerialize 439.75ns 2.27M
FrozenFreeze 21.53% 2.04us 489.59K
FrozenFreezePreallocate 62.33% 705.48ns 1.42M
----------------------------------------------------------------------------
CompactDeserialize 787.59ns 1.27M
FrozenThaw 98.97% 795.77ns 1.26M
============================================================================
#endif
int main(int argc, char** argv) {
google::InitGoogleLogging(argv[0]);
gflags::ParseCommandLineFlags(&argc, &argv, true);
folly::runBenchmarks();
return 0;
}
| facebook/fbthrift | thrift/lib/cpp2/frozen/test/FrozenSerializationBench.cpp | C++ | apache-2.0 | 4,076 |
package com.keeps.ksxtmanager.system.service;
import java.util.List;
import com.keeps.core.service.SoftService;
import com.keeps.model.TDict;
import com.keeps.model.TDictType;
import com.keeps.tools.utils.page.Page;
import com.keeps.utils.TreeNode;
/**
* <p>Title: DictService.java</p>
* <p>Description: 字典SERVICE接口 </p>
* <p>Copyright: Copyright (c) KEEPS</p>
* @author keeps
* @version v 1.00
* @date 创建日期:2017年1月19日
* 修改日期:
* 修改人:
* 复审人:
*/
public interface DictService extends SoftService{
public Page queryDictList(TDict dict);
public List<TreeNode> getDictTree(String code);
public List<TDict> getDictList(TDict dict);
public List<TDictType> getDictTypeList(TDictType tDictType);
public TDict getDictById(Integer id);
public TDictType geTDictTypeById(Integer id);
public String deleteDictById(String ids);
public String deleteDictTypeById(Integer id);
public List<TreeNode> getDictTypeTree();
public List<TreeNode> getDicttypeTreeByCode(String code);
public List<TreeNode> getDictTypeSelectByCode(String code);
public String saveOrUpdateDict(TDict dict);
public String saveOrUpdateDictType(TDictType dictType);
public List<TDictType> getDictTypeByCode(String code);
public List<TDict> getDictByCode(String code);
}
| keepsl/keepsmis | ksxtmanager/src/main/java/com/keeps/ksxtmanager/system/service/DictService.java | Java | apache-2.0 | 1,385 |
package com.yaochen.boss.dao;
import java.util.List;
import org.springframework.stereotype.Component;
import com.ycsoft.beans.core.cust.CCust;
import com.ycsoft.beans.core.prod.CProdInclude;
import com.ycsoft.daos.abstracts.BaseEntityDao;
import com.ycsoft.daos.core.JDBCException;
@Component
public class ProdIncludeDao extends BaseEntityDao<CCust> {
public ProdIncludeDao(){}
//设置产品之间的关系
public void saveProdInclude(String userId,List<CProdInclude> includeList) throws Exception{
for (CProdInclude include :includeList){
String sql = "insert into c_prod_include_lxr (cust_id,user_id,prod_sn,include_prod_sn) " +
" values (?,?,?,?)";
executeUpdate(sql,include.getCust_id(),include.getUser_id(),include.getProd_sn(),include.getInclude_prod_sn());
}
}
}
| leopardoooo/cambodia | boss-job/src/main/java/com/yaochen/boss/dao/ProdIncludeDao.java | Java | apache-2.0 | 826 |
// 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;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.injected.editor.DocumentWindow;
import com.intellij.lang.ASTNode;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.application.*;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.DocumentRunnable;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.editor.ex.PrioritizedInternalDocumentListener;
import com.intellij.openapi.editor.impl.DocumentImpl;
import com.intellij.openapi.editor.impl.EditorDocumentPriorities;
import com.intellij.openapi.editor.impl.FrozenDocument;
import com.intellij.openapi.editor.impl.event.RetargetRangeMarkers;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.FileIndexFacade;
import com.intellij.openapi.util.*;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.file.impl.FileManager;
import com.intellij.psi.impl.file.impl.FileManagerImpl;
import com.intellij.psi.impl.smartPointers.SmartPointerManagerImpl;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.tree.FileElement;
import com.intellij.psi.text.BlockSupport;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.*;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.UIUtil;
import consulo.application.TransactionGuardEx;
import consulo.disposer.Disposable;
import consulo.disposer.Disposer;
import consulo.logging.Logger;
import consulo.util.dataholder.Key;
import consulo.util.lang.DeprecatedMethodException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.TestOnly;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
public abstract class PsiDocumentManagerBase extends PsiDocumentManager implements DocumentListener, Disposable {
static final Logger LOG = Logger.getInstance(PsiDocumentManagerBase.class);
private static final Key<Document> HARD_REF_TO_DOCUMENT = Key.create("HARD_REFERENCE_TO_DOCUMENT");
private static final Key<List<Runnable>> ACTION_AFTER_COMMIT = Key.create("ACTION_AFTER_COMMIT");
protected final Project myProject;
private final PsiManager myPsiManager;
protected final DocumentCommitProcessor myDocumentCommitProcessor;
final Set<Document> myUncommittedDocuments = ContainerUtil.newConcurrentSet();
private final Map<Document, UncommittedInfo> myUncommittedInfos = ContainerUtil.newConcurrentMap();
boolean myStopTrackingDocuments;
private boolean myPerformBackgroundCommit = true;
private volatile boolean myIsCommitInProgress;
private static volatile boolean ourIsFullReparseInProgress;
private final PsiToDocumentSynchronizer mySynchronizer;
private final List<Listener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList();
protected PsiDocumentManagerBase(@Nonnull Project project, DocumentCommitProcessor documentCommitProcessor) {
myProject = project;
myPsiManager = PsiManager.getInstance(project);
myDocumentCommitProcessor = documentCommitProcessor;
mySynchronizer = new PsiToDocumentSynchronizer(this, project.getMessageBus());
myPsiManager.addPsiTreeChangeListener(mySynchronizer);
project.getMessageBus().connect(this).subscribe(PsiDocumentTransactionListener.TOPIC, (document, file) -> {
myUncommittedDocuments.remove(document);
});
}
@Override
@Nullable
public PsiFile getPsiFile(@Nonnull Document document) {
if (document instanceof DocumentWindow && !((DocumentWindow)document).isValid()) {
return null;
}
PsiFile psiFile = getCachedPsiFile(document);
if (psiFile != null) {
return ensureValidFile(psiFile, "Cached PSI");
}
final VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
if (virtualFile == null || !virtualFile.isValid()) return null;
psiFile = getPsiFile(virtualFile);
if (psiFile == null) return null;
fireFileCreated(document, psiFile);
return psiFile;
}
@Nonnull
private static PsiFile ensureValidFile(@Nonnull PsiFile psiFile, @Nonnull String debugInfo) {
if (!psiFile.isValid()) throw new PsiInvalidElementAccessException(psiFile, debugInfo);
return psiFile;
}
@Deprecated
//@ApiStatus.ScheduledForRemoval(inVersion = "2017")
// todo remove when plugins come to their senses and stopped using it
// todo to be removed in idea 17
public static void cachePsi(@Nonnull Document document, @Nullable PsiFile file) {
DeprecatedMethodException.report("Unsupported method");
}
public void associatePsi(@Nonnull Document document, @Nullable PsiFile file) {
throw new UnsupportedOperationException();
}
@Override
public PsiFile getCachedPsiFile(@Nonnull Document document) {
final VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
if (virtualFile == null || !virtualFile.isValid()) return null;
return getCachedPsiFile(virtualFile);
}
@Nullable
FileViewProvider getCachedViewProvider(@Nonnull Document document) {
final VirtualFile virtualFile = getVirtualFile(document);
if (virtualFile == null) return null;
return getFileManager().findCachedViewProvider(virtualFile);
}
@Nullable
private static VirtualFile getVirtualFile(@Nonnull Document document) {
final VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
if (virtualFile == null || !virtualFile.isValid()) return null;
return virtualFile;
}
@Nullable
PsiFile getCachedPsiFile(@Nonnull VirtualFile virtualFile) {
return getFileManager().getCachedPsiFile(virtualFile);
}
@Nullable
private PsiFile getPsiFile(@Nonnull VirtualFile virtualFile) {
return getFileManager().findFile(virtualFile);
}
@Nonnull
private FileManager getFileManager() {
return ((PsiManagerEx)myPsiManager).getFileManager();
}
@Override
public Document getDocument(@Nonnull PsiFile file) {
Document document = getCachedDocument(file);
if (document != null) {
if (!file.getViewProvider().isPhysical()) {
PsiUtilCore.ensureValid(file);
associatePsi(document, file);
}
return document;
}
FileViewProvider viewProvider = file.getViewProvider();
if (!viewProvider.isEventSystemEnabled()) return null;
document = FileDocumentManager.getInstance().getDocument(viewProvider.getVirtualFile());
if (document != null) {
if (document.getTextLength() != file.getTextLength()) {
String message = "Document/PSI mismatch: " + file + " (" + file.getClass() + "); physical=" + viewProvider.isPhysical();
if (document.getTextLength() + file.getTextLength() < 8096) {
message += "\n=== document ===\n" + document.getText() + "\n=== PSI ===\n" + file.getText();
}
throw new AssertionError(message);
}
if (!viewProvider.isPhysical()) {
PsiUtilCore.ensureValid(file);
associatePsi(document, file);
file.putUserData(HARD_REF_TO_DOCUMENT, document);
}
}
return document;
}
@Override
public Document getCachedDocument(@Nonnull PsiFile file) {
if (!file.isPhysical()) return null;
VirtualFile vFile = file.getViewProvider().getVirtualFile();
return FileDocumentManager.getInstance().getCachedDocument(vFile);
}
@Override
public void commitAllDocuments() {
ApplicationManager.getApplication().assertIsWriteThread();
((TransactionGuardEx)TransactionGuard.getInstance()).assertWriteActionAllowed();
if (myUncommittedDocuments.isEmpty()) return;
final Document[] documents = getUncommittedDocuments();
for (Document document : documents) {
if (isCommitted(document)) {
boolean success = doCommitWithoutReparse(document);
LOG.error("Committed document in uncommitted set: " + document + ", force-committed=" + success);
}
else if (!doCommit(document)) {
LOG.error("Couldn't commit " + document);
}
}
assertEverythingCommitted();
}
@Override
public boolean commitAllDocumentsUnderProgress() {
Application application = ApplicationManager.getApplication();
//backward compatibility with unit tests
if (application.isUnitTestMode()) {
commitAllDocuments();
return true;
}
assert !application.isWriteAccessAllowed() : "Do not call commitAllDocumentsUnderProgress inside write-action";
final int semaphoreTimeoutInMs = 50;
final Runnable commitAllDocumentsRunnable = () -> {
Semaphore semaphore = new Semaphore(1);
application.invokeLater(() -> {
PsiDocumentManager.getInstance(myProject).performWhenAllCommitted(() -> {
semaphore.up();
});
});
while (!semaphore.waitFor(semaphoreTimeoutInMs)) {
ProgressManager.checkCanceled();
}
};
return ProgressManager.getInstance().runProcessWithProgressSynchronously(commitAllDocumentsRunnable, "Processing Documents", true, myProject);
}
private void assertEverythingCommitted() {
LOG.assertTrue(!hasUncommitedDocuments(), myUncommittedDocuments);
}
@VisibleForTesting
public boolean doCommitWithoutReparse(@Nonnull Document document) {
return finishCommitInWriteAction(document, Collections.emptyList(), Collections.emptyList(), true, true);
}
@Override
public void performForCommittedDocument(@Nonnull final Document doc, @Nonnull final Runnable action) {
Document document = getTopLevelDocument(doc);
if (isCommitted(document)) {
action.run();
}
else {
addRunOnCommit(document, action);
}
}
private final Map<Object, Runnable> actionsWhenAllDocumentsAreCommitted = new LinkedHashMap<>(); //accessed from EDT only
private static final Object PERFORM_ALWAYS_KEY = ObjectUtil.sentinel("PERFORM_ALWAYS");
/**
* Cancel previously registered action and schedules (new) action to be executed when all documents are committed.
*
* @param key the (unique) id of the action.
* @param action The action to be executed after automatic commit.
* This action will overwrite any action which was registered under this key earlier.
* The action will be executed in EDT.
* @return true if action has been run immediately, or false if action was scheduled for execution later.
*/
public boolean cancelAndRunWhenAllCommitted(@NonNls @Nonnull Object key, @Nonnull final Runnable action) {
ApplicationManager.getApplication().assertIsDispatchThread();
if (myProject.isDisposed()) {
action.run();
return true;
}
if (myUncommittedDocuments.isEmpty()) {
if (!isCommitInProgress()) {
// in case of fireWriteActionFinished() we didn't execute 'actionsWhenAllDocumentsAreCommitted' yet
assert actionsWhenAllDocumentsAreCommitted.isEmpty() : actionsWhenAllDocumentsAreCommitted;
}
action.run();
return true;
}
checkWeAreOutsideAfterCommitHandler();
actionsWhenAllDocumentsAreCommitted.put(key, action);
return false;
}
public static void addRunOnCommit(@Nonnull Document document, @Nonnull Runnable action) {
synchronized (ACTION_AFTER_COMMIT) {
List<Runnable> list = document.getUserData(ACTION_AFTER_COMMIT);
if (list == null) {
document.putUserData(ACTION_AFTER_COMMIT, list = new SmartList<>());
}
list.add(action);
}
}
private static List<Runnable> getAndClearActionsAfterCommit(@Nonnull Document document) {
List<Runnable> list;
synchronized (ACTION_AFTER_COMMIT) {
list = document.getUserData(ACTION_AFTER_COMMIT);
if (list != null) {
list = new ArrayList<>(list);
document.putUserData(ACTION_AFTER_COMMIT, null);
}
}
return list;
}
@Override
public void commitDocument(@Nonnull final Document doc) {
final Document document = getTopLevelDocument(doc);
if (isEventSystemEnabled(document)) {
((TransactionGuardEx)TransactionGuard.getInstance()).assertWriteActionAllowed();
}
if (!isCommitted(document)) {
doCommit(document);
}
}
private boolean isEventSystemEnabled(Document document) {
FileViewProvider viewProvider = getCachedViewProvider(document);
return viewProvider != null && viewProvider.isEventSystemEnabled() && !AbstractFileViewProvider.isFreeThreaded(viewProvider);
}
boolean finishCommit(@Nonnull final Document document,
@Nonnull List<? extends BooleanRunnable> finishProcessors,
@Nonnull List<? extends BooleanRunnable> reparseInjectedProcessors,
final boolean synchronously,
@Nonnull final Object reason) {
assert !myProject.isDisposed() : "Already disposed";
ApplicationManager.getApplication().assertIsDispatchThread();
final boolean[] ok = {true};
Runnable runnable = new DocumentRunnable(document, myProject) {
@Override
public void run() {
ok[0] = finishCommitInWriteAction(document, finishProcessors, reparseInjectedProcessors, synchronously, false);
}
};
if (synchronously) {
runnable.run();
}
else {
ApplicationManager.getApplication().runWriteAction(runnable);
}
if (ok[0]) {
// run after commit actions outside write action
runAfterCommitActions(document);
if (DebugUtil.DO_EXPENSIVE_CHECKS && !ApplicationInfoImpl.isInPerformanceTest()) {
checkAllElementsValid(document, reason);
}
}
return ok[0];
}
protected boolean finishCommitInWriteAction(@Nonnull final Document document,
@Nonnull List<? extends BooleanRunnable> finishProcessors,
@Nonnull List<? extends BooleanRunnable> reparseInjectedProcessors,
final boolean synchronously,
boolean forceNoPsiCommit) {
ApplicationManager.getApplication().assertIsDispatchThread();
if (myProject.isDisposed()) return false;
assert !(document instanceof DocumentWindow);
VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
if (virtualFile != null) {
getSmartPointerManager().fastenBelts(virtualFile);
}
FileViewProvider viewProvider = forceNoPsiCommit ? null : getCachedViewProvider(document);
myIsCommitInProgress = true;
Ref<Boolean> success = new Ref<>(true);
try {
ProgressManager.getInstance().executeNonCancelableSection(() -> {
if (viewProvider == null) {
handleCommitWithoutPsi(document);
}
else {
success.set(commitToExistingPsi(document, finishProcessors, reparseInjectedProcessors, synchronously, virtualFile));
}
});
}
catch (Throwable e) {
try {
forceReload(virtualFile, viewProvider);
}
finally {
LOG.error(e);
}
}
finally {
if (success.get()) {
myUncommittedDocuments.remove(document);
}
myIsCommitInProgress = false;
}
return success.get();
}
private boolean commitToExistingPsi(@Nonnull Document document,
@Nonnull List<? extends BooleanRunnable> finishProcessors,
@Nonnull List<? extends BooleanRunnable> reparseInjectedProcessors,
boolean synchronously,
@Nullable VirtualFile virtualFile) {
for (BooleanRunnable finishRunnable : finishProcessors) {
boolean success = finishRunnable.run();
if (synchronously) {
assert success : finishRunnable + " in " + finishProcessors;
}
if (!success) {
return false;
}
}
clearUncommittedInfo(document);
if (virtualFile != null) {
getSmartPointerManager().updatePointerTargetsAfterReparse(virtualFile);
}
FileViewProvider viewProvider = getCachedViewProvider(document);
if (viewProvider != null) {
viewProvider.contentsSynchronized();
}
for (BooleanRunnable runnable : reparseInjectedProcessors) {
if (!runnable.run()) return false;
}
return true;
}
void forceReload(VirtualFile virtualFile, @Nullable FileViewProvider viewProvider) {
if (viewProvider != null) {
((AbstractFileViewProvider)viewProvider).markInvalidated();
}
if (virtualFile != null) {
((FileManagerImpl)getFileManager()).forceReload(virtualFile);
}
}
private void checkAllElementsValid(@Nonnull Document document, @Nonnull final Object reason) {
final PsiFile psiFile = getCachedPsiFile(document);
if (psiFile != null) {
psiFile.accept(new PsiRecursiveElementWalkingVisitor() {
@Override
public void visitElement(PsiElement element) {
if (!element.isValid()) {
throw new AssertionError("Commit to '" + psiFile.getVirtualFile() + "' has led to invalid element: " + element + "; Reason: '" + reason + "'");
}
}
});
}
}
private boolean doCommit(@Nonnull final Document document) {
assert !myIsCommitInProgress : "Do not call commitDocument() from inside PSI change listener";
// otherwise there are many clients calling commitAllDocs() on PSI childrenChanged()
if (getSynchronizer().isDocumentAffectedByTransactions(document)) return false;
final PsiFile psiFile = getPsiFile(document);
if (psiFile == null) {
myUncommittedDocuments.remove(document);
runAfterCommitActions(document);
return true; // the project must be closing or file deleted
}
Runnable runnable = () -> {
myIsCommitInProgress = true;
try {
myDocumentCommitProcessor.commitSynchronously(document, myProject, psiFile);
}
finally {
myIsCommitInProgress = false;
}
assert !isInUncommittedSet(document) : "Document :" + document;
};
ApplicationManager.getApplication().runWriteAction(runnable);
return true;
}
// true if the PSI is being modified and events being sent
public boolean isCommitInProgress() {
return myIsCommitInProgress || isFullReparseInProgress();
}
public static boolean isFullReparseInProgress() {
return ourIsFullReparseInProgress;
}
@Override
public <T> T commitAndRunReadAction(@Nonnull final Computable<T> computation) {
final Ref<T> ref = Ref.create(null);
commitAndRunReadAction(() -> ref.set(computation.compute()));
return ref.get();
}
@Override
public void reparseFiles(@Nonnull Collection<? extends VirtualFile> files, boolean includeOpenFiles) {
FileContentUtilCore.reparseFiles(files);
}
@Override
public void commitAndRunReadAction(@Nonnull final Runnable runnable) {
final Application application = ApplicationManager.getApplication();
if (application.isDispatchThread()) {
commitAllDocuments();
runnable.run();
return;
}
if (application.isReadAccessAllowed()) {
LOG.error("Don't call commitAndRunReadAction inside ReadAction, it will cause a deadlock. " + Thread.currentThread());
}
while (true) {
boolean executed = ReadAction.compute(() -> {
if (myUncommittedDocuments.isEmpty()) {
runnable.run();
return true;
}
return false;
});
if (executed) break;
TransactionId contextTransaction = TransactionGuard.getInstance().getContextTransaction();
Semaphore semaphore = new Semaphore(1);
application.invokeLater(() -> {
if (myProject.isDisposed()) {
// committedness doesn't matter anymore; give clients a chance to do checkCanceled
semaphore.up();
return;
}
performWhenAllCommitted(() -> semaphore.up(), contextTransaction);
}, ModalityState.any());
while (!semaphore.waitFor(10)) {
ProgressManager.checkCanceled();
}
}
}
/**
* Schedules action to be executed when all documents are committed.
*
* @return true if action has been run immediately, or false if action was scheduled for execution later.
*/
@Override
public boolean performWhenAllCommitted(@Nonnull final Runnable action) {
return performWhenAllCommitted(action, TransactionGuard.getInstance().getContextTransaction());
}
private boolean performWhenAllCommitted(@Nonnull Runnable action, @Nullable TransactionId context) {
ApplicationManager.getApplication().assertIsDispatchThread();
checkWeAreOutsideAfterCommitHandler();
assert !myProject.isDisposed() : "Already disposed: " + myProject;
if (myUncommittedDocuments.isEmpty()) {
action.run();
return true;
}
CompositeRunnable actions = (CompositeRunnable)actionsWhenAllDocumentsAreCommitted.get(PERFORM_ALWAYS_KEY);
if (actions == null) {
actions = new CompositeRunnable();
actionsWhenAllDocumentsAreCommitted.put(PERFORM_ALWAYS_KEY, actions);
}
actions.add(action);
if (context != null) {
// re-add all uncommitted documents into the queue with this new modality
// because this client obviously expects them to commit even inside modal dialog
for (Document document : myUncommittedDocuments) {
myDocumentCommitProcessor.commitAsynchronously(myProject, document, "re-added with context " + context + " because performWhenAllCommitted(" + context + ") was called", context);
}
}
return false;
}
@Override
public void performLaterWhenAllCommitted(@Nonnull final Runnable runnable) {
performLaterWhenAllCommitted(runnable, ModalityState.defaultModalityState());
}
@Override
public void performLaterWhenAllCommitted(@Nonnull final Runnable runnable, final ModalityState modalityState) {
final Runnable whenAllCommitted = () -> ApplicationManager.getApplication().invokeLater(() -> {
if (hasUncommitedDocuments()) {
// no luck, will try later
performLaterWhenAllCommitted(runnable);
}
else {
runnable.run();
}
}, modalityState, myProject.getDisposed());
if (ApplicationManager.getApplication().isDispatchThread() && isInsideCommitHandler()) {
whenAllCommitted.run();
}
else {
UIUtil.invokeLaterIfNeeded(() -> {
if (!myProject.isDisposed()) performWhenAllCommitted(whenAllCommitted);
});
}
}
private static class CompositeRunnable extends ArrayList<Runnable> implements Runnable {
@Override
public void run() {
for (Runnable runnable : this) {
runnable.run();
}
}
}
private void runAfterCommitActions(@Nonnull Document document) {
if (!ApplicationManager.getApplication().isDispatchThread()) {
// have to run in EDT to guarantee data structure safe access and "execute in EDT" callbacks contract
ApplicationManager.getApplication().invokeLater(() -> {
if (!myProject.isDisposed() && isCommitted(document)) runAfterCommitActions(document);
});
return;
}
ApplicationManager.getApplication().assertIsDispatchThread();
List<Runnable> list = getAndClearActionsAfterCommit(document);
if (list != null) {
for (final Runnable runnable : list) {
runnable.run();
}
}
if (!hasUncommitedDocuments() && !actionsWhenAllDocumentsAreCommitted.isEmpty()) {
List<Runnable> actions = new ArrayList<>(actionsWhenAllDocumentsAreCommitted.values());
beforeCommitHandler();
List<Pair<Runnable, Throwable>> exceptions = new ArrayList<>();
try {
for (Runnable action : actions) {
try {
action.run();
}
catch (ProcessCanceledException e) {
// some actions are crazy enough to use PCE for their own control flow.
// swallow and ignore to not disrupt completely unrelated control flow.
}
catch (Throwable e) {
exceptions.add(Pair.create(action, e));
}
}
}
finally {
// unblock adding listeners
actionsWhenAllDocumentsAreCommitted.clear();
}
for (Pair<Runnable, Throwable> pair : exceptions) {
Runnable action = pair.getFirst();
Throwable e = pair.getSecond();
LOG.error("During running " + action, e);
}
}
}
private void beforeCommitHandler() {
actionsWhenAllDocumentsAreCommitted.put(PERFORM_ALWAYS_KEY, EmptyRunnable.getInstance()); // to prevent listeners from registering new actions during firing
}
private void checkWeAreOutsideAfterCommitHandler() {
if (isInsideCommitHandler()) {
throw new IncorrectOperationException("You must not call performWhenAllCommitted()/cancelAndRunWhenCommitted() from within after-commit handler");
}
}
private boolean isInsideCommitHandler() {
return actionsWhenAllDocumentsAreCommitted.get(PERFORM_ALWAYS_KEY) == EmptyRunnable.getInstance();
}
@Override
public void addListener(@Nonnull Listener listener) {
myListeners.add(listener);
}
@Override
public void removeListener(@Nonnull Listener listener) {
myListeners.remove(listener);
}
@Override
public boolean isDocumentBlockedByPsi(@Nonnull Document doc) {
return false;
}
@Override
public void doPostponedOperationsAndUnblockDocument(@Nonnull Document doc) {
}
void fireDocumentCreated(@Nonnull Document document, PsiFile file) {
myProject.getMessageBus().syncPublisher(PsiDocumentListener.TOPIC).documentCreated(document, file, myProject);
for (Listener listener : myListeners) {
listener.documentCreated(document, file);
}
}
private void fireFileCreated(@Nonnull Document document, @Nonnull PsiFile file) {
myProject.getMessageBus().syncPublisher(PsiDocumentListener.TOPIC).fileCreated(file, document);
for (Listener listener : myListeners) {
listener.fileCreated(file, document);
}
}
@Override
@Nonnull
public CharSequence getLastCommittedText(@Nonnull Document document) {
return getLastCommittedDocument(document).getImmutableCharSequence();
}
@Override
public long getLastCommittedStamp(@Nonnull Document document) {
return getLastCommittedDocument(getTopLevelDocument(document)).getModificationStamp();
}
@Override
@Nullable
public Document getLastCommittedDocument(@Nonnull PsiFile file) {
Document document = getDocument(file);
return document == null ? null : getLastCommittedDocument(document);
}
@Nonnull
public DocumentEx getLastCommittedDocument(@Nonnull Document document) {
if (document instanceof FrozenDocument) return (DocumentEx)document;
if (document instanceof DocumentWindow) {
DocumentWindow window = (DocumentWindow)document;
Document delegate = window.getDelegate();
if (delegate instanceof FrozenDocument) return (DocumentEx)window;
if (!window.isValid()) {
throw new AssertionError("host committed: " + isCommitted(delegate) + ", window=" + window);
}
UncommittedInfo info = myUncommittedInfos.get(delegate);
DocumentWindow answer = info == null ? null : info.myFrozenWindows.get(document);
if (answer == null) answer = freezeWindow(window);
if (info != null) answer = ConcurrencyUtil.cacheOrGet(info.myFrozenWindows, window, answer);
return (DocumentEx)answer;
}
assert document instanceof DocumentImpl;
UncommittedInfo info = myUncommittedInfos.get(document);
return info != null ? info.myFrozen : ((DocumentImpl)document).freeze();
}
@Nonnull
protected DocumentWindow freezeWindow(@Nonnull DocumentWindow document) {
throw new UnsupportedOperationException();
}
@Nonnull
public List<DocumentEvent> getEventsSinceCommit(@Nonnull Document document) {
assert document instanceof DocumentImpl : document;
UncommittedInfo info = myUncommittedInfos.get(document);
if (info != null) {
//noinspection unchecked
return (List<DocumentEvent>)info.myEvents.clone();
}
return Collections.emptyList();
}
@Override
@Nonnull
public Document[] getUncommittedDocuments() {
ApplicationManager.getApplication().assertReadAccessAllowed();
//noinspection UnnecessaryLocalVariable
Document[] documents = myUncommittedDocuments.toArray(Document.EMPTY_ARRAY);
return documents; // java.util.ConcurrentHashMap.keySet().toArray() guaranteed to return array with no nulls
}
boolean isInUncommittedSet(@Nonnull Document document) {
return myUncommittedDocuments.contains(getTopLevelDocument(document));
}
@Override
public boolean isUncommited(@Nonnull Document document) {
return !isCommitted(document);
}
@Override
public boolean isCommitted(@Nonnull Document document) {
document = getTopLevelDocument(document);
if (getSynchronizer().isInSynchronization(document)) return true;
return (!(document instanceof DocumentEx) || !((DocumentEx)document).isInEventsHandling()) && !isInUncommittedSet(document);
}
@Nonnull
private static Document getTopLevelDocument(@Nonnull Document document) {
return document instanceof DocumentWindow ? ((DocumentWindow)document).getDelegate() : document;
}
@Override
public boolean hasUncommitedDocuments() {
return !myIsCommitInProgress && !myUncommittedDocuments.isEmpty();
}
@Override
public void beforeDocumentChange(@Nonnull DocumentEvent event) {
if (myStopTrackingDocuments || myProject.isDisposed()) return;
final Document document = event.getDocument();
VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
boolean isRelevant = virtualFile != null && isRelevant(virtualFile);
if (document instanceof DocumentImpl && !myUncommittedInfos.containsKey(document)) {
myUncommittedInfos.put(document, new UncommittedInfo((DocumentImpl)document));
}
final FileViewProvider viewProvider = getCachedViewProvider(document);
boolean inMyProject = viewProvider != null && viewProvider.getManager() == myPsiManager;
if (!isRelevant || !inMyProject) {
return;
}
final List<PsiFile> files = viewProvider.getAllFiles();
PsiFile psiCause = null;
for (PsiFile file : files) {
if (file == null) {
throw new AssertionError("View provider " + viewProvider + " (" + viewProvider.getClass() + ") returned null in its files array: " + files + " for file " + viewProvider.getVirtualFile());
}
if (PsiToDocumentSynchronizer.isInsideAtomicChange(file)) {
psiCause = file;
}
}
if (psiCause == null) {
beforeDocumentChangeOnUnlockedDocument(viewProvider);
}
}
protected void beforeDocumentChangeOnUnlockedDocument(@Nonnull final FileViewProvider viewProvider) {
}
@Override
public void documentChanged(@Nonnull DocumentEvent event) {
if (myStopTrackingDocuments || myProject.isDisposed()) return;
final Document document = event.getDocument();
VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
boolean isRelevant = virtualFile != null && isRelevant(virtualFile);
final FileViewProvider viewProvider = getCachedViewProvider(document);
if (viewProvider == null) {
handleCommitWithoutPsi(document);
return;
}
boolean inMyProject = viewProvider.getManager() == myPsiManager;
if (!isRelevant || !inMyProject) {
clearUncommittedInfo(document);
return;
}
List<PsiFile> files = viewProvider.getAllFiles();
if (files.isEmpty()) {
handleCommitWithoutPsi(document);
return;
}
boolean commitNecessary = files.stream().noneMatch(file -> PsiToDocumentSynchronizer.isInsideAtomicChange(file) || !(file instanceof PsiFileImpl));
boolean forceCommit = ApplicationManager.getApplication().hasWriteAction(ExternalChangeAction.class) &&
(SystemProperties.getBooleanProperty("idea.force.commit.on.external.change", false) ||
ApplicationManager.getApplication().isHeadlessEnvironment() && !ApplicationManager.getApplication().isUnitTestMode());
// Consider that it's worth to perform complete re-parse instead of merge if the whole document text is replaced and
// current document lines number is roughly above 5000. This makes sense in situations when external change is performed
// for the huge file (that causes the whole document to be reloaded and 'merge' way takes a while to complete).
if (event.isWholeTextReplaced() && document.getTextLength() > 100000) {
document.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, Boolean.TRUE);
}
if (commitNecessary) {
assert !(document instanceof DocumentWindow);
myUncommittedDocuments.add(document);
if (forceCommit) {
commitDocument(document);
}
else if (!document.isInBulkUpdate() && myPerformBackgroundCommit) {
myDocumentCommitProcessor.commitAsynchronously(myProject, document, event, TransactionGuard.getInstance().getContextTransaction());
}
}
else {
clearUncommittedInfo(document);
}
}
@Override
public void bulkUpdateStarting(@Nonnull Document document) {
document.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, Boolean.TRUE);
}
@Override
public void bulkUpdateFinished(@Nonnull Document document) {
myDocumentCommitProcessor.commitAsynchronously(myProject, document, "Bulk update finished", TransactionGuard.getInstance().getContextTransaction());
}
class PriorityEventCollector implements PrioritizedInternalDocumentListener {
@Override
public int getPriority() {
return EditorDocumentPriorities.RANGE_MARKER;
}
@Override
public void moveTextHappened(@Nonnull Document document, int start, int end, int base) {
UncommittedInfo info = myUncommittedInfos.get(document);
if (info != null) {
info.myEvents.add(new RetargetRangeMarkers(document, start, end, base));
}
}
@Override
public void documentChanged(@Nonnull DocumentEvent event) {
UncommittedInfo info = myUncommittedInfos.get(event.getDocument());
if (info != null) {
info.myEvents.add(event);
}
}
}
void handleCommitWithoutPsi(@Nonnull Document document) {
final UncommittedInfo prevInfo = clearUncommittedInfo(document);
if (prevInfo == null) {
return;
}
myUncommittedDocuments.remove(document);
if (!myProject.isInitialized() || myProject.isDisposed() || myProject.isDefault()) {
return;
}
VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
if (virtualFile != null) {
FileManager fileManager = getFileManager();
FileViewProvider viewProvider = fileManager.findCachedViewProvider(virtualFile);
if (viewProvider != null) {
// we can end up outside write action here if the document has forUseInNonAWTThread=true
ApplicationManager.getApplication().runWriteAction((ExternalChangeAction)() -> ((AbstractFileViewProvider)viewProvider).onContentReload());
}
else if (FileIndexFacade.getInstance(myProject).isInContent(virtualFile)) {
ApplicationManager.getApplication().runWriteAction((ExternalChangeAction)() -> ((FileManagerImpl)fileManager).firePropertyChangedForUnloadedPsi());
}
}
runAfterCommitActions(document);
}
@Nullable
private UncommittedInfo clearUncommittedInfo(@Nonnull Document document) {
UncommittedInfo info = myUncommittedInfos.remove(document);
if (info != null) {
getSmartPointerManager().updatePointers(document, info.myFrozen, info.myEvents);
}
return info;
}
private SmartPointerManagerImpl getSmartPointerManager() {
return (SmartPointerManagerImpl)SmartPointerManager.getInstance(myProject);
}
private boolean isRelevant(@Nonnull VirtualFile virtualFile) {
return !myProject.isDisposed() && !virtualFile.getFileType().isBinary();
}
public static boolean checkConsistency(@Nonnull PsiFile psiFile, @Nonnull Document document) {
//todo hack
if (psiFile.getVirtualFile() == null) return true;
CharSequence editorText = document.getCharsSequence();
int documentLength = document.getTextLength();
if (psiFile.textMatches(editorText)) {
LOG.assertTrue(psiFile.getTextLength() == documentLength);
return true;
}
char[] fileText = psiFile.textToCharArray();
@SuppressWarnings("NonConstantStringShouldBeStringBuffer") @NonNls String error =
"File '" + psiFile.getName() + "' text mismatch after reparse. " + "File length=" + fileText.length + "; Doc length=" + documentLength + "\n";
int i = 0;
for (; i < documentLength; i++) {
if (i >= fileText.length) {
error += "editorText.length > psiText.length i=" + i + "\n";
break;
}
if (i >= editorText.length()) {
error += "editorText.length > psiText.length i=" + i + "\n";
break;
}
if (editorText.charAt(i) != fileText[i]) {
error += "first unequal char i=" + i + "\n";
break;
}
}
//error += "*********************************************" + "\n";
//if (i <= 500){
// error += "Equal part:" + editorText.subSequence(0, i) + "\n";
//}
//else{
// error += "Equal part start:\n" + editorText.subSequence(0, 200) + "\n";
// error += "................................................" + "\n";
// error += "................................................" + "\n";
// error += "................................................" + "\n";
// error += "Equal part end:\n" + editorText.subSequence(i - 200, i) + "\n";
//}
error += "*********************************************" + "\n";
error += "Editor Text tail:(" + (documentLength - i) + ")\n";// + editorText.subSequence(i, Math.min(i + 300, documentLength)) + "\n";
error += "*********************************************" + "\n";
error += "Psi Text tail:(" + (fileText.length - i) + ")\n";
error += "*********************************************" + "\n";
if (document instanceof DocumentWindow) {
error += "doc: '" + document.getText() + "'\n";
error += "psi: '" + psiFile.getText() + "'\n";
error += "ast: '" + psiFile.getNode().getText() + "'\n";
error += psiFile.getLanguage() + "\n";
PsiElement context = InjectedLanguageManager.getInstance(psiFile.getProject()).getInjectionHost(psiFile);
if (context != null) {
error += "context: " + context + "; text: '" + context.getText() + "'\n";
error += "context file: " + context.getContainingFile() + "\n";
}
error += "document window ranges: " + Arrays.asList(((DocumentWindow)document).getHostRanges()) + "\n";
}
LOG.error(error);
//document.replaceString(0, documentLength, psiFile.getText());
return false;
}
@VisibleForTesting
@TestOnly
public void clearUncommittedDocuments() {
myUncommittedInfos.clear();
myUncommittedDocuments.clear();
mySynchronizer.cleanupForNextTest();
}
@TestOnly
public void disableBackgroundCommit(@Nonnull Disposable parentDisposable) {
assert myPerformBackgroundCommit;
myPerformBackgroundCommit = false;
Disposer.register(parentDisposable, () -> myPerformBackgroundCommit = true);
}
@Override
public void dispose() {
clearUncommittedDocuments();
}
@Nonnull
public PsiToDocumentSynchronizer getSynchronizer() {
return mySynchronizer;
}
@SuppressWarnings("AssignmentToStaticFieldFromInstanceMethod")
public void reparseFileFromText(@Nonnull PsiFileImpl file) {
ApplicationManager.getApplication().assertIsDispatchThread();
if (isCommitInProgress()) throw new IllegalStateException("Re-entrant commit is not allowed");
FileElement node = file.calcTreeElement();
CharSequence text = node.getChars();
ourIsFullReparseInProgress = true;
try {
WriteAction.run(() -> {
ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
if (indicator == null) indicator = new EmptyProgressIndicator();
DiffLog log = BlockSupportImpl.makeFullParse(file, node, text, indicator, text).log;
log.doActualPsiChange(file);
file.getViewProvider().contentsSynchronized();
});
}
finally {
ourIsFullReparseInProgress = false;
}
}
private static class UncommittedInfo {
private final FrozenDocument myFrozen;
private final ArrayList<DocumentEvent> myEvents = new ArrayList<>();
private final ConcurrentMap<DocumentWindow, DocumentWindow> myFrozenWindows = ContainerUtil.newConcurrentMap();
private UncommittedInfo(@Nonnull DocumentImpl original) {
myFrozen = original.freeze();
}
}
@Nonnull
List<BooleanRunnable> reparseChangedInjectedFragments(@Nonnull Document hostDocument,
@Nonnull PsiFile hostPsiFile,
@Nonnull TextRange range,
@Nonnull ProgressIndicator indicator,
@Nonnull ASTNode oldRoot,
@Nonnull ASTNode newRoot) {
return Collections.emptyList();
}
@TestOnly
public boolean isDefaultProject() {
return myProject.isDefault();
}
}
| consulo/consulo | modules/base/core-impl/src/main/java/com/intellij/psi/impl/PsiDocumentManagerBase.java | Java | apache-2.0 | 42,122 |
package com.github.czyzby.uedi.test.ambiguous;
import com.github.czyzby.uedi.stereotype.Singleton;
public class AmbiguousInjector implements Singleton {
private Ambiguous ambiguousA;
private Ambiguous ambiguousB;
private Ambiguous named;
public Ambiguous getA() {
return ambiguousA;
}
public Ambiguous getB() {
return ambiguousB;
}
public Ambiguous getNamed() {
return named;
}
}
| czyzby/gdx-lml | uedi/src/test/java/com/github/czyzby/uedi/test/ambiguous/AmbiguousInjector.java | Java | apache-2.0 | 445 |
/*
* Copyright 2014-2016 Mikhail Shugay
*
* 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.antigenomics.mageri.core.variant.model;
import java.io.Serializable;
import java.util.Arrays;
public class ErrorRateEstimate implements Serializable {
public static ErrorRateEstimate createDummy(int statisticCount) {
double[] statistics = new double[statisticCount];
Arrays.fill(statistics, Double.NaN);
return new ErrorRateEstimate(0.0, statistics);
}
private final double[] statistics;
private final double errorRate;
public ErrorRateEstimate(double errorRate, double... statistics) {
this.errorRate = errorRate;
this.statistics = statistics;
}
public double[] getStatistics() {
return statistics;
}
public double getErrorRate() {
return errorRate;
}
public String getErrorRateEstimateRowPart() {
String res = "";
if (statistics.length > 0) {
for (double statistic : statistics) {
res += "\t" + (float) statistic;
}
}
return res;
}
}
| mikessh/mageri | src/main/java/com/antigenomics/mageri/core/variant/model/ErrorRateEstimate.java | Java | apache-2.0 | 1,639 |
/*
* Copyright 2000-2009 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.lang.properties;
import com.intellij.lang.properties.parsing.PropertiesTokenTypes;
import com.intellij.lang.properties.parsing._PropertiesLexer;
import com.intellij.lexer.LayeredLexer;
import com.intellij.lexer.StringLiteralLexer;
import com.intellij.psi.tree.IElementType;
/**
* @author cdr
*/
public class PropertiesHighlightingLexer extends LayeredLexer{
public PropertiesHighlightingLexer() {
super(new _PropertiesLexer());
registerSelfStoppingLayer(new StringLiteralLexer(StringLiteralLexer.NO_QUOTE_CHAR, PropertiesTokenTypes.VALUE_CHARACTERS, true, "#!=:"),
new IElementType[]{PropertiesTokenTypes.VALUE_CHARACTERS},
IElementType.EMPTY_ARRAY);
registerSelfStoppingLayer(new StringLiteralLexer(StringLiteralLexer.NO_QUOTE_CHAR, PropertiesTokenTypes.KEY_CHARACTERS, true, "#!=: "),
new IElementType[]{PropertiesTokenTypes.KEY_CHARACTERS},
IElementType.EMPTY_ARRAY);
}
}
| consulo/consulo-properties | src/main/java/com/intellij/lang/properties/PropertiesHighlightingLexer.java | Java | apache-2.0 | 1,637 |
package http;
import java.io.Serializable;
public class HttpMessage implements Serializable{
private static final long serialVersionUID = -1114764212343485987L;
private HttpRequest httpRequest;
private HttpResponse httpResponse;
public HttpMessage(HttpRequest request){
this.httpRequest = request;
}
public HttpRequest getHttpRequest() {
return httpRequest;
}
public void setHttpRequest(HttpRequest httpRequest) {
this.httpRequest = httpRequest;
}
public HttpResponse getHttpResponse() {
return httpResponse;
}
public void setHttpResponse(HttpResponse httpResponse) {
this.httpResponse = httpResponse;
}
}
| OgaworldEX/ORS | src/http/HttpMessage.java | Java | apache-2.0 | 703 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Gdata
* @subpackage Gdata
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* @see Zend_Gdata_Extension
*/
require_once 'Zend/Gdata/Extension.php';
/**
* Data model for gd:extendedProperty element, used by some Gdata
* services to implement arbitrary name/value pair storage
*
* @category Zend
* @package Zend_Gdata
* @subpackage Gdata
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_Extension_ExtendedProperty extends Zend_Gdata_Extension
{
protected $_rootElement = 'extendedProperty';
protected $_name = null;
protected $_value = null;
public function __construct($name = null, $value = null)
{
parent::__construct();
$this->_name = $name;
$this->_value = $value;
}
public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
{
$element = parent::getDOM($doc, $majorVersion, $minorVersion);
if ($this->_name !== null) {
$element->setAttribute('name', $this->_name);
}
if ($this->_value !== null) {
$element->setAttribute('value', $this->_value);
}
return $element;
}
protected function takeAttributeFromDOM($attribute)
{
switch ($attribute->localName) {
case 'name':
$this->_name = $attribute->nodeValue;
break;
case 'value':
$this->_value = $attribute->nodeValue;
break;
default:
parent::takeAttributeFromDOM($attribute);
}
}
public function __toString()
{
return $this->getName() . '=' . $this->getValue();
}
public function getName()
{
return $this->_name;
}
public function setName($value)
{
$this->_name = $value;
return $this;
}
public function getValue()
{
return $this->_value;
}
public function setValue($value)
{
$this->_value = $value;
return $this;
}
}
| ankuradhey/dealtrip | library/Zend/Gdata/Extension/ExtendedProperty.php | PHP | apache-2.0 | 2,841 |
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.people.v1.model;
/**
* The response for deleting a contact's photo.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the People API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class DeleteContactPhotoResponse extends com.google.api.client.json.GenericJson {
/**
* The updated person, if person_fields is set in the DeleteContactPhotoRequest; otherwise this
* will be unset.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Person person;
/**
* The updated person, if person_fields is set in the DeleteContactPhotoRequest; otherwise this
* will be unset.
* @return value or {@code null} for none
*/
public Person getPerson() {
return person;
}
/**
* The updated person, if person_fields is set in the DeleteContactPhotoRequest; otherwise this
* will be unset.
* @param person person or {@code null} for none
*/
public DeleteContactPhotoResponse setPerson(Person person) {
this.person = person;
return this;
}
@Override
public DeleteContactPhotoResponse set(String fieldName, Object value) {
return (DeleteContactPhotoResponse) super.set(fieldName, value);
}
@Override
public DeleteContactPhotoResponse clone() {
return (DeleteContactPhotoResponse) super.clone();
}
}
| googleapis/google-api-java-client-services | clients/google-api-services-people/v1/1.31.0/com/google/api/services/people/v1/model/DeleteContactPhotoResponse.java | Java | apache-2.0 | 2,351 |
<?
function sanitizepostdata($data) {
return trim(addslashes($data));
}
function sanitizedbdata($data) {
return trim(stripslashes($data));
}
function executeScriptAfterPageLoad() {
global $SCRIPT_PENDING_FOR_EXECUTION;
$allCode = '';
if($SCRIPT_PENDING_FOR_EXECUTION && count($SCRIPT_PENDING_FOR_EXECUTION)) {
foreach($SCRIPT_PENDING_FOR_EXECUTION as $eachCode) {
$allCode .= $eachCode."\n";
}
}
if($allCode!='') {
echo "<script>\n$(function(){\r\t".$allCode."});\n</script>\r\n";
}
}
function addScriptForExec($code) {
global $SCRIPT_PENDING_FOR_EXECUTION;
$SCRIPT_PENDING_FOR_EXECUTION[] = $code;
}
//Upload File
//Params :: File[ $_FILES[name] ], UPLOAD DIR, NEW NAME, $ACCEPT
//Return ::
/*
Filename :: Uploaded
-1 :: Not uploaded
-2 :: trying to upload file without extension
-3 :: trying to upload file that is not accepted
-4 :: UPLOAD_ERR_OK returns false
-5 :: not uploaded
*/
function UploadFile($IMG,$UPLOAD_DIR='uploads/',$NEW_NAME,$accept = array('png','jpeg','jpg','gif')) {
$ret = -1;
if($IMG != '' && $UPLOAD_DIR != '') {
$fileExtArr = explode('.',$IMG['name']);
if(count($fileExtArr)>1) {
$fileExt = $fileExtArr[count($fileExtArr)-1];
if(in_array($fileExt,$accept)) {
if($NEW_NAME=='') {
$NEW_NAME = date('YmdHis').'_Upload'.$fileExt;
}
if($IMG['error'] == UPLOAD_ERR_OK) {
$UPLOAD_DIR = rtrim($UPLOAD_DIR,'/');
if(!file_exists($UPLOAD_DIR)) {
mkdir($UPLOAD_DIR, 0777, true);
}
if(move_uploaded_file($IMG['tmp_name'],$UPLOAD_DIR.'/'.$NEW_NAME)) {
$ret = 1;
} else {
$ret = -5;
}
} else {
$ret = -4;
}
} else {
$ret = -3;
}
} else {
$ret = -2;
}
}
return $ret;
}
/*
parameters ::
top_offset = "60",
msg_type = "info/success/warning/error",
msg_align = "left/center/right",
msg_width = "350",
msg_delay = "5000",
*/
function setNotification($message,$top_offset=150,$message_type="success",$message_align="center",$message_width=390,$message_delay=6000) {
if($message_type != '' && $top_offset != '' && $message_align != '' && is_numeric($message_width) && is_numeric($message_delay)) {
$_SESSION['NOTIFICATION']['THIS_NOTE'] = array(
'message'=>$message,
'message_type'=>$message_type,
'message_top_offset'=>$top_offset,
'message_align'=>$message_align,
'message_width'=>$message_width,
'message_delay'=>$message_delay
);
}
}
function displayNotification() {
if(isset($_SESSION['NOTIFICATION']['THIS_NOTE']['message']) && !empty($_SESSION['NOTIFICATION']['THIS_NOTE']['message'])) {
$notification = $_SESSION['NOTIFICATION']['THIS_NOTE'];
addScriptForExec("$.fn.PopInformation('".$notification['message']."','".$notification['message_type']."','".$notification['message_top_offset']."','".$notification['message_align']."','".$notification['message_width']."','".$notification['message_delay']."');");
$_SESSION['NOTIFICATION']['THIS_NOTE']['message'] = '';
}
}
?> | pritamdalal90/pdftoword | includes/functions.php | PHP | apache-2.0 | 3,112 |
/*
* 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.asterix.common.utils;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.hyracks.storage.am.common.api.ITreeIndexFrame;
import org.apache.hyracks.storage.am.lsm.common.impls.AbstractLSMIndexFileManager;
import org.apache.hyracks.storage.am.lsm.common.impls.ConcurrentMergePolicyFactory;
/**
* A static class that stores storage constants
*/
public class StorageConstants {
public static final String STORAGE_ROOT_DIR_NAME = "storage";
public static final String PARTITION_DIR_PREFIX = "partition_";
/**
* Any file that shares the same directory as the LSM index files must
* begin with ".". Otherwise {@link AbstractLSMIndexFileManager} will try to
* use them as index files.
*/
public static final String INDEX_CHECKPOINT_FILE_PREFIX = ".idx_checkpoint_";
public static final String METADATA_FILE_NAME = ".metadata";
public static final String MASK_FILE_PREFIX = ".mask_";
public static final String COMPONENT_MASK_FILE_PREFIX = MASK_FILE_PREFIX + "C_";
public static final float DEFAULT_TREE_FILL_FACTOR = 1.00f;
public static final String DEFAULT_COMPACTION_POLICY_NAME = ConcurrentMergePolicyFactory.NAME;
public static final String DEFAULT_FILTERED_DATASET_COMPACTION_POLICY_NAME = "correlated-prefix";
public static final Map<String, String> DEFAULT_COMPACTION_POLICY_PROPERTIES;
/**
* The storage version of AsterixDB related artifacts (e.g. log files, checkpoint files, etc..).
*/
private static final int LOCAL_STORAGE_VERSION = 5;
/**
* The storage version of AsterixDB stack.
*/
public static final int VERSION = LOCAL_STORAGE_VERSION + ITreeIndexFrame.Constants.VERSION;
static {
DEFAULT_COMPACTION_POLICY_PROPERTIES = new LinkedHashMap<>();
DEFAULT_COMPACTION_POLICY_PROPERTIES.put(ConcurrentMergePolicyFactory.MAX_COMPONENT_COUNT, "30");
DEFAULT_COMPACTION_POLICY_PROPERTIES.put(ConcurrentMergePolicyFactory.MIN_MERGE_COMPONENT_COUNT, "3");
DEFAULT_COMPACTION_POLICY_PROPERTIES.put(ConcurrentMergePolicyFactory.MAX_MERGE_COMPONENT_COUNT, "10");
DEFAULT_COMPACTION_POLICY_PROPERTIES.put(ConcurrentMergePolicyFactory.SIZE_RATIO, "1.2");
}
private StorageConstants() {
}
}
| apache/incubator-asterixdb | asterixdb/asterix-common/src/main/java/org/apache/asterix/common/utils/StorageConstants.java | Java | apache-2.0 | 3,098 |
/*
* Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
* LICENSE file.
*/
package com.gemstone.gemfire.internal.cache.persistence.soplog;
import org.apache.hadoop.hbase.util.Bytes;
import com.gemstone.gemfire.internal.cache.persistence.soplog.SortedReader.SerializedComparator;
/**
* Compares objects byte-by-byte. This is fast and sufficient for cases when
* lexicographic ordering is not important or the serialization is order-
* preserving.
*
* @author bakera
*/
public class ByteComparator implements SerializedComparator {
@Override
public int compare(byte[] rhs, byte[] lhs) {
return compare(rhs, 0, rhs.length, lhs, 0, lhs.length);
}
@Override
public int compare(byte[] r, int rOff, int rLen, byte[] l, int lOff, int lLen) {
return compareBytes(r, rOff, rLen, l, lOff, lLen);
}
/**
* Compares two byte arrays element-by-element.
*
* @param r the right array
* @param rOff the offset of r
* @param rLen the length of r to compare
* @param l the left array
* @param lOff the offset of l
* @param lLen the length of l to compare
* @return -1 if r < l; 0 if r == l; 1 if r > 1
*/
public static int compareBytes(byte[] r, int rOff, int rLen, byte[] l, int lOff, int lLen) {
return Bytes.compareTo(r, rOff, rLen, l, lOff, lLen);
}
}
| gemxd/gemfirexd-oss | gemfire-core/src/main/java/com/gemstone/gemfire/internal/cache/persistence/soplog/ByteComparator.java | Java | apache-2.0 | 1,907 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package listeners;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;
import com.google.inject.struts2.Struts2GuicePluginModule;
import guice.EJBModule;
import org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter;
/**
*
* @author sergio
*/
public class GuiceListener extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return Guice.createInjector(new Struts2GuicePluginModule(),
new ServletModule() {
@Override
protected void configureServlets() {
// Struts 2 setup
bind(StrutsPrepareAndExecuteFilter.class).in(Singleton.class);
filter("/*").through(StrutsPrepareAndExecuteFilter.class);
}
},
new EJBModule()
);
}
}
| sergio11/struts2-hibernate | ejercicio4-web/src/main/java/listeners/GuiceListener.java | Java | apache-2.0 | 1,267 |
#region Copyright and License
// Copyright 2010..2015 Alexander Reinert
//
// This file is part of the ARSoft.Tools.Net - C# DNS client/server and SPF Library (http://arsofttoolsnet.codeplex.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.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ARSoft.Tools.Net.Dns
{
/// <summary>
/// <para>DS Hash Understood option</para>
/// <para>
/// Defined in
/// <see cref="!:http://tools.ietf.org/html/rfc6975">RFC 6975</see>
/// </para>
/// </summary>
public class DsHashUnderstoodOption : EDnsOptionBase
{
/// <summary>
/// List of Algorithms
/// </summary>
public List<DnsSecAlgorithm> Algorithms { get; private set; }
internal DsHashUnderstoodOption()
: base(EDnsOptionType.DsHashUnderstood) {}
/// <summary>
/// Creates a new instance of the DsHashUnderstoodOption class
/// </summary>
/// <param name="algorithms">The list of algorithms</param>
public DsHashUnderstoodOption(List<DnsSecAlgorithm> algorithms)
: this()
{
Algorithms = algorithms;
}
internal override void ParseData(byte[] resultData, int startPosition, int length)
{
Algorithms = new List<DnsSecAlgorithm>(length);
for (int i = 0; i < length; i++)
{
Algorithms.Add((DnsSecAlgorithm) resultData[startPosition++]);
}
}
internal override ushort DataLength => (ushort) (Algorithms?.Count ?? 0);
internal override void EncodeData(byte[] messageData, ref int currentPosition)
{
foreach (var algorithm in Algorithms)
{
messageData[currentPosition++] = (byte) algorithm;
}
}
}
} | huoxudong125/ARSoft.Tools.Net | ARSoft.Tools.Net/Dns/EDns/DsHashUnderstoodOption.cs | C# | apache-2.0 | 2,167 |
package com.coolweather.app.db;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.coolweather.app.model.City;
import com.coolweather.app.model.County;
import com.coolweather.app.model.Province;
public class CoolWeatherDB {
/*
* Êý¾Ý¿âÃû
*/
public static final String DB_NAME = "cool_weather";
/*
* Êý¾Ý¿â°æ±¾
*/
public static final int VERSION = 1;
private static CoolWeatherDB coolWeatherDB;
private SQLiteDatabase db;
/*
* ½«¹¹Ôì·½·¨Ë½Óл¯
*/
private CoolWeatherDB(Context context){
CoolWeatherOpenHelper dbHelper = new CoolWeatherOpenHelper(context,DB_NAME,null,VERSION);
db = dbHelper.getWritableDatabase();
}
/*
* »ñÈ¡CoolWeatherDBʵÀý
* */
public synchronized static CoolWeatherDB getInstance(Context context){
if(coolWeatherDB == null){
coolWeatherDB = new CoolWeatherDB(context);
}
return coolWeatherDB;
}
/*
* ½«ProvinceʵÀý´æ´¢µ½Êý¾Ý¿â¡£
* */
public void saveProvince(Province province){
if (province !=null){
ContentValues values = new ContentValues();
values.put("province_name", province.getProvinceName());
db.insert("Province", null, values);
}
}
/*
* ´ÓÊý¾Ý¿â¶Áȡȫ¹úËùÓÐÊ¡·ÝµÄÐÅÏ¢¡£
* */
public List<Province> loadProvinces(){
List<Province>list = new ArrayList<Province>();
Cursor cursor = db.query("Province", null, null,null, null, null, null);
if(cursor.moveToFirst()){
do{
Province province = new Province();
province.setId(cursor.getInt(cursor.getColumnIndex("id")));
province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name")));
list.add(province);
}while(cursor.moveToNext());
}
return list;
}
/*
* ½«CityÊý¾Ý´æ´¢µ½Êý¾Ý¿âÖÐ
*/
public void saveCity(City city) {
if(city !=null){
ContentValues values = new ContentValues();
values.put("city_name", city.getCityName());
values.put("province_id", city.getProvinceId());
db.insert("City", null, values);
}
}
/*
* ´ÓÊý¾Ý¿â¶ÁȡijʡÏÂËùÓеijÇÊÐÐÅÏ¢
* */
public List<City> loadCities(int provinceId){
List<City>list = new ArrayList<City>();
Cursor cursor = db.query("City", null, "province_id = ?",new String[] {String.valueOf(provinceId) },null,null,null);
if(cursor.moveToFirst()){
do {
City city = new City();
city.setId(cursor.getInt(cursor.getColumnIndex("id")));
city.setCityName(cursor.getString(cursor.getColumnIndex("city_name")));
city.setProvinceId(provinceId);
list.add(city);
}while(cursor.moveToNext());
}
return list;
}
/*
* ½«CountyʵÀý´æ´¢µ½Êý¾Ý¿â¡£
*/
public void saveCounty(County county){
if(county !=null){
ContentValues values = new ContentValues();
values.put("county_name", county.getCountyName());
values.put("city_id", county.getCityId());
db.insert("County", null, values);
}
}
/*
* ´ÓÊý¾Ý¿â¶Áȡij³ÇÊÐÏÂËùÓеÄÏØÐÅÏ¢¡£
*/
public List<County> loadCounty(int cityId){
List<County> list = new ArrayList<County>();
Cursor cursor = db.query("County", null, "city_id = ?", new String [] {String.valueOf(cityId)}, null, null,null);
if (cursor.moveToFirst()){
do{
County county = new County();
county.setCityId(cursor.getInt(cursor.getColumnIndex("id")));
county.setCountyName(cursor.getString(cursor.getColumnIndex("county_name")));
county.setCityId(cityId);
list.add(county);
}while(cursor.moveToNext());
}
return list;
}
}
| yhhyes/coolweather | src/com/coolweather/app/db/CoolWeatherDB.java | Java | apache-2.0 | 3,550 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/privacy/dlp/v2/dlp.proto
package com.google.privacy.dlp.v2;
public interface ColorOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.privacy.dlp.v2.Color)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* The amount of red in the color as a value in the interval [0, 1].
* </pre>
*
* <code>float red = 1;</code>
*
* @return The red.
*/
float getRed();
/**
*
*
* <pre>
* The amount of green in the color as a value in the interval [0, 1].
* </pre>
*
* <code>float green = 2;</code>
*
* @return The green.
*/
float getGreen();
/**
*
*
* <pre>
* The amount of blue in the color as a value in the interval [0, 1].
* </pre>
*
* <code>float blue = 3;</code>
*
* @return The blue.
*/
float getBlue();
}
| googleapis/java-dlp | proto-google-cloud-dlp-v2/src/main/java/com/google/privacy/dlp/v2/ColorOrBuilder.java | Java | apache-2.0 | 1,515 |
/*
* 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.
*
* Contributions from 2013-2017 where performed either by US government
* employees, or under US Veterans Health Administration contracts.
*
* US Veterans Health Administration contributions by government employees
* are work of the U.S. Government and are not subject to copyright
* protection in the United States. Portions contributed by government
* employees are USGovWork (17USC §105). Not subject to copyright.
*
* Contribution by contractors to the US Veterans Health Administration
* during this period are contractually contributed under the
* Apache License, Version 2.0.
*
* See: https://www.usa.gov/government-works
*
* Contributions prior to 2013:
*
* Copyright (C) International Health Terminology Standards Development Organisation.
* Licensed under the Apache License, Version 2.0.
*
*/
package sh.isaac.mojo;
//~--- non-JDK imports --------------------------------------------------------
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import sh.isaac.api.LookupService;
//~--- classes ----------------------------------------------------------------
/**
* Goal which shuts down an open data store.
*/
@Mojo(
defaultPhase = LifecyclePhase.PROCESS_RESOURCES,
name = "shutdown-isaac"
)
public class Shutdown
extends AbstractMojo {
/**
* Execute.
*
* @throws MojoExecutionException the mojo execution exception
*/
@Override
public void execute()
throws MojoExecutionException {
Headless.setHeadless();
try {
long start = System.currentTimeMillis();
getLog().info("Shutdown terminology store");
// ASSUMES setup has run already
getLog().info(" Shutting Down");
LookupService.shutdownSystem();
getLog().info("Done shutting down terminology store in " + (System.currentTimeMillis() - start) + " ms");
} catch (final Exception e) {
throw new MojoExecutionException("Database shutdown failure", e);
}
}
}
| OSEHRA/ISAAC | core/mojo/src/main/java/sh/isaac/mojo/Shutdown.java | Java | apache-2.0 | 2,748 |
/*
Copyright 2012-2022 Marco De Salvo
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.
*/
namespace RDFSharp.Model
{
/// <summary>
/// RDFVocabulary is an helper for handy usage of supported RDF vocabularies.
/// </summary>
public static partial class RDFVocabulary
{
#region CRM
/// <summary>
/// CRM represents the CIDOC CRM 5.0.4 vocabulary.
/// </summary>
public static class CRM
{
#region Properties
/// <summary>
/// crm
/// </summary>
public static readonly string PREFIX = "crm";
/// <summary>
/// http://www.cidoc-crm.org/cidoc-crm/
/// </summary>
public static readonly string BASE_URI = "http://www.cidoc-crm.org/cidoc-crm/";
/// <summary>
/// http://www.cidoc-crm.org/sites/default/files/cidoc_crm_v5.0.4_official_release.rdfs
/// </summary>
public static readonly string DEREFERENCE_URI = "http://www.cidoc-crm.org/sites/default/files/cidoc_crm_v5.0.4_official_release.rdfs";
/// <summary>
/// crm:E1_CRM_Entity
/// </summary>
public static readonly RDFResource E1_CRM_ENTITY = new RDFResource(string.Concat(CRM.BASE_URI, "E1_CRM_Entity"));
/// <summary>
/// crm:E2_Temporal_Entity
/// </summary>
public static readonly RDFResource E2_TEMPORAL_ENTITY = new RDFResource(string.Concat(CRM.BASE_URI, "E2_Temporal_Entity"));
/// <summary>
/// crm:E3_Condition_State
/// </summary>
public static readonly RDFResource E3_CONDITION_STATE = new RDFResource(string.Concat(CRM.BASE_URI, "E3_Condition_State"));
/// <summary>
/// crm:E4_Period
/// </summary>
public static readonly RDFResource E4_PERIOD = new RDFResource(string.Concat(CRM.BASE_URI, "E4_Period"));
/// <summary>
/// crm:E5_Event
/// </summary>
public static readonly RDFResource E5_EVENT = new RDFResource(string.Concat(CRM.BASE_URI, "E5_Event"));
/// <summary>
/// crm:E6_Destruction
/// </summary>
public static readonly RDFResource E6_DESTRUCTION = new RDFResource(string.Concat(CRM.BASE_URI, "E6_Destruction"));
/// <summary>
/// crm:E7_Activity
/// </summary>
public static readonly RDFResource E7_ACTIVITY = new RDFResource(string.Concat(CRM.BASE_URI, "E7_Activity"));
/// <summary>
/// crm:E8_Acquisition
/// </summary>
public static readonly RDFResource E8_ACQUISITION = new RDFResource(string.Concat(CRM.BASE_URI, "E8_Acquisition"));
/// <summary>
/// crm:E9_Move
/// </summary>
public static readonly RDFResource E9_MOVE = new RDFResource(string.Concat(CRM.BASE_URI, "E9_Move"));
/// <summary>
/// crm:E10_Transfer_of_Custody
/// </summary>
public static readonly RDFResource E10_TRANSFER_OF_CUSTODY = new RDFResource(string.Concat(CRM.BASE_URI, "E10_Transfer_of_Custody"));
/// <summary>
/// crm:E11_Modification
/// </summary>
public static readonly RDFResource E11_MODIFICATION = new RDFResource(string.Concat(CRM.BASE_URI, "E11_Modification"));
/// <summary>
/// crm:E12_Production
/// </summary>
public static readonly RDFResource E12_PRODUCTION = new RDFResource(string.Concat(CRM.BASE_URI, "E12_Production"));
/// <summary>
/// crm:E13_Attribute_Assignment
/// </summary>
public static readonly RDFResource E13_ATTRIBUTE_ASSIGNMENT = new RDFResource(string.Concat(CRM.BASE_URI, "E13_Attribute_Assignment"));
/// <summary>
/// crm:E14_Condition_Assessment
/// </summary>
public static readonly RDFResource E14_CONDITION_ASSESSMENT = new RDFResource(string.Concat(CRM.BASE_URI, "E14_Condition_Assessment"));
/// <summary>
/// crm:E15_Identifier_Assignment
/// </summary>
public static readonly RDFResource E15_IDENTIFIER_ASSIGNMENT = new RDFResource(string.Concat(CRM.BASE_URI, "E15_Identifier_Assignment"));
/// <summary>
/// crm:E16_Measurement
/// </summary>
public static readonly RDFResource E16_MEASUREMENT = new RDFResource(string.Concat(CRM.BASE_URI, "E16_Measurement"));
/// <summary>
/// crm:E17_Type_Assignment
/// </summary>
public static readonly RDFResource E17_TYPE_ASSIGNMENT = new RDFResource(string.Concat(CRM.BASE_URI, "E17_Type_Assignment"));
/// <summary>
/// crm:E18_Physical_Thing
/// </summary>
public static readonly RDFResource E18_PHYSICAL_THING = new RDFResource(string.Concat(CRM.BASE_URI, "E18_Physical_Thing"));
/// <summary>
/// crm:E19_Physical_Object
/// </summary>
public static readonly RDFResource E19_PHYSICAL_OBJECT = new RDFResource(string.Concat(CRM.BASE_URI, "E19_Physical_Object"));
/// <summary>
/// crm:E20_Biological_Object
/// </summary>
public static readonly RDFResource E20_BIOLOGICAL_OBJECT = new RDFResource(string.Concat(CRM.BASE_URI, "E20_Biological_Object"));
/// <summary>
/// crm:E21_Person
/// </summary>
public static readonly RDFResource E21_PERSON = new RDFResource(string.Concat(CRM.BASE_URI, "E21_Person"));
/// <summary>
/// crm:E22_Man-Made_Object
/// </summary>
public static readonly RDFResource E22_MAN_MADE_OBJECT = new RDFResource(string.Concat(CRM.BASE_URI, "E22_Man-Made_Object"));
/// <summary>
/// crm:E24_Physical_Man-Made_Thing
/// </summary>
public static readonly RDFResource E24_PHYSICAL_MAN_MADE_THING = new RDFResource(string.Concat(CRM.BASE_URI, "E24_Physical_Man-Made_Thing"));
/// <summary>
/// crm:E25_Man-Made_Feature
/// </summary>
public static readonly RDFResource E25_MAN_MADE_FEATURE = new RDFResource(string.Concat(CRM.BASE_URI, "E25_Man-Made_Feature"));
/// <summary>
/// crm:E26_Physical_Feature
/// </summary>
public static readonly RDFResource E26_PHYSICAL_FEATURE = new RDFResource(string.Concat(CRM.BASE_URI, "E26_Physical_Feature"));
/// <summary>
/// crm:E27_Site
/// </summary>
public static readonly RDFResource E27_SITE = new RDFResource(string.Concat(CRM.BASE_URI, "E27_Site"));
/// <summary>
/// crm:E28_Conceptual_Object
/// </summary>
public static readonly RDFResource E28_CONCEPTUAL_OBJECT = new RDFResource(string.Concat(CRM.BASE_URI, "E28_Conceptual_Object"));
/// <summary>
/// crm:E29_Design_or_Procedure
/// </summary>
public static readonly RDFResource E29_DESIGN_OR_PROCEDURE = new RDFResource(string.Concat(CRM.BASE_URI, "E29_Design_or_Procedure"));
/// <summary>
/// crm:E30_Right
/// </summary>
public static readonly RDFResource E30_RIGHT = new RDFResource(string.Concat(CRM.BASE_URI, "E30_Right"));
/// <summary>
/// crm:E31_Document
/// </summary>
public static readonly RDFResource E31_DOCUMENT = new RDFResource(string.Concat(CRM.BASE_URI, "E31_Document"));
/// <summary>
/// crm:E32_Authority_Document
/// </summary>
public static readonly RDFResource E32_AUTHORITY_DOCUMENT = new RDFResource(string.Concat(CRM.BASE_URI, "E32_Authority_Document"));
/// <summary>
/// crm:E33_Linguistic_Object
/// </summary>
public static readonly RDFResource E33_LINGUISTIC_OBJECT = new RDFResource(string.Concat(CRM.BASE_URI, "E33_Linguistic_Object"));
/// <summary>
/// crm:E34_Inscription
/// </summary>
public static readonly RDFResource E34_INSCRIPTION = new RDFResource(string.Concat(CRM.BASE_URI, "E34_Inscription"));
/// <summary>
/// crm:E35_Title
/// </summary>
public static readonly RDFResource E35_TITLE = new RDFResource(string.Concat(CRM.BASE_URI, "E35_Title"));
/// <summary>
/// crm:E36_Visual_Item
/// </summary>
public static readonly RDFResource E36_VISUAL_ITEM = new RDFResource(string.Concat(CRM.BASE_URI, "E36_Visual_Item"));
/// <summary>
/// crm:E37_Mark
/// </summary>
public static readonly RDFResource E37_MARK = new RDFResource(string.Concat(CRM.BASE_URI, "E37_Mark"));
/// <summary>
/// crm:E38_Image
/// </summary>
public static readonly RDFResource E38_IMAGE = new RDFResource(string.Concat(CRM.BASE_URI, "E38_Image"));
/// <summary>
/// crm:E39_Actor
/// </summary>
public static readonly RDFResource E39_ACTOR = new RDFResource(string.Concat(CRM.BASE_URI, "E39_Actor"));
/// <summary>
/// crm:E40_Legal_Body
/// </summary>
public static readonly RDFResource E40_LEGAL_BODY = new RDFResource(string.Concat(CRM.BASE_URI, "E40_Legal_Body"));
/// <summary>
/// crm:E41_Appellation
/// </summary>
public static readonly RDFResource E41_APPELLATION = new RDFResource(string.Concat(CRM.BASE_URI, "E41_Appellation"));
/// <summary>
/// crm:E42_Identifier
/// </summary>
public static readonly RDFResource E42_IDENTIFIER = new RDFResource(string.Concat(CRM.BASE_URI, "E42_Identifier"));
/// <summary>
/// crm:E44_Place_Appellation
/// </summary>
public static readonly RDFResource E44_PLACE_APPELLATION = new RDFResource(string.Concat(CRM.BASE_URI, "E44_Place_Appellation"));
/// <summary>
/// crm:E45_Address
/// </summary>
public static readonly RDFResource E45_ADDRESS = new RDFResource(string.Concat(CRM.BASE_URI, "E45_Address"));
/// <summary>
/// crm:E46_Section_Definition
/// </summary>
public static readonly RDFResource E46_SECTION_DEFINITION = new RDFResource(string.Concat(CRM.BASE_URI, "E46_Section_Definition"));
/// <summary>
/// crm:E47_Spatial_Coordinates
/// </summary>
public static readonly RDFResource E47_SPATIAL_COORDINATES = new RDFResource(string.Concat(CRM.BASE_URI, "E47_Spatial_Coordinates"));
/// <summary>
/// crm:E48_Place_Name
/// </summary>
public static readonly RDFResource E48_PLACE_NAME = new RDFResource(string.Concat(CRM.BASE_URI, "E48_Place_Name"));
/// <summary>
/// crm:E49_Time_Appellation
/// </summary>
public static readonly RDFResource E49_TIME_APPELLATION = new RDFResource(string.Concat(CRM.BASE_URI, "E49_Time_Appellation"));
/// <summary>
/// crm:E50_Date
/// </summary>
public static readonly RDFResource E50_DATE = new RDFResource(string.Concat(CRM.BASE_URI, "E50_Date"));
/// <summary>
/// crm:E51_Contact_Point
/// </summary>
public static readonly RDFResource E51_CONTACT_POINT = new RDFResource(string.Concat(CRM.BASE_URI, "E51_Contact_Point"));
/// <summary>
/// crm:E52_Time-Span
/// </summary>
public static readonly RDFResource E52_TIME_SPAN = new RDFResource(string.Concat(CRM.BASE_URI, "E52_Time-Span"));
/// <summary>
/// crm:E53_Place
/// </summary>
public static readonly RDFResource E53_PLACE = new RDFResource(string.Concat(CRM.BASE_URI, "E53_Place"));
/// <summary>
/// crm:E54_Dimension
/// </summary>
public static readonly RDFResource E54_DIMENSION = new RDFResource(string.Concat(CRM.BASE_URI, "E54_Dimension"));
/// <summary>
/// crm:E55_Type
/// </summary>
public static readonly RDFResource E55_TYPE = new RDFResource(string.Concat(CRM.BASE_URI, "E55_Type"));
/// <summary>
/// crm:E56_Language
/// </summary>
public static readonly RDFResource E56_LANGUAGE = new RDFResource(string.Concat(CRM.BASE_URI, "E56_Language"));
/// <summary>
/// crm:E57_Material
/// </summary>
public static readonly RDFResource E57_MATERIAL = new RDFResource(string.Concat(CRM.BASE_URI, "E57_Material"));
/// <summary>
/// crm:E58_Measurement_Unit
/// </summary>
public static readonly RDFResource E58_MEASUREMENT_UNIT = new RDFResource(string.Concat(CRM.BASE_URI, "E58_Measurement_Unit"));
/// <summary>
/// crm:E63_Beginning_of_Existence
/// </summary>
public static readonly RDFResource E63_BEGINNING_OF_EXISTENCE = new RDFResource(string.Concat(CRM.BASE_URI, "E63_Beginning_of_Existence"));
/// <summary>
/// crm:E64_End_of_Existence
/// </summary>
public static readonly RDFResource E64_END_OF_EXISTENCE = new RDFResource(string.Concat(CRM.BASE_URI, "E64_End_of_Existence"));
/// <summary>
/// crm:E65_Creation
/// </summary>
public static readonly RDFResource E65_CREATION = new RDFResource(string.Concat(CRM.BASE_URI, "E65_Creation"));
/// <summary>
/// crm:E66_Formation
/// </summary>
public static readonly RDFResource E66_FORMATION = new RDFResource(string.Concat(CRM.BASE_URI, "E66_Formation"));
/// <summary>
/// crm:E67_Birth
/// </summary>
public static readonly RDFResource E67_BIRTH = new RDFResource(string.Concat(CRM.BASE_URI, "E67_Birth"));
/// <summary>
/// crm:E68_Dissolution
/// </summary>
public static readonly RDFResource E68_DISSOLUTION = new RDFResource(string.Concat(CRM.BASE_URI, "E68_Dissolution"));
/// <summary>
/// crm:E69_Death
/// </summary>
public static readonly RDFResource E69_DEATH = new RDFResource(string.Concat(CRM.BASE_URI, "E69_Death"));
/// <summary>
/// crm:E70_Thing
/// </summary>
public static readonly RDFResource E70_THING = new RDFResource(string.Concat(CRM.BASE_URI, "E70_Thing"));
/// <summary>
/// crm:E71_Man-Made_Thing
/// </summary>
public static readonly RDFResource E71_MAN_MADE_THING = new RDFResource(string.Concat(CRM.BASE_URI, "E71_Man-Made_Thing"));
/// <summary>
/// crm:E72_Legal_Object
/// </summary>
public static readonly RDFResource E72_LEGAL_OBJECT = new RDFResource(string.Concat(CRM.BASE_URI, "E72_Legal_Object"));
/// <summary>
/// crm:E73_Information_Object
/// </summary>
public static readonly RDFResource E73_INFORMATION_OBJECT = new RDFResource(string.Concat(CRM.BASE_URI, "E73_Information_Object"));
/// <summary>
/// crm:E74_Group
/// </summary>
public static readonly RDFResource E74_GROUP = new RDFResource(string.Concat(CRM.BASE_URI, "E74_Group"));
/// <summary>
/// crm:E75_Conceptual_Object_Appellation
/// </summary>
public static readonly RDFResource E75_CONCEPTUAL_OBJECT_APPELLATION = new RDFResource(string.Concat(CRM.BASE_URI, "E75_Conceptual_Object_Appellation"));
/// <summary>
/// crm:E77_Persistent_Item
/// </summary>
public static readonly RDFResource E77_PERSISTENT_ITEM = new RDFResource(string.Concat(CRM.BASE_URI, "E77_Persistent_Item"));
/// <summary>
/// crm:E78_Collection
/// </summary>
public static readonly RDFResource E78_COLLECTION = new RDFResource(string.Concat(CRM.BASE_URI, "E78_Collection"));
/// <summary>
/// crm:E79_Part_Addition
/// </summary>
public static readonly RDFResource E79_PART_ADDITION = new RDFResource(string.Concat(CRM.BASE_URI, "E79_Part_Addition"));
/// <summary>
/// crm:E80_Part_Removal
/// </summary>
public static readonly RDFResource E80_PART_REMOVAL = new RDFResource(string.Concat(CRM.BASE_URI, "E80_Part_Removal"));
/// <summary>
/// crm:E81_Transformation
/// </summary>
public static readonly RDFResource E81_TRANSFORMATION = new RDFResource(string.Concat(CRM.BASE_URI, "E81_Transformation"));
/// <summary>
/// crm:E82_Actor_Appellation
/// </summary>
public static readonly RDFResource E82_ACTOR_APPELLATION = new RDFResource(string.Concat(CRM.BASE_URI, "E82_Actor_Appellation"));
/// <summary>
/// crm:E83_Type_Creation
/// </summary>
public static readonly RDFResource E83_TYPE_CREATION = new RDFResource(string.Concat(CRM.BASE_URI, "E83_Type_Creation"));
/// <summary>
/// crm:E84_Information_Carrier
/// </summary>
public static readonly RDFResource E84_INFORMATION_CARRIER = new RDFResource(string.Concat(CRM.BASE_URI, "E84_Information_Carrier"));
/// <summary>
/// crm:E85_Joining
/// </summary>
public static readonly RDFResource E85_JOINING = new RDFResource(string.Concat(CRM.BASE_URI, "E85_Joining"));
/// <summary>
/// crm:E86_Leaving
/// </summary>
public static readonly RDFResource E86_LEAVING = new RDFResource(string.Concat(CRM.BASE_URI, "E86_Leaving"));
/// <summary>
/// crm:E87_Curation_Activity
/// </summary>
public static readonly RDFResource E87_CURATION_ACTIVITY = new RDFResource(string.Concat(CRM.BASE_URI, "E87_Curation_Activity"));
/// <summary>
/// crm:E89_Propositional_Object
/// </summary>
public static readonly RDFResource E89_PROPOSITIONAL_OBJECT = new RDFResource(string.Concat(CRM.BASE_URI, "E89_Propositional_Object"));
/// <summary>
/// crm:E90_Symbolic_Object
/// </summary>
public static readonly RDFResource E90_SYMBOLIC_OBJECT = new RDFResource(string.Concat(CRM.BASE_URI, "E90_Symbolic_Object"));
/// <summary>
/// crm:P1_is_identified_by
/// </summary>
public static readonly RDFResource P1_IS_IDENTIFIED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P1_is_identified_by"));
/// <summary>
/// crm:P1i_identifies
/// </summary>
public static readonly RDFResource P1I_IDENTIFIES = new RDFResource(string.Concat(CRM.BASE_URI, "P1i_identifies"));
/// <summary>
/// crm:P2_has_type
/// </summary>
public static readonly RDFResource P2_HAS_TYPE = new RDFResource(string.Concat(CRM.BASE_URI, "P2_has_type"));
/// <summary>
/// crm:P2i_is_type_of
/// </summary>
public static readonly RDFResource P2I_IS_TYPE_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P2i_is_type_of"));
/// <summary>
/// crm:P3_has_note
/// </summary>
public static readonly RDFResource P3_HAS_NOTE = new RDFResource(string.Concat(CRM.BASE_URI, "P3_has_note"));
/// <summary>
/// crm:P4_has_time-span
/// </summary>
public static readonly RDFResource P4_HAS_TIME_SPAN = new RDFResource(string.Concat(CRM.BASE_URI, "P4_has_time-span"));
/// <summary>
/// crm:P4i_is_time-span_of
/// </summary>
public static readonly RDFResource P4I_IS_TIME_SPAN_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P4i_is_time-span_of"));
/// <summary>
/// crm:P5_consists_of
/// </summary>
public static readonly RDFResource P5_CONSISTS_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P5_consists_of"));
/// <summary>
/// crm:P5i_forms_part_of
/// </summary>
public static readonly RDFResource P5I_FORMS_PART_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P5i_forms_part_of"));
/// <summary>
/// crm:P7_took_place_at
/// </summary>
public static readonly RDFResource P7_TOOK_PLACE_AT = new RDFResource(string.Concat(CRM.BASE_URI, "P7_took_place_at"));
/// <summary>
/// crm:P7i_witnessed
/// </summary>
public static readonly RDFResource P7I_WITNESSED = new RDFResource(string.Concat(CRM.BASE_URI, "P7i_witnessed"));
/// <summary>
/// crm:P8_took_place_on_or_within
/// </summary>
public static readonly RDFResource P8_TOOK_PLACE_ON_OR_WITHIN = new RDFResource(string.Concat(CRM.BASE_URI, "P8_took_place_on_or_within"));
/// <summary>
/// crm:P8i_witnessed
/// </summary>
public static readonly RDFResource P8I_WITNESSED = new RDFResource(string.Concat(CRM.BASE_URI, "P8i_witnessed"));
/// <summary>
/// crm:P9_consists_of
/// </summary>
public static readonly RDFResource P9_CONSISTS_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P9_consists_of"));
/// <summary>
/// crm:P9i_forms_part_of
/// </summary>
public static readonly RDFResource P9I_FORMS_PART_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P9i_forms_part_of"));
/// <summary>
/// crm:P10_falls_within
/// </summary>
public static readonly RDFResource P10_FALLS_WITHIN = new RDFResource(string.Concat(CRM.BASE_URI, "P10_falls_within"));
/// <summary>
/// crm:P10i_contains
/// </summary>
public static readonly RDFResource P10I_CONTAINS = new RDFResource(string.Concat(CRM.BASE_URI, "P10i_contains"));
/// <summary>
/// crm:P11_had_participant
/// </summary>
public static readonly RDFResource P11_HAD_PARTICIPANT = new RDFResource(string.Concat(CRM.BASE_URI, "P11_had_participant"));
/// <summary>
/// crm:P11i_participated_in
/// </summary>
public static readonly RDFResource P11I_PARTICIPATED_IN = new RDFResource(string.Concat(CRM.BASE_URI, "P11i_participated_in"));
/// <summary>
/// crm:P12_occurred_in_the_presence_of
/// </summary>
public static readonly RDFResource P12_OCCURRED_IN_THE_PRESENCE_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P12_occurred_in_the_presence_of"));
/// <summary>
/// crm:P12i_was_present_at
/// </summary>
public static readonly RDFResource P12I_WAS_PRESENT_AT = new RDFResource(string.Concat(CRM.BASE_URI, "P12i_was_present_at"));
/// <summary>
/// crm:P13_destroyed
/// </summary>
public static readonly RDFResource P13_DESTROYED = new RDFResource(string.Concat(CRM.BASE_URI, "P13_destroyed"));
/// <summary>
/// crm:P13i_was_destroyed_by
/// </summary>
public static readonly RDFResource P13I_WAS_DESTROYED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P13i_was_destroyed_by"));
/// <summary>
/// crm:P14_carried_out_by
/// </summary>
public static readonly RDFResource P14_CARRIED_OUT_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P14_carried_out_by"));
/// <summary>
/// crm:P14i_performed
/// </summary>
public static readonly RDFResource P14I_PERFORMED = new RDFResource(string.Concat(CRM.BASE_URI, "P14i_performed"));
/// <summary>
/// crm:P15_was_influenced_by
/// </summary>
public static readonly RDFResource P15_WAS_INFLUENCED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P15_was_influenced_by"));
/// <summary>
/// crm:P15i_influenced
/// </summary>
public static readonly RDFResource P15I_INFLUENCED = new RDFResource(string.Concat(CRM.BASE_URI, "P15i_influenced"));
/// <summary>
/// crm:P16_used_specific_object
/// </summary>
public static readonly RDFResource P16_USED_SPECIFIC_OBJECT = new RDFResource(string.Concat(CRM.BASE_URI, "P16_used_specific_object"));
/// <summary>
/// crm:P16i_was_used_for
/// </summary>
public static readonly RDFResource P16I_WAS_USED_FOR = new RDFResource(string.Concat(CRM.BASE_URI, "P16i_was_used_for"));
/// <summary>
/// crm:P17_was_motivated_by
/// </summary>
public static readonly RDFResource P17_WAS_MOTIVATED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P17_was_motivated_by"));
/// <summary>
/// crm:P17i_motivated
/// </summary>
public static readonly RDFResource P17I_MOTIVATED = new RDFResource(string.Concat(CRM.BASE_URI, "P17i_motivated"));
/// <summary>
/// crm:P19_was_intended_use_of
/// </summary>
public static readonly RDFResource P19_WAS_INTENDED_USE_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P19_was_intended_use_of"));
/// <summary>
/// crm:P19i_was_made_for
/// </summary>
public static readonly RDFResource P19I_WAS_MADE_FOR = new RDFResource(string.Concat(CRM.BASE_URI, "P19i_was_made_for"));
/// <summary>
/// crm:P20_had_specific_purpose
/// </summary>
public static readonly RDFResource P20_HAD_SPECIFIC_PURPOSE = new RDFResource(string.Concat(CRM.BASE_URI, "P20_had_specific_purpose"));
/// <summary>
/// crm:P20i_was_purpose_of
/// </summary>
public static readonly RDFResource P20I_WAS_PURPOSE_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P20i_was_purpose_of"));
/// <summary>
/// crm:P21_had_general_purpose
/// </summary>
public static readonly RDFResource P21_HAD_GENERAL_PURPOSE = new RDFResource(string.Concat(CRM.BASE_URI, "P21_had_general_purpose"));
/// <summary>
/// crm:P21i_was_purpose_of
/// </summary>
public static readonly RDFResource P21I_WAS_PURPOSE_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P21i_was_purpose_of"));
/// <summary>
/// crm:P22_transferred_title_to
/// </summary>
public static readonly RDFResource P22_TRANSFERRED_TITLE_TO = new RDFResource(string.Concat(CRM.BASE_URI, "P22_transferred_title_to"));
/// <summary>
/// crm:P22i_acquired_title_through
/// </summary>
public static readonly RDFResource P22I_ACQUIRED_TITLE_THROUGH = new RDFResource(string.Concat(CRM.BASE_URI, "P22i_acquired_title_through"));
/// <summary>
/// crm:P23_transferred_title_from
/// </summary>
public static readonly RDFResource P23_TRANSFERRED_TITLE_FROM = new RDFResource(string.Concat(CRM.BASE_URI, "P23_transferred_title_from"));
/// <summary>
/// crm:P23i_surrendered_title_through
/// </summary>
public static readonly RDFResource P23I_SURRENDERED_TITLE_THROUGH = new RDFResource(string.Concat(CRM.BASE_URI, "P23i_surrendered_title_through"));
/// <summary>
/// crm:P24_transferred_title_of
/// </summary>
public static readonly RDFResource P24_TRANSFERRED_TITLE_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P24_transferred_title_of"));
/// <summary>
/// crm:P24i_changed_ownership_through
/// </summary>
public static readonly RDFResource P24I_CHANGED_OWNERSHIP_THROUGH = new RDFResource(string.Concat(CRM.BASE_URI, "P24i_changed_ownership_through"));
/// <summary>
/// crm:P25_moved
/// </summary>
public static readonly RDFResource P25_MOVED = new RDFResource(string.Concat(CRM.BASE_URI, "P25_moved"));
/// <summary>
/// crm:P25i_moved_by
/// </summary>
public static readonly RDFResource P25I_MOVED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P25i_moved_by"));
/// <summary>
/// crm:P26_moved_to
/// </summary>
public static readonly RDFResource P26_MOVED_TO = new RDFResource(string.Concat(CRM.BASE_URI, "P26_moved_to"));
/// <summary>
/// crm:P26i_was_destination_of
/// </summary>
public static readonly RDFResource P26I_WAS_DESTINATION_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P26i_was_destination_of"));
/// <summary>
/// crm:P27_moved_from
/// </summary>
public static readonly RDFResource P27_MOVED_FROM = new RDFResource(string.Concat(CRM.BASE_URI, "P27_moved_from"));
/// <summary>
/// crm:P27i_was_origin_of
/// </summary>
public static readonly RDFResource P27I_WAS_ORIGIN_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P27i_was_origin_of"));
/// <summary>
/// crm:P28_custody_surrendered_by
/// </summary>
public static readonly RDFResource P28_CUSTODY_SURRENDERED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P28_custody_surrendered_by"));
/// <summary>
/// crm:P28i_surrendered_custody_through
/// </summary>
public static readonly RDFResource P28I_SURRENDERED_CUSTODY_THROUGH = new RDFResource(string.Concat(CRM.BASE_URI, "P28i_surrendered_custody_through"));
/// <summary>
/// crm:P29_custody_received_by
/// </summary>
public static readonly RDFResource P29_CUSTODY_RECEIVED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P29_custody_received_by"));
/// <summary>
/// crm:P29i_received_custody_through
/// </summary>
public static readonly RDFResource P29I_RECEIVED_CUSTODY_THROUGH = new RDFResource(string.Concat(CRM.BASE_URI, "P29i_received_custody_through"));
/// <summary>
/// crm:P30_transferred_custody_of
/// </summary>
public static readonly RDFResource P30_TRANSFERRED_CUSTODY_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P30_transferred_custody_of"));
/// <summary>
/// crm:P30i_custody_transferred_through
/// </summary>
public static readonly RDFResource P30I_CUSTODY_TRANSFERRED_THROUGH = new RDFResource(string.Concat(CRM.BASE_URI, "P30i_custody_transferred_through"));
/// <summary>
/// crm:P31_has_modified
/// </summary>
public static readonly RDFResource P31_HAS_MODIFIED = new RDFResource(string.Concat(CRM.BASE_URI, "P31_has_modified"));
/// <summary>
/// crm:P31i_was_modified_by
/// </summary>
public static readonly RDFResource P31I_WAS_MODIFIED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P31i_was_modified_by"));
/// <summary>
/// crm:P32_used_general_technique
/// </summary>
public static readonly RDFResource P32_USED_GENERAL_TECHNIQUE = new RDFResource(string.Concat(CRM.BASE_URI, "P32_used_general_technique"));
/// <summary>
/// crm:P32i_was_technique_of
/// </summary>
public static readonly RDFResource P32I_WAS_TECHNIQUE_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P32i_was_technique_of"));
/// <summary>
/// crm:P33_used_specific_technique
/// </summary>
public static readonly RDFResource P33_USED_SPECIFIC_TECHNIQUE = new RDFResource(string.Concat(CRM.BASE_URI, "P33_used_specific_technique"));
/// <summary>
/// crm:P33i_was_used_by
/// </summary>
public static readonly RDFResource P33I_WAS_USED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P33i_was_used_by"));
/// <summary>
/// crm:P34_concerned
/// </summary>
public static readonly RDFResource P34_CONCERNED = new RDFResource(string.Concat(CRM.BASE_URI, "P34_concerned"));
/// <summary>
/// crm:P34i_was_assessed_by
/// </summary>
public static readonly RDFResource P34I_WAS_ASSESSED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P34i_was_assessed_by"));
/// <summary>
/// crm:P35_has_identified
/// </summary>
public static readonly RDFResource P35_HAS_IDENTIFIED = new RDFResource(string.Concat(CRM.BASE_URI, "P35_has_identified"));
/// <summary>
/// crm:P35i_was_identified_by
/// </summary>
public static readonly RDFResource P35I_WAS_IDENTIFIED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P35i_was_identified_by"));
/// <summary>
/// crm:P37_assigned
/// </summary>
public static readonly RDFResource P37_ASSIGNED = new RDFResource(string.Concat(CRM.BASE_URI, "P37_assigned"));
/// <summary>
/// crm:P37i_was_assigned_by
/// </summary>
public static readonly RDFResource P37I_WAS_ASSIGNED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P37i_was_assigned_by"));
/// <summary>
/// crm:P38_deassigned
/// </summary>
public static readonly RDFResource P38_DEASSIGNED = new RDFResource(string.Concat(CRM.BASE_URI, "P38_deassigned"));
/// <summary>
/// crm:P38i_was_deassigned_by
/// </summary>
public static readonly RDFResource P38I_WAS_DEASSIGNED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P38i_was_deassigned_by"));
/// <summary>
/// crm:P39_measured
/// </summary>
public static readonly RDFResource P39_MEASURED = new RDFResource(string.Concat(CRM.BASE_URI, "P39_measured"));
/// <summary>
/// crm:P39i_was_measured_by
/// </summary>
public static readonly RDFResource P39I_WAS_MEASURED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P39i_was_measured_by"));
/// <summary>
/// crm:P40_observed_dimension
/// </summary>
public static readonly RDFResource P40_OBSERVED_DIMENSION = new RDFResource(string.Concat(CRM.BASE_URI, "P40_observed_dimension"));
/// <summary>
/// crm:P40i_was_observed_in
/// </summary>
public static readonly RDFResource P40I_WAS_OBSERVED_IN = new RDFResource(string.Concat(CRM.BASE_URI, "P40i_was_observed_in"));
/// <summary>
/// crm:P41_classified
/// </summary>
public static readonly RDFResource P41_CLASSIFIED = new RDFResource(string.Concat(CRM.BASE_URI, "P41_classified"));
/// <summary>
/// crm:P41i_was_classified_by
/// </summary>
public static readonly RDFResource P41I_WAS_CLASSIFIED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P41i_was_classified_by"));
/// <summary>
/// crm:P42_assigned
/// </summary>
public static readonly RDFResource P42_ASSIGNED = new RDFResource(string.Concat(CRM.BASE_URI, "P42_assigned"));
/// <summary>
/// crm:P42i_was_assigned_by
/// </summary>
public static readonly RDFResource P42I_WAS_ASSIGNED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P42i_was_assigned_by"));
/// <summary>
/// crm:P43_has_dimension
/// </summary>
public static readonly RDFResource P43_HAS_DIMENSION = new RDFResource(string.Concat(CRM.BASE_URI, "P43_has_dimension"));
/// <summary>
/// crm:P43i_is_dimension_of
/// </summary>
public static readonly RDFResource P43I_IS_DIMENSION_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P43i_is_dimension_of"));
/// <summary>
/// crm:P44_has_condition
/// </summary>
public static readonly RDFResource P44_HAS_CONDITION = new RDFResource(string.Concat(CRM.BASE_URI, "P44_has_condition"));
/// <summary>
/// crm:P44i_is_condition_of
/// </summary>
public static readonly RDFResource P44I_IS_CONDITION_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P44i_is_condition_of"));
/// <summary>
/// crm:P45_consists_of
/// </summary>
public static readonly RDFResource P45_CONSISTS_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P45_consists_of"));
/// <summary>
/// crm:P45i_is_incorporated_in
/// </summary>
public static readonly RDFResource P45I_IS_INCORPORATED_IN = new RDFResource(string.Concat(CRM.BASE_URI, "P45i_is_incorporated_in"));
/// <summary>
/// crm:P46_is_composed_of
/// </summary>
public static readonly RDFResource P46_IS_COMPOSED_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P46_is_composed_of"));
/// <summary>
/// crm:P46i_forms_part_of
/// </summary>
public static readonly RDFResource P46I_FORMS_PART_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P46i_forms_part_of"));
/// <summary>
/// crm:P48_has_preferred_identifier
/// </summary>
public static readonly RDFResource P48_HAS_PREFERRED_IDENTIFIER = new RDFResource(string.Concat(CRM.BASE_URI, "P48_has_preferred_identifier"));
/// <summary>
/// crm:P48i_is_preferred_identifier_of
/// </summary>
public static readonly RDFResource P48I_IS_PREFERRED_IDENTIFIER_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P48i_is_preferred_identifier_of"));
/// <summary>
/// crm:P49_has_former_or_current_keeper
/// </summary>
public static readonly RDFResource P49_HAS_FORMER_OR_CURRENT_KEEPER = new RDFResource(string.Concat(CRM.BASE_URI, "P49_has_former_or_current_keeper"));
/// <summary>
/// crm:P49i_is_former_or_current_keeper_of
/// </summary>
public static readonly RDFResource P49I_IS_FORMER_OR_CURRENT_KEEPER_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P49i_is_former_or_current_keeper_of"));
/// <summary>
/// crm:P50_has_current_keeper
/// </summary>
public static readonly RDFResource P50_HAS_CURRENT_KEEPER = new RDFResource(string.Concat(CRM.BASE_URI, "P50_has_current_keeper"));
/// <summary>
/// crm:P50i_is_current_keeper_of
/// </summary>
public static readonly RDFResource P50I_IS_CURRENT_KEEPER_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P50i_is_current_keeper_of"));
/// <summary>
/// crm:P51_has_former_or_current_owner
/// </summary>
public static readonly RDFResource P51_HAS_FORMER_OR_CURRENT_OWNER = new RDFResource(string.Concat(CRM.BASE_URI, "P51_has_former_or_current_owner"));
/// <summary>
/// crm:P51i_is_former_or_current_owner_of
/// </summary>
public static readonly RDFResource P51I_IS_FORMER_OR_CURRENT_OWNER_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P51i_is_former_or_current_owner_of"));
/// <summary>
/// crm:P52_has_current_owner
/// </summary>
public static readonly RDFResource P52_HAS_CURRENT_OWNER = new RDFResource(string.Concat(CRM.BASE_URI, "P52_has_current_owner"));
/// <summary>
/// crm:P52i_is_current_owner_of
/// </summary>
public static readonly RDFResource P52I_IS_CURRENT_OWNER_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P52i_is_current_owner_of"));
/// <summary>
/// crm:P53_has_former_or_current_location
/// </summary>
public static readonly RDFResource P53_HAS_FORMER_OR_CURRENT_LOCATION = new RDFResource(string.Concat(CRM.BASE_URI, "P53_has_former_or_current_location"));
/// <summary>
/// crm:P53i_is_former_or_current_location_of
/// </summary>
public static readonly RDFResource P53I_IS_FORMER_OR_CURRENT_LOCATION_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P53i_is_former_or_current_location_of"));
/// <summary>
/// crm:P54_has_current_permanent_location
/// </summary>
public static readonly RDFResource P54_HAS_CURRENT_PERMANENT_LOCATION = new RDFResource(string.Concat(CRM.BASE_URI, "P54_has_current_permanent_location"));
/// <summary>
/// crm:P54i_is_current_permanent_location_of
/// </summary>
public static readonly RDFResource P54I_IS_CURRENT_PERMANENT_LOCATION_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P54i_is_current_permanent_location_of"));
/// <summary>
/// crm:P55_has_current_location
/// </summary>
public static readonly RDFResource P55_HAS_CURRENT_LOCATION = new RDFResource(string.Concat(CRM.BASE_URI, "P55_has_current_location"));
/// <summary>
/// crm:P55i_currently_holds
/// </summary>
public static readonly RDFResource P55I_CURRENTLY_HOLDS = new RDFResource(string.Concat(CRM.BASE_URI, "P55i_currently_holds"));
/// <summary>
/// crm:P56_bears_feature
/// </summary>
public static readonly RDFResource P56_BEARS_FEATURE = new RDFResource(string.Concat(CRM.BASE_URI, "P56_bears_feature"));
/// <summary>
/// crm:P56i_is_found_on
/// </summary>
public static readonly RDFResource P56I_IS_FOUND_ON = new RDFResource(string.Concat(CRM.BASE_URI, "P56i_is_found_on"));
/// <summary>
/// crm:P57_has_number_of_parts
/// </summary>
public static readonly RDFResource P57_HAS_NUMBER_OF_PARTS = new RDFResource(string.Concat(CRM.BASE_URI, "P57_has_number_of_parts"));
/// <summary>
/// crm:P58_has_section_definition
/// </summary>
public static readonly RDFResource P58_HAS_SECTION_DEFINITION = new RDFResource(string.Concat(CRM.BASE_URI, "P58_has_section_definition"));
/// <summary>
/// crm:P58i_defines_section
/// </summary>
public static readonly RDFResource P58I_DEFINES_SECTION = new RDFResource(string.Concat(CRM.BASE_URI, "P58i_defines_section"));
/// <summary>
/// crm:P59_has_section
/// </summary>
public static readonly RDFResource P59_HAS_SECTION = new RDFResource(string.Concat(CRM.BASE_URI, "P59_has_section"));
/// <summary>
/// crm:P59i_is_located_on_or_within
/// </summary>
public static readonly RDFResource P59I_IS_LOCATED_ON_OR_WITHIN = new RDFResource(string.Concat(CRM.BASE_URI, "P59i_is_located_on_or_within"));
/// <summary>
/// crm:P62_depicts
/// </summary>
public static readonly RDFResource P62_DEPICTS = new RDFResource(string.Concat(CRM.BASE_URI, "P62_depicts"));
/// <summary>
/// crm:P62i_is_depicted_by
/// </summary>
public static readonly RDFResource P62I_IS_DEPICTED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P62i_is_depicted_by"));
/// <summary>
/// crm:P65_shows_visual_item
/// </summary>
public static readonly RDFResource P65_SHOWS_VISUAL_ITEM = new RDFResource(string.Concat(CRM.BASE_URI, "P65_shows_visual_item"));
/// <summary>
/// crm:P65i_is_shown_by
/// </summary>
public static readonly RDFResource P65I_IS_SHOWN_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P65i_is_shown_by"));
/// <summary>
/// crm:P67_refers_to
/// </summary>
public static readonly RDFResource P67_REFERS_TO = new RDFResource(string.Concat(CRM.BASE_URI, "P67_refers_to"));
/// <summary>
/// crm:P67i_is_referred_to_by
/// </summary>
public static readonly RDFResource P67I_IS_REFERRED_TO_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P67i_is_referred_to_by"));
/// <summary>
/// crm:P68_foresees_use_of
/// </summary>
public static readonly RDFResource P68_FORESEES_USE_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P68_foresees_use_of"));
/// <summary>
/// crm:P68i_use_foreseen_by
/// </summary>
public static readonly RDFResource P68I_USE_FORESEEN_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P68i_use_foreseen_by"));
/// <summary>
/// crm:P69_is_associated_with
/// </summary>
public static readonly RDFResource P69_IS_ASSOCIATED_WITH = new RDFResource(string.Concat(CRM.BASE_URI, "P69_is_associated_with"));
/// <summary>
/// crm:P70_documents
/// </summary>
public static readonly RDFResource P70_DOCUMENTS = new RDFResource(string.Concat(CRM.BASE_URI, "P70_documents"));
/// <summary>
/// crm:P70i_is_documented_in
/// </summary>
public static readonly RDFResource P70I_IS_DOCUMENTED_IN = new RDFResource(string.Concat(CRM.BASE_URI, "P70i_is_documented_in"));
/// <summary>
/// crm:P71_lists
/// </summary>
public static readonly RDFResource P71_LISTS = new RDFResource(string.Concat(CRM.BASE_URI, "P71_lists"));
/// <summary>
/// crm:P71i_is_listed_in
/// </summary>
public static readonly RDFResource P71I_IS_LISTED_IN = new RDFResource(string.Concat(CRM.BASE_URI, "P71i_is_listed_in"));
/// <summary>
/// crm:P72_has_language
/// </summary>
public static readonly RDFResource P72_HAS_LANGUAGE = new RDFResource(string.Concat(CRM.BASE_URI, "P72_has_language"));
/// <summary>
/// crm:P72i_is_language_of
/// </summary>
public static readonly RDFResource P72I_IS_LANGUAGE_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P72i_is_language_of"));
/// <summary>
/// crm:P73_has_translation
/// </summary>
public static readonly RDFResource P73_HAS_TRANSLATION = new RDFResource(string.Concat(CRM.BASE_URI, "P73_has_translation"));
/// <summary>
/// crm:P73i_is_translation_of
/// </summary>
public static readonly RDFResource P73I_IS_TRANSLATION_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P73i_is_translation_of"));
/// <summary>
/// crm:P74_has_current_or_former_residence
/// </summary>
public static readonly RDFResource P74_HAS_CURRENT_OR_FORMER_RESIDENCE = new RDFResource(string.Concat(CRM.BASE_URI, "P74_has_current_or_former_residence"));
/// <summary>
/// crm:P74i_is_current_or_former_residence_of
/// </summary>
public static readonly RDFResource P74I_IS_CURRENT_OR_FORMER_RESIDENCE_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P74i_is_current_or_former_residence_of"));
/// <summary>
/// crm:P75_possesses
/// </summary>
public static readonly RDFResource P75_POSSESSES = new RDFResource(string.Concat(CRM.BASE_URI, "P75_possesses"));
/// <summary>
/// crm:P75i_is_possessed_by
/// </summary>
public static readonly RDFResource P75I_IS_POSSESSED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P75i_is_possessed_by"));
/// <summary>
/// crm:P76_has_contact_point
/// </summary>
public static readonly RDFResource P76_HAS_CONTACT_POINT = new RDFResource(string.Concat(CRM.BASE_URI, "P76_has_contact_point"));
/// <summary>
/// crm:P76i_provides_access_to
/// </summary>
public static readonly RDFResource P76I_PROVIDES_ACCESS_TO = new RDFResource(string.Concat(CRM.BASE_URI, "P76i_provides_access_to"));
/// <summary>
/// crm:P78_is_identified_by
/// </summary>
public static readonly RDFResource P78_IS_IDENTIFIED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P78_is_identified_by"));
/// <summary>
/// crm:P78i_identifies
/// </summary>
public static readonly RDFResource P78I_IDENTIFIES = new RDFResource(string.Concat(CRM.BASE_URI, "P78i_identifies"));
/// <summary>
/// crm:P79_beginning_is_qualified_by
/// </summary>
public static readonly RDFResource P79_BEGINNING_IS_QUALIFIED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P79_beginning_is_qualified_by"));
/// <summary>
/// crm:P80_end_is_qualified_by
/// </summary>
public static readonly RDFResource P80_END_IS_QUALIFIED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P80_end_is_qualified_by"));
/// <summary>
/// crm:P81_ongoing_throughout
/// </summary>
public static readonly RDFResource P81_ONGOING_THROUGHOUT = new RDFResource(string.Concat(CRM.BASE_URI, "P81_ongoing_throughout"));
/// <summary>
/// crm:P82_at_some_time_within
/// </summary>
public static readonly RDFResource P82_AT_SOME_TIME_WITHIN = new RDFResource(string.Concat(CRM.BASE_URI, "P82_at_some_time_within"));
/// <summary>
/// crm:P83_had_at_least_duration
/// </summary>
public static readonly RDFResource P83_HAD_AT_LEAST_DURATION = new RDFResource(string.Concat(CRM.BASE_URI, "P83_had_at_least_duration"));
/// <summary>
/// crm:P83i_was_minimum_duration_of
/// </summary>
public static readonly RDFResource P83I_WAS_MINIMUM_DURATION_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P83i_was_minimum_duration_of"));
/// <summary>
/// crm:P84_had_at_most_duration
/// </summary>
public static readonly RDFResource P84_HAD_AT_MOST_DURATION = new RDFResource(string.Concat(CRM.BASE_URI, "P84_had_at_most_duration"));
/// <summary>
/// crm:P84i_was_maximum_duration_of
/// </summary>
public static readonly RDFResource P84I_WAS_MAXIMUM_DURATION_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P84i_was_maximum_duration_of"));
/// <summary>
/// crm:P86_falls_within
/// </summary>
public static readonly RDFResource P86_FALLS_WITHIN = new RDFResource(string.Concat(CRM.BASE_URI, "P86_falls_within"));
/// <summary>
/// crm:P86i_contains
/// </summary>
public static readonly RDFResource P86I_CONTAINS = new RDFResource(string.Concat(CRM.BASE_URI, "P86i_contains"));
/// <summary>
/// crm:P87_is_identified_by
/// </summary>
public static readonly RDFResource P87_IS_IDENTIFIED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P87_is_identified_by"));
/// <summary>
/// crm:P87i_identifies
/// </summary>
public static readonly RDFResource P87I_IDENTIFIES = new RDFResource(string.Concat(CRM.BASE_URI, "P87i_identifies"));
/// <summary>
/// crm:P88_consists_of
/// </summary>
public static readonly RDFResource P88_CONSISTS_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P88_consists_of"));
/// <summary>
/// crm:P88i_forms_part_of
/// </summary>
public static readonly RDFResource P88I_FORMS_PART_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P88i_forms_part_of"));
/// <summary>
/// crm:P89_falls_within
/// </summary>
public static readonly RDFResource P89_FALLS_WITHIN = new RDFResource(string.Concat(CRM.BASE_URI, "P89_falls_within"));
/// <summary>
/// crm:P89i_contains
/// </summary>
public static readonly RDFResource P89I_CONTAINS = new RDFResource(string.Concat(CRM.BASE_URI, "P89i_contains"));
/// <summary>
/// crm:P90_has_value
/// </summary>
public static readonly RDFResource P90_HAS_VALUE = new RDFResource(string.Concat(CRM.BASE_URI, "P90_has_value"));
/// <summary>
/// crm:P91_has_unit
/// </summary>
public static readonly RDFResource P91_HAS_UNIT = new RDFResource(string.Concat(CRM.BASE_URI, "P91_has_unit"));
/// <summary>
/// crm:P91i_is_unit_of
/// </summary>
public static readonly RDFResource P91I_IS_UNIT_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P91i_is_unit_of"));
/// <summary>
/// crm:P92_brought_into_existence
/// </summary>
public static readonly RDFResource P92_BROUGHT_INTO_EXISTENCE = new RDFResource(string.Concat(CRM.BASE_URI, "P92_brought_into_existence"));
/// <summary>
/// crm:P92i_was_brought_into_existence_by
/// </summary>
public static readonly RDFResource P92I_WAS_BROUGHT_INTO_EXISTENCE_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P92i_was_brought_into_existence_by"));
/// <summary>
/// crm:P93_took_out_of_existence
/// </summary>
public static readonly RDFResource P93_TOOK_OUT_OF_EXISTENCE = new RDFResource(string.Concat(CRM.BASE_URI, "P93_took_out_of_existence"));
/// <summary>
/// crm:P93i_was_taken_out_of_existence_by
/// </summary>
public static readonly RDFResource P93I_WAS_TAKEN_OUT_OF_EXISTENCE_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P93i_was_taken_out_of_existence_by"));
/// <summary>
/// crm:P94_has_created
/// </summary>
public static readonly RDFResource P94_HAS_CREATED = new RDFResource(string.Concat(CRM.BASE_URI, "P94_has_created"));
/// <summary>
/// crm:P94i_was_created_by
/// </summary>
public static readonly RDFResource P94I_WAS_CREATED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P94i_was_created_by"));
/// <summary>
/// crm:P95_has_formed
/// </summary>
public static readonly RDFResource P95_HAS_FORMED = new RDFResource(string.Concat(CRM.BASE_URI, "P95_has_formed"));
/// <summary>
/// crm:P95i_was_formed_by
/// </summary>
public static readonly RDFResource P95I_WAS_FORMED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P95i_was_formed_by"));
/// <summary>
/// crm:P96_by_mother
/// </summary>
public static readonly RDFResource P96_BY_MOTHER = new RDFResource(string.Concat(CRM.BASE_URI, "P96_by_mother"));
/// <summary>
/// crm:P96i_gave_birth
/// </summary>
public static readonly RDFResource P96I_GAVE_BIRTH = new RDFResource(string.Concat(CRM.BASE_URI, "P96i_gave_birth"));
/// <summary>
/// crm:P97_from_father
/// </summary>
public static readonly RDFResource P97_FROM_FATHER = new RDFResource(string.Concat(CRM.BASE_URI, "P97_from_father"));
/// <summary>
/// crm:P97i_was_father_for
/// </summary>
public static readonly RDFResource P97I_WAS_FATHER_FOR = new RDFResource(string.Concat(CRM.BASE_URI, "P97i_was_father_for"));
/// <summary>
/// crm:P98_brought_into_life
/// </summary>
public static readonly RDFResource P98_BROUGHT_INTO_LIFE = new RDFResource(string.Concat(CRM.BASE_URI, "P98_brought_into_life"));
/// <summary>
/// crm:P98i_was_born
/// </summary>
public static readonly RDFResource P98I_WAS_BORN = new RDFResource(string.Concat(CRM.BASE_URI, "P98i_was_born"));
/// <summary>
/// crm:P99_dissolved
/// </summary>
public static readonly RDFResource P99_DISSOLVED = new RDFResource(string.Concat(CRM.BASE_URI, "P99_dissolved"));
/// <summary>
/// crm:P99i_was_dissolved_by
/// </summary>
public static readonly RDFResource P99I_WAS_DISSOLVED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P99i_was_dissolved_by"));
/// <summary>
/// crm:P100_was_death_of
/// </summary>
public static readonly RDFResource P100_WAS_DEATH_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P100_was_death_of"));
/// <summary>
/// crm:P100i_died_in
/// </summary>
public static readonly RDFResource P100I_DIED_IN = new RDFResource(string.Concat(CRM.BASE_URI, "P100i_died_in"));
/// <summary>
/// crm:P101_had_as_general_use
/// </summary>
public static readonly RDFResource P101_HAD_AS_GENERAL_USE = new RDFResource(string.Concat(CRM.BASE_URI, "P101_had_as_general_use"));
/// <summary>
/// crm:P101i_was_use_of
/// </summary>
public static readonly RDFResource P101I_WAS_USE_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P101i_was_use_of"));
/// <summary>
/// crm:P102_has_title
/// </summary>
public static readonly RDFResource P102_HAS_TITLE = new RDFResource(string.Concat(CRM.BASE_URI, "P102_has_title"));
/// <summary>
/// crm:P102i_is_title_of
/// </summary>
public static readonly RDFResource P102I_IS_TITLE_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P102i_is_title_of"));
/// <summary>
/// crm:P103_was_intended_for
/// </summary>
public static readonly RDFResource P103_WAS_INTENDED_FOR = new RDFResource(string.Concat(CRM.BASE_URI, "P103_was_intended_for"));
/// <summary>
/// crm:P103i_was_intention_of
/// </summary>
public static readonly RDFResource P103I_WAS_INTENTION_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P103i_was_intention_of"));
/// <summary>
/// crm:P104_is_subject_to
/// </summary>
public static readonly RDFResource P104_IS_SUBJECT_TO = new RDFResource(string.Concat(CRM.BASE_URI, "P104_is_subject_to"));
/// <summary>
/// crm:P104i_applies_to
/// </summary>
public static readonly RDFResource P104I_APPLIES_TO = new RDFResource(string.Concat(CRM.BASE_URI, "P104i_applies_to"));
/// <summary>
/// crm:P105_right_held_by
/// </summary>
public static readonly RDFResource P105_RIGHT_HELD_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P105_right_held_by"));
/// <summary>
/// crm:P105i_has_right_on
/// </summary>
public static readonly RDFResource P105I_HAS_RIGHT_ON = new RDFResource(string.Concat(CRM.BASE_URI, "P105i_has_right_on"));
/// <summary>
/// crm:P106_is_composed_of
/// </summary>
public static readonly RDFResource P106_IS_COMPOSED_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P106_is_composed_of"));
/// <summary>
/// crm:P106i_forms_part_of
/// </summary>
public static readonly RDFResource P106I_FORMS_PART_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P106i_forms_part_of"));
/// <summary>
/// crm:P107_has_current_or_former_member
/// </summary>
public static readonly RDFResource P107_HAS_CURRENT_OR_FORMER_MEMBER = new RDFResource(string.Concat(CRM.BASE_URI, "P107_has_current_or_former_member"));
/// <summary>
/// crm:P107i_is_current_or_former_member_of
/// </summary>
public static readonly RDFResource P107I_IS_CURRENT_OR_FORMER_MEMBER_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P107i_is_current_or_former_member_of"));
/// <summary>
/// crm:P108_has_produced
/// </summary>
public static readonly RDFResource P108_HAS_PRODUCED = new RDFResource(string.Concat(CRM.BASE_URI, "P108_has_produced"));
/// <summary>
/// crm:P108i_was_produced_by
/// </summary>
public static readonly RDFResource P108I_WAS_PRODUCED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P108i_was_produced_by"));
/// <summary>
/// crm:P109_has_current_or_former_curator
/// </summary>
public static readonly RDFResource P109_HAS_CURRENT_OR_FORMER_CURATOR = new RDFResource(string.Concat(CRM.BASE_URI, "P109_has_current_or_former_curator"));
/// <summary>
/// crm:P109i_is_current_or_former_curator_of
/// </summary>
public static readonly RDFResource P109I_IS_CURRENT_OR_FORMER_CURATOR_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P109i_is_current_or_former_curator_of"));
/// <summary>
/// crm:P110_augmented
/// </summary>
public static readonly RDFResource P110_AUGMENTED = new RDFResource(string.Concat(CRM.BASE_URI, "P110_augmented"));
/// <summary>
/// crm:P110i_was_augmented_by
/// </summary>
public static readonly RDFResource P110I_WAS_AUGMENTED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P110i_was_augmented_by"));
/// <summary>
/// crm:P111_added
/// </summary>
public static readonly RDFResource P111_ADDED = new RDFResource(string.Concat(CRM.BASE_URI, "P111_added"));
/// <summary>
/// crm:P111i_was_added_by
/// </summary>
public static readonly RDFResource P111I_WAS_ADDED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P111i_was_added_by"));
/// <summary>
/// crm:P112_diminished
/// </summary>
public static readonly RDFResource P112_DIMINISHED = new RDFResource(string.Concat(CRM.BASE_URI, "P112_diminished"));
/// <summary>
/// crm:P112i_was_diminished_by
/// </summary>
public static readonly RDFResource P112I_WAS_DIMINISHED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P112i_was_diminished_by"));
/// <summary>
/// crm:P113_removed
/// </summary>
public static readonly RDFResource P113_REMOVED = new RDFResource(string.Concat(CRM.BASE_URI, "P113_removed"));
/// <summary>
/// crm:P113i_was_removed_by
/// </summary>
public static readonly RDFResource P113I_WAS_REMOVED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P113i_was_removed_by"));
/// <summary>
/// crm:P114_is_equal_in_time_to
/// </summary>
public static readonly RDFResource P114_IS_EQUAL_IN_TIME_TO = new RDFResource(string.Concat(CRM.BASE_URI, "P114_is_equal_in_time_to"));
/// <summary>
/// crm:P115_finishes
/// </summary>
public static readonly RDFResource P115_FINISHES = new RDFResource(string.Concat(CRM.BASE_URI, "P115_finishes"));
/// <summary>
/// crm:P115i_is_finished_by
/// </summary>
public static readonly RDFResource P115I_IS_FINISHED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P115i_is_finished_by"));
/// <summary>
/// crm:P116_starts
/// </summary>
public static readonly RDFResource P116_STARTS = new RDFResource(string.Concat(CRM.BASE_URI, "P116_starts"));
/// <summary>
/// crm:P116i_is_started_by
/// </summary>
public static readonly RDFResource P116I_IS_STARTED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P116i_is_started_by"));
/// <summary>
/// crm:P117_occurs_during
/// </summary>
public static readonly RDFResource P117_OCCURS_DURING = new RDFResource(string.Concat(CRM.BASE_URI, "P117_occurs_during"));
/// <summary>
/// crm:P117i_includes
/// </summary>
public static readonly RDFResource P117I_INCLUDES = new RDFResource(string.Concat(CRM.BASE_URI, "P117i_includes"));
/// <summary>
/// crm:P118_overlaps_in_time_with
/// </summary>
public static readonly RDFResource P118_OVERLAPS_IN_TIME_WITH = new RDFResource(string.Concat(CRM.BASE_URI, "P118_overlaps_in_time_with"));
/// <summary>
/// crm:P118i_is_overlapped_in_time_by
/// </summary>
public static readonly RDFResource P118I_IS_OVERLAPPED_IN_TIME_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P118i_is_overlapped_in_time_by"));
/// <summary>
/// crm:P119_meets_in_time_with
/// </summary>
public static readonly RDFResource P119_MEETS_IN_TIME_WITH = new RDFResource(string.Concat(CRM.BASE_URI, "P119_meets_in_time_with"));
/// <summary>
/// crm:P119i_is_met_in_time_by
/// </summary>
public static readonly RDFResource P119I_IS_MET_IN_TIME_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P119i_is_met_in_time_by"));
/// <summary>
/// crm:P120_occurs_before
/// </summary>
public static readonly RDFResource P120_OCCURS_BEFORE = new RDFResource(string.Concat(CRM.BASE_URI, "P120_occurs_before"));
/// <summary>
/// crm:P120i_occurs_after
/// </summary>
public static readonly RDFResource P120I_OCCURS_AFTER = new RDFResource(string.Concat(CRM.BASE_URI, "P120i_occurs_after"));
/// <summary>
/// crm:P121_overlaps_with
/// </summary>
public static readonly RDFResource P121_OVERLAPS_WITH = new RDFResource(string.Concat(CRM.BASE_URI, "P121_overlaps_with"));
/// <summary>
/// crm:P122_borders_with
/// </summary>
public static readonly RDFResource P122_BORDERS_WITH = new RDFResource(string.Concat(CRM.BASE_URI, "P122_borders_with"));
/// <summary>
/// crm:P123_resulted_in
/// </summary>
public static readonly RDFResource P123_RESULTED_IN = new RDFResource(string.Concat(CRM.BASE_URI, "P123_resulted_in"));
/// <summary>
/// crm:P123i_resulted_from
/// </summary>
public static readonly RDFResource P123I_RESULTED_FROM = new RDFResource(string.Concat(CRM.BASE_URI, "P123i_resulted_from"));
/// <summary>
/// crm:P124_transformed
/// </summary>
public static readonly RDFResource P124_TRANSFORMED = new RDFResource(string.Concat(CRM.BASE_URI, "P124_transformed"));
/// <summary>
/// crm:P124i_was_transformed_by
/// </summary>
public static readonly RDFResource P124I_WAS_TRANSFORMED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P124i_was_transformed_by"));
/// <summary>
/// crm:P125_used_object_of_type
/// </summary>
public static readonly RDFResource P125_USED_OBJECT_OF_TYPE = new RDFResource(string.Concat(CRM.BASE_URI, "P125_used_object_of_type"));
/// <summary>
/// crm:P125i_was_type_of_object_used_in
/// </summary>
public static readonly RDFResource P125I_WAS_TYPE_OF_OBJECT_USED_IN = new RDFResource(string.Concat(CRM.BASE_URI, "P125i_was_type_of_object_used_in"));
/// <summary>
/// crm:P126_employed
/// </summary>
public static readonly RDFResource P126_EMPLOYED = new RDFResource(string.Concat(CRM.BASE_URI, "P126_employed"));
/// <summary>
/// crm:P126i_was_employed_in
/// </summary>
public static readonly RDFResource P126I_WAS_EMPLOYED_IN = new RDFResource(string.Concat(CRM.BASE_URI, "P126i_was_employed_in"));
/// <summary>
/// crm:P127_has_broader_term
/// </summary>
public static readonly RDFResource P127_HAS_BROADER_TERM = new RDFResource(string.Concat(CRM.BASE_URI, "P127_has_broader_term"));
/// <summary>
/// crm:P127i_has_narrower_term
/// </summary>
public static readonly RDFResource P127I_HAS_NARROWER_TERM = new RDFResource(string.Concat(CRM.BASE_URI, "P127i_has_narrower_term"));
/// <summary>
/// crm:P128_carries
/// </summary>
public static readonly RDFResource P128_CARRIES = new RDFResource(string.Concat(CRM.BASE_URI, "P128_carries"));
/// <summary>
/// crm:P128i_is_carried_by
/// </summary>
public static readonly RDFResource P128I_IS_CARRIED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P128i_is_carried_by"));
/// <summary>
/// crm:P129_is_about
/// </summary>
public static readonly RDFResource P129_IS_ABOUT = new RDFResource(string.Concat(CRM.BASE_URI, "P129_is_about"));
/// <summary>
/// crm:P129i_is_subject_of
/// </summary>
public static readonly RDFResource P129I_IS_SUBJECT_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P129i_is_subject_of"));
/// <summary>
/// crm:P130_shows_features_of
/// </summary>
public static readonly RDFResource P130_SHOWS_FEATURES_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P130_shows_features_of"));
/// <summary>
/// crm:P130i_features_are_also_found_on
/// </summary>
public static readonly RDFResource P130I_FEATURES_ARE_ALSO_FOUND_ON = new RDFResource(string.Concat(CRM.BASE_URI, "P130i_features_are_also_found_on"));
/// <summary>
/// crm:P131_is_identified_by
/// </summary>
public static readonly RDFResource P131_IS_IDENTIFIED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P131_is_identified_by"));
/// <summary>
/// crm:P131i_identifies
/// </summary>
public static readonly RDFResource P131I_IDENTIFIES = new RDFResource(string.Concat(CRM.BASE_URI, "P131i_identifies"));
/// <summary>
/// crm:P132_overlaps_with
/// </summary>
public static readonly RDFResource P132_OVERLAPS_WITH = new RDFResource(string.Concat(CRM.BASE_URI, "P132_overlaps_with"));
/// <summary>
/// crm:P133_is_separated_from
/// </summary>
public static readonly RDFResource P133_IS_SEPARATED_FROM = new RDFResource(string.Concat(CRM.BASE_URI, "P133_is_separated_from"));
/// <summary>
/// crm:P134_continued
/// </summary>
public static readonly RDFResource P134_CONTINUED = new RDFResource(string.Concat(CRM.BASE_URI, "P134_continued"));
/// <summary>
/// crm:P134i_was_continued_by
/// </summary>
public static readonly RDFResource P134I_WAS_CONTINUED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P134i_was_continued_by"));
/// <summary>
/// crm:P135_created_type
/// </summary>
public static readonly RDFResource P135_CREATED_TYPE = new RDFResource(string.Concat(CRM.BASE_URI, "P135_created_type"));
/// <summary>
/// crm:P135i_was_created_by
/// </summary>
public static readonly RDFResource P135I_WAS_CREATED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P135i_was_created_by"));
/// <summary>
/// crm:P136_was_based_on
/// </summary>
public static readonly RDFResource P136_WAS_BASED_ON = new RDFResource(string.Concat(CRM.BASE_URI, "P136_was_based_on"));
/// <summary>
/// crm:P136i_supported_type_creation
/// </summary>
public static readonly RDFResource P136I_SUPPORTED_TYPE_CREATION = new RDFResource(string.Concat(CRM.BASE_URI, "P136i_supported_type_creation"));
/// <summary>
/// crm:P137_exemplifies
/// </summary>
public static readonly RDFResource P137_EXEMPLIFIES = new RDFResource(string.Concat(CRM.BASE_URI, "P137_exemplifies"));
/// <summary>
/// crm:P137i_is_exemplified_by
/// </summary>
public static readonly RDFResource P137I_IS_EXEMPLIFIED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P137i_is_exemplified_by"));
/// <summary>
/// crm:P138_represents
/// </summary>
public static readonly RDFResource P138_REPRESENTS = new RDFResource(string.Concat(CRM.BASE_URI, "P138_represents"));
/// <summary>
/// crm:P138i_has_representation
/// </summary>
public static readonly RDFResource P138I_HAS_REPRESENTATION = new RDFResource(string.Concat(CRM.BASE_URI, "P138i_has_representation"));
/// <summary>
/// crm:P139_has_alternative_form
/// </summary>
public static readonly RDFResource P139_HAS_ALTERNATIVE_FORM = new RDFResource(string.Concat(CRM.BASE_URI, "P139_has_alternative_form"));
/// <summary>
/// crm:P140_assigned_attribute_to
/// </summary>
public static readonly RDFResource P140_ASSIGNED_ATTRIBUTE_TO = new RDFResource(string.Concat(CRM.BASE_URI, "P140_assigned_attribute_to"));
/// <summary>
/// crm:P140i_was_attributed_by
/// </summary>
public static readonly RDFResource P140I_WAS_ATTRIBUTED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P140i_was_attributed_by"));
/// <summary>
/// crm:P141_assigned
/// </summary>
public static readonly RDFResource P141_ASSIGNED = new RDFResource(string.Concat(CRM.BASE_URI, "P141_assigned"));
/// <summary>
/// crm:P141i_was_assigned_by
/// </summary>
public static readonly RDFResource P141I_WAS_ASSIGNED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P141i_was_assigned_by"));
/// <summary>
/// crm:P142_used_constituent
/// </summary>
public static readonly RDFResource P142_USED_CONSTITUENT = new RDFResource(string.Concat(CRM.BASE_URI, "P142_used_constituent"));
/// <summary>
/// crm:P142i_was_used_in
/// </summary>
public static readonly RDFResource P142I_WAS_USED_IN = new RDFResource(string.Concat(CRM.BASE_URI, "P142i_was_used_in"));
/// <summary>
/// crm:P143_joined
/// </summary>
public static readonly RDFResource P143_JOINED = new RDFResource(string.Concat(CRM.BASE_URI, "P143_joined"));
/// <summary>
/// crm:P143i_was_joined_by
/// </summary>
public static readonly RDFResource P143I_WAS_JOINED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P143i_was_joined_by"));
/// <summary>
/// crm:P144_joined_with
/// </summary>
public static readonly RDFResource P144_JOINED_WITH = new RDFResource(string.Concat(CRM.BASE_URI, "P144_joined_with"));
/// <summary>
/// crm:P144i_gained_member_by
/// </summary>
public static readonly RDFResource P144I_GAINED_MEMBER_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P144i_gained_member_by"));
/// <summary>
/// crm:P145_separated
/// </summary>
public static readonly RDFResource P145_SEPARATED = new RDFResource(string.Concat(CRM.BASE_URI, "P145_separated"));
/// <summary>
/// crm:P145i_left_by
/// </summary>
public static readonly RDFResource P145I_LEFT_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P145i_left_by"));
/// <summary>
/// crm:P146_separated_from
/// </summary>
public static readonly RDFResource P146_SEPARATED_FROM = new RDFResource(string.Concat(CRM.BASE_URI, "P146_separated_from"));
/// <summary>
/// crm:P146i_lost_member_by
/// </summary>
public static readonly RDFResource P146I_LOST_MEMBER_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P146i_lost_member_by"));
/// <summary>
/// crm:P147_curated
/// </summary>
public static readonly RDFResource P147_CURATED = new RDFResource(string.Concat(CRM.BASE_URI, "P147_curated"));
/// <summary>
/// crm:P147i_was_curated_by
/// </summary>
public static readonly RDFResource P147I_WAS_CURATED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P147i_was_curated_by"));
/// <summary>
/// crm:P148_has_component
/// </summary>
public static readonly RDFResource P148_HAS_COMPONENT = new RDFResource(string.Concat(CRM.BASE_URI, "P148_has_component"));
/// <summary>
/// crm:P148i_is_component_of
/// </summary>
public static readonly RDFResource P148I_IS_COMPONENT_OF = new RDFResource(string.Concat(CRM.BASE_URI, "P148i_is_component_of"));
/// <summary>
/// crm:P149_is_identified_by
/// </summary>
public static readonly RDFResource P149_IS_IDENTIFIED_BY = new RDFResource(string.Concat(CRM.BASE_URI, "P149_is_identified_by"));
/// <summary>
/// crm:P149i_identifies
/// </summary>
public static readonly RDFResource P149I_IDENTIFIES = new RDFResource(string.Concat(CRM.BASE_URI, "P149i_identifies"));
#endregion
}
#endregion
}
} | mdesalvo/RDFSharp | RDFSharp/Model/Vocabularies/CRM.cs | C# | apache-2.0 | 81,589 |
/*
Copyright 2014 Bojan Savric
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.jhlabs.map.proj;
import com.jhlabs.map.MapMath;
import java.awt.geom.*;
public class McBrydeThomasFlatPolarSinusoidalProjection extends PseudoCylindricalProjection {
private static final double m = 0.5;
private static final double n = 1 + 0.25 * Math.PI;
private static final double C_y = Math.sqrt((m + 1) / n);
private static final double C_x = C_y / (m + 1);
private static final int MAX_ITER = 8;
private static final double LOOP_TOL = 1e-7;
public Point2D.Double project(double lam, double phi, Point2D.Double xy) {
int i;
double k, V;
k = n * Math.sin(phi);
for (i = MAX_ITER; i > 0;) {
phi -= V = (m * phi + Math.sin(phi) - k) / (m + Math.cos(phi));
if (Math.abs(V) < LOOP_TOL) {
break;
}
--i;
}
if (i == 0) {
throw new ProjectionException("F_ERROR");
}
xy.x = C_x * lam * (m + Math.cos(phi));
xy.y = C_y * phi;
return xy;
}
public Point2D.Double projectInverse(double x, double y, Point2D.Double lp) {
y /= C_y;
lp.y = MapMath.asin((m * y + Math.sin(y)) / n);
lp.x = x / (C_x * (m + Math.cos(y)));
return lp;
}
public boolean hasInverse() {
return true;
}
public boolean isEqualArea() {
return true;
}
public String toString() {
return "McBryde-Thomas Flat Polar Sinusoidal";
}
}
| OSUCartography/JMapProjLib | src/com/jhlabs/map/proj/McBrydeThomasFlatPolarSinusoidalProjection.java | Java | apache-2.0 | 2,052 |
import { prettyPrint, types } from 'recast';
import { emitConstrainedTranslation } from '../../src/emitting/constraint';
import Context from '../../src/emitting/context';
import { EqualityNode, IgnoreNode, IneqNode, ValueNode } from '../../src/trees/constraint';
const b = types.builders;
const nullExpr = b.identifier('null');
const five = b.literal(5);
function makeEmptyPos() {
return {
firstColumn: 0,
firstLine: 0,
lastColumn: 0,
lastLine: 0,
};
}
function makeIgnoreConstraint(varName: string): IgnoreNode {
return {
op: '!',
operand: {
name: varName,
pos: makeEmptyPos(),
type: 'identifier',
},
pos: makeEmptyPos(),
};
}
function makeEqualityConstraint(varName: string, value: string | number): EqualityNode {
let rhs: ValueNode;
if (typeof value === 'string') {
rhs = {
pos: makeEmptyPos(),
type: 'enum',
value: value,
};
} else {
rhs = {
pos: makeEmptyPos(),
type: 'number',
value: value,
};
}
return {
lhs: {
name: varName,
pos: makeEmptyPos(),
type: 'identifier',
},
op: '=',
pos: makeEmptyPos(),
rhs: rhs,
};
}
function makeInequalityConstraint(varName: string, value: number, op: '>' | '<' | '>=' | '<=' = '>'): IneqNode {
return {
lhs: {
name: varName,
pos: makeEmptyPos(),
type: 'identifier',
},
op: op,
pos: makeEmptyPos(),
rhs: {
pos: makeEmptyPos(),
type: 'number',
value: value,
},
};
}
describe('Emitting - Constraints', () => {
it('Emits simple return statement with no constraints', () => {
const ctx = new Context();
const res = prettyPrint(
emitConstrainedTranslation(
{
input: '',
nodes: [],
},
nullExpr,
ctx,
),
);
expect(res.code).toMatchInlineSnapshot(`"return null;"`);
});
it('Emits simple return statement with just ignore constraints', () => {
const ctx = new Context();
const res = prettyPrint(
emitConstrainedTranslation(
{
input: '!someVar',
nodes: [makeIgnoreConstraint('someVar')],
},
nullExpr,
ctx,
),
);
expect(res.code).toMatchInlineSnapshot(`"return null;"`);
});
it('Emits simple if statement on single constraint', () => {
const ctx = new Context();
const res = prettyPrint(
emitConstrainedTranslation(
{
input: 'someVar=5',
nodes: [makeEqualityConstraint('someVar', 5)],
},
nullExpr,
ctx,
),
);
expect(res.code).toMatchInlineSnapshot(`
"if (vars.someVar === 5) {
return null;
}"
`);
});
it('Emits simple if statement on multiple constraints with one ignore constraint', () => {
const ctx = new Context();
const res = prettyPrint(
emitConstrainedTranslation(
{
input: 'someVar=5,!someOtherVar',
nodes: [makeEqualityConstraint('someVar', 5), makeIgnoreConstraint('someOtherVar')],
},
nullExpr,
ctx,
),
);
expect(res.code).toMatchInlineSnapshot(`
"if (vars.someVar === 5) {
return null;
}"
`);
});
it('Emits simple if statement on constraint with multiple tests', () => {
const ctx = new Context();
const res = prettyPrint(
emitConstrainedTranslation(
{
input: 'someVar=5,someOtherVar<10',
nodes: [makeEqualityConstraint('someVar', 5), makeInequalityConstraint('someOtherVar', 10)],
},
five,
ctx,
),
);
expect(res.code).toMatchInlineSnapshot(`
"if (vars.someVar === 5 && vars.someOtherVar > 10) {
return 5;
}"
`);
});
});
| secoya/hablar.js | test/emitting/constraint.ts | TypeScript | apache-2.0 | 3,419 |
<?php
/**
* This file is part of the SevenShores/NetSuite library
* AND originally from the NetSuite PHP Toolkit.
*
* New content:
* @package ryanwinchester/netsuite-php
* @copyright Copyright (c) Ryan Winchester
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
* @link https://github.com/ryanwinchester/netsuite-php
*
* Original content:
* @copyright Copyright (c) NetSuite Inc.
* @license https://raw.githubusercontent.com/ryanwinchester/netsuite-php/master/original/NetSuite%20Application%20Developer%20License%20Agreement.txt
* @link http://www.netsuite.com/portal/developers/resources/suitetalk-sample-applications.shtml
*
* generated: 2019-06-12 10:27:00 AM PDT
*/
namespace NetSuite\Classes;
class PaymentMethodSearchBasic extends SearchRecordBasic {
public $account;
public $creditCard;
public $externalId;
public $externalIdString;
public $internalId;
public $internalIdNumber;
public $isDebitCard;
public $isInactive;
public $name;
static $paramtypesmap = array(
"account" => "SearchMultiSelectField",
"creditCard" => "SearchBooleanField",
"externalId" => "SearchMultiSelectField",
"externalIdString" => "SearchStringField",
"internalId" => "SearchMultiSelectField",
"internalIdNumber" => "SearchLongField",
"isDebitCard" => "SearchBooleanField",
"isInactive" => "SearchBooleanField",
"name" => "SearchStringField",
);
}
| fungku/netsuite-php | src/Classes/PaymentMethodSearchBasic.php | PHP | apache-2.0 | 1,505 |
'use strict';
var _ = require('underscore');
var express = require('express');
var router = express.Router();
var ObjectId = require('mongoose').Types.ObjectId;
var path = require('path');
/**
* @apiDefine group Group based access
* Resource access controlled by user's groups
*/
/**
* @apiDefine access Authenticated user access only
* User should sign in for the request
*/
/**
* @api {get} / Get home page
* @apiName GetHomePage
* @apiGroup Home
*/
router.get('/', (req, res) => res.sendFile(path.join(__dirname, 'public', 'index.html')));
module.exports = router;
module.exports.getCollection = function(req, res, model, condition) {
let id = req.params.id;
let cond = id ? {
_id: new ObjectId(id)
} : {};
condition = _.extend(cond, condition);
model.find(condition, (err, result) => {
if (err) {
throw err;
}
res.send(result);
});
}; | vartomi/pmt-backend | routes/index.js | JavaScript | apache-2.0 | 886 |
# Copyright 2017 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.
# This setup file is used when running cloud training or cloud dataflow jobs.
from setuptools import setup, find_packages
setup(
name='trainer',
version='1.0.0',
packages=find_packages(),
description='Google Cloud Datalab helper sub-package',
author='Google',
author_email='google-cloud-datalab-feedback@googlegroups.com',
keywords=[
],
license="Apache Software License",
long_description="""
""",
install_requires=[
'tensorflow==1.15.2',
'protobuf==3.1.0',
'pillow==6.2.0', # ML Engine does not have PIL installed
],
package_data={
},
data_files=[],
)
| googledatalab/pydatalab | solutionbox/ml_workbench/tensorflow/setup.py | Python | apache-2.0 | 1,189 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 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("Simple4")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Simple4")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("13053df3-823e-4179-98c5-4b06cd37b74a")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| SteelToeOSS/Samples | Configuration/src/AspDotNet4/Simple/Properties/AssemblyInfo.cs | C# | apache-2.0 | 1,345 |
/*
Copyright (c) 2014-2016 DataStax
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.
*/
#ifndef __CASS_TOKEN_AWARE_POLICY_HPP_INCLUDED__
#define __CASS_TOKEN_AWARE_POLICY_HPP_INCLUDED__
#include "token_map.hpp"
#include "load_balancing.hpp"
#include "host.hpp"
#include "scoped_ptr.hpp"
namespace cass {
class TokenAwarePolicy : public ChainedLoadBalancingPolicy {
public:
TokenAwarePolicy(LoadBalancingPolicy* child_policy)
: ChainedLoadBalancingPolicy(child_policy)
, index_(0) {}
virtual ~TokenAwarePolicy() {}
virtual void init(const Host::Ptr& connected_host, const HostMap& hosts, Random* random);
virtual QueryPlan* new_query_plan(const std::string& connected_keyspace,
RequestHandler* request_handler,
const TokenMap* token_map);
LoadBalancingPolicy* new_instance() { return new TokenAwarePolicy(child_policy_->new_instance()); }
private:
class TokenAwareQueryPlan : public QueryPlan {
public:
TokenAwareQueryPlan(LoadBalancingPolicy* child_policy, QueryPlan* child_plan, const CopyOnWriteHostVec& replicas, size_t start_index)
: child_policy_(child_policy)
, child_plan_(child_plan)
, replicas_(replicas)
, index_(start_index)
, remaining_(replicas->size()) {}
Host::Ptr compute_next();
private:
LoadBalancingPolicy* child_policy_;
ScopedPtr<QueryPlan> child_plan_;
CopyOnWriteHostVec replicas_;
size_t index_;
size_t remaining_;
};
size_t index_;
private:
DISALLOW_COPY_AND_ASSIGN(TokenAwarePolicy);
};
} // namespace cass
#endif
| hpcc-systems/cpp-driver | src/token_aware_policy.hpp | C++ | apache-2.0 | 2,110 |
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.tasks.compile.incremental.cache;
import org.gradle.api.internal.tasks.compile.incremental.analyzer.ClassAnalysisCache;
import org.gradle.api.internal.tasks.compile.incremental.deps.LocalClassSetAnalysisStore;
import org.gradle.api.internal.tasks.compile.incremental.jar.JarSnapshotCache;
import org.gradle.api.internal.tasks.compile.incremental.jar.LocalJarClasspathSnapshotStore;
public interface CompileCaches {
ClassAnalysisCache getClassAnalysisCache();
JarSnapshotCache getJarSnapshotCache();
LocalJarClasspathSnapshotStore getLocalJarClasspathSnapshotStore();
LocalClassSetAnalysisStore getLocalClassSetAnalysisStore();
}
| gstevey/gradle | subprojects/language-java/src/main/java/org/gradle/api/internal/tasks/compile/incremental/cache/CompileCaches.java | Java | apache-2.0 | 1,295 |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.text;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.Layout;
import android.text.Layout.Alignment;
import androidx.annotation.ColorInt;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.util.Assertions;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/** Contains information about a specific cue, including textual content and formatting data. */
// This class shouldn't be sub-classed. If a subtitle format needs additional fields, either they
// should be generic enough to be added here, or the format-specific decoder should pass the
// information around in a sidecar object.
public final class Cue {
/** The empty cue. */
public static final Cue EMPTY = new Cue.Builder().setText("").build();
/** An unset position, width or size. */
// Note: We deliberately don't use Float.MIN_VALUE because it's positive & very close to zero.
public static final float DIMEN_UNSET = -Float.MAX_VALUE;
/**
* The type of anchor, which may be unset. One of {@link #TYPE_UNSET}, {@link #ANCHOR_TYPE_START},
* {@link #ANCHOR_TYPE_MIDDLE} or {@link #ANCHOR_TYPE_END}.
*/
@Documented
@Retention(RetentionPolicy.SOURCE)
@IntDef({TYPE_UNSET, ANCHOR_TYPE_START, ANCHOR_TYPE_MIDDLE, ANCHOR_TYPE_END})
public @interface AnchorType {}
/** An unset anchor, line, text size or vertical type value. */
public static final int TYPE_UNSET = Integer.MIN_VALUE;
/**
* Anchors the left (for horizontal positions) or top (for vertical positions) edge of the cue
* box.
*/
public static final int ANCHOR_TYPE_START = 0;
/**
* Anchors the middle of the cue box.
*/
public static final int ANCHOR_TYPE_MIDDLE = 1;
/**
* Anchors the right (for horizontal positions) or bottom (for vertical positions) edge of the cue
* box.
*/
public static final int ANCHOR_TYPE_END = 2;
/**
* The type of line, which may be unset. One of {@link #TYPE_UNSET}, {@link #LINE_TYPE_FRACTION}
* or {@link #LINE_TYPE_NUMBER}.
*/
@Documented
@Retention(RetentionPolicy.SOURCE)
@IntDef({TYPE_UNSET, LINE_TYPE_FRACTION, LINE_TYPE_NUMBER})
public @interface LineType {}
/**
* Value for {@link #lineType} when {@link #line} is a fractional position.
*/
public static final int LINE_TYPE_FRACTION = 0;
/**
* Value for {@link #lineType} when {@link #line} is a line number.
*/
public static final int LINE_TYPE_NUMBER = 1;
/**
* The type of default text size for this cue, which may be unset. One of {@link #TYPE_UNSET},
* {@link #TEXT_SIZE_TYPE_FRACTIONAL}, {@link #TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING} or {@link
* #TEXT_SIZE_TYPE_ABSOLUTE}.
*/
@Documented
@Retention(RetentionPolicy.SOURCE)
@IntDef({
TYPE_UNSET,
TEXT_SIZE_TYPE_FRACTIONAL,
TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING,
TEXT_SIZE_TYPE_ABSOLUTE
})
public @interface TextSizeType {}
/** Text size is measured as a fraction of the viewport size minus the view padding. */
public static final int TEXT_SIZE_TYPE_FRACTIONAL = 0;
/** Text size is measured as a fraction of the viewport size, ignoring the view padding */
public static final int TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING = 1;
/** Text size is measured in number of pixels. */
public static final int TEXT_SIZE_TYPE_ABSOLUTE = 2;
/**
* The type of vertical layout for this cue, which may be unset (i.e. horizontal). One of {@link
* #TYPE_UNSET}, {@link #VERTICAL_TYPE_RL} or {@link #VERTICAL_TYPE_LR}.
*/
@Documented
@Retention(RetentionPolicy.SOURCE)
@IntDef({
TYPE_UNSET,
VERTICAL_TYPE_RL,
VERTICAL_TYPE_LR,
})
public @interface VerticalType {}
/** Vertical right-to-left (e.g. for Japanese). */
public static final int VERTICAL_TYPE_RL = 1;
/** Vertical left-to-right (e.g. for Mongolian). */
public static final int VERTICAL_TYPE_LR = 2;
/**
* The cue text, or null if this is an image cue. Note the {@link CharSequence} may be decorated
* with styling spans.
*/
@Nullable public final CharSequence text;
/** The alignment of the cue text within the cue box, or null if the alignment is undefined. */
@Nullable public final Alignment textAlignment;
/** The cue image, or null if this is a text cue. */
@Nullable public final Bitmap bitmap;
/**
* The position of the cue box within the viewport in the direction orthogonal to the writing
* direction (determined by {@link #verticalType}), or {@link #DIMEN_UNSET}. When set, the
* interpretation of the value depends on the value of {@link #lineType}.
*
* <p>The measurement direction depends on {@link #verticalType}:
*
* <ul>
* <li>For {@link #TYPE_UNSET} (i.e. horizontal), this is the vertical position relative to the
* top of the viewport.
* <li>For {@link #VERTICAL_TYPE_LR} this is the horizontal position relative to the left of the
* viewport.
* <li>For {@link #VERTICAL_TYPE_RL} this is the horizontal position relative to the right of
* the viewport.
* </ul>
*/
public final float line;
/**
* The type of the {@link #line} value.
*
* <ul>
* <li>{@link #LINE_TYPE_FRACTION} indicates that {@link #line} is a fractional position within
* the viewport (measured to the part of the cue box determined by {@link #lineAnchor}).
* <li>{@link #LINE_TYPE_NUMBER} indicates that {@link #line} is a viewport line number. The
* viewport is divided into lines (each equal in size to the first line of the cue box). The
* cue box is positioned to align with the viewport lines as follows:
* <ul>
* <li>{@link #lineAnchor}) is ignored.
* <li>When {@code line} is greater than or equal to 0 the first line in the cue box is
* aligned with a viewport line, with 0 meaning the first line of the viewport.
* <li>When {@code line} is negative the last line in the cue box is aligned with a
* viewport line, with -1 meaning the last line of the viewport.
* <li>For horizontal text the start and end of the viewport are the top and bottom
* respectively.
* </ul>
* </ul>
*/
public final @LineType int lineType;
/**
* The cue box anchor positioned by {@link #line} when {@link #lineType} is {@link
* #LINE_TYPE_FRACTION}.
*
* <p>One of:
*
* <ul>
* <li>{@link #ANCHOR_TYPE_START}
* <li>{@link #ANCHOR_TYPE_MIDDLE}
* <li>{@link #ANCHOR_TYPE_END}
* <li>{@link #TYPE_UNSET}
* </ul>
*
* <p>For the normal case of horizontal text, {@link #ANCHOR_TYPE_START}, {@link
* #ANCHOR_TYPE_MIDDLE} and {@link #ANCHOR_TYPE_END} correspond to the top, middle and bottom of
* the cue box respectively.
*/
public final @AnchorType int lineAnchor;
/**
* The fractional position of the {@link #positionAnchor} of the cue box within the viewport in
* the direction orthogonal to {@link #line}, or {@link #DIMEN_UNSET}.
*
* <p>The measurement direction depends on {@link #verticalType}.
*
* <ul>
* <li>For {@link #TYPE_UNSET} (i.e. horizontal), this is the horizontal position relative to
* the left of the viewport. Note that positioning is relative to the left of the viewport
* even in the case of right-to-left text.
* <li>For {@link #VERTICAL_TYPE_LR} and {@link #VERTICAL_TYPE_RL} (i.e. vertical), this is the
* vertical position relative to the top of the viewport.
* </ul>
*/
public final float position;
/**
* The cue box anchor positioned by {@link #position}. One of {@link #ANCHOR_TYPE_START}, {@link
* #ANCHOR_TYPE_MIDDLE}, {@link #ANCHOR_TYPE_END} and {@link #TYPE_UNSET}.
*
* <p>For the normal case of horizontal text, {@link #ANCHOR_TYPE_START}, {@link
* #ANCHOR_TYPE_MIDDLE} and {@link #ANCHOR_TYPE_END} correspond to the left, middle and right of
* the cue box respectively.
*/
public final @AnchorType int positionAnchor;
/**
* The size of the cue box in the writing direction specified as a fraction of the viewport size
* in that direction, or {@link #DIMEN_UNSET}.
*/
public final float size;
/**
* The bitmap height as a fraction of the of the viewport size, or {@link #DIMEN_UNSET} if the
* bitmap should be displayed at its natural height given the bitmap dimensions and the specified
* {@link #size}.
*/
public final float bitmapHeight;
/**
* Specifies whether or not the {@link #windowColor} property is set.
*/
public final boolean windowColorSet;
/**
* The fill color of the window.
*/
public final int windowColor;
/**
* The default text size type for this cue's text, or {@link #TYPE_UNSET} if this cue has no
* default text size.
*/
public final @TextSizeType int textSizeType;
/**
* The default text size for this cue's text, or {@link #DIMEN_UNSET} if this cue has no default
* text size.
*/
public final float textSize;
/**
* The vertical formatting of this Cue, or {@link #TYPE_UNSET} if the cue has no vertical setting
* (and so should be horizontal).
*/
public final @VerticalType int verticalType;
/**
* The shear angle in degrees to be applied to this Cue, expressed in graphics coordinates. This
* results in a skew transform for the block along the inline progression axis.
*/
public final float shearDegrees;
/**
* Creates a text cue whose {@link #textAlignment} is null, whose type parameters are set to
* {@link #TYPE_UNSET} and whose dimension parameters are set to {@link #DIMEN_UNSET}.
*
* @param text See {@link #text}.
* @deprecated Use {@link Builder}.
*/
@SuppressWarnings("deprecation")
@Deprecated
public Cue(CharSequence text) {
this(
text,
/* textAlignment= */ null,
/* line= */ DIMEN_UNSET,
/* lineType= */ TYPE_UNSET,
/* lineAnchor= */ TYPE_UNSET,
/* position= */ DIMEN_UNSET,
/* positionAnchor= */ TYPE_UNSET,
/* size= */ DIMEN_UNSET);
}
/**
* Creates a text cue.
*
* @param text See {@link #text}.
* @param textAlignment See {@link #textAlignment}.
* @param line See {@link #line}.
* @param lineType See {@link #lineType}.
* @param lineAnchor See {@link #lineAnchor}.
* @param position See {@link #position}.
* @param positionAnchor See {@link #positionAnchor}.
* @param size See {@link #size}.
* @deprecated Use {@link Builder}.
*/
@SuppressWarnings("deprecation")
@Deprecated
public Cue(
CharSequence text,
@Nullable Alignment textAlignment,
float line,
@LineType int lineType,
@AnchorType int lineAnchor,
float position,
@AnchorType int positionAnchor,
float size) {
this(
text,
textAlignment,
line,
lineType,
lineAnchor,
position,
positionAnchor,
size,
/* windowColorSet= */ false,
/* windowColor= */ Color.BLACK);
}
/**
* Creates a text cue.
*
* @param text See {@link #text}.
* @param textAlignment See {@link #textAlignment}.
* @param line See {@link #line}.
* @param lineType See {@link #lineType}.
* @param lineAnchor See {@link #lineAnchor}.
* @param position See {@link #position}.
* @param positionAnchor See {@link #positionAnchor}.
* @param size See {@link #size}.
* @param textSizeType See {@link #textSizeType}.
* @param textSize See {@link #textSize}.
* @deprecated Use {@link Builder}.
*/
@SuppressWarnings("deprecation")
@Deprecated
public Cue(
CharSequence text,
@Nullable Alignment textAlignment,
float line,
@LineType int lineType,
@AnchorType int lineAnchor,
float position,
@AnchorType int positionAnchor,
float size,
@TextSizeType int textSizeType,
float textSize) {
this(
text,
textAlignment,
/* bitmap= */ null,
line,
lineType,
lineAnchor,
position,
positionAnchor,
textSizeType,
textSize,
size,
/* bitmapHeight= */ DIMEN_UNSET,
/* windowColorSet= */ false,
/* windowColor= */ Color.BLACK,
/* verticalType= */ TYPE_UNSET,
/* shearDegrees= */ 0f);
}
/**
* Creates a text cue.
*
* @param text See {@link #text}.
* @param textAlignment See {@link #textAlignment}.
* @param line See {@link #line}.
* @param lineType See {@link #lineType}.
* @param lineAnchor See {@link #lineAnchor}.
* @param position See {@link #position}.
* @param positionAnchor See {@link #positionAnchor}.
* @param size See {@link #size}.
* @param windowColorSet See {@link #windowColorSet}.
* @param windowColor See {@link #windowColor}.
* @deprecated Use {@link Builder}.
*/
@Deprecated
public Cue(
CharSequence text,
@Nullable Alignment textAlignment,
float line,
@LineType int lineType,
@AnchorType int lineAnchor,
float position,
@AnchorType int positionAnchor,
float size,
boolean windowColorSet,
int windowColor) {
this(
text,
textAlignment,
/* bitmap= */ null,
line,
lineType,
lineAnchor,
position,
positionAnchor,
/* textSizeType= */ TYPE_UNSET,
/* textSize= */ DIMEN_UNSET,
size,
/* bitmapHeight= */ DIMEN_UNSET,
windowColorSet,
windowColor,
/* verticalType= */ TYPE_UNSET,
/* shearDegrees= */ 0f);
}
private Cue(
@Nullable CharSequence text,
@Nullable Alignment textAlignment,
@Nullable Bitmap bitmap,
float line,
@LineType int lineType,
@AnchorType int lineAnchor,
float position,
@AnchorType int positionAnchor,
@TextSizeType int textSizeType,
float textSize,
float size,
float bitmapHeight,
boolean windowColorSet,
int windowColor,
@VerticalType int verticalType,
float shearDegrees) {
// Exactly one of text or bitmap should be set.
if (text == null) {
Assertions.checkNotNull(bitmap);
} else {
Assertions.checkArgument(bitmap == null);
}
this.text = text;
this.textAlignment = textAlignment;
this.bitmap = bitmap;
this.line = line;
this.lineType = lineType;
this.lineAnchor = lineAnchor;
this.position = position;
this.positionAnchor = positionAnchor;
this.size = size;
this.bitmapHeight = bitmapHeight;
this.windowColorSet = windowColorSet;
this.windowColor = windowColor;
this.textSizeType = textSizeType;
this.textSize = textSize;
this.verticalType = verticalType;
this.shearDegrees = shearDegrees;
}
/** Returns a new {@link Cue.Builder} initialized with the same values as this Cue. */
public Builder buildUpon() {
return new Cue.Builder(this);
}
/** A builder for {@link Cue} objects. */
public static final class Builder {
@Nullable private CharSequence text;
@Nullable private Bitmap bitmap;
@Nullable private Alignment textAlignment;
private float line;
@LineType private int lineType;
@AnchorType private int lineAnchor;
private float position;
@AnchorType private int positionAnchor;
@TextSizeType private int textSizeType;
private float textSize;
private float size;
private float bitmapHeight;
private boolean windowColorSet;
@ColorInt private int windowColor;
@VerticalType private int verticalType;
private float shearDegrees;
public Builder() {
text = null;
bitmap = null;
textAlignment = null;
line = DIMEN_UNSET;
lineType = TYPE_UNSET;
lineAnchor = TYPE_UNSET;
position = DIMEN_UNSET;
positionAnchor = TYPE_UNSET;
textSizeType = TYPE_UNSET;
textSize = DIMEN_UNSET;
size = DIMEN_UNSET;
bitmapHeight = DIMEN_UNSET;
windowColorSet = false;
windowColor = Color.BLACK;
verticalType = TYPE_UNSET;
}
private Builder(Cue cue) {
text = cue.text;
bitmap = cue.bitmap;
textAlignment = cue.textAlignment;
line = cue.line;
lineType = cue.lineType;
lineAnchor = cue.lineAnchor;
position = cue.position;
positionAnchor = cue.positionAnchor;
textSizeType = cue.textSizeType;
textSize = cue.textSize;
size = cue.size;
bitmapHeight = cue.bitmapHeight;
windowColorSet = cue.windowColorSet;
windowColor = cue.windowColor;
verticalType = cue.verticalType;
shearDegrees = cue.shearDegrees;
}
/**
* Sets the cue text.
*
* <p>Note that {@code text} may be decorated with styling spans.
*
* @see Cue#text
*/
public Builder setText(CharSequence text) {
this.text = text;
return this;
}
/**
* Gets the cue text.
*
* @see Cue#text
*/
@Nullable
public CharSequence getText() {
return text;
}
/**
* Sets the cue image.
*
* @see Cue#bitmap
*/
public Builder setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
return this;
}
/**
* Gets the cue image.
*
* @see Cue#bitmap
*/
@Nullable
public Bitmap getBitmap() {
return bitmap;
}
/**
* Sets the alignment of the cue text within the cue box.
*
* <p>Passing null means the alignment is undefined.
*
* @see Cue#textAlignment
*/
public Builder setTextAlignment(@Nullable Layout.Alignment textAlignment) {
this.textAlignment = textAlignment;
return this;
}
/**
* Gets the alignment of the cue text within the cue box, or null if the alignment is undefined.
*
* @see Cue#textAlignment
*/
@Nullable
public Alignment getTextAlignment() {
return textAlignment;
}
/**
* Sets the position of the cue box within the viewport in the direction orthogonal to the
* writing direction.
*
* @see Cue#line
* @see Cue#lineType
*/
public Builder setLine(float line, @LineType int lineType) {
this.line = line;
this.lineType = lineType;
return this;
}
/**
* Gets the position of the {@code lineAnchor} of the cue box within the viewport in the
* direction orthogonal to the writing direction.
*
* @see Cue#line
*/
public float getLine() {
return line;
}
/**
* Gets the type of the value of {@link #getLine()}.
*
* @see Cue#lineType
*/
@LineType
public int getLineType() {
return lineType;
}
/**
* Sets the cue box anchor positioned by {@link #setLine(float, int) line}.
*
* @see Cue#lineAnchor
*/
public Builder setLineAnchor(@AnchorType int lineAnchor) {
this.lineAnchor = lineAnchor;
return this;
}
/**
* Gets the cue box anchor positioned by {@link #setLine(float, int) line}.
*
* @see Cue#lineAnchor
*/
@AnchorType
public int getLineAnchor() {
return lineAnchor;
}
/**
* Sets the fractional position of the {@link #setPositionAnchor(int) positionAnchor} of the cue
* box within the viewport in the direction orthogonal to {@link #setLine(float, int) line}.
*
* @see Cue#position
*/
public Builder setPosition(float position) {
this.position = position;
return this;
}
/**
* Gets the fractional position of the {@link #setPositionAnchor(int) positionAnchor} of the cue
* box within the viewport in the direction orthogonal to {@link #setLine(float, int) line}.
*
* @see Cue#position
*/
public float getPosition() {
return position;
}
/**
* Sets the cue box anchor positioned by {@link #setPosition(float) position}.
*
* @see Cue#positionAnchor
*/
public Builder setPositionAnchor(@AnchorType int positionAnchor) {
this.positionAnchor = positionAnchor;
return this;
}
/**
* Gets the cue box anchor positioned by {@link #setPosition(float) position}.
*
* @see Cue#positionAnchor
*/
@AnchorType
public int getPositionAnchor() {
return positionAnchor;
}
/**
* Sets the default text size and type for this cue's text.
*
* @see Cue#textSize
* @see Cue#textSizeType
*/
public Builder setTextSize(float textSize, @TextSizeType int textSizeType) {
this.textSize = textSize;
this.textSizeType = textSizeType;
return this;
}
/**
* Gets the default text size type for this cue's text.
*
* @see Cue#textSizeType
*/
@TextSizeType
public int getTextSizeType() {
return textSizeType;
}
/**
* Gets the default text size for this cue's text.
*
* @see Cue#textSize
*/
public float getTextSize() {
return textSize;
}
/**
* Sets the size of the cue box in the writing direction specified as a fraction of the viewport
* size in that direction.
*
* @see Cue#size
*/
public Builder setSize(float size) {
this.size = size;
return this;
}
/**
* Gets the size of the cue box in the writing direction specified as a fraction of the viewport
* size in that direction.
*
* @see Cue#size
*/
public float getSize() {
return size;
}
/**
* Sets the bitmap height as a fraction of the viewport size.
*
* @see Cue#bitmapHeight
*/
public Builder setBitmapHeight(float bitmapHeight) {
this.bitmapHeight = bitmapHeight;
return this;
}
/**
* Gets the bitmap height as a fraction of the viewport size.
*
* @see Cue#bitmapHeight
*/
public float getBitmapHeight() {
return bitmapHeight;
}
/**
* Sets the fill color of the window.
*
* <p>Also sets {@link Cue#windowColorSet} to true.
*
* @see Cue#windowColor
* @see Cue#windowColorSet
*/
public Builder setWindowColor(@ColorInt int windowColor) {
this.windowColor = windowColor;
this.windowColorSet = true;
return this;
}
/** Sets {@link Cue#windowColorSet} to false. */
public Builder clearWindowColor() {
this.windowColorSet = false;
return this;
}
/**
* Returns true if the fill color of the window is set.
*
* @see Cue#windowColorSet
*/
public boolean isWindowColorSet() {
return windowColorSet;
}
/**
* Gets the fill color of the window.
*
* @see Cue#windowColor
*/
@ColorInt
public int getWindowColor() {
return windowColor;
}
/**
* Sets the vertical formatting for this Cue.
*
* @see Cue#verticalType
*/
public Builder setVerticalType(@VerticalType int verticalType) {
this.verticalType = verticalType;
return this;
}
/** Sets the shear angle for this Cue. */
public Builder setShearDegrees(float shearDegrees) {
this.shearDegrees = shearDegrees;
return this;
}
/**
* Gets the vertical formatting for this Cue.
*
* @see Cue#verticalType
*/
@VerticalType
public int getVerticalType() {
return verticalType;
}
/** Build the cue. */
public Cue build() {
return new Cue(
text,
textAlignment,
bitmap,
line,
lineType,
lineAnchor,
position,
positionAnchor,
textSizeType,
textSize,
size,
bitmapHeight,
windowColorSet,
windowColor,
verticalType,
shearDegrees);
}
}
}
| amzn/exoplayer-amazon-port | library/common/src/main/java/com/google/android/exoplayer2/text/Cue.java | Java | apache-2.0 | 24,639 |
/**
* 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.hcatalog.mapreduce;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.Assert;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocalFileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.SerDeInfo;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.ql.io.RCFileInputFormat;
import org.apache.hadoop.hive.ql.io.RCFileOutputFormat;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.columnar.ColumnarSerDe;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobStatus;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hcatalog.HcatTestUtils;
import org.apache.hcatalog.common.HCatConstants;
import org.apache.hcatalog.common.HCatUtil;
import org.apache.hcatalog.data.DefaultHCatRecord;
import org.apache.hcatalog.data.HCatRecord;
import org.apache.hcatalog.data.schema.HCatFieldSchema;
import org.apache.hcatalog.data.schema.HCatSchema;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertTrue;
/**
* Test for HCatOutputFormat. Writes a partition using HCatOutputFormat and reads
* it back using HCatInputFormat, checks the column values and counts.
*/
public abstract class HCatMapReduceTest extends HCatBaseTest {
private static final Logger LOG = LoggerFactory.getLogger(HCatMapReduceTest.class);
protected static String dbName = MetaStoreUtils.DEFAULT_DATABASE_NAME;
protected static String tableName = "testHCatMapReduceTable";
protected String inputFormat = RCFileInputFormat.class.getName();
protected String outputFormat = RCFileOutputFormat.class.getName();
protected String serdeClass = ColumnarSerDe.class.getName();
private static List<HCatRecord> writeRecords = new ArrayList<HCatRecord>();
private static List<HCatRecord> readRecords = new ArrayList<HCatRecord>();
protected abstract List<FieldSchema> getPartitionKeys();
protected abstract List<FieldSchema> getTableColumns();
private static FileSystem fs;
@BeforeClass
public static void setUpOneTime() throws Exception {
fs = new LocalFileSystem();
fs.initialize(fs.getWorkingDirectory().toUri(), new Configuration());
HiveConf hiveConf = new HiveConf();
hiveConf.setInt(HCatConstants.HCAT_HIVE_CLIENT_EXPIRY_TIME, 0);
// Hack to initialize cache with 0 expiry time causing it to return a new hive client every time
// Otherwise the cache doesn't play well with the second test method with the client gets closed() in the
// tearDown() of the previous test
HCatUtil.getHiveClient(hiveConf);
MapCreate.writeCount = 0;
MapRead.readCount = 0;
}
@After
public void deleteTable() throws Exception {
try {
String databaseName = (dbName == null) ? MetaStoreUtils.DEFAULT_DATABASE_NAME : dbName;
client.dropTable(databaseName, tableName);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
@Before
public void createTable() throws Exception {
String databaseName = (dbName == null) ? MetaStoreUtils.DEFAULT_DATABASE_NAME : dbName;
try {
client.dropTable(databaseName, tableName);
} catch (Exception e) {
} //can fail with NoSuchObjectException
Table tbl = new Table();
tbl.setDbName(databaseName);
tbl.setTableName(tableName);
tbl.setTableType("MANAGED_TABLE");
StorageDescriptor sd = new StorageDescriptor();
sd.setCols(getTableColumns());
tbl.setPartitionKeys(getPartitionKeys());
tbl.setSd(sd);
sd.setBucketCols(new ArrayList<String>(2));
sd.setSerdeInfo(new SerDeInfo());
sd.getSerdeInfo().setName(tbl.getTableName());
sd.getSerdeInfo().setParameters(new HashMap<String, String>());
sd.getSerdeInfo().getParameters().put(serdeConstants.SERIALIZATION_FORMAT, "1");
sd.getSerdeInfo().setSerializationLib(serdeClass);
sd.setInputFormat(inputFormat);
sd.setOutputFormat(outputFormat);
Map<String, String> tableParams = new HashMap<String, String>();
tbl.setParameters(tableParams);
client.createTable(tbl);
}
//Create test input file with specified number of rows
private void createInputFile(Path path, int rowCount) throws IOException {
if (fs.exists(path)) {
fs.delete(path, true);
}
FSDataOutputStream os = fs.create(path);
for (int i = 0; i < rowCount; i++) {
os.writeChars(i + "\n");
}
os.close();
}
public static class MapCreate extends
Mapper<LongWritable, Text, BytesWritable, HCatRecord> {
static int writeCount = 0; //test will be in local mode
@Override
public void map(LongWritable key, Text value, Context context
) throws IOException, InterruptedException {
{
try {
HCatRecord rec = writeRecords.get(writeCount);
context.write(null, rec);
writeCount++;
} catch (Exception e) {
e.printStackTrace(System.err); //print since otherwise exception is lost
throw new IOException(e);
}
}
}
}
public static class MapRead extends
Mapper<WritableComparable, HCatRecord, BytesWritable, Text> {
static int readCount = 0; //test will be in local mode
@Override
public void map(WritableComparable key, HCatRecord value, Context context
) throws IOException, InterruptedException {
{
try {
readRecords.add(value);
readCount++;
} catch (Exception e) {
e.printStackTrace(); //print since otherwise exception is lost
throw new IOException(e);
}
}
}
}
Job runMRCreate(Map<String, String> partitionValues,
List<HCatFieldSchema> partitionColumns, List<HCatRecord> records,
int writeCount, boolean assertWrite) throws Exception {
return runMRCreate(partitionValues, partitionColumns, records, writeCount, assertWrite, true);
}
/**
* Run a local map reduce job to load data from in memory records to an HCatalog Table
* @param partitionValues
* @param partitionColumns
* @param records data to be written to HCatalog table
* @param writeCount
* @param assertWrite
* @param asSingleMapTask
* @return
* @throws Exception
*/
Job runMRCreate(Map<String, String> partitionValues,
List<HCatFieldSchema> partitionColumns, List<HCatRecord> records,
int writeCount, boolean assertWrite, boolean asSingleMapTask) throws Exception {
writeRecords = records;
MapCreate.writeCount = 0;
Configuration conf = new Configuration();
Job job = new Job(conf, "hcat mapreduce write test");
job.setJarByClass(this.getClass());
job.setMapperClass(HCatMapReduceTest.MapCreate.class);
// input/output settings
job.setInputFormatClass(TextInputFormat.class);
if (asSingleMapTask) {
// One input path would mean only one map task
Path path = new Path(fs.getWorkingDirectory(), "mapred/testHCatMapReduceInput");
createInputFile(path, writeCount);
TextInputFormat.setInputPaths(job, path);
} else {
// Create two input paths so that two map tasks get triggered. There could be other ways
// to trigger two map tasks.
Path path = new Path(fs.getWorkingDirectory(), "mapred/testHCatMapReduceInput");
createInputFile(path, writeCount / 2);
Path path2 = new Path(fs.getWorkingDirectory(), "mapred/testHCatMapReduceInput2");
createInputFile(path2, (writeCount - writeCount / 2));
TextInputFormat.setInputPaths(job, path, path2);
}
job.setOutputFormatClass(HCatOutputFormat.class);
OutputJobInfo outputJobInfo = OutputJobInfo.create(dbName, tableName, partitionValues);
HCatOutputFormat.setOutput(job, outputJobInfo);
job.setMapOutputKeyClass(BytesWritable.class);
job.setMapOutputValueClass(DefaultHCatRecord.class);
job.setNumReduceTasks(0);
HCatOutputFormat.setSchema(job, new HCatSchema(partitionColumns));
boolean success = job.waitForCompletion(true);
// Ensure counters are set when data has actually been read.
if (partitionValues != null) {
assertTrue(job.getCounters().getGroup("FileSystemCounters")
.findCounter("FILE_BYTES_READ").getValue() > 0);
}
if (!HcatTestUtils.isHadoop23() && !HcatTestUtils.isHadoop2_0()) {
// Local mode outputcommitter hook is not invoked in Hadoop 1.x
if (success) {
new FileOutputCommitterContainer(job, null).commitJob(job);
} else {
new FileOutputCommitterContainer(job, null).abortJob(job, JobStatus.State.FAILED);
}
}
if (assertWrite) {
// we assert only if we expected to assert with this call.
Assert.assertEquals(writeCount, MapCreate.writeCount);
}
return job;
}
List<HCatRecord> runMRRead(int readCount) throws Exception {
return runMRRead(readCount, null);
}
/**
* Run a local map reduce job to read records from HCatalog table and verify if the count is as expected
* @param readCount
* @param filter
* @return
* @throws Exception
*/
List<HCatRecord> runMRRead(int readCount, String filter) throws Exception {
MapRead.readCount = 0;
readRecords.clear();
Configuration conf = new Configuration();
Job job = new Job(conf, "hcat mapreduce read test");
job.setJarByClass(this.getClass());
job.setMapperClass(HCatMapReduceTest.MapRead.class);
// input/output settings
job.setInputFormatClass(HCatInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
HCatInputFormat.setInput(job, dbName, tableName).setFilter(filter);
job.setMapOutputKeyClass(BytesWritable.class);
job.setMapOutputValueClass(Text.class);
job.setNumReduceTasks(0);
Path path = new Path(fs.getWorkingDirectory(), "mapred/testHCatMapReduceOutput");
if (fs.exists(path)) {
fs.delete(path, true);
}
TextOutputFormat.setOutputPath(job, path);
job.waitForCompletion(true);
Assert.assertEquals(readCount, MapRead.readCount);
return readRecords;
}
protected HCatSchema getTableSchema() throws Exception {
Configuration conf = new Configuration();
Job job = new Job(conf, "hcat mapreduce read schema test");
job.setJarByClass(this.getClass());
// input/output settings
job.setInputFormatClass(HCatInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
HCatInputFormat.setInput(job, dbName, tableName);
return HCatInputFormat.getTableSchema(job);
}
}
| cloudera/hcatalog | core/src/test/java/org/apache/hcatalog/mapreduce/HCatMapReduceTest.java | Java | apache-2.0 | 13,101 |
/**
* Websocket Client
*/
(function() {
window.Socket = window.Socket || {}
var PacketTypes = {
Command : 0,
Status : 1
}
class Socket {
constructor(uri, game) {
uri = uri || ""
if(uri.length <= 0) {
let loc = window.location
uri = 'ws:'
if(loc.protocol === 'https:') {
uri = 'wss:'
}
uri += '//' + loc.host
uri += loc.pathname + 'ws'
}
this.game = game
this.ready = false
this.socket = new WebSocket(uri)
this.socket.binaryType = "arraybuffer"
this.socket.onopen = () => { this.onOpen() }
this.socket.onmessage = (ev) => { this.onMessage(ev) }
this.socket.onclose = () => { this.onClose() }
}
get closed() {
this.socket.readyState == WebSocket.CLOSED
}
close() {
this.socket.close()
}
onOpen() {
this.ready = true
}
onMessage(ev) {
let data = new Uint8Array(ev.data)
let packetObject = msgpack.unpack(data)
// If data is not correctly
if(packetObject == null || packetObject.Type == "undefined") {
return
}
switch(packetObject.Type) {
case PacketTypes.Command:
this.pushCommand(packetObject.Data)
break
case PacketTypes.Status:
this.handleStatus(packetObject.Data)
break
}
}
send(type, data) {
// Ignore send data if socket not open
if(this.socket.readyState != WebSocket.OPEN) {
return
}
let rawPacket = {
Type: type,
Data: data
}
// Should package as binary
let packet = new Uint8Array(msgpack.pack(rawPacket))
this.socket.send(packet)
}
execCommand(name, team, params) {
params = params || {}
this.send(
PacketTypes.Command,
{
Name: name,
Team: team,
Params: params
}
)
}
pushCommand(data) {
let CommandClass = Command[data.Name]
if(!CommandClass) { // Invalid command
return
}
let CommandInstance = new CommandClass(this.game, data.Team)
CommandInstance.deserialize(data.Params)
// Send command
Command.Resolver.push(CommandInstance)
}
handleStatus(stat) {
// TODO: the handler can improve more
switch(stat.Name){
case "Register":
if(stat.Value == 1) {
Game.Status = GameStatus.Registered
this.updateStatus("Match", 0)
}
break
case "Match":
if(stat.Value == 1) {
Game.Status = GameStatus.Start
}
break
case "Exit":
Game.Status = GameStatus.End
break
}
}
updateStatus(name, value) {
this.send(
PacketTypes.Status,
{
Name: name,
Value: value
}
)
}
onClose() {
}
}
window.Socket = Socket
window.PacketType = PacketTypes
}())
| BasalticStudio/Walrus-vs-Slime | js/Socket.js | JavaScript | apache-2.0 | 3,768 |
/**
* JacobGen generated file --- do not edit
*
* (http://www.sourceforge.net/projects/jacob-project */
package com.pew.itunes;
import com.jacob.com.*;
public class IITVisual extends Dispatch {
public static final String componentName = "iTunesLib.IITVisual";
public IITVisual() {
super(componentName);
}
/**
* This constructor is used instead of a case operation to
* turn a Dispatch object into a wider object - it must exist
* in every wrapper class whose instances may be returned from
* method calls wrapped in VT_DISPATCH Variants.
*/
public IITVisual(Dispatch d) {
// take over the IDispatch pointer
m_pDispatch = d.m_pDispatch;
// null out the input's pointer
d.m_pDispatch = 0;
}
public IITVisual(String compName) {
super(compName);
}
/**
* Wrapper for calling the ActiveX-Method with input-parameter(s).
* @return the result is of type String
*/
public String getName() {
return Dispatch.get(this, "Name").toString();
}
}
| Eminenz/itunesJacobExample | src/com/pew/itunes/IITVisual.java | Java | apache-2.0 | 979 |
(function() {
function getParentIndex(levels, level, index) {
if (level > 0) {
for (var i = index - 1; i >= 0; i--) {
if (levels[i] == level - 1) {
return i;
}
}
}
return -1;
}
function hasLittleBrother(levels, level, index) {
if (index < levels.length - 1) {
for (var i = index + 1; i < levels.length; i++) {
if (levels[i] == level) {
return true;
} else if (levels[i] < level) {
return false;
}
}
}
return false;
}
function getParentTempData(tempdatas, tempdata, prefixIndex) {
for (var i = 0; i < prefixIndex - 1; i++) {
tempdata = tempdatas[tempdata.parentIndex];
}
return tempdata;
}
function getPrefixInner(tempdatas, tempdata, prefixIndex) {
// If level = 3, then prefixIndex array will be: [3, 2, 1]
// prefixIndex === 1 will always present the nearest prefix next to the Text.
if (prefixIndex === 1) {
if (tempdata.littleBrother) {
return '<div class="x-elbow"></div>';
}
else {
return '<div class="x-elbow-end"></div>';
}
} else {
var parentdata = getParentTempData(tempdatas, tempdata, prefixIndex);
if (parentdata.littleBrother) {
return '<div class="x-elbow-line"></div>';
}
else {
return '<div class="x-elbow-empty"></div>';
}
}
return "";
}
function getPrefix(tempdatas, index) {
var tempdata = tempdatas[index];
var level = tempdata.level;
var prefix = [];
for (var i = level; i > 0; i--) {
prefix.push(getPrefixInner(tempdatas, tempdata, i));
}
return prefix.join('');
}
F.simulateTree = {
transform: function(datas) {
if (!datas.length || datas[0].length < 4) {
return datas;
}
//// store: new Ext.data.ArrayStore({ fields: ['value', 'text', 'enabled', 'prefix'] })
//// Sample data:
//[
// ["0", "jQuery", 0, 0],
// ["1", "Core", 0, 1],
// ["2", "Selectors", 0, 1],
// ["3", "Basic Filters", 1, 2],
// ["4", "Content Filters", 1, 2],
// ["41", "Contains", 1, 3],
// ["5", "Attribute Filters", 1, 2],
// ["6", "Traversing", 1, 1],
// ["7", "Filtering", 1, 2],
// ["8", "Finding", 1, 2],
// ["9", "Events", 0, 1],
// ["10", "Page Load", 1, 2],
// ["11", "Event Handling", 1, 2],
// ["12", "Interaction Helpers", 1, 2],
// ["13", "Ajax", 1, 1]
//]
var levels = [];
Ext.Array.each(datas, function (data, index) {
levels.push(data[3]);
});
var tempdatas = [];
Ext.Array.each(levels, function (level, index) {
tempdatas.push({
'level': level,
'parentIndex': getParentIndex(levels, level, index),
'littleBrother': hasLittleBrother(levels, level, index)
});
});
var newdatas = [];
Ext.Array.each(datas, function (data, index) {
newdatas.push([data[0], data[1], data[2], getPrefix(tempdatas, index)]);
});
return newdatas;
}
};
})(); | u0hz/FineUI | src/FineUI.Examples/extjs_builder/js/F/F.simulateTree.js | JavaScript | apache-2.0 | 3,857 |
/**
* Copyright 2016, 2017 Peter Zybrick and others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Pete Zybrick
* @version 1.0.0, 2017-09
*
*/
package com.pzybrick.iote2e.ws.nrt;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.cache.CacheException;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.avro.util.Utf8;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.pzybrick.iote2e.common.ignite.IgniteGridConnection;
import com.pzybrick.iote2e.common.ignite.ThreadIgniteSubscribe;
import com.pzybrick.iote2e.common.utils.Iote2eConstants;
import com.pzybrick.iote2e.common.utils.Iote2eUtils;
import com.pzybrick.iote2e.schema.avro.Iote2eResult;
import com.pzybrick.iote2e.schema.avro.OPERATION;
import com.pzybrick.iote2e.schema.util.Iote2eResultReuseItem;
import com.pzybrick.iote2e.schema.util.Iote2eSchemaConstants;
/**
* The Class ServerSideSocketNearRealTime.
*/
@ClientEndpoint
@ServerEndpoint(value = "/nrt/")
public class ServerSideSocketNearRealTime {
/** The Constant logger. */
private static final Logger logger = LogManager.getLogger(ServerSideSocketNearRealTime.class);
/** The session. */
private Session session;
/** The thread ignite subscribe temperature. */
private ThreadIgniteSubscribe threadIgniteSubscribeTemperature;
/** The thread ignite subscribe omh. */
private ThreadIgniteSubscribe threadIgniteSubscribeOmh;
/** The thread ignite subscribe bdbb. */
private ThreadIgniteSubscribe threadIgniteSubscribeBdbb;
/**
* Gets the session.
*
* @return the session
*/
public Session getSession() {
return session;
}
/**
* Sets the session.
*
* @param session the new session
*/
public void setSession(Session session) {
this.session = session;
}
/**
* Instantiates a new server side socket near real time.
*/
public ServerSideSocketNearRealTime() {
}
/**
* On web socket connect.
*
* @param session the session
* @throws Exception the exception
*/
@OnOpen
public void onWebSocketConnect(Session session) throws Exception {
this.session = session;
ThreadEntryPointNearRealTime.serverSideSocketNearRealTimes.put(Iote2eConstants.SOCKET_KEY_NRT, this);
threadIgniteSubscribeTemperature = ThreadIgniteSubscribe.startThreadSubscribe( ThreadEntryPointNearRealTime.masterConfig, Iote2eConstants.IGNITE_KEY_NRT_TEMPERATURE,
ThreadEntryPointNearRealTime.toClientIote2eResults, (Thread)null );
threadIgniteSubscribeOmh = ThreadIgniteSubscribe.startThreadSubscribe( ThreadEntryPointNearRealTime.masterConfig, Iote2eConstants.IGNITE_KEY_NRT_OMH,
ThreadEntryPointNearRealTime.toClientIote2eResults, (Thread)null );
threadIgniteSubscribeBdbb = ThreadIgniteSubscribe.startThreadSubscribe( ThreadEntryPointNearRealTime.masterConfig, Iote2eConstants.IGNITE_KEY_NRT_BDBB,
ThreadEntryPointNearRealTime.toClientIote2eResults, (Thread)null );
//new ThreadPumpTestData().start();
logger.info("Socket Connected: " + session.getId());
}
/**
* On web socket text.
*
* @param message the message
*/
@OnMessage
public void onWebSocketText(String message) {
logger.debug("onWebSocketText " + message);
}
/**
* On web socket byte.
*
* @param bytes the bytes
*/
@OnMessage
public void onWebSocketByte(byte[] bytes) {
logger.debug("onWebSocketByte len=" + bytes.length);
}
/**
* On web socket close.
*
* @param reason the reason
*/
@OnClose
public void onWebSocketClose(CloseReason reason) {
boolean isRemove = ThreadEntryPointNearRealTime.serverSideSocketNearRealTimes.remove(Iote2eConstants.SOCKET_KEY_NRT, this);
logger.info("Socket Closed: " + reason + ", isRemove=" + isRemove);
shutdownThreadIgniteSubscribe();
}
/**
* On web socket error.
*
* @param cause the cause
*/
@OnError
public void onWebSocketError(Throwable cause) {
boolean isRemove = ThreadEntryPointNearRealTime.serverSideSocketNearRealTimes.remove(Iote2eConstants.SOCKET_KEY_NRT, this);
logger.info("Socket Error: " + cause.getMessage() + ", isRemove=" + isRemove);
shutdownThreadIgniteSubscribe();
}
/**
* Shutdown thread ignite subscribe.
*/
private void shutdownThreadIgniteSubscribe() {
logger.debug("Shutting down threadIgniteSubscribe");
try {
threadIgniteSubscribeTemperature.shutdown();
threadIgniteSubscribeOmh.shutdown();
threadIgniteSubscribeBdbb.shutdown();
threadIgniteSubscribeTemperature.join(5000);
threadIgniteSubscribeOmh.join(5000);
threadIgniteSubscribeBdbb.join(5000);
} catch( InterruptedException e ) {
} catch( Exception e ) {
logger.error(e.getMessage());
}
}
/**
* The Class ThreadPumpTestData.
*/
public class ThreadPumpTestData extends Thread {
/** The shutdown. */
private boolean shutdown;
/**
* Shutdown.
*/
public void shutdown() {
logger.info("Shutdown");
shutdown = true;
interrupt();
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
logger.info("ThreadPumpTestData Run");
final List<String> rpis = Arrays.asList("rpi-001","rpi-002","rpi-003");
final float tempMin = 30.0f;
final float tempMax = 50.0f;
final float tempIncr = 4.0f;
try {
IgniteGridConnection igniteGridConnection = new IgniteGridConnection().connect(ThreadEntryPointNearRealTime.masterConfig);
Iote2eResultReuseItem iote2eResultReuseItem = new Iote2eResultReuseItem();
List<PumpTemperatureItem> pumpTemperatureItems = new ArrayList<PumpTemperatureItem>();
pumpTemperatureItems.add( new PumpTemperatureItem("rpi-001", tempMin ));
pumpTemperatureItems.add( new PumpTemperatureItem("rpi-002", tempMin + tempIncr ));
pumpTemperatureItems.add( new PumpTemperatureItem("rpi-003", tempMin + (2*tempIncr) ));
TemperatureSensorItem temperatureSensorItem = new TemperatureSensorItem();
while( true ) {
for( PumpTemperatureItem pumpTemperatureItem : pumpTemperatureItems ) {
Map<CharSequence,CharSequence> pairs = new HashMap<CharSequence,CharSequence>();
pairs.put( new Utf8(Iote2eSchemaConstants.PAIRNAME_SENSOR_NAME), new Utf8("temp1"));
pairs.put( new Utf8(Iote2eSchemaConstants.PAIRNAME_SENSOR_VALUE), new Utf8(String.valueOf(pumpTemperatureItem.getDegreesC()) ));
Iote2eResult iote2eResult = Iote2eResult.newBuilder()
.setPairs(pairs)
//.setMetadata(ruleEvalResult.getMetadata())
.setLoginName("$nrt$")
.setSourceName(new Utf8(pumpTemperatureItem.getSourceName()))
.setSourceType("temp")
.setRequestUuid(new Utf8(UUID.randomUUID().toString()))
.setRequestTimestamp(new Utf8(Iote2eUtils.getDateNowUtc8601()))
.setOperation(OPERATION.SENSORS_VALUES)
.setResultCode(0)
.setResultTimestamp( new Utf8(Iote2eUtils.getDateNowUtc8601()))
.setResultUuid( new Utf8(UUID.randomUUID().toString()))
.build();
// EntryPointNearRealTime.toClientIote2eResults.add( iote2eResult );
boolean isSuccess = false;
Exception lastException = null;
long timeoutAt = System.currentTimeMillis() + (15*1000L);
while( System.currentTimeMillis() < timeoutAt ) {
try {
igniteGridConnection.getCache().put(Iote2eConstants.IGNITE_KEY_NRT_TEMPERATURE, iote2eResultReuseItem.toByteArray(iote2eResult));
isSuccess = true;
logger.debug("cache.put successful, cache name={}, pk={}, iote2eResult={}", igniteGridConnection.getCache().getName(), Iote2eConstants.IGNITE_KEY_NRT_TEMPERATURE, iote2eResult.toString() );
break;
} catch( CacheException cacheException ) {
lastException = cacheException;
logger.warn("cache.put failed with CacheException, will retry, cntRetry={}" );
try { Thread.sleep(1000L); } catch(Exception e ) {}
} catch( Exception e ) {
logger.error(e.getMessage(),e);
throw e;
}
}
if( !isSuccess ) {
logger.error("Ignite cache write failure, pk={}, iote2eResult={}, lastException: {}", Iote2eConstants.IGNITE_KEY_NRT_TEMPERATURE, iote2eResult.toString(), lastException.getLocalizedMessage(), lastException);
throw new Exception( lastException);
}
if( pumpTemperatureItem.isIncreasing ) pumpTemperatureItem.setDegreesC(pumpTemperatureItem.getDegreesC() + tempIncr );
else pumpTemperatureItem.setDegreesC(pumpTemperatureItem.getDegreesC() - tempIncr);
if( pumpTemperatureItem.getDegreesC() > tempMax ) pumpTemperatureItem.setIncreasing(false);
else if( pumpTemperatureItem.getDegreesC() < tempMin ) pumpTemperatureItem.setIncreasing(true);
}
try {
sleep(1000L);
} catch (InterruptedException e) {}
if (shutdown)
return;
}
} catch (Exception e) {
logger.error("Exception processing target text message", e);
}
logger.info("Exit");
}
}
/**
* The Class PumpTemperatureItem.
*/
private class PumpTemperatureItem {
/** The source name. */
private String sourceName;
/** The degrees C. */
private float degreesC;
/** The is increasing. */
private boolean isIncreasing = true;
/**
* Instantiates a new pump temperature item.
*
* @param rpiName the rpi name
* @param temperature the temperature
*/
public PumpTemperatureItem(String rpiName, float temperature) {
super();
this.sourceName = rpiName;
this.degreesC = temperature;
}
/**
* Gets the source name.
*
* @return the source name
*/
public String getSourceName() {
return sourceName;
}
/**
* Sets the source name.
*
* @param sourceName the source name
* @return the pump temperature item
*/
public PumpTemperatureItem setSourceName(String sourceName) {
this.sourceName = sourceName;
return this;
}
/**
* Gets the degrees C.
*
* @return the degrees C
*/
public float getDegreesC() {
return degreesC;
}
/**
* Checks if is increasing.
*
* @return true, if is increasing
*/
public boolean isIncreasing() {
return isIncreasing;
}
/**
* Sets the degrees C.
*
* @param degreesC the degrees C
* @return the pump temperature item
*/
public PumpTemperatureItem setDegreesC(float degreesC) {
this.degreesC = degreesC;
return this;
}
/**
* Sets the increasing.
*
* @param isIncreasing the is increasing
* @return the pump temperature item
*/
public PumpTemperatureItem setIncreasing(boolean isIncreasing) {
this.isIncreasing = isIncreasing;
return this;
}
}
} | petezybrick/iote2e | iote2e-ws/src/main/java/com/pzybrick/iote2e/ws/nrt/ServerSideSocketNearRealTime.java | Java | apache-2.0 | 11,460 |
/*
* Copyright 2010-2017 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.
*/
#include <aws/sagemaker/model/AlgorithmSortBy.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace SageMaker
{
namespace Model
{
namespace AlgorithmSortByMapper
{
static const int Name_HASH = HashingUtils::HashString("Name");
static const int CreationTime_HASH = HashingUtils::HashString("CreationTime");
AlgorithmSortBy GetAlgorithmSortByForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == Name_HASH)
{
return AlgorithmSortBy::Name;
}
else if (hashCode == CreationTime_HASH)
{
return AlgorithmSortBy::CreationTime;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<AlgorithmSortBy>(hashCode);
}
return AlgorithmSortBy::NOT_SET;
}
Aws::String GetNameForAlgorithmSortBy(AlgorithmSortBy enumValue)
{
switch(enumValue)
{
case AlgorithmSortBy::Name:
return "Name";
case AlgorithmSortBy::CreationTime:
return "CreationTime";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace AlgorithmSortByMapper
} // namespace Model
} // namespace SageMaker
} // namespace Aws
| cedral/aws-sdk-cpp | aws-cpp-sdk-sagemaker/source/model/AlgorithmSortBy.cpp | C++ | apache-2.0 | 2,448 |
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "threads.h"
#include "Logger/Logger.h"
#include "Basics/tri-strings.h"
////////////////////////////////////////////////////////////////////////////////
/// @brief data block for thread starter
////////////////////////////////////////////////////////////////////////////////
struct thread_data_t {
void (*_starter)(void*);
void* _data;
std::string _name;
thread_data_t(void (*starter)(void*), void* data, char const* name)
: _starter(starter),
_data(data),
_name(name) {}
};
////////////////////////////////////////////////////////////////////////////////
/// @brief starter function for thread
////////////////////////////////////////////////////////////////////////////////
static DWORD __stdcall ThreadStarter(void* data) {
TRI_ASSERT(data != nullptr);
// this will automatically free the thread struct when leaving this function
std::unique_ptr<thread_data_t> d(static_cast<thread_data_t*>(data));
try {
d->_starter(d->_data);
} catch (...) {
// we must not throw from here
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief initializes a thread
////////////////////////////////////////////////////////////////////////////////
void TRI_InitThread(TRI_thread_t* thread) { *thread = 0; }
////////////////////////////////////////////////////////////////////////////////
/// @brief starts a thread
////////////////////////////////////////////////////////////////////////////////
bool TRI_StartThread(TRI_thread_t* thread, TRI_tid_t* threadId,
char const* name, void (*starter)(void*), void* data) {
std::unique_ptr<thread_data_t> d;
try {
d.reset(new thread_data_t(starter, data, name));
} catch (...) {
LOG_TOPIC(ERR, arangodb::Logger::FIXME) << "could not start thread: out of memory";
return false;
}
TRI_ASSERT(d != nullptr);
*thread = CreateThread(0, // default security attributes
0, // use default stack size
ThreadStarter, // thread function name
d.release(), // argument to thread function
0, // use default creation flags
threadId); // returns the thread identifier
if (*thread == 0) {
LOG_TOPIC(ERR, arangodb::Logger::FIXME) << "could not start thread: " << strerror(errno) << " ";
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief waits for a thread to finish
////////////////////////////////////////////////////////////////////////////////
int TRI_JoinThread(TRI_thread_t* thread) {
DWORD result = WaitForSingleObject(*thread, INFINITE);
switch (result) {
case WAIT_ABANDONED: {
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "threads-win32.c:TRI_JoinThread:could not join thread --> WAIT_ABANDONED"; FATAL_ERROR_EXIT();
}
case WAIT_OBJECT_0: {
// everything ok
break;
}
case WAIT_TIMEOUT: {
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "threads-win32.c:TRI_JoinThread:could not joint thread --> WAIT_TIMEOUT"; FATAL_ERROR_EXIT();
}
case WAIT_FAILED: {
result = GetLastError();
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "threads-win32.c:TRI_JoinThread:could not join thread --> WAIT_FAILED - reason -->" << result; FATAL_ERROR_EXIT();
}
}
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief checks if this thread is the thread passed as a parameter
////////////////////////////////////////////////////////////////////////////////
bool TRI_IsSelfThread(TRI_thread_t* thread) {
// ...........................................................................
// The GetThreadID(...) function is only available in Windows Vista or Higher
// TODO: Change the TRI_thread_t into a structure which stores the thread id
// as well as the thread handle. This can then be passed around
// ...........................................................................
return (GetCurrentThreadId() == GetThreadId(thread));
}
////////////////////////////////////////////////////////////////////////////////
/// @brief allow cancelation
////////////////////////////////////////////////////////////////////////////////
void TRI_AllowCancelation(void) {
// TODO: No native implementation of this
}
////////////////////////////////////////////////////////////////////////////////
/// @brief sets the process affinity
////////////////////////////////////////////////////////////////////////////////
void TRI_SetProcessorAffinity(TRI_thread_t* thread, size_t core) {}
| joerg84/arangodb | lib/Basics/threads-win32.cpp | C++ | apache-2.0 | 5,728 |
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.tutorial.TutorialTVScenes
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon import NPCToons, TTEmote
import random
class CEOScene(ThreeDScene):
CameraPos = [(0, 203.5, 23.5, 0, 350, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'CEOScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BanquetInterior_1')
self.geom.reparentTo(self)
self.ceo = BossCog()
dna = SuitDNA()
dna.newBossCog('c')
self.ceo.setDNA(dna)
self.ceo.reparentTo(self)
self.ceo.setPosHpr(0, 236.5, 0, 180, 0, 0)
self.ceo.loop('Bb_neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.ceo:
self.ceo.delete()
self.ceo = None
ThreeDScene.delete(self)
return
class HeadHunterScene(ThreeDScene):
CameraPos = [(-22, -12.5, 7, 92, -6, 0)]
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'HeadHunterScene', effects)
self.geom = loader.loadModel('phase_12/models/bossbotHQ/BossbotEntranceRoom')
self.geom.reparentTo(self)
self.cog = Suit()
dna = SuitDNA()
dna.newSuit('hh')
self.cog.setDNA(dna)
self.cog.reparentTo(self)
self.cog.setPosHpr(-32.5, -12.5, 0.02, 270, 0, 0)
self.cog.nametag3d.removeNode()
self.cog.nametag.destroy()
self.cog.loop('neutral')
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
if self.cog:
self.cog.delete()
self.cog = None
ThreeDScene.delete(self)
return
class ScientistScene(ThreeDScene):
CameraPos = [(-47.5, 0.5, 3.415, 90, 0, 0)]
ToonPos = {2018: (-59, -1.5, 0.02, 270, 0, 0),
2019: (-59, 0.5, 0.02, 270, 0, 0),
2020: (-59, 2.5, 0.02, 270, 0, 0)}
RandomEmotes = ['wave',
'angry',
'applause',
'cringe',
'confused',
'slip-forward',
'slip-backward',
'resistance-salute',
'surprise',
'cry',
'furious',
'laugh',
'idea',
'taunt',
'rage']
def __init__(self, effects = []):
ThreeDScene.__init__(self, 'ScientistScene', effects)
self.geom = loader.loadModel('phase_3.5/models/modules/tt_m_ara_int_toonhall')
self.geom.reparentTo(self)
self.taskStarted = False
self.npcs = []
for id, posHpr in self.ToonPos.iteritems():
npc = NPCToons.createLocalNPC(id)
npc.reparentTo(self.geom)
npc.setPosHpr(*posHpr)
npc.nametag3d.removeNode()
npc.nametag.destroy()
self.npcs.append(npc)
def delete(self):
if self.geom:
self.geom.removeNode()
self.geom = None
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
npc.delete()
self.npcs = []
self.taskStarted = False
ThreeDScene.delete(self)
return
def startTask(self):
if self.taskStarted:
return
for i, npc in enumerate(self.npcs):
taskMgr.doMethodLater(0.25 * i, lambda task, npc = npc: self.doRandomEmote(npc, task), npc.uniqueName('randomEmote'))
self.taskStarted = True
def stopTask(self):
if not self.taskStarted:
return
for npc in self.npcs:
taskMgr.remove(npc.uniqueName('randomEmote'))
self.taskStarted = False
def doRandomEmote(self, npc, task):
Emote.globalEmote.doEmote(npc, TTEmote.Emotes.index(random.choice(self.RandomEmotes)), 0)
task.delayTime = npc.emoteTrack.getDuration() + 1.0
return task.again | DedMemez/ODS-August-2017 | tutorial/TutorialTVScenes.py | Python | apache-2.0 | 4,254 |
// Copyright 2015 Square, Inc.
package retrofit.converter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.ResponseBody;
import java.io.IOException;
import java.lang.reflect.Type;
import okio.Buffer;
import org.assertj.core.api.AbstractCharSequenceAssert;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
public final class GsonConverterTest {
private Converter converter;
interface Example {
String getName();
}
class Impl implements Example {
private final String theName;
Impl(String name) {
theName = name;
}
@Override public String getName() {
return theName;
}
}
@Before public void setUp() {
Gson gson = new GsonBuilder()
.registerTypeAdapter(Example.class, new JsonSerializer<Example>() {
@Override public JsonElement serialize(Example example, Type type,
JsonSerializationContext json) {
JsonObject object = new JsonObject();
object.addProperty("name", example.getName());
return object;
}
})
.create();
converter = new GsonConverter(gson);
}
@Test public void serialization() throws IOException {
RequestBody body = converter.toBody(new Impl("value"), Impl.class);
assertBody(body).isEqualTo("{\"theName\":\"value\"}");
}
@Test public void serializationTypeUsed() throws IOException {
RequestBody body = converter.toBody(new Impl("value"), Example.class);
assertBody(body).isEqualTo("{\"name\":\"value\"}");
}
@Test public void deserialization() throws IOException {
ResponseBody body =
ResponseBody.create(MediaType.parse("text/plain"), "{\"theName\":\"value\"}");
Impl impl = (Impl) converter.fromBody(body, Impl.class);
assertEquals("value", impl.getName());
}
private static AbstractCharSequenceAssert<?, String> assertBody(RequestBody body) throws IOException {
Buffer buffer = new Buffer();
body.writeTo(buffer);
return assertThat(buffer.readUtf8());
}
}
| murat8505/REST_client_retrofit | retrofit/src/test/java/retrofit/converter/GsonConverterTest.java | Java | apache-2.0 | 2,382 |
/*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* The Apereo Foundation 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.unitime.timetable.gwt.client.rooms;
import java.util.ArrayList;
import java.util.List;
import org.unitime.timetable.gwt.client.GwtHint;
import org.unitime.timetable.gwt.client.widgets.SimpleForm;
import org.unitime.timetable.gwt.command.client.GwtRpcService;
import org.unitime.timetable.gwt.command.client.GwtRpcServiceAsync;
import org.unitime.timetable.gwt.resources.GwtMessages;
import org.unitime.timetable.gwt.shared.RoomInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomPictureInterface;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
/**
* @author Tomas Muller
*/
public class RoomHint {
private static long sLastLocationId = -1;
private static GwtRpcServiceAsync RPC = GWT.create(GwtRpcService.class);
private static final GwtMessages MESSAGES = GWT.create(GwtMessages.class);
private static boolean sShowHint = false;
private static Timer sLastSwapper = null;
public static Widget content(RoomInterface.RoomHintResponse room, String prefix, String distance) {
if (sLastSwapper != null) {
sLastSwapper.cancel(); sLastSwapper = null;
}
SimpleForm form = new SimpleForm();
form.removeStyleName("unitime-NotPrintableBottomLine");
if (prefix != null && prefix.contains("{0}")) {
String label = prefix.replace("{0}", room.getLabel());
if (prefix.contains("{1}"))
label = label.replace("{1}", room.hasDisplayName() ? room.getDisplayName() : room.hasRoomTypeLabel() ? room.getRoomTypeLabel() : "");
form.addRow(new Label(label, false));
} else {
form.addRow(new Label((prefix == null || prefix.isEmpty() ? "" : prefix + " ") + (room.hasDisplayName() || room.hasRoomTypeLabel() ? MESSAGES.label(room.getLabel(), room.hasDisplayName() ? room.getDisplayName() : room.getRoomTypeLabel()) : room.getLabel()), false));
}
List<String> urls = new ArrayList<String>();
if (room.hasMiniMapUrl()) {
urls.add(room.getMiniMapUrl());
}
if (room.hasPictures()) {
for (RoomPictureInterface picture: room.getPictures())
urls.add(GWT.getHostPageBaseURL() + "picture?id=" + picture.getUniqueId());
}
if (!urls.isEmpty()) {
Image image = new Image(urls.get(0));
image.setStyleName("minimap");
form.addRow(image);
if (urls.size() > 1) {
sLastSwapper = new ImageSwapper(image, urls);
sLastSwapper.scheduleRepeating(3000);
}
}
if (room.hasCapacity()) {
if (room.hasExamCapacity()) {
if (room.hasExamType()) {
form.addRow(MESSAGES.propRoomCapacity(), new Label(MESSAGES.capacityWithExamType(room.getCapacity().toString(), room.getExamCapacity().toString(), room.getExamType()), false));
} else {
form.addRow(MESSAGES.propRoomCapacity(), new Label(MESSAGES.capacityWithExam(room.getCapacity().toString(), room.getExamCapacity().toString()), false));
}
} else {
form.addRow(MESSAGES.propRoomCapacity(), new Label(MESSAGES.capacity(room.getCapacity().toString()), false));
}
}
if (room.hasArea())
form.addRow(MESSAGES.propRoomArea(), new HTML(room.getArea(), false));
if (room.hasFeatures())
for (String name: room.getFeatureNames())
form.addRow(name + ":", new Label(room.getFeatures(name)));
if (room.hasGroups())
form.addRow(MESSAGES.propRoomGroups(), new Label(room.getGroups()));
if (room.hasEventStatus())
form.addRow(MESSAGES.propRoomEventStatus(), new Label(room.getEventStatus()));
if (room.hasEventDepartment())
form.addRow(MESSAGES.propRoomEventDepartment(), new Label(room.getEventDepartment()));
if (room.hasBreakTime())
form.addRow(MESSAGES.propRoomBreakTime(), new Label(MESSAGES.breakTime(room.getBreakTime().toString())));
if (room.hasNote())
form.addRow(new HTML(room.getNote()));
if (room.isIgnoreRoomCheck())
form.addRow(new HTML(MESSAGES.ignoreRoomCheck()));
if (distance != null && !distance.isEmpty() && !"0".equals(distance))
form.addRow(MESSAGES.propRoomDistance(), new Label(MESSAGES.roomDistance(distance), false));
SimplePanel panel = new SimplePanel(form);
panel.setStyleName("unitime-RoomHint");
return panel;
}
/** Never use from GWT code */
public static void _showRoomHint(JavaScriptObject source, String locationId, String prefix, String distance, String note) {
showHint((Element) source.cast(), Long.valueOf(locationId), prefix, distance, note, true);
}
public static void showHint(final Element relativeObject, final long locationId, final String prefix, final String distance, final boolean showRelativeToTheObject) {
showHint(relativeObject, locationId, prefix, distance, null, showRelativeToTheObject);
}
public static void showHint(final Element relativeObject, final long locationId, final String prefix, final String distance, final String note, final boolean showRelativeToTheObject) {
sLastLocationId = locationId;
sShowHint = true;
RPC.execute(RoomInterface.RoomHintRequest.load(locationId), new AsyncCallback<RoomInterface.RoomHintResponse>() {
@Override
public void onFailure(Throwable caught) {
}
@Override
public void onSuccess(RoomInterface.RoomHintResponse result) {
if (result != null && locationId == sLastLocationId && sShowHint) {
if (note != null) result.setNote(note);
GwtHint.showHint(relativeObject, content(result, prefix, distance), showRelativeToTheObject);
}
}
});
}
public static void hideHint() {
sShowHint = false;
if (sLastSwapper != null) {
sLastSwapper.cancel(); sLastSwapper = null;
}
GwtHint.hideHint();
}
public static native void createTriggers()/*-{
$wnd.showGwtRoomHint = function(source, content, prefix, distance, note) {
@org.unitime.timetable.gwt.client.rooms.RoomHint::_showRoomHint(Lcom/google/gwt/core/client/JavaScriptObject;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)(source, content, prefix, distance, note);
};
$wnd.hideGwtRoomHint = function() {
@org.unitime.timetable.gwt.client.rooms.RoomHint::hideHint()();
};
}-*/;
private static class ImageSwapper extends Timer {
Image iImage;
List<String> iUrls;
int iIndex;
ImageSwapper(Image image, List<String> urls) {
iImage = image; iUrls = urls; iIndex = 0;
}
@Override
public void run() {
iIndex ++;
iImage.setUrl(iUrls.get(iIndex % iUrls.size()));
if (!iImage.isAttached()) cancel();
}
}
}
| zuzanamullerova/unitime | JavaSource/org/unitime/timetable/gwt/client/rooms/RoomHint.java | Java | apache-2.0 | 7,518 |
package com.hardis.connect.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hardis.connect.R;
import com.hardis.connect.adapter.FeedsFragmentAdapter;
import com.github.florent37.materialviewpager.MaterialViewPagerHelper;
import com.github.florent37.materialviewpager.adapter.RecyclerViewMaterialAdapter;
import java.util.ArrayList;
import java.util.List;
public class FeedsFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
public static FeedsFragment newInstance() {
return new FeedsFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_recyclerview, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
//permet un affichage sous forme liste verticale
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
//100 faux contenu
List<Object> mContentItems = new ArrayList<>();
for (int i = 0; i < 100; ++i)
mContentItems.add(new Object());
//penser à passer notre Adapter (ici : FeedsFragmentAdapter) à un RecyclerViewMaterialAdapter
mAdapter = new RecyclerViewMaterialAdapter(new FeedsFragmentAdapter(mContentItems));
mRecyclerView.setAdapter(mAdapter);
//notifier le MaterialViewPager qu'on va utiliser une RecyclerView
MaterialViewPagerHelper.registerRecyclerView(getActivity(), mRecyclerView, null);
}
}
| Har-insa/front-end | app/src/main/java/com/hardis/connect/fragment/FeedsFragment.java | Java | apache-2.0 | 2,144 |
package table;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class WelcomeWindow implements Runnable {
private JFrame frame;
private String fileName="image.png";
public void run() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int a=screenSize.width/2-250;
int b=screenSize.height/2-250;
frame = new JFrame("»¶ÓʹÓÃÁõÊöÇåÏÈÉú±àдµÄÈí¼þ");
frame.setBounds(a-80, b, 500, 500);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
URL base = this.getClass().getResource(fileName);
//Properties property= System.getProperties();
//String classPath=property.get("java.class.path").toString();
//String path=base.toString().substring(6).replace("Drawing/bin/table/", "").replace("le:/","").replace("drawing.jar!/table/","")+"Image/image.gif";
String path=base.getPath();
System.out.println(path);
//System.out.println("classPath is:"+classPath);
JLabel lable=new JLabel(new ImageIcon(base));
lable.setSize(500, 500);
lable.setVisible(true);
frame.add(lable, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
//JOptionPane.showMessageDialog(frame, path+"\n");
}
}
| nanchengking/Drawing | src/table/WelcomeWindow.java | Java | apache-2.0 | 1,380 |
/* Copyright 2010-2012 Alfresco Software, Ltd.
* Copyright 2012 Thorben Lindhauer
*
* Licensed under the Apache License, ersion 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.activiti.engine.impl.pvm.runtime;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmException;
import org.activiti.engine.impl.pvm.PvmExecution;
import org.activiti.engine.impl.pvm.PvmProcessDefinition;
import org.activiti.engine.impl.pvm.PvmProcessElement;
import org.activiti.engine.impl.pvm.PvmProcessInstance;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.delegate.ActivityExecution;
import org.activiti.engine.impl.pvm.delegate.ExecutionListenerExecution;
import org.activiti.engine.impl.pvm.delegate.SignallableActivityBehavior;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;
import org.activiti.engine.impl.pvm.process.TransitionImpl;
/**
* @author Tom Baeyens
* @author Joram Barrez
*/
public class ExecutionImpl implements Serializable, ActivityExecution,
ExecutionListenerExecution, PvmExecution, InterpretableExecution {
private static final long serialVersionUID = 1L;
private static Logger log = Logger.getLogger(ExecutionImpl.class.getName());
// current position
// /////////////////////////////////////////////////////////
protected ProcessDefinitionImpl processDefinition;
/** current activity */
protected ActivityImpl activity;
/** current transition. is null when there is no transition being taken. */
protected TransitionImpl transition = null;
/**
* the process instance. this is the root of the execution tree. the
* processInstance of a process instance is a self reference.
*/
protected ExecutionImpl processInstance;
/** the parent execution */
protected ExecutionImpl parent;
/** nested executions representing scopes or concurrent paths */
protected List<ExecutionImpl> executions;
/** super execution, not-null if this execution is part of a subprocess */
protected ExecutionImpl superExecution;
/**
* reference to a subprocessinstance, not-null if currently subprocess is
* started from this execution
*/
protected ExecutionImpl subProcessInstance;
/** only available until the process instance is started */
protected StartingExecution startingExecution;
// state/type of execution
// //////////////////////////////////////////////////
/**
* indicates if this execution represents an active path of execution.
* Executions are made inactive in the following situations:
* <ul>
* <li>an execution enters a nested scope</li>
* <li>an execution is split up into multiple concurrent executions, then
* the parent is made inactive.</li>
* <li>an execution has arrived in a parallel gateway or join and that join
* has not yet activated/fired.</li>
* <li>an execution is ended.</li>
* </ul>
*/
protected boolean isActive = true;
protected boolean isScope = true;
protected boolean isConcurrent = false;
protected boolean isEnded = false;
protected boolean isEventScope = false;
protected Map<String, Object> variables = null;
// events
// ///////////////////////////////////////////////////////////////////
protected String eventName;
protected PvmProcessElement eventSource;
protected int executionListenerIndex = 0;
// cascade deletion ////////////////////////////////////////////////////////
protected boolean deleteRoot;
protected String deleteReason;
// replaced by
// //////////////////////////////////////////////////////////////
/**
* when execution structure is pruned during a takeAll, then the original
* execution has to be resolved to the replaced execution.
*
* @see {@link #takeAll(List, List)} {@link OutgoingExecution}
*/
protected ExecutionImpl replacedBy;
// atomic operations
// ////////////////////////////////////////////////////////
/**
* next operation. process execution is in fact runtime interpretation of
* the process model. each operation is a logical unit of interpretation of
* the process. so sequentially processing the operations drives the
* interpretation or execution of a process.
*
* @see AtomicOperation
* @see #performOperation(AtomicOperation)
*/
protected AtomicOperation nextOperation;
protected boolean isOperating = false;
/* Default constructor for ibatis/jpa/etc. */
public ExecutionImpl() {
}
public ExecutionImpl(ActivityImpl initial) {
startingExecution = new StartingExecution(initial);
}
// lifecycle methods
// ////////////////////////////////////////////////////////
/**
* creates a new execution. properties processDefinition, processInstance
* and activity will be initialized.
*/
public ExecutionImpl createExecution() {
// create the new child execution
ExecutionImpl createdExecution = newExecution();
// manage the bidirectional parent-child relation
ensureExecutionsInitialized();
executions.add(createdExecution);
createdExecution.setParent(this);
// initialize the new execution
createdExecution.setProcessDefinition(getProcessDefinition());
createdExecution.setProcessInstance(getProcessInstance());
createdExecution.setActivity(getActivity());
return createdExecution;
}
/** instantiates a new execution. can be overridden by subclasses */
protected ExecutionImpl newExecution() {
return new ExecutionImpl();
}
public PvmProcessInstance createSubProcessInstance(
PvmProcessDefinition processDefinition) {
ExecutionImpl subProcessInstance = newExecution();
// manage bidirectional super-subprocess relation
subProcessInstance.setSuperExecution(this);
this.setSubProcessInstance(subProcessInstance);
// Initialize the new execution
subProcessInstance
.setProcessDefinition((ProcessDefinitionImpl) processDefinition);
subProcessInstance.setProcessInstance(subProcessInstance);
return subProcessInstance;
}
public void initialize() {
}
public void destroy() {
setScope(false);
}
public void remove() {
ensureParentInitialized();
if (parent != null) {
parent.ensureExecutionsInitialized();
parent.executions.remove(this);
}
// remove event scopes:
List<InterpretableExecution> childExecutions = new ArrayList<InterpretableExecution>(
getExecutions());
for (InterpretableExecution childExecution : childExecutions) {
if (childExecution.isEventScope()) {
log.fine("removing eventScope " + childExecution);
childExecution.destroy();
childExecution.remove();
}
}
}
// parent
// ///////////////////////////////////////////////////////////////////
/** ensures initialization and returns the parent */
public ExecutionImpl getParent() {
ensureParentInitialized();
return parent;
}
/**
* all updates need to go through this setter as subclasses can override
* this method
*/
public void setParent(InterpretableExecution parent) {
this.parent = (ExecutionImpl) parent;
}
/**
* must be called before memberfield parent is used. can be used by
* subclasses to provide parent member field initialization.
*/
protected void ensureParentInitialized() {
}
// executions
// ///////////////////////////////////////////////////////////////
/** ensures initialization and returns the non-null executions list */
public List<ExecutionImpl> getExecutions() {
ensureExecutionsInitialized();
return executions;
}
public ExecutionImpl getSuperExecution() {
ensureSuperExecutionInitialized();
return superExecution;
}
public void setSuperExecution(ExecutionImpl superExecution) {
this.superExecution = superExecution;
if (superExecution != null) {
superExecution.setSubProcessInstance(null);
}
}
// Meant to be overridden by persistent subclasseses
protected void ensureSuperExecutionInitialized() {
}
public ExecutionImpl getSubProcessInstance() {
ensureSubProcessInstanceInitialized();
return subProcessInstance;
}
public void setSubProcessInstance(InterpretableExecution subProcessInstance) {
this.subProcessInstance = (ExecutionImpl) subProcessInstance;
}
// Meant to be overridden by persistent subclasses
protected void ensureSubProcessInstanceInitialized() {
}
public void deleteCascade(String deleteReason) {
this.deleteReason = deleteReason;
this.deleteRoot = true;
performOperation(AtomicOperation.DELETE_CASCADE);
}
/**
* removes an execution. if there are nested executions, those will be ended
* recursively. if there is a parent, this method removes the bidirectional
* relation between parent and this execution.
*/
public void end() {
isActive = false;
isEnded = true;
performOperation(AtomicOperation.ACTIVITY_END);
}
/** searches for an execution positioned in the given activity */
public ExecutionImpl findExecution(String activityId) {
if ((getActivity() != null)
&& (getActivity().getId().equals(activityId))) {
return this;
}
for (ExecutionImpl nestedExecution : getExecutions()) {
ExecutionImpl result = nestedExecution.findExecution(activityId);
if (result != null) {
return result;
}
}
return null;
}
public List<String> findActiveActivityIds() {
List<String> activeActivityIds = new ArrayList<String>();
collectActiveActivityIds(activeActivityIds);
return activeActivityIds;
}
protected void collectActiveActivityIds(List<String> activeActivityIds) {
ensureActivityInitialized();
if (isActive && activity != null) {
activeActivityIds.add(activity.getId());
}
ensureExecutionsInitialized();
for (ExecutionImpl execution : executions) {
execution.collectActiveActivityIds(activeActivityIds);
}
}
/**
* must be called before memberfield executions is used. can be used by
* subclasses to provide executions member field initialization.
*/
protected void ensureExecutionsInitialized() {
if (executions == null) {
executions = new ArrayList<ExecutionImpl>();
}
}
// process definition
// ///////////////////////////////////////////////////////
/** ensures initialization and returns the process definition. */
public ProcessDefinitionImpl getProcessDefinition() {
ensureProcessDefinitionInitialized();
return processDefinition;
}
public String getProcessDefinitionId() {
return getProcessDefinition().getId();
}
/**
* for setting the process definition, this setter must be used as
* subclasses can override
*/
/**
* must be called before memberfield processDefinition is used. can be used
* by subclasses to provide processDefinition member field initialization.
*/
protected void ensureProcessDefinitionInitialized() {
}
// process instance
// /////////////////////////////////////////////////////////
/** ensures initialization and returns the process instance. */
public ExecutionImpl getProcessInstance() {
ensureProcessInstanceInitialized();
return processInstance;
}
public String getProcessInstanceId() {
return getProcessInstance().getId();
}
public String getBusinessKey() {
return getProcessInstance().getBusinessKey();
}
public String getProcessBusinessKey() {
return getProcessInstance().getBusinessKey();
}
/**
* for setting the process instance, this setter must be used as subclasses
* can override
*/
public void setProcessInstance(InterpretableExecution processInstance) {
this.processInstance = (ExecutionImpl) processInstance;
}
/**
* must be called before memberfield processInstance is used. can be used by
* subclasses to provide processInstance member field initialization.
*/
protected void ensureProcessInstanceInitialized() {
}
// activity
// /////////////////////////////////////////////////////////////////
/** ensures initialization and returns the activity */
public ActivityImpl getActivity() {
ensureActivityInitialized();
return activity;
}
/**
* sets the current activity. can be overridden by subclasses. doesn't
* require initialization.
*/
public void setActivity(ActivityImpl activity) {
this.activity = activity;
}
/**
* must be called before the activity member field or getActivity() is
* called
*/
protected void ensureActivityInitialized() {
}
// scopes
// ///////////////////////////////////////////////////////////////////
protected void ensureScopeInitialized() {
}
public boolean isScope() {
return isScope;
}
public void setScope(boolean isScope) {
this.isScope = isScope;
}
// process instance start implementation
// ////////////////////////////////////
public void start() {
if (startingExecution == null && isProcessInstance()) {
startingExecution = new StartingExecution(
processDefinition.getInitial());
}
performOperation(AtomicOperation.PROCESS_START);
}
// methods that translate to operations
// /////////////////////////////////////
public void signal(String signalName, Object signalData) {
ensureActivityInitialized();
SignallableActivityBehavior activityBehavior = (SignallableActivityBehavior) activity
.getActivityBehavior();
try {
activityBehavior.signal(this, signalName, signalData);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new PvmException("couldn't process signal '" + signalName
+ "' on activity '" + activity.getId() + "': "
+ e.getMessage(), e);
}
}
public void take(PvmTransition transition) {
if (this.transition != null) {
throw new PvmException("already taking a transition");
}
if (transition == null) {
throw new PvmException("transition is null");
}
setTransition((TransitionImpl) transition);
performOperation(AtomicOperation.TRANSITION_NOTIFY_LISTENER_END);
}
public void executeActivity(PvmActivity activity) {
setActivity((ActivityImpl) activity);
performOperation(AtomicOperation.ACTIVITY_START);
}
public List<ActivityExecution> findInactiveConcurrentExecutions(
PvmActivity activity) {
List<ActivityExecution> inactiveConcurrentExecutionsInActivity = new ArrayList<ActivityExecution>();
List<ActivityExecution> otherConcurrentExecutions = new ArrayList<ActivityExecution>();
if (isConcurrent()) {
List<? extends ActivityExecution> concurrentExecutions = getParent()
.getExecutions();
for (ActivityExecution concurrentExecution : concurrentExecutions) {
if (concurrentExecution.getActivity() == activity) {
if (concurrentExecution.isActive()) {
throw new PvmException(
"didn't expect active execution in " + activity
+ ". bug?");
}
inactiveConcurrentExecutionsInActivity
.add(concurrentExecution);
} else {
otherConcurrentExecutions.add(concurrentExecution);
}
}
} else {
if (!isActive()) {
inactiveConcurrentExecutionsInActivity.add(this);
} else {
otherConcurrentExecutions.add(this);
}
}
if (log.isLoggable(Level.FINE)) {
log.fine("inactive concurrent executions in '" + activity + "': "
+ inactiveConcurrentExecutionsInActivity);
log.fine("other concurrent executions: "
+ otherConcurrentExecutions);
}
return inactiveConcurrentExecutionsInActivity;
}
@SuppressWarnings("unchecked")
public void takeAll(List<PvmTransition> transitions,
List<ActivityExecution> recyclableExecutions) {
transitions = new ArrayList<PvmTransition>(transitions);
recyclableExecutions = (recyclableExecutions != null ? new ArrayList<ActivityExecution>(
recyclableExecutions) : new ArrayList<ActivityExecution>());
if (recyclableExecutions.size() > 1) {
for (ActivityExecution recyclableExecution : recyclableExecutions) {
if (((ExecutionImpl) recyclableExecution).isScope()) {
throw new PvmException(
"joining scope executions is not allowed");
}
}
}
ExecutionImpl concurrentRoot = ((isConcurrent && !isScope) ? getParent()
: this);
List<ExecutionImpl> concurrentActiveExecutions = new ArrayList<ExecutionImpl>();
for (ExecutionImpl execution : concurrentRoot.getExecutions()) {
if (execution.isActive()) {
concurrentActiveExecutions.add(execution);
}
}
if (log.isLoggable(Level.FINE)) {
log.fine("transitions to take concurrent: " + transitions);
log.fine("active concurrent executions: "
+ concurrentActiveExecutions);
}
if ((transitions.size() == 1) && (concurrentActiveExecutions.isEmpty())) {
List<ExecutionImpl> recyclableExecutionImpls = (List) recyclableExecutions;
for (ExecutionImpl prunedExecution : recyclableExecutionImpls) {
// End the pruned executions if necessary.
// Some recyclable executions are inactivated (joined
// executions)
// Others are already ended (end activities)
if (!prunedExecution.isEnded()) {
log.fine("pruning execution " + prunedExecution);
prunedExecution.remove();
}
}
log.fine("activating the concurrent root " + concurrentRoot
+ " as the single path of execution going forward");
concurrentRoot.setActive(true);
concurrentRoot.setActivity(activity);
concurrentRoot.setConcurrent(false);
concurrentRoot.take(transitions.get(0));
} else {
List<OutgoingExecution> outgoingExecutions = new ArrayList<OutgoingExecution>();
recyclableExecutions.remove(concurrentRoot);
log.fine("recyclable executions for reused: "
+ recyclableExecutions);
// first create the concurrent executions
while (!transitions.isEmpty()) {
PvmTransition outgoingTransition = transitions.remove(0);
ExecutionImpl outgoingExecution = null;
if (recyclableExecutions.isEmpty()) {
outgoingExecution = concurrentRoot.createExecution();
log.fine("new " + outgoingExecution
+ " created to take transition "
+ outgoingTransition);
} else {
outgoingExecution = (ExecutionImpl) recyclableExecutions
.remove(0);
log.fine("recycled " + outgoingExecution
+ " to take transition " + outgoingTransition);
}
outgoingExecution.setActive(true);
outgoingExecution.setScope(false);
outgoingExecution.setConcurrent(true);
outgoingExecutions.add(new OutgoingExecution(outgoingExecution,
outgoingTransition, true));
}
// prune the executions that are not recycled
for (ActivityExecution prunedExecution : recyclableExecutions) {
log.fine("pruning execution " + prunedExecution);
prunedExecution.end();
}
// then launch all the concurrent executions
for (OutgoingExecution outgoingExecution : outgoingExecutions) {
outgoingExecution.take();
}
}
}
public void performOperation(AtomicOperation executionOperation) {
this.nextOperation = executionOperation;
if (!isOperating) {
isOperating = true;
while (nextOperation != null) {
AtomicOperation currentOperation = this.nextOperation;
this.nextOperation = null;
if (log.isLoggable(Level.FINEST)) {
log.finest("AtomicOperation: " + currentOperation + " on "
+ this);
}
currentOperation.execute(this);
}
isOperating = false;
}
}
public boolean isActive(String activityId) {
return findExecution(activityId) != null;
}
// variables
// ////////////////////////////////////////////////////////////////
public Object getVariable(String variableName) {
ensureVariablesInitialized();
// If value is found in this scope, return it
if (variables.containsKey(variableName)) {
return variables.get(variableName);
}
// If value not found in this scope, check the parent scope
ensureParentInitialized();
if (parent != null) {
return parent.getVariable(variableName);
}
// Variable is nowhere to be found
return null;
}
public Map<String, Object> getVariables() {
Map<String, Object> collectedVariables = new HashMap<String, Object>();
collectVariables(collectedVariables);
return collectedVariables;
}
protected void collectVariables(Map<String, Object> collectedVariables) {
ensureParentInitialized();
if (parent != null) {
parent.collectVariables(collectedVariables);
}
ensureVariablesInitialized();
for (String variableName : variables.keySet()) {
collectedVariables.put(variableName, variables.get(variableName));
}
}
public void setVariables(Map<String, ? extends Object> variables) {
ensureVariablesInitialized();
if (variables != null) {
for (String variableName : variables.keySet()) {
setVariable(variableName, variables.get(variableName));
}
}
}
public void setVariable(String variableName, Object value) {
ensureVariablesInitialized();
if (variables.containsKey(variableName)) {
setVariableLocally(variableName, value);
} else {
ensureParentInitialized();
if (parent != null) {
parent.setVariable(variableName, value);
} else {
setVariableLocally(variableName, value);
}
}
}
public void setVariableLocally(String variableName, Object value) {
log.fine("setting variable '" + variableName + "' to value '" + value
+ "' on " + this);
variables.put(variableName, value);
}
public boolean hasVariable(String variableName) {
ensureVariablesInitialized();
if (variables.containsKey(variableName)) {
return true;
}
ensureParentInitialized();
if (parent != null) {
return parent.hasVariable(variableName);
}
return false;
}
protected void ensureVariablesInitialized() {
if (variables == null) {
variables = new HashMap<String, Object>();
}
}
// toString
// /////////////////////////////////////////////////////////////////
public String toString() {
if (isProcessInstance()) {
return "ProcessInstance[" + getToStringIdentity() + "]";
} else {
return (isEventScope ? "EventScope" : "")
+ (isConcurrent ? "Concurrent" : "")
+ (isScope() ? "Scope" : "") + "Execution["
+ getToStringIdentity() + "]";
}
}
protected String getToStringIdentity() {
return Integer.toString(System.identityHashCode(this));
}
// customized getters and setters
// ///////////////////////////////////////////
public boolean isProcessInstance() {
ensureParentInitialized();
return parent == null;
}
public void inactivate() {
this.isActive = false;
}
// allow for subclasses to expose a real id
// /////////////////////////////////
public String getId() {
return null;
}
// getters and setters
// //////////////////////////////////////////////////////
public TransitionImpl getTransition() {
return transition;
}
public void setTransition(TransitionImpl transition) {
this.transition = transition;
}
public Integer getExecutionListenerIndex() {
return executionListenerIndex;
}
public void setExecutionListenerIndex(Integer executionListenerIndex) {
this.executionListenerIndex = executionListenerIndex;
}
public boolean isConcurrent() {
return isConcurrent;
}
public void setConcurrent(boolean isConcurrent) {
this.isConcurrent = isConcurrent;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
public boolean isEnded() {
return isEnded;
}
public void setProcessDefinition(ProcessDefinitionImpl processDefinition) {
this.processDefinition = processDefinition;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public PvmProcessElement getEventSource() {
return eventSource;
}
public void setEventSource(PvmProcessElement eventSource) {
this.eventSource = eventSource;
}
public String getDeleteReason() {
return deleteReason;
}
public void setDeleteReason(String deleteReason) {
this.deleteReason = deleteReason;
}
public ExecutionImpl getReplacedBy() {
return replacedBy;
}
public void setReplacedBy(InterpretableExecution replacedBy) {
this.replacedBy = (ExecutionImpl) replacedBy;
}
public void setExecutions(List<ExecutionImpl> executions) {
this.executions = executions;
}
public boolean isDeleteRoot() {
return deleteRoot;
}
public void createVariableLocal(String variableName, Object value) {
}
public void createVariablesLocal(Map<String, ? extends Object> variables) {
}
public Object getVariableLocal(Object variableName) {
return null;
}
public Set<String> getVariableNames() {
return null;
}
public Set<String> getVariableNamesLocal() {
return null;
}
public Map<String, Object> getVariablesLocal() {
return null;
}
public boolean hasVariableLocal(String variableName) {
return false;
}
public boolean hasVariables() {
return false;
}
public boolean hasVariablesLocal() {
return false;
}
public void removeVariable(String variableName) {
}
public void removeVariableLocal(String variableName) {
}
public void removeVariables() {
}
public void removeVariablesLocal() {
}
public Object setVariableLocal(String variableName, Object value) {
return null;
}
public void setVariablesLocal(Map<String, ? extends Object> variables) {
}
public boolean isEventScope() {
return isEventScope;
}
public void setEventScope(boolean isEventScope) {
this.isEventScope = isEventScope;
}
public StartingExecution getStartingExecution() {
return startingExecution;
}
public void disposeStartingExecution() {
startingExecution = null;
}
}
| ThorbenLindhauer/activiti-engine-ppi | modules/activiti-engine/src/main/java/org/activiti/engine/impl/pvm/runtime/ExecutionImpl.java | Java | apache-2.0 | 25,877 |
import cs50
import sys
def main():
if len(sys.argv) != 2:
print("You should provide cmd line arguments!")
exit(1)
#if sys.argv[1].isalpha() == False:
#print("You should provide valid key!")
#exit(1)
kplainText = int(sys.argv[1])
cipher = []
plainText = cs50.get_string()
for symbol in plainText:
if symbol.isalpha():
cipher.append(caesar(symbol, kplainText))
else:
cipher.append(symbol)
print("".join(cipher))
exit(0)
def caesar(char, kplainText):
if char.isupper():
return chr(((ord(char) - 65 + kplainText) % 26) + 65)
else:
return chr(((ord(char) - 97 + kplainText) % 26) + 97)
if __name__ == "__main__":
main()
# #include <ctype.h>
# #include <string.h>
# #include <cs50.h>
# #include <stdio.h>
# #include <stdlib.h>
# //define my caesarCipher
# void caesarCipher(char* plainText,int key);
# def int main(int argc, char* argv[]): # //{//????????????????/char*
# if argc is not 2:
# # {
# print("Usage: ./caesar k\n")
# #return 1
# #}
# #//printf(" %s\n", argv[1]);
# int key = atoi(sys.argv[1])
# char plainText[101]
# print("plaintext: ")#;//ask user
# fgets(plainText, sizeof(plainText), stdin);//get user input & store it in planText var++++++++
# print("ciphertext: ")#;//print the ciphered text
# caesarCipher(plainText,key)
# //system(pause);//connect out if not use wind---------------------------???????????????
# # return 0;
# #}
# void caesarCipher(char* plainText, int key){//key pomen mestami on first plaiiiiiiiiiin
# int i = 0
# char cipher
# int cipherValue
# while plainText[i] != '\0' and strlen(plainText) -1 > i :break#// for(int i=1,len=strlen(name);i<len;i++)
# if isalpha(plainText[i]) and islower(plainText[i]):
# cipherValue = ((int)((plainText[i]) - 97 + key) % 26 + 97)
# cipher = (char)(cipherValue);printf("%c", cipher)
# i++
# else:
# if isalpha(plainText[i]) and isupper(plainText[i]):# // if isaph char
# cipherValue = ((int)(plainText[i] - 65 + key) % 26 + 65)
# cipher = (char)(cipherValue)
# print("%c", cipher)
# i++
# else: #//if not isaplha low or up
# print("%c", plainText[i])
# i++
# print("\n")
#} | DInnaD/CS50 | pset6/caesar.py | Python | apache-2.0 | 2,532 |
/**
* @license
* Copyright Color-Coding Studio. All Rights Reserved.
*
* Use of this source code is governed by an Apache License, Version 2.0
* that can be found in the LICENSE file at http://www.apache.org/licenses/LICENSE-2.0
*/
namespace sap {
export namespace extension {
export namespace m {
/**
* 对象项目
*/
sap.m.ObjectListItem.extend("sap.extension.m.ObjectListItem", {
metadata: {
properties: {
},
events: {}
},
renderer: {
},
});
/**
* 数据对象项目
*/
ObjectListItem.extend("sap.extension.m.DataObjectListItem", {
metadata: {
properties: {
/** 数据信息 */
dataInfo: { type: "any" },
/** 用户字段模式 */
userFieldsMode: { type: "string" },
/** 属性过滤器 */
propertyFilter: { type: "function" },
},
events: {}
},
renderer: {
},
/**
* 获取数据信息
*/
getDataInfo(this: DataObjectListItem): { code: string, name?: string } | string | Function | shell.bo.IBizObjectInfo {
return this.getProperty("dataInfo");
},
/**
* 设置数据信息
* @param value 数据信息
*/
setDataInfo(this: DataObjectListItem, value: { code: string, name?: string } | string | Function | shell.bo.IBizObjectInfo): DataObjectListItem {
return this.setProperty("dataInfo", value);
},
/** 重构设置 */
applySettings(this: DataObjectListItem, mSettings: any, oScope?: any): DataObjectListItem {
if (ibas.objects.isNull(mSettings.userFieldsMode)) {
mSettings.userFieldsMode = "attribute";
}
ObjectListItem.prototype.applySettings.apply(this, arguments);
// 设置其他属性
let dataInfo: any = this.getDataInfo();
if (typeof dataInfo === "string") {
dataInfo = {
code: dataInfo,
};
} else if (typeof dataInfo === "function") {
dataInfo = {
code: dataInfo.BUSINESS_OBJECT_CODE,
name: ibas.objects.nameOf(dataInfo),
};
}
if (typeof dataInfo === "object"
&& (!ibas.strings.isEmpty(this.getUserFieldsMode()) && !ibas.strings.equalsIgnoreCase(this.getUserFieldsMode(), "none"))) {
if (dataInfo.properties instanceof Array) {
propertyControls.call(this, dataInfo);
} else {
let info: { code: string, name?: string } = dataInfo;
let boRepository: shell.bo.IBORepositoryShell = ibas.boFactory.create(shell.bo.BO_REPOSITORY_SHELL);
boRepository.fetchBizObjectInfo({
user: ibas.variablesManager.getValue(ibas.VARIABLE_NAME_USER_CODE),
boCode: ibas.config.applyVariables(info.code),
boName: info.name,
onCompleted: (opRslt) => {
if (opRslt.resultCode !== 0) {
ibas.logger.log(new Error(opRslt.message));
} else {
propertyControls.call(this, opRslt.resultObjects.firstOrDefault());
}
}
});
}
}
return this;
},
init(this: DataObjectListItem): void {
(<any>ObjectListItem.prototype).init.apply(this, arguments);
this.attachModelContextChange(undefined, function (event: sap.ui.base.Event): void {
let source: any = event.getSource();
if (source instanceof ObjectListItem) {
let content: any = source.getBindingContext();
if (content instanceof sap.ui.model.Context) {
let data: any = content.getObject();
if (!ibas.objects.isNull(data)) {
let userFields: ibas.IUserFields = data.userFields;
if (!ibas.objects.isNull(userFields)) {
for (let item of source.getAttributes()) {
let bindingInfo: any = managedobjects.bindingInfo(item, "bindingValue");
if (!ibas.objects.isNull(bindingInfo)) {
userfields.check(userFields, bindingInfo);
}
}
}
}
}
}
});
}
});
function propertyControls(this: DataObjectListItem, boInfo: shell.bo.IBizObjectInfo): void {
if (!boInfo || !(boInfo.properties instanceof Array)) {
return;
}
let properties: shell.bo.IBizPropertyInfo[] = Object.assign([], boInfo.properties);
for (let item of this.getAttributes()) {
let bindingPath: string = managedobjects.bindingPath(item);
let index: number = properties.findIndex(c => c && ibas.strings.equalsIgnoreCase(c.name, bindingPath));
if (index < 0) {
return;
}
let propertyInfo: shell.bo.IBizPropertyInfo = properties[index];
if (!ibas.objects.isNull(propertyInfo)) {
if (propertyInfo.authorised === ibas.emAuthoriseType.NONE) {
this.removeAttribute(item);
continue;
}
// 修正位置
if (propertyInfo.position > 0) {
let index: number = this.indexOfAttribute(item);
let position: number = propertyInfo.position - 1;
if (position < index) {
this.removeAttribute(item);
this.insertAttribute(item, position);
} else if (position > index) {
this.removeAttribute(item);
this.insertAttribute(item, position - 1);
}
}
properties[index] = null;
}
}
if (this.getUserFieldsMode() === "attribute") {
for (let property of properties) {
if (ibas.objects.isNull(property)) {
continue;
}
if (ibas.objects.isNull(property.authorised)) {
continue;
}
if (property.authorised === ibas.emAuthoriseType.NONE) {
continue;
}
property = factories.newProperty(property, boInfo);
let element: any = factories.newComponent(property, "Object");
if (property.systemed === true && element instanceof sap.m.ObjectAttribute) {
element.setTitle(ibas.i18n.prop(ibas.strings.format("bo_{0}_{1}", boInfo.name, property.name).toLowerCase()));
}
let content: any = this.getBindingContext();
if (content instanceof sap.ui.model.Context) {
let data: any = content.getObject();
if (!ibas.objects.isNull(data)) {
let userFields: ibas.IUserFields = data.userFields;
if (!ibas.objects.isNull(userFields)) {
let bindingInfo: any = managedobjects.bindingInfo(element, "bindingValue");
if (!ibas.objects.isNull(bindingInfo)) {
userfields.check(userFields, bindingInfo);
}
}
}
}
if (property.position > 0) {
this.insertAttribute(element, property.position);
} else {
this.addAttribute(element);
}
}
}
}
}
}
}
| color-coding/ibas-typescript | openui5/extensions/components/ObjectListItem.ts | TypeScript | apache-2.0 | 9,676 |
/*
* Copyright 2015-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.marsbits.restfbmessenger.sample;
import static java.lang.String.format;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import org.springframework.stereotype.Component;
import com.github.marsbits.restfbmessenger.Messenger;
import com.github.marsbits.restfbmessenger.webhook.AbstractCallbackHandler;
import com.restfb.types.send.IdMessageRecipient;
import com.restfb.types.send.MediaAttachment;
import com.restfb.types.webhook.messaging.CoordinatesItem;
import com.restfb.types.webhook.messaging.MessageItem;
import com.restfb.types.webhook.messaging.MessagingAttachment;
import com.restfb.types.webhook.messaging.MessagingItem;
/**
* The Echo {@code CallbackHandler}.
*
* @author Marcel Overdijk
*/
@Component
public class EchoCallbackHandler extends AbstractCallbackHandler {
private static final Logger logger = Logger.getLogger(EchoCallbackHandler.class.getName());
@Override
public void onMessage(Messenger messenger, MessagingItem messaging) {
String senderId = messaging.getSender().getId();
MessageItem message = messaging.getMessage();
logger.fine(format("Message received from %s: %s", senderId, message.getText()));
IdMessageRecipient recipient = new IdMessageRecipient(senderId);
messenger.send().markSeen(recipient);
messenger.send().typingOn(recipient);
sleep(TimeUnit.SECONDS, 1);
if (message.getText() != null) {
// Echo the received text message
messenger.send().textMessage(recipient, format("Echo: %s", message.getText()));
} else {
if (message.getAttachments() != null) {
for (MessagingAttachment attachment : message.getAttachments()) {
String type = attachment.getType();
if ("location".equals(type)) {
// Echo the received location as text message(s)
CoordinatesItem coordinates = attachment.getPayload().getCoordinates();
Double lat = coordinates.getLat();
Double longVal = coordinates.getLongVal();
messenger.send().textMessage(recipient, format("Lat: %s", lat));
messenger.send().textMessage(recipient, format("Long: %s", longVal));
} else {
// Echo the attachment
String url = attachment.getPayload().getUrl();
messenger.send().attachment(recipient,
MediaAttachment.Type.valueOf(type.toUpperCase()), url);
}
}
}
}
messenger.send().typingOff(recipient);
}
private void sleep(TimeUnit timeUnit, long duration) {
try {
timeUnit.sleep(duration);
} catch (InterruptedException ignore) {
}
}
}
| marsbits/restfbmessenger | samples/restfbmessenger-echo-spring-boot/src/main/java/com/github/marsbits/restfbmessenger/sample/EchoCallbackHandler.java | Java | apache-2.0 | 3,553 |
// Copyright 2018 The Periph Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.
// Package jtag will eventually define the API to communicate with devices over
// the JTAG protocol.
//
// See https://en.wikipedia.org/wiki/JTAG for background information.
package jtag
| google/periph | conn/jtag/jtag.go | GO | apache-2.0 | 367 |
package org.altbeacon.bluetooth;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
*
* This class provides relief for Android Bug 67272. This bug in the Bluedroid stack causes crashes
* in Android's BluetoothService when scanning for BLE devices encounters a large number of unique
* devices. It is rare for most users but can be problematic for those with apps scanning for
* Bluetooth LE devices in the background (e.g. beacon-enabled apps), especially when these users
* are around Bluetooth LE devices that randomize their mac address like Gimbal beacons.
*
* This class can both recover from crashes and prevent crashes from happening in the first place
*
* More details on the bug can be found at the following URLs:
*
* https://code.google.com/p/android/issues/detail?id=67272
* https://github.com/RadiusNetworks/android-ibeacon-service/issues/16
*
* Version 1.0
*
* Created by dyoung on 3/24/14.
*/
@TargetApi(5)
public class BluetoothCrashResolver {
private static final String TAG = "BluetoothCrashResolver";
private static final boolean PREEMPTIVE_ACTION_ENABLED = true;
private boolean debugEnabled = false;
/**
* This is not the same file that bluedroid uses. This is just to maintain state of this module
*/
private static final String DISTINCT_BLUETOOTH_ADDRESSES_FILE = "BluetoothCrashResolverState.txt";
private boolean recoveryInProgress = false;
private boolean discoveryStartConfirmed = false;
private long lastBluetoothOffTime = 0l;
private long lastBluetoothTurningOnTime = 0l;
private long lastBluetoothCrashDetectionTime = 0l;
private int detectedCrashCount = 0;
private int recoveryAttemptCount = 0;
private boolean lastRecoverySucceeded = false;
private long lastStateSaveTime = 0l;
private static final long MIN_TIME_BETWEEN_STATE_SAVES_MILLIS = 60000l;
private Context context = null;
private UpdateNotifier updateNotifier;
private Set<String> distinctBluetoothAddresses = new HashSet<String>();
private DiscoveryCanceller discoveryCanceller = new DiscoveryCanceller();
/**
// It is very likely a crash if Bluetooth turns off and comes
// back on in an extremely short interval. Testing on a Nexus 4 shows
// that when the BluetoothService crashes, the time between the STATE_OFF
// and the STATE_TURNING_ON ranges from 0ms-684ms
// Out of 3614 samples:
// 99.4% (3593) < 600 ms
// 84.7% (3060) < 500 ms
// So we will assume any power off sequence of < 600ms to be a crash
//
// While it is possible to manually turn bluetooth off then back on in
// about 600ms, but it is pretty hard to do.
//
*/
private static final long SUSPICIOUSLY_SHORT_BLUETOOTH_OFF_INTERVAL_MILLIS = 600l;
/**
* The Bluedroid stack can only track only 1990 unique Bluetooth mac addresses without crashing
*/
private static final int BLUEDROID_MAX_BLUETOOTH_MAC_COUNT = 1990;
/**
* The discovery process will pare back the mac address list to 256, but more may
* be found in the time we let the discovery process run, depending hon how many BLE
* devices are around.
*/
private static final int BLUEDROID_POST_DISCOVERY_ESTIMATED_BLUETOOTH_MAC_COUNT = 400;
/**
* It takes a little over 2 seconds after discovery is started before the pared-down mac file
* is written to persistent storage. We let discovery run for a few more seconds just to be
* sure.
*/
private static final int TIME_TO_LET_DISCOVERY_RUN_MILLIS = 5000; /* if 0, it means forever */
/**
* Constructor should be called only once per long-running process that does Bluetooth LE
* scanning. Must call start() to make it do anything.
*
* @param context the Activity or Service that is doing the Bluetooth scanning
*/
public BluetoothCrashResolver(Context context) {
this.context = context.getApplicationContext();
if (isDebugEnabled()) Log.d(TAG, "constructed");
loadState();
}
/**
* Starts looking for crashes of the Bluetooth LE system and taking proactive steps to stop
* crashes from happening. Proactive steps require calls to notifyScannedDevice(Device device)
* so that crashes can be predicted ahead of time.
*/
public void start() {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
context.registerReceiver(receiver, filter);
if (isDebugEnabled()) Log.d(TAG, "started listening for BluetoothAdapter events");
}
/**
* Stops looking for crashes. Does not need to be called in normal operations, but may be
* useful for testing.
*/
public void stop() {
context.unregisterReceiver(receiver);
if (isDebugEnabled()) Log.d(TAG, "stopped listening for BluetoothAdapter events");
saveState();
}
/**
* Enable debug logging. By default no debug lines are logged.
*/
public void enableDebug() {
debugEnabled = true;
}
/**
* Disable debug logging
*/
public void disableDebug() {
debugEnabled = false;
}
/**
* Call this method from your BluetoothAdapter.LeScanCallback method.
* Doing so is optional, but if you do, this class will be able to count the number of
* disctinct bluetooth devices scanned, and prevent crashes before they happen.
*
* This works very well if the app containing this class is the only one running bluetooth
* LE scans on the device, or it is constantly doing scans (e.g. is in the foreground for
* extended periods of time.)
*
* This will not work well if the application using this class is only scanning periodically
* (e.g. when in the background to save battery) and another application is also scanning on
* the same device, because this class will only get the counts from this application.
*
* Future augmentation of this class may improve this by somehow centralizing the list of
* unique scanned devices.
*
* @param device
*/
@TargetApi(18)
public void notifyScannedDevice(BluetoothDevice device, BluetoothAdapter.LeScanCallback scanner) {
int oldSize = 0, newSize = 0;
if (isDebugEnabled()) oldSize = distinctBluetoothAddresses.size();
synchronized(distinctBluetoothAddresses) {
distinctBluetoothAddresses.add(device.getAddress());
}
if (isDebugEnabled()) {
newSize = distinctBluetoothAddresses.size();
if (oldSize != newSize && newSize % 100 == 0) {
if (isDebugEnabled()) Log.d(TAG, "Distinct bluetooth devices seen: "+distinctBluetoothAddresses.size());
}
}
if (distinctBluetoothAddresses.size() > getCrashRiskDeviceCount()) {
if (PREEMPTIVE_ACTION_ENABLED && !recoveryInProgress) {
Log.w(TAG, "Large number of bluetooth devices detected: "+distinctBluetoothAddresses.size()+" Proactively attempting to clear out address list to prevent a crash");
Log.w(TAG, "Stopping LE Scan");
BluetoothAdapter.getDefaultAdapter().stopLeScan(scanner);
startRecovery();
processStateChange();
}
}
}
public void crashDetected() {
if (android.os.Build.VERSION.SDK_INT < 18) {
if (isDebugEnabled()) Log.d(TAG, "Ignoring crashes before SDK 18, because BLE is unsupported.");
return;
}
Log.w(TAG, "BluetoothService crash detected");
if (distinctBluetoothAddresses.size() > 0) {
if (isDebugEnabled()) Log.d(TAG, "Distinct bluetooth devices seen at crash: "+distinctBluetoothAddresses.size());
}
long nowTimestamp = new Date().getTime();
lastBluetoothCrashDetectionTime = nowTimestamp;
detectedCrashCount++;
if (recoveryInProgress) {
if (isDebugEnabled()) Log.d(TAG, "Ignoring bluetooth crash because recovery is already in progress.");
}
else {
startRecovery();
}
processStateChange();
}
public long getLastBluetoothCrashDetectionTime() {
return lastBluetoothCrashDetectionTime;
}
public int getDetectedCrashCount() {
return detectedCrashCount;
}
public int getRecoveryAttemptCount() {
return recoveryAttemptCount;
}
public boolean isLastRecoverySucceeded() {
return lastRecoverySucceeded;
}
public boolean isRecoveryInProgress() { return recoveryInProgress; }
public interface UpdateNotifier {
public void dataUpdated();
}
public void setUpdateNotifier(UpdateNotifier updateNotifier) {
this.updateNotifier = updateNotifier;
}
/**
Used to force a recovery operation
*/
public void forceFlush() {
startRecovery();
processStateChange();
}
private boolean isDebugEnabled() {
return debugEnabled;
}
private int getCrashRiskDeviceCount() {
// 1990 distinct devices tracked by Bluedroid will cause a crash. But we don't know how many
// devices bluedroid is tracking, we only know how many we have seen, which will be smaller
// than the number tracked by bluedroid because the number we track does not include its
// initial state. We therefore assume that there are some devices being tracked by bluedroid
// after a recovery operation or on startup
return BLUEDROID_MAX_BLUETOOTH_MAC_COUNT-BLUEDROID_POST_DISCOVERY_ESTIMATED_BLUETOOTH_MAC_COUNT;
}
private void processStateChange() {
if (updateNotifier != null) {
updateNotifier.dataUpdated();
}
if (new Date().getTime() - lastStateSaveTime > MIN_TIME_BETWEEN_STATE_SAVES_MILLIS) {
saveState();
}
}
@TargetApi(17)
private void startRecovery() {
// The discovery operation will start by clearing out the bluetooth mac list to only the 256
// most recently seen BLE mac addresses.
recoveryAttemptCount++;
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (isDebugEnabled()) Log.d(TAG, "about to check if discovery is active");
if (!adapter.isDiscovering()) {
Log.w(TAG, "Recovery attempt started");
recoveryInProgress = true;
discoveryStartConfirmed = false;
if (isDebugEnabled()) Log.d(TAG, "about to command discovery");
if (!adapter.startDiscovery()) {
Log.w(TAG, "Can't start discovery. Is bluetooth turned on?");
}
if (isDebugEnabled()) Log.d(TAG, "startDiscovery commanded. isDiscovering()="+adapter.isDiscovering());
// We don't actually need to do a discovery -- we just need to kick one off so the
// mac list will be pared back to 256. Because discovery is an expensive operation in
// terms of battery, we will cancel it.
if (TIME_TO_LET_DISCOVERY_RUN_MILLIS > 0 ) {
if (isDebugEnabled()) Log.d(TAG, "We will be cancelling this discovery in "+TIME_TO_LET_DISCOVERY_RUN_MILLIS+" milliseconds.");
discoveryCanceller.doInBackground();
}
else {
Log.d(TAG, "We will let this discovery run its course.");
}
}
else {
Log.w(TAG, "Already discovering. Recovery attempt abandoned.");
}
}
private void finishRecovery() {
Log.w(TAG, "Recovery attempt finished");
synchronized(distinctBluetoothAddresses) {
distinctBluetoothAddresses.clear();
}
recoveryInProgress = false;
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
if (recoveryInProgress) {
if (isDebugEnabled()) Log.d(TAG, "Bluetooth discovery finished");
finishRecovery();
}
else {
if (isDebugEnabled()) Log.d(TAG, "Bluetooth discovery finished (external)");
}
}
if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
if (recoveryInProgress) {
discoveryStartConfirmed = true;
if (isDebugEnabled()) Log.d(TAG, "Bluetooth discovery started");
}
else {
if (isDebugEnabled()) Log.d(TAG, "Bluetooth discovery started (external)");
}
}
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.ERROR:
if (isDebugEnabled()) Log.d(TAG, "Bluetooth state is ERROR");
break;
case BluetoothAdapter.STATE_OFF:
if (isDebugEnabled()) Log.d(TAG, "Bluetooth state is OFF");
lastBluetoothOffTime = new Date().getTime();
break;
case BluetoothAdapter.STATE_TURNING_OFF:
break;
case BluetoothAdapter.STATE_ON:
if (isDebugEnabled()) Log.d(TAG, "Bluetooth state is ON");
if (isDebugEnabled()) Log.d(TAG, "Bluetooth was turned off for "+(lastBluetoothTurningOnTime - lastBluetoothOffTime)+" milliseconds");
if (lastBluetoothTurningOnTime - lastBluetoothOffTime < SUSPICIOUSLY_SHORT_BLUETOOTH_OFF_INTERVAL_MILLIS) {
crashDetected();
}
break;
case BluetoothAdapter.STATE_TURNING_ON:
lastBluetoothTurningOnTime = new Date().getTime();
if (isDebugEnabled()) Log.d(TAG, "Bluetooth state is TURNING_ON");
break;
}
}
}
};
private void saveState() {
FileOutputStream outputStream = null;
OutputStreamWriter writer = null;
lastStateSaveTime = new Date().getTime();
try {
outputStream = context.openFileOutput(DISTINCT_BLUETOOTH_ADDRESSES_FILE, Context.MODE_PRIVATE);
writer = new OutputStreamWriter(outputStream);
writer.write(lastBluetoothCrashDetectionTime+"\n");
writer.write(detectedCrashCount+"\n");
writer.write(recoveryAttemptCount+"\n");
writer.write(lastRecoverySucceeded ? "1\n" : "0\n");
synchronized (distinctBluetoothAddresses) {
for (String mac : distinctBluetoothAddresses) {
writer.write(mac);
writer.write("\n");
}
}
} catch (IOException e) {
Log.w(TAG, "Can't write macs to "+DISTINCT_BLUETOOTH_ADDRESSES_FILE);
}
finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e1) { }
}
}
if (isDebugEnabled()) Log.d(TAG, "Wrote "+distinctBluetoothAddresses.size()+" bluetooth addresses");
}
private void loadState() {
FileInputStream inputStream = null;
BufferedReader reader = null;
try {
inputStream = context.openFileInput(DISTINCT_BLUETOOTH_ADDRESSES_FILE);
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
line = reader.readLine();
if (line != null) {
lastBluetoothCrashDetectionTime = Long.parseLong(line);
}
line = reader.readLine();
if (line != null) {
detectedCrashCount = Integer.parseInt(line);
}
line = reader.readLine();
if (line != null) {
recoveryAttemptCount = Integer.parseInt(line);
}
line = reader.readLine();
if (line != null) {
lastRecoverySucceeded = false;
if (line.equals("1")) {
lastRecoverySucceeded = true;
}
}
String mac;
while ((mac = reader.readLine()) != null) {
distinctBluetoothAddresses.add(mac);
}
} catch (IOException e) {
Log.w(TAG, "Can't read macs from "+DISTINCT_BLUETOOTH_ADDRESSES_FILE);
} catch (NumberFormatException e) {
Log.w(TAG, "Can't parse file "+DISTINCT_BLUETOOTH_ADDRESSES_FILE);
}
finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) { }
}
}
if (isDebugEnabled()) Log.d(TAG, "Read "+distinctBluetoothAddresses.size()+" bluetooth addresses");
}
private class DiscoveryCanceller extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(TIME_TO_LET_DISCOVERY_RUN_MILLIS);
if (!discoveryStartConfirmed) {
Log.w(TAG, "BluetoothAdapter.ACTION_DISCOVERY_STARTED never received. Recovery may fail.");
}
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter.isDiscovering()) {
if (isDebugEnabled()) Log.d(TAG, "Cancelling discovery");
adapter.cancelDiscovery();
}
else {
if (isDebugEnabled()) Log.d(TAG, "Discovery not running. Won't cancel it");
}
} catch (InterruptedException e) {
if (isDebugEnabled()) Log.d(TAG, "DiscoveryCanceller sleep interrupted.");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
}
| yangjae/android-beacon-library | src/main/java/org/altbeacon/bluetooth/BluetoothCrashResolver.java | Java | apache-2.0 | 19,332 |
package org.apache.lucene.spatial.query;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.shape.Point;
import com.spatial4j.core.shape.Rectangle;
import com.spatial4j.core.shape.Shape;
/**
* Principally holds the query {@link Shape} and the {@link SpatialOperation}.
* It's used as an argument to some methods on {@link org.apache.lucene.spatial.SpatialStrategy}.
*
* @lucene.experimental
*/
public class SpatialArgs {
public static final double DEFAULT_DISTERRPCT = 0.025d;
private SpatialOperation operation;
private Shape shape;
private Double distErrPct;
private Double distErr;
public SpatialArgs(SpatialOperation operation, Shape shape) {
if (operation == null || shape == null)
throw new NullPointerException("operation and shape are required");
this.operation = operation;
this.shape = shape;
}
/**
* Computes the distance given a shape and the {@code distErrPct}. The
* algorithm is the fraction of the distance from the center of the query
* shape to its furthest bounding box corner.
*
* @param shape Mandatory.
* @param distErrPct 0 to 0.5
* @param ctx Mandatory
* @return A distance (in degrees).
*/
public static double calcDistanceFromErrPct(Shape shape, double distErrPct, SpatialContext ctx) {
if (distErrPct < 0 || distErrPct > 0.5) {
throw new IllegalArgumentException("distErrPct " + distErrPct + " must be between [0 to 0.5]");
}
if (distErrPct == 0 || shape instanceof Point) {
return 0;
}
Rectangle bbox = shape.getBoundingBox();
//The diagonal distance should be the same computed from any opposite corner,
// and this is the longest distance that might be occurring within the shape.
double diagonalDist = ctx.getDistCalc().distance(
ctx.makePoint(bbox.getMinX(), bbox.getMinY()), bbox.getMaxX(), bbox.getMaxY());
return diagonalDist * 0.5 * distErrPct;
}
/**
* Gets the error distance that specifies how precise the query shape is. This
* looks at {@link #getDistErr()}, {@link #getDistErrPct()}, and {@code
* defaultDistErrPct}.
* @param defaultDistErrPct 0 to 0.5
* @return >= 0
*/
public double resolveDistErr(SpatialContext ctx, double defaultDistErrPct) {
if (distErr != null)
return distErr;
double distErrPct = (this.distErrPct != null ? this.distErrPct : defaultDistErrPct);
return calcDistanceFromErrPct(shape, distErrPct, ctx);
}
/** Check if the arguments make sense -- throw an exception if not */
public void validate() throws IllegalArgumentException {
if (operation.isTargetNeedsArea() && !shape.hasArea()) {
throw new IllegalArgumentException(operation + " only supports geometry with area");
}
if (distErr != null && distErrPct != null)
throw new IllegalArgumentException("Only distErr or distErrPct can be specified.");
}
@Override
public String toString() {
return SpatialArgsParser.writeSpatialArgs(this);
}
//------------------------------------------------
// Getters & Setters
//------------------------------------------------
public SpatialOperation getOperation() {
return operation;
}
public void setOperation(SpatialOperation operation) {
this.operation = operation;
}
public Shape getShape() {
return shape;
}
public void setShape(Shape shape) {
this.shape = shape;
}
/**
* A measure of acceptable error of the shape as a fraction. This effectively
* inflates the size of the shape but should not shrink it.
*
* @return 0 to 0.5
* @see #calcDistanceFromErrPct(com.spatial4j.core.shape.Shape, double,
* com.spatial4j.core.context.SpatialContext)
*/
public Double getDistErrPct() {
return distErrPct;
}
public void setDistErrPct(Double distErrPct) {
if (distErrPct != null)
this.distErrPct = distErrPct;
}
/**
* The acceptable error of the shape. This effectively inflates the
* size of the shape but should not shrink it.
*
* @return >= 0
*/
public Double getDistErr() {
return distErr;
}
public void setDistErr(Double distErr) {
this.distErr = distErr;
}
}
| terrancesnyder/solr-analytics | lucene/spatial/src/java/org/apache/lucene/spatial/query/SpatialArgs.java | Java | apache-2.0 | 4,992 |
using ConsoleApp1.Unsafe;
namespace ConsoleApp1.Unsafe
{
using System;
// ポインターを受け付ける Unsafe 版
unsafe class Stream
{
// 書き込み先は Safe 版と同じ
byte[] _buffer = new byte[100];
int _offset = 0;
public void Read(byte* data, int length)
{
fixed (byte* p = _buffer)
{
Buffer.MemoryCopy(p + _offset, data, length, length);
}
_offset += length;
}
public void Write(byte* data, int length)
{
fixed (byte* p = _buffer)
{
Buffer.MemoryCopy(data, p + _offset, 100 - _offset, length);
}
_offset += length;
}
public void Seek(int offset) => _offset = offset;
}
}
namespace ConsoleApp1.Unsafe1
{
unsafe static class PointExtensions
{
public static void Save(this Stream s, Point[] points)
{
var buffer = stackalloc byte[sizeof(double)];
var pb = (double*)buffer;
foreach (var p in points)
{
*pb = p.X;
s.Write(buffer, sizeof(double));
*pb = p.Y;
s.Write(buffer, sizeof(double));
*pb = p.Z;
s.Write(buffer, sizeof(double));
}
}
public static void Load(this Stream s, Point[] points)
{
var buffer = stackalloc byte[sizeof(double)];
var pb = (double*)buffer;
for (int i = 0; i < points.Length; i++)
{
s.Read(buffer, sizeof(double));
points[i].X = *pb;
s.Read(buffer, sizeof(double));
points[i].Y = *pb;
s.Read(buffer, sizeof(double));
points[i].Z = *pb;
}
}
}
struct Copier : IPointCopier
{
public void Copy(Point[] from, Point[] to)
{
var s = new Stream();
s.Save(from);
s.Seek(0);
s.Load(to);
}
}
}
namespace ConsoleApp1.Unsafe2
{
unsafe static class PointExtensions
{
public static void Save(this Stream s, Point[] points)
{
fixed(Point* p = points)
{
s.Write((byte*)p, 24 * points.Length);
}
}
public static void Load(this Stream s, Point[] points)
{
fixed (Point* p = points)
{
s.Read((byte*)p, 24 * points.Length);
}
}
}
struct Copier : IPointCopier
{
public void Copy(Point[] from, Point[] to)
{
var s = new Stream();
s.Save(from);
s.Seek(0);
s.Load(to);
}
}
}
| ufcpp/UfcppSample | Demo/2017/SpanAsSafePointer/ConsoleApp1/Unsafe/Stream.cs | C# | apache-2.0 | 2,837 |
import React from 'react';
import PropTypes from 'prop-types';
import ColumnChooserRow from '../ColumnChooserRow';
import { columnsPropTypes } from '../../columnChooser.propTypes';
const ColumnChooserTable = ({ columns = [], id, onChangeCheckbox, t }) =>
columns.map(column => (
<ColumnChooserRow key={column.key}>
<ColumnChooserRow.Checkbox
checked={column.visible}
id={id}
dataFeature="column-chooser.select"
description={t('CHECKBOX_DISPLAY_COLUMN_DESCRIPTION', {
defaultValue: 'display the column {{label}}',
label: column.label,
})}
label={column.label}
locked={column.locked}
onChange={onChangeCheckbox}
t={t}
/>
</ColumnChooserRow>
));
ColumnChooserTable.propTypes = {
columns: columnsPropTypes,
id: PropTypes.string.isRequired,
onChangeCheckbox: PropTypes.func.isRequired,
t: PropTypes.func.isRequired,
};
export default ColumnChooserTable;
| Talend/ui | packages/components/src/List/Toolbar/ColumnChooserButton/ColumnChooser/ColumnChooserTable/ColumnChooserTable.component.js | JavaScript | apache-2.0 | 914 |
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript">
function display(d) {
$('#tr_gbook_guest').css("display",d);
$('#tr_seccode').css("display",d);
}
</script>
<div id="body">
<div class="space">
<div class="subtitle">操作提示</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr><td>如果您开启了 Modoer 个人空间跳转到 UCHome 的个人空间时,本模块功能将失效。</td></tr>
</table>
</div>
<?=form_begin(cpurl($module,$act))?>
<div class="space">
<div class="subtitle"><?=$MOD['name']?> - 参数设置</div>
<ul class="cptab">
<li class="selected" id="btn_config1"><a href="javascript:;" onclick="tabSelect(1,'config');" onfocus="this.blur()">显示配置</a></li>
</ul>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" id="config1">
<tr>
<td class="altbg1" width="45%"><strong>个人空间的菜单组:</strong>设置前台个人空间的导航菜单;<span class="font_2">模板仅支持 1 级分类,地址内支持参数<span class="font_1">(uid)</span>替换成访问空间的真实uid号</span></td>
<td width="*">
<select name="modcfg[space_menuid]">
<option value="">==选择菜单组==</option>
<?=form_menu_main($modcfg['space_menuid'])?>
</select>
</td>
</tr>
<tr>
<td class="altbg1"><strong>个人空间默认风格:</strong>会员注册时默认设置的个人空间风格</td>
<td><select name="modcfg[templateid]">
<option value="0">默认风格</option>
<?=form_template('space', $modcfg['templateid'])?>
</select></td>
</tr>
<tr>
<td width="45%" class="altbg1"><strong>启用游客记录:</strong>当启动游客记录功能,个人空间将记录游客的ID(前提是该游客已登录网站)</td>
<td width="*"><?=form_bool('modcfg[recordguest]', $modcfg['recordguest'])?></td>
</tr>
<tr>
<td class="altbg1"><strong>空间默认标题</strong>可用变量说明:网站名:{sitename};注册会员名:{username}</td>
<td><input type="text" name="modcfg[spacename]" value="<?=$modcfg['spacename']?>" class="txtbox" /></td>
</tr>
<tr>
<td class="altbg1"><strong>空间默认说明</strong>可用变量同上</td>
<td><input type="text" name="modcfg[spacedescribe]" value="<?=$modcfg['spacedescribe']?>" class="txtbox" /></td>
</tr>
<tr>
<td class="altbg1"><strong>首页点评显示条数目:</strong>在个人空间首页中,显示的点评数目</td>
<td><?=form_radio('modcfg[index_reviews]',array('5'=>'5条','10'=>'10条','20'=>'20条'),$modcfg['index_reviews'])?></td>
</tr>
<tr>
<td class="altbg1"><strong>首页留言显示条数目:</strong>在个人空间首页中,显示的留言数目</td>
<td><?=form_radio('modcfg[index_gbooks]',array('5'=>'5条','10'=>'10条','20'=>'20条'),$modcfg['index_gbooks'])?></td>
</tr>
<tr>
<td class="altbg1"><strong>点评页面显示条数目:</strong>在个人空间点评栏目中,显示的点评数目</td>
<td><?=form_radio('modcfg[reviews]',array('10'=>'10条','20'=>'20条','40'=>'40条'),$modcfg['reviews'])?></td>
</tr>
<tr>
<td class="altbg1"><strong>留言页面显示条数目:</strong>在个人空间点评栏目中,显示的留言数目</td>
<td><?=form_radio('modcfg[gbooks]',array('10'=>'10条','20'=>'20条','40'=>'40条'),$modcfg['gbooks'])?></td>
</tr>
</table>
</div>
<center>
<input type="submit" name="dosubmit" value=" 提交 " class="btn" />
</center>
<?=form_end()?>
</div> | h136799711/20150615modoer_marry | core/modules/space/admin/templates/config.tpl.php | PHP | apache-2.0 | 4,237 |
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package flags
import (
"fmt"
"strconv"
)
// additional types
type int8Value int8
type int16Value int16
type int32Value int32
type f32Value float32
type uint8Value uint8
type uint32Value uint32
type uint16Value uint16
// Var handlers for each of the types
func newInt8Value(p *int8) *int8Value {
return (*int8Value)(p)
}
func newInt16Value(p *int16) *int16Value {
return (*int16Value)(p)
}
func newInt32Value(p *int32) *int32Value {
return (*int32Value)(p)
}
func newFloat32Value(p *float32) *f32Value {
return (*f32Value)(p)
}
func newUint8Value(p *uint8) *uint8Value {
return (*uint8Value)(p)
}
func newUint16Value(p *uint16) *uint16Value {
return (*uint16Value)(p)
}
func newUint32Value(p *uint32) *uint32Value {
return (*uint32Value)(p)
}
// Setters for each of the types
func (f *int8Value) Set(s string) error {
v, err := strconv.ParseInt(s, 10, 8)
if err != nil {
return err
}
*f = int8Value(v)
return nil
}
func (f *int16Value) Set(s string) error {
v, err := strconv.ParseInt(s, 10, 16)
if err != nil {
return err
}
*f = int16Value(v)
return nil
}
func (f *int32Value) Set(s string) error {
v, err := strconv.ParseInt(s, 10, 32)
if err != nil {
return err
}
*f = int32Value(v)
return nil
}
func (f *f32Value) Set(s string) error {
v, err := strconv.ParseFloat(s, 32)
if err != nil {
return err
}
*f = f32Value(v)
return nil
}
func (f *uint8Value) Set(s string) error {
v, err := strconv.ParseUint(s, 10, 8)
if err != nil {
return err
}
*f = uint8Value(v)
return nil
}
func (f *uint16Value) Set(s string) error {
v, err := strconv.ParseUint(s, 10, 16)
if err != nil {
return err
}
*f = uint16Value(v)
return nil
}
func (f *uint32Value) Set(s string) error {
v, err := strconv.ParseUint(s, 10, 32)
if err != nil {
return err
}
*f = uint32Value(v)
return nil
}
// Getters for each of the types
func (f *int8Value) Get() interface{} { return int8(*f) }
func (f *int16Value) Get() interface{} { return int16(*f) }
func (f *int32Value) Get() interface{} { return int32(*f) }
func (f *f32Value) Get() interface{} { return float32(*f) }
func (f *uint8Value) Get() interface{} { return uint8(*f) }
func (f *uint16Value) Get() interface{} { return uint16(*f) }
func (f *uint32Value) Get() interface{} { return uint32(*f) }
// Stringers for each of the types
func (f *int8Value) String() string { return fmt.Sprintf("%v", *f) }
func (f *int16Value) String() string { return fmt.Sprintf("%v", *f) }
func (f *int32Value) String() string { return fmt.Sprintf("%v", *f) }
func (f *f32Value) String() string { return fmt.Sprintf("%v", *f) }
func (f *uint8Value) String() string { return fmt.Sprintf("%v", *f) }
func (f *uint16Value) String() string { return fmt.Sprintf("%v", *f) }
func (f *uint32Value) String() string { return fmt.Sprintf("%v", *f) }
// string slice
// string slice
type strSlice struct {
s *[]string
set bool // if there a flag defined via command line, the slice will be cleared first.
}
func newStringSlice(p *[]string) *strSlice {
return &strSlice{
s: p,
set: false,
}
}
func (s *strSlice) Set(str string) error {
if !s.set {
*s.s = (*s.s)[:0]
s.set = true
}
*s.s = append(*s.s, str)
return nil
}
func (s *strSlice) Get() interface{} {
return []string(*s.s)
}
func (s *strSlice) String() string {
return fmt.Sprintf("%v", s.s)
}
// int slice
type intSlice struct {
s *[]int
set bool
}
func newIntSlice(p *[]int) *intSlice {
return &intSlice{
s: p,
set: false,
}
}
func (is *intSlice) Set(str string) error {
i, err := strconv.Atoi(str)
if err != nil {
return err
}
if !is.set {
*is.s = (*is.s)[:0]
is.set = true
}
*is.s = append(*is.s, i)
return nil
}
func (is *intSlice) Get() interface{} {
return []int(*is.s)
}
func (is *intSlice) String() string {
return fmt.Sprintf("%v", is.s)
}
// float64 slice
type float64Slice struct {
s *[]float64
set bool
}
func newFloat64Slice(p *[]float64) *float64Slice {
return &float64Slice{
s: p,
set: false,
}
}
func (is *float64Slice) Set(str string) error {
i, err := strconv.ParseFloat(str, 64)
if err != nil {
return err
}
if !is.set {
*is.s = (*is.s)[:0]
is.set = true
}
*is.s = append(*is.s, i)
return nil
}
func (is *float64Slice) Get() interface{} {
return []float64(*is.s)
}
func (is *float64Slice) String() string {
return fmt.Sprintf("%v", is.s)
}
| heroiclabs/nakama | flags/vars.go | GO | apache-2.0 | 5,471 |
/*
* 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.facebook.presto.operator.scalar;
import com.facebook.presto.annotation.UsedByGeneratedCode;
import com.facebook.presto.common.block.Block;
import com.facebook.presto.common.block.BlockBuilder;
import com.facebook.presto.common.block.SingleRowBlockWriter;
import com.facebook.presto.common.function.OperatorType;
import com.facebook.presto.common.function.SqlFunctionProperties;
import com.facebook.presto.common.type.RowType;
import com.facebook.presto.common.type.RowType.Field;
import com.facebook.presto.common.type.StandardTypes;
import com.facebook.presto.metadata.BoundVariables;
import com.facebook.presto.metadata.FunctionAndTypeManager;
import com.facebook.presto.metadata.SqlOperator;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.util.JsonCastException;
import com.facebook.presto.util.JsonUtil.BlockBuilderAppender;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.google.common.collect.ImmutableList;
import io.airlift.slice.Slice;
import java.lang.invoke.MethodHandle;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static com.facebook.presto.common.type.TypeSignature.parseTypeSignature;
import static com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.ArgumentProperty.valueTypeArgumentProperty;
import static com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.NullConvention.RETURN_NULL_ON_NULL;
import static com.facebook.presto.spi.StandardErrorCode.INVALID_CAST_ARGUMENT;
import static com.facebook.presto.spi.function.Signature.withVariadicBound;
import static com.facebook.presto.util.Failures.checkCondition;
import static com.facebook.presto.util.JsonUtil.BlockBuilderAppender.createBlockBuilderAppender;
import static com.facebook.presto.util.JsonUtil.JSON_FACTORY;
import static com.facebook.presto.util.JsonUtil.canCastFromJson;
import static com.facebook.presto.util.JsonUtil.createJsonParser;
import static com.facebook.presto.util.JsonUtil.getFieldNameToIndex;
import static com.facebook.presto.util.JsonUtil.parseJsonToSingleRowBlock;
import static com.facebook.presto.util.JsonUtil.truncateIfNecessaryForErrorMessage;
import static com.facebook.presto.util.Reflection.methodHandle;
import static com.fasterxml.jackson.core.JsonToken.START_ARRAY;
import static com.fasterxml.jackson.core.JsonToken.START_OBJECT;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
public class JsonToRowCast
extends SqlOperator
{
public static final JsonToRowCast JSON_TO_ROW = new JsonToRowCast();
private static final MethodHandle METHOD_HANDLE = methodHandle(JsonToRowCast.class, "toRow", RowType.class, BlockBuilderAppender[].class, Optional.class, SqlFunctionProperties.class, Slice.class);
private JsonToRowCast()
{
super(OperatorType.CAST,
ImmutableList.of(withVariadicBound("T", "row")),
ImmutableList.of(),
parseTypeSignature("T"),
ImmutableList.of(parseTypeSignature(StandardTypes.JSON)));
}
@Override
public BuiltInScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, FunctionAndTypeManager functionAndTypeManager)
{
checkArgument(arity == 1, "Expected arity to be 1");
RowType rowType = (RowType) boundVariables.getTypeVariable("T");
checkCondition(canCastFromJson(rowType), INVALID_CAST_ARGUMENT, "Cannot cast JSON to %s", rowType);
List<Field> rowFields = rowType.getFields();
BlockBuilderAppender[] fieldAppenders = rowFields.stream()
.map(rowField -> createBlockBuilderAppender(rowField.getType()))
.toArray(BlockBuilderAppender[]::new);
MethodHandle methodHandle = METHOD_HANDLE.bindTo(rowType).bindTo(fieldAppenders).bindTo(getFieldNameToIndex(rowFields));
return new BuiltInScalarFunctionImplementation(
true,
ImmutableList.of(valueTypeArgumentProperty(RETURN_NULL_ON_NULL)),
methodHandle);
}
@UsedByGeneratedCode
public static Block toRow(
RowType rowType,
BlockBuilderAppender[] fieldAppenders,
Optional<Map<String, Integer>> fieldNameToIndex,
SqlFunctionProperties properties,
Slice json)
{
try (JsonParser jsonParser = createJsonParser(JSON_FACTORY, json)) {
jsonParser.nextToken();
if (jsonParser.getCurrentToken() == JsonToken.VALUE_NULL) {
return null;
}
if (jsonParser.getCurrentToken() != START_ARRAY && jsonParser.getCurrentToken() != START_OBJECT) {
throw new JsonCastException(format("Expected a json array or object, but got %s", jsonParser.getText()));
}
BlockBuilder rowBlockBuilder = rowType.createBlockBuilder(null, 1);
parseJsonToSingleRowBlock(
jsonParser,
(SingleRowBlockWriter) rowBlockBuilder.beginBlockEntry(),
fieldAppenders,
fieldNameToIndex);
rowBlockBuilder.closeEntry();
if (jsonParser.nextToken() != null) {
throw new JsonCastException(format("Unexpected trailing token: %s", jsonParser.getText()));
}
return rowType.getObject(rowBlockBuilder, 0);
}
catch (PrestoException | JsonCastException e) {
throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast to %s. %s\n%s", rowType, e.getMessage(), truncateIfNecessaryForErrorMessage(json)), e);
}
catch (Exception e) {
throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast to %s.\n%s", rowType, truncateIfNecessaryForErrorMessage(json)), e);
}
}
}
| prestodb/presto | presto-main/src/main/java/com/facebook/presto/operator/scalar/JsonToRowCast.java | Java | apache-2.0 | 6,466 |