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 |
|---|---|---|---|---|---|
'use strict';
var gulp = tars.packages.gulp;
var cache = tars.packages.cache;
var plumber = tars.packages.plumber;
var notifier = tars.helpers.notifier;
var browserSync = tars.packages.browserSync;
var staticFolderName = tars.config.fs.staticFolderName;
/**
* Move fonts-files to dev directory
*/
module.exports = function () {
return gulp.task('other:move-fonts', function () {
return gulp.src('./markup/' + staticFolderName + '/fonts/**/*.*')
.pipe(plumber({
errorHandler: function (error) {
notifier.error('An error occurred while moving fonts.', error);
}
}))
.pipe(cache('move-fonts'))
.pipe(gulp.dest('./dev/' + staticFolderName + '/fonts'))
.pipe(browserSync.reload({ stream: true }))
.pipe(
notifier.success('Fonts\'ve been moved')
);
});
};
| mik639/TZA | tars/tasks/other/move-fonts.js | JavaScript | mit | 923 |
# require 'analytic/response_analytic'
module AssignmentTeamAnalytic
#======= general ==========#
def num_participants
self.participants.count
end
def num_reviews
self.responses.count
end
#========== score ========#
def average_review_score
if self.num_reviews == 0
return 0
else
review_scores.inject(:+).to_f / num_reviews
end
end
def max_review_score
review_scores.max
end
def min_review_score
review_scores.min
end
#======= word count =======#
def total_review_word_count
review_word_counts.inject(:+)
end
def average_review_word_count
if self.num_reviews == 0
return 0
else
total_review_word_count.to_f / num_reviews
end
end
def max_review_word_count
review_word_counts.max
end
def min_review_word_count
review_word_counts.min
end
#===== character count ====#
def total_review_character_count
review_character_counts.inject(:+)
end
def average_review_character_count
if num_reviews == 0
0
else
total_review_character_count.to_f / num_reviews
end
end
def max_review_character_count
review_character_counts.max
end
def min_review_character_count
review_character_counts.min
end
def review_character_counts
list = []
self.responses.each do |response|
list << response.total_character_count
end
if list.empty?
[0]
else
list
end
end
# return an array containing the score of all the reviews
def review_scores
list = []
self.responses.each do |response|
list << response.average_score
end
if list.empty?
[0]
else
list
end
end
def review_word_counts
list = []
self.responses.each do |response|
list << response.total_word_count
end
if list.empty?
[0]
else
list
end
end
#======= unused ============#
# #return students in the participants
# def student_list
# students = Array.new
# self.participants.each do |participant|
# if participant.user.role_id == Role.student.id
# students << participant
# end
# end
# students
# end
#
# def num_students
# self.students.count
# end
end
| akshayjain114/expertiza | expertiza-master/app/models/analytic/assignment_team_analytic.rb | Ruby | mit | 2,250 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autofac.Builder;
using Autofac.Core.Registration;
using Autofac.Core.Lifetime;
using Autofac.Core.Activators.Reflection;
using Autofac.Core;
using System.Reflection;
using Autofac.Core.Activators.ProvidedInstance;
namespace Autofac.Test
{
static class Factory
{
public static IComponentRegistration CreateSingletonRegistration(IEnumerable<Service> services, IInstanceActivator activator)
{
return CreateRegistration(services, activator, new RootScopeLifetime(), InstanceSharing.Shared);
}
public static IComponentRegistration CreateSingletonRegistration(Type implementation)
{
return CreateSingletonRegistration(
new Service[] { new TypedService(implementation) },
CreateReflectionActivator(implementation));
}
public static IComponentRegistration CreateRegistration(IEnumerable<Service> services, IInstanceActivator activator, IComponentLifetime lifetime, InstanceSharing sharing)
{
return new ComponentRegistration(
Guid.NewGuid(),
activator,
lifetime,
sharing,
InstanceOwnership.OwnedByLifetimeScope,
services,
NoMetadata);
}
public static IComponentRegistration CreateSingletonObjectRegistration(object instance)
{
return RegistrationBuilder
.ForDelegate((c, p) => instance)
.SingleInstance()
.CreateRegistration();
}
public static IComponentRegistration CreateSingletonObjectRegistration()
{
return CreateSingletonRegistration(
new Service[] { new TypedService(typeof(object)) },
CreateReflectionActivator(typeof(object)));
}
public static ReflectionActivator CreateReflectionActivator(Type implementation)
{
return CreateReflectionActivator(
implementation,
NoParameters);
}
public static ReflectionActivator CreateReflectionActivator(Type implementation, IEnumerable<Parameter> parameters)
{
return CreateReflectionActivator(
implementation,
parameters,
NoProperties);
}
public static ReflectionActivator CreateReflectionActivator(Type implementation, IEnumerable<Parameter> parameters, IEnumerable<Parameter> properties)
{
return new ReflectionActivator(
implementation,
new DefaultConstructorFinder(),
new MostParametersConstructorSelector(),
parameters,
properties);
}
public static ProvidedInstanceActivator CreateProvidedInstanceActivator(object instance)
{
return new ProvidedInstanceActivator(instance);
}
public static readonly IContainer EmptyContainer = new Container();
public static readonly IComponentContext EmptyContext = new Container();
public static readonly IEnumerable<Parameter> NoParameters = Enumerable.Empty<Parameter>();
public static readonly IEnumerable<Parameter> NoProperties = Enumerable.Empty<Parameter>();
public static readonly IDictionary<string, object> NoMetadata = new Dictionary<string, object>();
}
}
| oconics/Autofac | test/Autofac.Test/Factory.cs | C# | mit | 3,512 |
/******************************************************************************
*
*
*
* Copyright (C) 1997-2015 by Dimitri van Heesch.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation under the terms of the GNU General Public License is hereby
* granted. No representations are made about the suitability of this software
* for any purpose. It is provided "as is" without express or implied warranty.
* See the GNU General Public License for more details.
*
* Documents produced by Doxygen are derivative works derived from the
* input used in their production; they are not affected by this license.
*
*/
#include "define.h"
#include "config.h"
Define::Define()
{
fileDef=0;
lineNr=1;
columnNr=1;
nargs=-1;
undef=FALSE;
varArgs=FALSE;
isPredefined=FALSE;
nonRecursive=FALSE;
}
Define::Define(const Define &d)
: name(d.name),definition(d.definition),fileName(d.fileName)
{
//name=d.name; definition=d.definition; fileName=d.fileName;
lineNr=d.lineNr;
columnNr=d.columnNr;
nargs=d.nargs;
undef=d.undef;
varArgs=d.varArgs;
isPredefined=d.isPredefined;
nonRecursive=d.nonRecursive;
fileDef=0;
}
Define::~Define()
{
}
bool Define::hasDocumentation()
{
return definition && (doc || Config_getBool("EXTRACT_ALL"));
}
| chintal/doxygen | src/define.cpp | C++ | gpl-2.0 | 1,325 |
<?php
namespace Drupal\jsonapi\JsonApiResource;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Drupal\Core\Url;
use Drupal\jsonapi\JsonApiSpec;
use Drupal\jsonapi\ResourceType\ResourceType;
use Drupal\jsonapi\Routing\Routes;
/**
* Represents references from one resource object to other resource object(s).
*
* @internal JSON:API maintains no PHP API since its API is the HTTP API. This
* class may change at any time and this will break any dependencies on it.
*
* @see https://www.drupal.org/project/drupal/issues/3032787
* @see jsonapi.api.php
*/
class Relationship implements TopLevelDataInterface {
/**
* The context resource object of the relationship.
*
* A relationship object represents references from a resource object in
* which it’s defined to other resource objects. Respectively, the "context"
* of the relationship and the "target(s)" of the relationship.
*
* A relationship object's context either comes from the resource object that
* contains it or, in the case that the relationship object is accessed
* directly via a relationship URL, from its `self` URL, which should identify
* the resource to which it belongs.
*
* @var \Drupal\jsonapi\JsonApiResource\ResourceObject
*
* @see https://jsonapi.org/format/#document-resource-object-relationships
* @see https://jsonapi.org/recommendations/#urls-relationships
*/
protected $context;
/**
* The data of the relationship object.
*
* @var \Drupal\jsonapi\JsonApiResource\RelationshipData
*/
protected $data;
/**
* The relationship's public field name.
*
* @var string
*/
protected $fieldName;
/**
* The relationship object's links.
*
* @var \Drupal\jsonapi\JsonApiResource\LinkCollection
*/
protected $links;
/**
* The relationship object's meta member.
*
* @var array
*/
protected $meta;
/**
* Relationship constructor.
*
* This constructor is protected by design. To create a new relationship, use
* static::createFromEntityReferenceField().
*
* @param string $public_field_name
* The public field name of the relationship field.
* @param \Drupal\jsonapi\JsonApiResource\RelationshipData $data
* The relationship data.
* @param \Drupal\jsonapi\JsonApiResource\LinkCollection $links
* Any links for the resource object, if a `self` link is not
* provided, one will be automatically added if the resource is locatable
* and is not internal.
* @param array $meta
* Any relationship metadata.
* @param \Drupal\jsonapi\JsonApiResource\ResourceObject $context
* The relationship's context resource object. Use the
* self::withContext() method to establish a context.
*
* @see \Drupal\jsonapi\JsonApiResource\Relationship::createFromEntityReferenceField()
*/
protected function __construct($public_field_name, RelationshipData $data, LinkCollection $links, array $meta, ResourceObject $context) {
$this->fieldName = $public_field_name;
$this->data = $data;
$this->links = $links->withContext($this);
$this->meta = $meta;
$this->context = $context;
}
/**
* Creates a new Relationship from an entity reference field.
*
* @param \Drupal\jsonapi\JsonApiResource\ResourceObject $context
* The context resource object of the relationship to be created.
* @param \Drupal\Core\Field\EntityReferenceFieldItemListInterface $field
* The entity reference field from which to create the relationship.
* @param \Drupal\jsonapi\JsonApiResource\LinkCollection $links
* (optional) Any extra links for the Relationship, if a `self` link is not
* provided, one will be automatically added if the context resource is
* locatable and is not internal.
* @param array $meta
* (optional) Any relationship metadata.
*
* @return static
* An instantiated relationship object.
*/
public static function createFromEntityReferenceField(ResourceObject $context, EntityReferenceFieldItemListInterface $field, LinkCollection $links = NULL, array $meta = []) {
$context_resource_type = $context->getResourceType();
$resource_field = $context_resource_type->getFieldByInternalName($field->getName());
return new static(
$resource_field->getPublicName(),
new RelationshipData(ResourceIdentifier::toResourceIdentifiers($field), $resource_field->hasOne() ? 1 : -1),
static::buildLinkCollectionFromEntityReferenceField($context, $field, $links ?: new LinkCollection([])),
$meta,
$context
);
}
/**
* Gets context resource object of the relationship.
*
* @return \Drupal\jsonapi\JsonApiResource\ResourceObject
* The context ResourceObject.
*
* @see \Drupal\jsonapi\JsonApiResource\Relationship::$context
*/
public function getContext() {
return $this->context;
}
/**
* Gets the relationship object's public field name.
*
* @return string
* The relationship's field name.
*/
public function getFieldName() {
return $this->fieldName;
}
/**
* Gets the relationship object's data.
*
* @return \Drupal\jsonapi\JsonApiResource\RelationshipData
* The relationship's data.
*/
public function getData() {
return $this->data;
}
/**
* Gets the relationship object's links.
*
* @return \Drupal\jsonapi\JsonApiResource\LinkCollection
* The relationship object's links.
*/
public function getLinks() {
return $this->links;
}
/**
* Gets the relationship object's metadata.
*
* @return array
* The relationship object's metadata.
*/
public function getMeta() {
return $this->meta;
}
/**
* {@inheritdoc}
*/
public function getOmissions() {
return new OmittedData([]);
}
/**
* {@inheritdoc}
*/
public function getMergedLinks(LinkCollection $top_level_links) {
// When directly fetching a relationship object, the relationship object's
// links become the top-level object's links unless they've been
// overridden. Overrides are especially important for the `self` link, which
// must match the link that generated the response. For example, the
// top-level `self` link might have an `include` query parameter that would
// be lost otherwise.
// See https://jsonapi.org/format/#fetching-relationships-responses-200 and
// https://jsonapi.org/format/#document-top-level.
return LinkCollection::merge($top_level_links, $this->getLinks()->filter(function ($key) use ($top_level_links) {
return !$top_level_links->hasLinkWithKey($key);
})->withContext($top_level_links->getContext()));
}
/**
* {@inheritdoc}
*/
public function getMergedMeta(array $top_level_meta) {
return NestedArray::mergeDeep($top_level_meta, $this->getMeta());
}
/**
* Builds a LinkCollection for the given entity reference field.
*
* @param \Drupal\jsonapi\JsonApiResource\ResourceObject $context
* The context resource object of the relationship object.
* @param \Drupal\Core\Field\EntityReferenceFieldItemListInterface $field
* The entity reference field from which to create the links.
* @param \Drupal\jsonapi\JsonApiResource\LinkCollection $links
* Any extra links for the Relationship, if a `self` link is not provided,
* one will be automatically added if the context resource is locatable and
* is not internal.
*
* @return \Drupal\jsonapi\JsonApiResource\LinkCollection
* The built links.
*/
protected static function buildLinkCollectionFromEntityReferenceField(ResourceObject $context, EntityReferenceFieldItemListInterface $field, LinkCollection $links) {
$context_resource_type = $context->getResourceType();
$public_field_name = $context_resource_type->getPublicName($field->getName());
if ($context_resource_type->isLocatable() && !$context_resource_type->isInternal()) {
$context_is_versionable = $context_resource_type->isVersionable();
if (!$links->hasLinkWithKey('self')) {
$route_name = Routes::getRouteName($context_resource_type, "$public_field_name.relationship.get");
$self_link = Url::fromRoute($route_name, ['entity' => $context->getId()]);
if ($context_is_versionable) {
$self_link->setOption('query', [JsonApiSpec::VERSION_QUERY_PARAMETER => $context->getVersionIdentifier()]);
}
$links = $links->withLink('self', new Link(new CacheableMetadata(), $self_link, 'self'));
}
$has_non_internal_resource_type = array_reduce($context_resource_type->getRelatableResourceTypesByField($public_field_name), function ($carry, ResourceType $target) {
return $carry ?: !$target->isInternal();
}, FALSE);
// If a `related` link was not provided, automatically generate one from
// the relationship object to the collection resource with all of the
// resources targeted by this relationship. However, that link should
// *not* be generated if all of the relatable resources are internal.
// That's because, in that case, a route will not exist for it.
if (!$links->hasLinkWithKey('related') && $has_non_internal_resource_type) {
$route_name = Routes::getRouteName($context_resource_type, "$public_field_name.related");
$related_link = Url::fromRoute($route_name, ['entity' => $context->getId()]);
if ($context_is_versionable) {
$related_link->setOption('query', [JsonApiSpec::VERSION_QUERY_PARAMETER => $context->getVersionIdentifier()]);
}
$links = $links->withLink('related', new Link(new CacheableMetadata(), $related_link, 'related'));
}
}
return $links;
}
}
| maskedjellybean/tee-prop | web/core/modules/jsonapi/src/JsonApiResource/Relationship.php | PHP | gpl-2.0 | 9,807 |
/*___Generated_by_IDEA___*/
package com.facebook.android;
/* This stub is only used by the IDE. It is NOT the R class actually packed into the APK */
public final class R {
} | TharinduKetipe/easywish | libraries/facebook/gen/com/facebook/android/R.java | Java | gpl-2.0 | 176 |
t = db.capped1;
t.drop();
db.createCollection("capped1" , {capped:true, size:1024 });
v = t.validate();
assert( v.valid , "A : " + tojson( v ) ); // SERVER-485
t.save( { x : 1 } )
assert( t.validate().valid , "B" )
| barakav/robomongo | src/third-party/mongodb/jstests/capped1.js | JavaScript | gpl-3.0 | 220 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Data/PokemonData.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Data {
/// <summary>Holder for reflection information generated from POGOProtos/Data/PokemonData.proto</summary>
public static partial class PokemonDataReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Data/PokemonData.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PokemonDataReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiFQT0dPUHJvdG9zL0RhdGEvUG9rZW1vbkRhdGEucHJvdG8SD1BPR09Qcm90",
"b3MuRGF0YRogUE9HT1Byb3Rvcy9FbnVtcy9Qb2tlbW9uSWQucHJvdG8aIlBP",
"R09Qcm90b3MvRW51bXMvUG9rZW1vbk1vdmUucHJvdG8aJlBPR09Qcm90b3Mv",
"SW52ZW50b3J5L0l0ZW0vSXRlbUlkLnByb3RvIpgGCgtQb2tlbW9uRGF0YRIK",
"CgJpZBgBIAEoBhIvCgpwb2tlbW9uX2lkGAIgASgOMhsuUE9HT1Byb3Rvcy5F",
"bnVtcy5Qb2tlbW9uSWQSCgoCY3AYAyABKAUSDwoHc3RhbWluYRgEIAEoBRIT",
"CgtzdGFtaW5hX21heBgFIAEoBRItCgZtb3ZlXzEYBiABKA4yHS5QT0dPUHJv",
"dG9zLkVudW1zLlBva2Vtb25Nb3ZlEi0KBm1vdmVfMhgHIAEoDjIdLlBPR09Q",
"cm90b3MuRW51bXMuUG9rZW1vbk1vdmUSGAoQZGVwbG95ZWRfZm9ydF9pZBgI",
"IAEoCRISCgpvd25lcl9uYW1lGAkgASgJEg4KBmlzX2VnZxgKIAEoCBIcChRl",
"Z2dfa21fd2Fsa2VkX3RhcmdldBgLIAEoARIbChNlZ2dfa21fd2Fsa2VkX3N0",
"YXJ0GAwgASgBEg4KBm9yaWdpbhgOIAEoBRIQCghoZWlnaHRfbRgPIAEoAhIR",
"Cgl3ZWlnaHRfa2cYECABKAISGQoRaW5kaXZpZHVhbF9hdHRhY2sYESABKAUS",
"GgoSaW5kaXZpZHVhbF9kZWZlbnNlGBIgASgFEhoKEmluZGl2aWR1YWxfc3Rh",
"bWluYRgTIAEoBRIVCg1jcF9tdWx0aXBsaWVyGBQgASgCEjMKCHBva2ViYWxs",
"GBUgASgOMiEuUE9HT1Byb3Rvcy5JbnZlbnRvcnkuSXRlbS5JdGVtSWQSGAoQ",
"Y2FwdHVyZWRfY2VsbF9pZBgWIAEoBBIYChBiYXR0bGVzX2F0dGFja2VkGBcg",
"ASgFEhgKEGJhdHRsZXNfZGVmZW5kZWQYGCABKAUSGAoQZWdnX2luY3ViYXRv",
"cl9pZBgZIAEoCRIYChBjcmVhdGlvbl90aW1lX21zGBogASgEEhQKDG51bV91",
"cGdyYWRlcxgbIAEoBRIgChhhZGRpdGlvbmFsX2NwX211bHRpcGxpZXIYHCAB",
"KAISEAoIZmF2b3JpdGUYHSABKAUSEAoIbmlja25hbWUYHiABKAkSEQoJZnJv",
"bV9mb3J0GB8gASgFYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::POGOProtos.Enums.PokemonIdReflection.Descriptor, global::POGOProtos.Enums.PokemonMoveReflection.Descriptor, global::POGOProtos.Inventory.Item.ItemIdReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Data.PokemonData), global::POGOProtos.Data.PokemonData.Parser, new[]{ "Id", "PokemonId", "Cp", "Stamina", "StaminaMax", "Move1", "Move2", "DeployedFortId", "OwnerName", "IsEgg", "EggKmWalkedTarget", "EggKmWalkedStart", "Origin", "HeightM", "WeightKg", "IndividualAttack", "IndividualDefense", "IndividualStamina", "CpMultiplier", "Pokeball", "CapturedCellId", "BattlesAttacked", "BattlesDefended", "EggIncubatorId", "CreationTimeMs", "NumUpgrades", "AdditionalCpMultiplier", "Favorite", "Nickname", "FromFort" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class PokemonData : pb::IMessage<PokemonData> {
private static readonly pb::MessageParser<PokemonData> _parser = new pb::MessageParser<PokemonData>(() => new PokemonData());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PokemonData> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Data.PokemonDataReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PokemonData() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PokemonData(PokemonData other) : this() {
id_ = other.id_;
pokemonId_ = other.pokemonId_;
cp_ = other.cp_;
stamina_ = other.stamina_;
staminaMax_ = other.staminaMax_;
move1_ = other.move1_;
move2_ = other.move2_;
deployedFortId_ = other.deployedFortId_;
ownerName_ = other.ownerName_;
isEgg_ = other.isEgg_;
eggKmWalkedTarget_ = other.eggKmWalkedTarget_;
eggKmWalkedStart_ = other.eggKmWalkedStart_;
origin_ = other.origin_;
heightM_ = other.heightM_;
weightKg_ = other.weightKg_;
individualAttack_ = other.individualAttack_;
individualDefense_ = other.individualDefense_;
individualStamina_ = other.individualStamina_;
cpMultiplier_ = other.cpMultiplier_;
pokeball_ = other.pokeball_;
capturedCellId_ = other.capturedCellId_;
battlesAttacked_ = other.battlesAttacked_;
battlesDefended_ = other.battlesDefended_;
eggIncubatorId_ = other.eggIncubatorId_;
creationTimeMs_ = other.creationTimeMs_;
numUpgrades_ = other.numUpgrades_;
additionalCpMultiplier_ = other.additionalCpMultiplier_;
favorite_ = other.favorite_;
nickname_ = other.nickname_;
fromFort_ = other.fromFort_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PokemonData Clone() {
return new PokemonData(this);
}
/// <summary>Field number for the "id" field.</summary>
public const int IdFieldNumber = 1;
private ulong id_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong Id {
get { return id_; }
set {
id_ = value;
}
}
/// <summary>Field number for the "pokemon_id" field.</summary>
public const int PokemonIdFieldNumber = 2;
private global::POGOProtos.Enums.PokemonId pokemonId_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.PokemonId PokemonId {
get { return pokemonId_; }
set {
pokemonId_ = value;
}
}
/// <summary>Field number for the "cp" field.</summary>
public const int CpFieldNumber = 3;
private int cp_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Cp {
get { return cp_; }
set {
cp_ = value;
}
}
/// <summary>Field number for the "stamina" field.</summary>
public const int StaminaFieldNumber = 4;
private int stamina_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Stamina {
get { return stamina_; }
set {
stamina_ = value;
}
}
/// <summary>Field number for the "stamina_max" field.</summary>
public const int StaminaMaxFieldNumber = 5;
private int staminaMax_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int StaminaMax {
get { return staminaMax_; }
set {
staminaMax_ = value;
}
}
/// <summary>Field number for the "move_1" field.</summary>
public const int Move1FieldNumber = 6;
private global::POGOProtos.Enums.PokemonMove move1_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.PokemonMove Move1 {
get { return move1_; }
set {
move1_ = value;
}
}
/// <summary>Field number for the "move_2" field.</summary>
public const int Move2FieldNumber = 7;
private global::POGOProtos.Enums.PokemonMove move2_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.PokemonMove Move2 {
get { return move2_; }
set {
move2_ = value;
}
}
/// <summary>Field number for the "deployed_fort_id" field.</summary>
public const int DeployedFortIdFieldNumber = 8;
private string deployedFortId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string DeployedFortId {
get { return deployedFortId_; }
set {
deployedFortId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "owner_name" field.</summary>
public const int OwnerNameFieldNumber = 9;
private string ownerName_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string OwnerName {
get { return ownerName_; }
set {
ownerName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "is_egg" field.</summary>
public const int IsEggFieldNumber = 10;
private bool isEgg_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool IsEgg {
get { return isEgg_; }
set {
isEgg_ = value;
}
}
/// <summary>Field number for the "egg_km_walked_target" field.</summary>
public const int EggKmWalkedTargetFieldNumber = 11;
private double eggKmWalkedTarget_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double EggKmWalkedTarget {
get { return eggKmWalkedTarget_; }
set {
eggKmWalkedTarget_ = value;
}
}
/// <summary>Field number for the "egg_km_walked_start" field.</summary>
public const int EggKmWalkedStartFieldNumber = 12;
private double eggKmWalkedStart_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double EggKmWalkedStart {
get { return eggKmWalkedStart_; }
set {
eggKmWalkedStart_ = value;
}
}
/// <summary>Field number for the "origin" field.</summary>
public const int OriginFieldNumber = 14;
private int origin_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Origin {
get { return origin_; }
set {
origin_ = value;
}
}
/// <summary>Field number for the "height_m" field.</summary>
public const int HeightMFieldNumber = 15;
private float heightM_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float HeightM {
get { return heightM_; }
set {
heightM_ = value;
}
}
/// <summary>Field number for the "weight_kg" field.</summary>
public const int WeightKgFieldNumber = 16;
private float weightKg_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float WeightKg {
get { return weightKg_; }
set {
weightKg_ = value;
}
}
/// <summary>Field number for the "individual_attack" field.</summary>
public const int IndividualAttackFieldNumber = 17;
private int individualAttack_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int IndividualAttack {
get { return individualAttack_; }
set {
individualAttack_ = value;
}
}
/// <summary>Field number for the "individual_defense" field.</summary>
public const int IndividualDefenseFieldNumber = 18;
private int individualDefense_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int IndividualDefense {
get { return individualDefense_; }
set {
individualDefense_ = value;
}
}
/// <summary>Field number for the "individual_stamina" field.</summary>
public const int IndividualStaminaFieldNumber = 19;
private int individualStamina_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int IndividualStamina {
get { return individualStamina_; }
set {
individualStamina_ = value;
}
}
/// <summary>Field number for the "cp_multiplier" field.</summary>
public const int CpMultiplierFieldNumber = 20;
private float cpMultiplier_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float CpMultiplier {
get { return cpMultiplier_; }
set {
cpMultiplier_ = value;
}
}
/// <summary>Field number for the "pokeball" field.</summary>
public const int PokeballFieldNumber = 21;
private global::POGOProtos.Inventory.Item.ItemId pokeball_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Inventory.Item.ItemId Pokeball {
get { return pokeball_; }
set {
pokeball_ = value;
}
}
/// <summary>Field number for the "captured_cell_id" field.</summary>
public const int CapturedCellIdFieldNumber = 22;
private ulong capturedCellId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong CapturedCellId {
get { return capturedCellId_; }
set {
capturedCellId_ = value;
}
}
/// <summary>Field number for the "battles_attacked" field.</summary>
public const int BattlesAttackedFieldNumber = 23;
private int battlesAttacked_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int BattlesAttacked {
get { return battlesAttacked_; }
set {
battlesAttacked_ = value;
}
}
/// <summary>Field number for the "battles_defended" field.</summary>
public const int BattlesDefendedFieldNumber = 24;
private int battlesDefended_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int BattlesDefended {
get { return battlesDefended_; }
set {
battlesDefended_ = value;
}
}
/// <summary>Field number for the "egg_incubator_id" field.</summary>
public const int EggIncubatorIdFieldNumber = 25;
private string eggIncubatorId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string EggIncubatorId {
get { return eggIncubatorId_; }
set {
eggIncubatorId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "creation_time_ms" field.</summary>
public const int CreationTimeMsFieldNumber = 26;
private ulong creationTimeMs_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong CreationTimeMs {
get { return creationTimeMs_; }
set {
creationTimeMs_ = value;
}
}
/// <summary>Field number for the "num_upgrades" field.</summary>
public const int NumUpgradesFieldNumber = 27;
private int numUpgrades_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int NumUpgrades {
get { return numUpgrades_; }
set {
numUpgrades_ = value;
}
}
/// <summary>Field number for the "additional_cp_multiplier" field.</summary>
public const int AdditionalCpMultiplierFieldNumber = 28;
private float additionalCpMultiplier_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float AdditionalCpMultiplier {
get { return additionalCpMultiplier_; }
set {
additionalCpMultiplier_ = value;
}
}
/// <summary>Field number for the "favorite" field.</summary>
public const int FavoriteFieldNumber = 29;
private int favorite_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Favorite {
get { return favorite_; }
set {
favorite_ = value;
}
}
/// <summary>Field number for the "nickname" field.</summary>
public const int NicknameFieldNumber = 30;
private string nickname_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Nickname {
get { return nickname_; }
set {
nickname_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "from_fort" field.</summary>
public const int FromFortFieldNumber = 31;
private int fromFort_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FromFort {
get { return fromFort_; }
set {
fromFort_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PokemonData);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PokemonData other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Id != other.Id) return false;
if (PokemonId != other.PokemonId) return false;
if (Cp != other.Cp) return false;
if (Stamina != other.Stamina) return false;
if (StaminaMax != other.StaminaMax) return false;
if (Move1 != other.Move1) return false;
if (Move2 != other.Move2) return false;
if (DeployedFortId != other.DeployedFortId) return false;
if (OwnerName != other.OwnerName) return false;
if (IsEgg != other.IsEgg) return false;
if (EggKmWalkedTarget != other.EggKmWalkedTarget) return false;
if (EggKmWalkedStart != other.EggKmWalkedStart) return false;
if (Origin != other.Origin) return false;
if (HeightM != other.HeightM) return false;
if (WeightKg != other.WeightKg) return false;
if (IndividualAttack != other.IndividualAttack) return false;
if (IndividualDefense != other.IndividualDefense) return false;
if (IndividualStamina != other.IndividualStamina) return false;
if (CpMultiplier != other.CpMultiplier) return false;
if (Pokeball != other.Pokeball) return false;
if (CapturedCellId != other.CapturedCellId) return false;
if (BattlesAttacked != other.BattlesAttacked) return false;
if (BattlesDefended != other.BattlesDefended) return false;
if (EggIncubatorId != other.EggIncubatorId) return false;
if (CreationTimeMs != other.CreationTimeMs) return false;
if (NumUpgrades != other.NumUpgrades) return false;
if (AdditionalCpMultiplier != other.AdditionalCpMultiplier) return false;
if (Favorite != other.Favorite) return false;
if (Nickname != other.Nickname) return false;
if (FromFort != other.FromFort) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Id != 0UL) hash ^= Id.GetHashCode();
if (PokemonId != 0) hash ^= PokemonId.GetHashCode();
if (Cp != 0) hash ^= Cp.GetHashCode();
if (Stamina != 0) hash ^= Stamina.GetHashCode();
if (StaminaMax != 0) hash ^= StaminaMax.GetHashCode();
if (Move1 != 0) hash ^= Move1.GetHashCode();
if (Move2 != 0) hash ^= Move2.GetHashCode();
if (DeployedFortId.Length != 0) hash ^= DeployedFortId.GetHashCode();
if (OwnerName.Length != 0) hash ^= OwnerName.GetHashCode();
if (IsEgg != false) hash ^= IsEgg.GetHashCode();
if (EggKmWalkedTarget != 0D) hash ^= EggKmWalkedTarget.GetHashCode();
if (EggKmWalkedStart != 0D) hash ^= EggKmWalkedStart.GetHashCode();
if (Origin != 0) hash ^= Origin.GetHashCode();
if (HeightM != 0F) hash ^= HeightM.GetHashCode();
if (WeightKg != 0F) hash ^= WeightKg.GetHashCode();
if (IndividualAttack != 0) hash ^= IndividualAttack.GetHashCode();
if (IndividualDefense != 0) hash ^= IndividualDefense.GetHashCode();
if (IndividualStamina != 0) hash ^= IndividualStamina.GetHashCode();
if (CpMultiplier != 0F) hash ^= CpMultiplier.GetHashCode();
if (Pokeball != 0) hash ^= Pokeball.GetHashCode();
if (CapturedCellId != 0UL) hash ^= CapturedCellId.GetHashCode();
if (BattlesAttacked != 0) hash ^= BattlesAttacked.GetHashCode();
if (BattlesDefended != 0) hash ^= BattlesDefended.GetHashCode();
if (EggIncubatorId.Length != 0) hash ^= EggIncubatorId.GetHashCode();
if (CreationTimeMs != 0UL) hash ^= CreationTimeMs.GetHashCode();
if (NumUpgrades != 0) hash ^= NumUpgrades.GetHashCode();
if (AdditionalCpMultiplier != 0F) hash ^= AdditionalCpMultiplier.GetHashCode();
if (Favorite != 0) hash ^= Favorite.GetHashCode();
if (Nickname.Length != 0) hash ^= Nickname.GetHashCode();
if (FromFort != 0) hash ^= FromFort.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Id != 0UL) {
output.WriteRawTag(9);
output.WriteFixed64(Id);
}
if (PokemonId != 0) {
output.WriteRawTag(16);
output.WriteEnum((int) PokemonId);
}
if (Cp != 0) {
output.WriteRawTag(24);
output.WriteInt32(Cp);
}
if (Stamina != 0) {
output.WriteRawTag(32);
output.WriteInt32(Stamina);
}
if (StaminaMax != 0) {
output.WriteRawTag(40);
output.WriteInt32(StaminaMax);
}
if (Move1 != 0) {
output.WriteRawTag(48);
output.WriteEnum((int) Move1);
}
if (Move2 != 0) {
output.WriteRawTag(56);
output.WriteEnum((int) Move2);
}
if (DeployedFortId.Length != 0) {
output.WriteRawTag(66);
output.WriteString(DeployedFortId);
}
if (OwnerName.Length != 0) {
output.WriteRawTag(74);
output.WriteString(OwnerName);
}
if (IsEgg != false) {
output.WriteRawTag(80);
output.WriteBool(IsEgg);
}
if (EggKmWalkedTarget != 0D) {
output.WriteRawTag(89);
output.WriteDouble(EggKmWalkedTarget);
}
if (EggKmWalkedStart != 0D) {
output.WriteRawTag(97);
output.WriteDouble(EggKmWalkedStart);
}
if (Origin != 0) {
output.WriteRawTag(112);
output.WriteInt32(Origin);
}
if (HeightM != 0F) {
output.WriteRawTag(125);
output.WriteFloat(HeightM);
}
if (WeightKg != 0F) {
output.WriteRawTag(133, 1);
output.WriteFloat(WeightKg);
}
if (IndividualAttack != 0) {
output.WriteRawTag(136, 1);
output.WriteInt32(IndividualAttack);
}
if (IndividualDefense != 0) {
output.WriteRawTag(144, 1);
output.WriteInt32(IndividualDefense);
}
if (IndividualStamina != 0) {
output.WriteRawTag(152, 1);
output.WriteInt32(IndividualStamina);
}
if (CpMultiplier != 0F) {
output.WriteRawTag(165, 1);
output.WriteFloat(CpMultiplier);
}
if (Pokeball != 0) {
output.WriteRawTag(168, 1);
output.WriteEnum((int) Pokeball);
}
if (CapturedCellId != 0UL) {
output.WriteRawTag(176, 1);
output.WriteUInt64(CapturedCellId);
}
if (BattlesAttacked != 0) {
output.WriteRawTag(184, 1);
output.WriteInt32(BattlesAttacked);
}
if (BattlesDefended != 0) {
output.WriteRawTag(192, 1);
output.WriteInt32(BattlesDefended);
}
if (EggIncubatorId.Length != 0) {
output.WriteRawTag(202, 1);
output.WriteString(EggIncubatorId);
}
if (CreationTimeMs != 0UL) {
output.WriteRawTag(208, 1);
output.WriteUInt64(CreationTimeMs);
}
if (NumUpgrades != 0) {
output.WriteRawTag(216, 1);
output.WriteInt32(NumUpgrades);
}
if (AdditionalCpMultiplier != 0F) {
output.WriteRawTag(229, 1);
output.WriteFloat(AdditionalCpMultiplier);
}
if (Favorite != 0) {
output.WriteRawTag(232, 1);
output.WriteInt32(Favorite);
}
if (Nickname.Length != 0) {
output.WriteRawTag(242, 1);
output.WriteString(Nickname);
}
if (FromFort != 0) {
output.WriteRawTag(248, 1);
output.WriteInt32(FromFort);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Id != 0UL) {
size += 1 + 8;
}
if (PokemonId != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) PokemonId);
}
if (Cp != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Cp);
}
if (Stamina != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Stamina);
}
if (StaminaMax != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(StaminaMax);
}
if (Move1 != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Move1);
}
if (Move2 != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Move2);
}
if (DeployedFortId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DeployedFortId);
}
if (OwnerName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(OwnerName);
}
if (IsEgg != false) {
size += 1 + 1;
}
if (EggKmWalkedTarget != 0D) {
size += 1 + 8;
}
if (EggKmWalkedStart != 0D) {
size += 1 + 8;
}
if (Origin != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Origin);
}
if (HeightM != 0F) {
size += 1 + 4;
}
if (WeightKg != 0F) {
size += 2 + 4;
}
if (IndividualAttack != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(IndividualAttack);
}
if (IndividualDefense != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(IndividualDefense);
}
if (IndividualStamina != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(IndividualStamina);
}
if (CpMultiplier != 0F) {
size += 2 + 4;
}
if (Pokeball != 0) {
size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) Pokeball);
}
if (CapturedCellId != 0UL) {
size += 2 + pb::CodedOutputStream.ComputeUInt64Size(CapturedCellId);
}
if (BattlesAttacked != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(BattlesAttacked);
}
if (BattlesDefended != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(BattlesDefended);
}
if (EggIncubatorId.Length != 0) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(EggIncubatorId);
}
if (CreationTimeMs != 0UL) {
size += 2 + pb::CodedOutputStream.ComputeUInt64Size(CreationTimeMs);
}
if (NumUpgrades != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(NumUpgrades);
}
if (AdditionalCpMultiplier != 0F) {
size += 2 + 4;
}
if (Favorite != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(Favorite);
}
if (Nickname.Length != 0) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(Nickname);
}
if (FromFort != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(FromFort);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PokemonData other) {
if (other == null) {
return;
}
if (other.Id != 0UL) {
Id = other.Id;
}
if (other.PokemonId != 0) {
PokemonId = other.PokemonId;
}
if (other.Cp != 0) {
Cp = other.Cp;
}
if (other.Stamina != 0) {
Stamina = other.Stamina;
}
if (other.StaminaMax != 0) {
StaminaMax = other.StaminaMax;
}
if (other.Move1 != 0) {
Move1 = other.Move1;
}
if (other.Move2 != 0) {
Move2 = other.Move2;
}
if (other.DeployedFortId.Length != 0) {
DeployedFortId = other.DeployedFortId;
}
if (other.OwnerName.Length != 0) {
OwnerName = other.OwnerName;
}
if (other.IsEgg != false) {
IsEgg = other.IsEgg;
}
if (other.EggKmWalkedTarget != 0D) {
EggKmWalkedTarget = other.EggKmWalkedTarget;
}
if (other.EggKmWalkedStart != 0D) {
EggKmWalkedStart = other.EggKmWalkedStart;
}
if (other.Origin != 0) {
Origin = other.Origin;
}
if (other.HeightM != 0F) {
HeightM = other.HeightM;
}
if (other.WeightKg != 0F) {
WeightKg = other.WeightKg;
}
if (other.IndividualAttack != 0) {
IndividualAttack = other.IndividualAttack;
}
if (other.IndividualDefense != 0) {
IndividualDefense = other.IndividualDefense;
}
if (other.IndividualStamina != 0) {
IndividualStamina = other.IndividualStamina;
}
if (other.CpMultiplier != 0F) {
CpMultiplier = other.CpMultiplier;
}
if (other.Pokeball != 0) {
Pokeball = other.Pokeball;
}
if (other.CapturedCellId != 0UL) {
CapturedCellId = other.CapturedCellId;
}
if (other.BattlesAttacked != 0) {
BattlesAttacked = other.BattlesAttacked;
}
if (other.BattlesDefended != 0) {
BattlesDefended = other.BattlesDefended;
}
if (other.EggIncubatorId.Length != 0) {
EggIncubatorId = other.EggIncubatorId;
}
if (other.CreationTimeMs != 0UL) {
CreationTimeMs = other.CreationTimeMs;
}
if (other.NumUpgrades != 0) {
NumUpgrades = other.NumUpgrades;
}
if (other.AdditionalCpMultiplier != 0F) {
AdditionalCpMultiplier = other.AdditionalCpMultiplier;
}
if (other.Favorite != 0) {
Favorite = other.Favorite;
}
if (other.Nickname.Length != 0) {
Nickname = other.Nickname;
}
if (other.FromFort != 0) {
FromFort = other.FromFort;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 9: {
Id = input.ReadFixed64();
break;
}
case 16: {
pokemonId_ = (global::POGOProtos.Enums.PokemonId) input.ReadEnum();
break;
}
case 24: {
Cp = input.ReadInt32();
break;
}
case 32: {
Stamina = input.ReadInt32();
break;
}
case 40: {
StaminaMax = input.ReadInt32();
break;
}
case 48: {
move1_ = (global::POGOProtos.Enums.PokemonMove) input.ReadEnum();
break;
}
case 56: {
move2_ = (global::POGOProtos.Enums.PokemonMove) input.ReadEnum();
break;
}
case 66: {
DeployedFortId = input.ReadString();
break;
}
case 74: {
OwnerName = input.ReadString();
break;
}
case 80: {
IsEgg = input.ReadBool();
break;
}
case 89: {
EggKmWalkedTarget = input.ReadDouble();
break;
}
case 97: {
EggKmWalkedStart = input.ReadDouble();
break;
}
case 112: {
Origin = input.ReadInt32();
break;
}
case 125: {
HeightM = input.ReadFloat();
break;
}
case 133: {
WeightKg = input.ReadFloat();
break;
}
case 136: {
IndividualAttack = input.ReadInt32();
break;
}
case 144: {
IndividualDefense = input.ReadInt32();
break;
}
case 152: {
IndividualStamina = input.ReadInt32();
break;
}
case 165: {
CpMultiplier = input.ReadFloat();
break;
}
case 168: {
pokeball_ = (global::POGOProtos.Inventory.Item.ItemId) input.ReadEnum();
break;
}
case 176: {
CapturedCellId = input.ReadUInt64();
break;
}
case 184: {
BattlesAttacked = input.ReadInt32();
break;
}
case 192: {
BattlesDefended = input.ReadInt32();
break;
}
case 202: {
EggIncubatorId = input.ReadString();
break;
}
case 208: {
CreationTimeMs = input.ReadUInt64();
break;
}
case 216: {
NumUpgrades = input.ReadInt32();
break;
}
case 229: {
AdditionalCpMultiplier = input.ReadFloat();
break;
}
case 232: {
Favorite = input.ReadInt32();
break;
}
case 242: {
Nickname = input.ReadString();
break;
}
case 248: {
FromFort = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| zzdragonjaizz/RocketBot | src/POGOProtos/Data/PokemonData.cs | C# | gpl-3.0 | 33,667 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <sys/socket.h>
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "base/posix/eintr_wrapper.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "ipc/unix_domain_socket_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class SocketAcceptor : public base::MessageLoopForIO::Watcher {
public:
SocketAcceptor(int fd, base::MessageLoopProxy* target_thread)
: server_fd_(-1),
target_thread_(target_thread),
started_watching_event_(false, false),
accepted_event_(false, false) {
target_thread->PostTask(FROM_HERE,
base::Bind(&SocketAcceptor::StartWatching, base::Unretained(this), fd));
}
~SocketAcceptor() override {
Close();
}
int server_fd() const { return server_fd_; }
void WaitUntilReady() {
started_watching_event_.Wait();
}
void WaitForAccept() {
accepted_event_.Wait();
}
void Close() {
if (watcher_.get()) {
target_thread_->PostTask(FROM_HERE,
base::Bind(&SocketAcceptor::StopWatching, base::Unretained(this),
watcher_.release()));
}
}
private:
void StartWatching(int fd) {
watcher_.reset(new base::MessageLoopForIO::FileDescriptorWatcher);
base::MessageLoopForIO::current()->WatchFileDescriptor(
fd, true, base::MessageLoopForIO::WATCH_READ, watcher_.get(), this);
started_watching_event_.Signal();
}
void StopWatching(base::MessageLoopForIO::FileDescriptorWatcher* watcher) {
watcher->StopWatchingFileDescriptor();
delete watcher;
}
void OnFileCanReadWithoutBlocking(int fd) override {
ASSERT_EQ(-1, server_fd_);
IPC::ServerAcceptConnection(fd, &server_fd_);
watcher_->StopWatchingFileDescriptor();
accepted_event_.Signal();
}
void OnFileCanWriteWithoutBlocking(int fd) override {}
int server_fd_;
base::MessageLoopProxy* target_thread_;
scoped_ptr<base::MessageLoopForIO::FileDescriptorWatcher> watcher_;
base::WaitableEvent started_watching_event_;
base::WaitableEvent accepted_event_;
DISALLOW_COPY_AND_ASSIGN(SocketAcceptor);
};
const base::FilePath GetChannelDir() {
#if defined(OS_ANDROID)
base::FilePath tmp_dir;
PathService::Get(base::DIR_CACHE, &tmp_dir);
return tmp_dir;
#else
return base::FilePath("/var/tmp");
#endif
}
class TestUnixSocketConnection {
public:
TestUnixSocketConnection()
: worker_("WorkerThread"),
server_listen_fd_(-1),
server_fd_(-1),
client_fd_(-1) {
socket_name_ = GetChannelDir().Append("TestSocket");
base::Thread::Options options;
options.message_loop_type = base::MessageLoop::TYPE_IO;
worker_.StartWithOptions(options);
}
bool CreateServerSocket() {
IPC::CreateServerUnixDomainSocket(socket_name_, &server_listen_fd_);
if (server_listen_fd_ < 0)
return false;
struct stat socket_stat;
stat(socket_name_.value().c_str(), &socket_stat);
EXPECT_TRUE(S_ISSOCK(socket_stat.st_mode));
acceptor_.reset(new SocketAcceptor(server_listen_fd_,
worker_.message_loop_proxy().get()));
acceptor_->WaitUntilReady();
return true;
}
bool CreateClientSocket() {
DCHECK(server_listen_fd_ >= 0);
IPC::CreateClientUnixDomainSocket(socket_name_, &client_fd_);
if (client_fd_ < 0)
return false;
acceptor_->WaitForAccept();
server_fd_ = acceptor_->server_fd();
return server_fd_ >= 0;
}
virtual ~TestUnixSocketConnection() {
if (client_fd_ >= 0)
close(client_fd_);
if (server_fd_ >= 0)
close(server_fd_);
if (server_listen_fd_ >= 0) {
close(server_listen_fd_);
unlink(socket_name_.value().c_str());
}
}
int client_fd() const { return client_fd_; }
int server_fd() const { return server_fd_; }
private:
base::Thread worker_;
base::FilePath socket_name_;
int server_listen_fd_;
int server_fd_;
int client_fd_;
scoped_ptr<SocketAcceptor> acceptor_;
};
// Ensure that IPC::CreateServerUnixDomainSocket creates a socket that
// IPC::CreateClientUnixDomainSocket can successfully connect to.
TEST(UnixDomainSocketUtil, Connect) {
TestUnixSocketConnection connection;
ASSERT_TRUE(connection.CreateServerSocket());
ASSERT_TRUE(connection.CreateClientSocket());
}
// Ensure that messages can be sent across the resulting socket.
TEST(UnixDomainSocketUtil, SendReceive) {
TestUnixSocketConnection connection;
ASSERT_TRUE(connection.CreateServerSocket());
ASSERT_TRUE(connection.CreateClientSocket());
const char buffer[] = "Hello, server!";
size_t buf_len = sizeof(buffer);
size_t sent_bytes =
HANDLE_EINTR(send(connection.client_fd(), buffer, buf_len, 0));
ASSERT_EQ(buf_len, sent_bytes);
char recv_buf[sizeof(buffer)];
size_t received_bytes =
HANDLE_EINTR(recv(connection.server_fd(), recv_buf, buf_len, 0));
ASSERT_EQ(buf_len, received_bytes);
ASSERT_EQ(0, memcmp(recv_buf, buffer, buf_len));
}
} // namespace
| michaelforfxhelp/fxhelprepo | third_party/chromium/ipc/unix_domain_socket_util_unittest.cc | C++ | mpl-2.0 | 5,234 |
/*
* Copyright 2000-2014 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.jetbrains.python.codeInsight.imports;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileSystemItem;
import com.intellij.psi.util.QualifiedName;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.python.psi.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* An immutable holder of information for one auto-import candidate.
* <p/>
* There can be do different flavors of such candidates:
* <ul>
* <li>Candidates based on existing imports in module. In this case {@link #getImportElement()} must return not {@code null}.</li>
* <li>Candidates not yet imported. In this case {@link #getPath()} must return not {@code null}.</li>
* </ul>
* <p/>
*
* @author dcheryasov
*/
// visibility is intentionally package-level
public class ImportCandidateHolder implements Comparable<ImportCandidateHolder> {
private final PsiElement myImportable;
private final PyImportElement myImportElement;
private final PsiFileSystemItem myFile;
private final QualifiedName myPath;
@Nullable private final String myAsName;
/**
* Creates new instance.
*
* @param importable an element that could be imported either from import element or from file.
* @param file the file which is the source of the importable (module for symbols, containing directory for modules and packages)
* @param importElement an existing import element that can be a source for the importable.
* @param path import path for the file, as a qualified name (a.b.c)
* For top-level imported symbols it's <em>qualified name of containing module</em> (or package for __init__.py).
* For modules and packages it should be <em>qualified name of their parental package</em>
* (empty for modules and packages located at source roots).
*
*/
public ImportCandidateHolder(@NotNull PsiElement importable, @NotNull PsiFileSystemItem file,
@Nullable PyImportElement importElement, @Nullable QualifiedName path, @Nullable String asName) {
myFile = file;
myImportable = importable;
myImportElement = importElement;
myPath = path;
myAsName = asName;
assert importElement != null || path != null; // one of these must be present
}
public ImportCandidateHolder(@NotNull PsiElement importable, @NotNull PsiFileSystemItem file,
@Nullable PyImportElement importElement, @Nullable QualifiedName path) {
this(importable, file, importElement, path, null);
}
@NotNull
public PsiElement getImportable() {
return myImportable;
}
@Nullable
public PyImportElement getImportElement() {
return myImportElement;
}
@NotNull
public PsiFileSystemItem getFile() {
return myFile;
}
@Nullable
public QualifiedName getPath() {
return myPath;
}
/**
* Helper method that builds an import path, handling all these "import foo", "import foo as bar", "from bar import foo", etc.
* Either importPath or importSource must be not null.
*
* @param name what is ultimately imported.
* @param importPath known path to import the name.
* @param source known ImportElement to import the name; its 'as' clause is used if present.
* @return a properly qualified name.
*/
@NotNull
public static String getQualifiedName(@NotNull String name, @Nullable QualifiedName importPath, @Nullable PyImportElement source) {
final StringBuilder sb = new StringBuilder();
if (source != null) {
final PsiElement parent = source.getParent();
if (parent instanceof PyFromImportStatement) {
sb.append(name);
}
else {
sb.append(source.getVisibleName()).append(".").append(name);
}
}
else {
if (importPath != null && importPath.getComponentCount() > 0) {
sb.append(importPath).append(".");
}
sb.append(name);
}
return sb.toString();
}
@NotNull
public String getPresentableText(@NotNull String myName) {
final StringBuilder sb = new StringBuilder(getQualifiedName(myName, myPath, myImportElement));
PsiElement parent = null;
if (myImportElement != null) {
parent = myImportElement.getParent();
}
if (myImportable instanceof PyFunction) {
sb.append("()");
}
else if (myImportable instanceof PyClass) {
final List<String> supers = ContainerUtil.mapNotNull(((PyClass)myImportable).getSuperClasses(null),
cls -> PyUtil.isObjectClass(cls) ? null : cls.getName());
if (!supers.isEmpty()) {
sb.append("(");
StringUtil.join(supers, ", ", sb);
sb.append(")");
}
}
if (parent instanceof PyFromImportStatement) {
sb.append(" from ");
final PyFromImportStatement fromImportStatement = (PyFromImportStatement)parent;
sb.append(StringUtil.repeat(".", fromImportStatement.getRelativeLevel()));
final PyReferenceExpression source = fromImportStatement.getImportSource();
if (source != null) {
sb.append(source.getReferencedName());
}
}
return sb.toString();
}
public int compareTo(@NotNull ImportCandidateHolder other) {
final int lRelevance = getRelevance();
final int rRelevance = other.getRelevance();
if (rRelevance != lRelevance) {
return rRelevance - lRelevance;
}
if (myPath != null && other.myPath != null) {
// prefer shorter paths
final int lengthDiff = myPath.getComponentCount() - other.myPath.getComponentCount();
if (lengthDiff != 0) {
return lengthDiff;
}
}
return Comparing.compare(myPath, other.myPath);
}
int getRelevance() {
final Project project = myImportable.getProject();
final PsiFile psiFile = myImportable.getContainingFile();
final VirtualFile vFile = psiFile == null ? null : psiFile.getVirtualFile();
if (vFile == null) return 0;
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
// files under project source are most relevant
final Module module = fileIndex.getModuleForFile(vFile);
if (module != null) return 3;
// then come files directly under Lib
if (vFile.getParent().getName().equals("Lib")) return 2;
// tests we don't want
if (vFile.getParent().getName().equals("test")) return 0;
return 1;
}
@Nullable
public String getAsName() {
return myAsName;
}
}
| ThiagoGarciaAlves/intellij-community | python/src/com/jetbrains/python/codeInsight/imports/ImportCandidateHolder.java | Java | apache-2.0 | 7,544 |
/*
* #%L
* Native ARchive plugin for Maven
* %%
* Copyright (C) 2002 - 2014 NAR Maven Plugin developers.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.maven_nar.cpptasks.types;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Path;
import com.github.maven_nar.cpptasks.CUtil;
/**
* An Ant Path object augmented with if and unless conditionals
*
* @author Curt Arnold
*/
public class ConditionalPath extends Path {
private String ifCond;
private String unlessCond;
public ConditionalPath(final Project project) {
super(project);
}
public ConditionalPath(final Project p, final String path) {
super(p, path);
}
/**
* Returns true if the Path's if and unless conditions (if any) are
* satisfied.
*/
public boolean isActive(final org.apache.tools.ant.Project p) throws BuildException {
return CUtil.isActive(p, this.ifCond, this.unlessCond);
}
/**
* Sets the property name for the 'if' condition.
*
* The path will be ignored unless the property is defined.
*
* The value of the property is insignificant, but values that would imply
* misinterpretation ("false", "no") will throw an exception when
* evaluated.
*
* @param propName
* property name
*/
public void setIf(final String propName) {
this.ifCond = propName;
}
/**
* Set the property name for the 'unless' condition.
*
* If named property is set, the path will be ignored.
*
* The value of the property is insignificant, but values that would imply
* misinterpretation ("false", "no") of the behavior will throw an
* exception when evaluated.
*
* @param propName
* name of property
*/
public void setUnless(final String propName) {
this.unlessCond = propName;
}
}
| dugilos/nar-maven-plugin | src/main/java/com/github/maven_nar/cpptasks/types/ConditionalPath.java | Java | apache-2.0 | 2,393 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.ml.dataframe.evaluation.regression;
import org.elasticsearch.client.ml.dataframe.evaluation.MlEvaluationNamedXContentProvider;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.test.AbstractXContentTestCase;
import java.io.IOException;
public class MeanSquaredErrorMetricResultTests extends AbstractXContentTestCase<MeanSquaredErrorMetric.Result> {
public static MeanSquaredErrorMetric.Result randomResult() {
return new MeanSquaredErrorMetric.Result(randomDouble());
}
@Override
protected MeanSquaredErrorMetric.Result createTestInstance() {
return randomResult();
}
@Override
protected MeanSquaredErrorMetric.Result doParseInstance(XContentParser parser) throws IOException {
return MeanSquaredErrorMetric.Result.fromXContent(parser);
}
@Override
protected boolean supportsUnknownFields() {
return true;
}
@Override
protected NamedXContentRegistry xContentRegistry() {
return new NamedXContentRegistry(new MlEvaluationNamedXContentProvider().getNamedXContentParsers());
}
}
| gingerwizard/elasticsearch | client/rest-high-level/src/test/java/org/elasticsearch/client/ml/dataframe/evaluation/regression/MeanSquaredErrorMetricResultTests.java | Java | apache-2.0 | 1,999 |
module MiqReport::Generator::Html
def build_html_rows(clickable_rows = false)
tz = get_time_zone(Time.zone.name) if Time.zone
html_rows = []
group_counter = 0
row = 0
self.rpt_options ||= {}
self.col_formats ||= [] # Backward compat - create empty array for formats
group_limit = self.rpt_options[:group_limit]
in_a_widget = self.rpt_options[:in_a_widget] || false
unless table.nil? || table.data.empty?
# Following line commented for now - for not showing repeating column values
# prev_data = String.new # Initialize the prev_data variable
hide_detail_rows = self.rpt_options.fetch_path(:summary, :hide_detail_rows) || false
row_limit = self.rpt_options && self.rpt_options[:row_limit] ? self.rpt_options[:row_limit] : 0
save_val = :_undefined_ # Hang on to the current group value
break_label = col_options.fetch_path(sortby[0], :break_label) unless sortby.nil? || col_options.nil? || in_a_widget
group_text = nil # Optionally override what gets displayed for the group (i.e. Chargeback)
use_table = sub_table ? sub_table : table
use_table.data.each_with_index do |d, d_idx|
break if row_limit != 0 && d_idx > row_limit - 1
output = ""
if ["y", "c"].include?(group) && !sortby.nil? && save_val != d.data[sortby[0]].to_s
unless d_idx == 0 # If not the first row, we are at a group break
unless group_limit && group_counter >= group_limit # If not past the limit
html_rows += build_group_html_rows(save_val, col_order.length, break_label, group_text)
group_counter += 1
end
end
save_val = d.data[sortby[0]].to_s
# Chargeback, sort by date, but show range
group_text = d.data["display_range"] if Chargeback.db_is_chargeback?(db) && sortby[0] == "start_date"
end
# Build click thru if string can be created
if clickable_rows && onclick = build_row_onclick(d.data)
output << "<tr class='row#{row}' #{onclick}>"
else
output << "<tr class='row#{row}-nocursor'>"
end
row = 1 - row
col_order.each_with_index do |c, c_idx|
build_html_col(output, c, self.col_formats[c_idx], d.data)
end
output << "</tr>"
html_rows << output unless hide_detail_rows
end
if ["y", "c"].include?(group) && !sortby.nil?
unless group_limit && group_counter >= group_limit
html_rows += build_group_html_rows(save_val, col_order.length, break_label, group_text)
html_rows += build_group_html_rows(:_total_, col_order.length)
end
end
end
html_rows
end
def build_html_col(output, col_name, col_format, row_data)
style = get_style_class(col_name, row_data, tz)
style_class = !style.nil? ? " class='#{style}'" : nil
if col_name == 'resource_type'
output << "<td#{style_class}>"
output << ui_lookup(:model => row_data[col_name]) # Lookup models in resource_type col
elsif db == 'Tenant' && TenantQuota.can_format_field?(col_name, row_data['tenant_quotas.name'])
output << "<td#{style_class} " + 'style="text-align:right">'
output << CGI.escapeHTML(TenantQuota.format_quota_value(col_name, row_data[col_name], row_data['tenant_quotas.name']))
elsif ['<compare>', '<drift>'].include?(db.to_s)
output << "<td#{style_class}>"
output << CGI.escapeHTML(row_data[col_name].to_s)
else
if row_data[col_name].kind_of?(Time)
output << "<td#{style_class} " + 'style="text-align:center">'
elsif row_data[col_name].kind_of?(Bignum) || row_data[col_name].kind_of?(Fixnum) || row_data[col_name].kind_of?(Float)
output << "<td#{style_class} " + 'style="text-align:right">'
else
output << "<td#{style_class}>"
end
output << CGI.escapeHTML(format(col_name.split("__").first, row_data[col_name],
:format => col_format || :_default_, :tz => tz))
end
output << '</td>'
end
# Depending on the model the table is based on, return the onclick string for the report row
def build_row_onclick(data_row)
onclick = nil
# Handle CI based report rows
if ['EmsCluster', 'ExtManagementSystem', 'Host', 'Storage', 'Vm', 'Service'].include?(db) && data_row['id']
controller = db == "ExtManagementSystem" ? "management_system" : db.underscore
donav = "DoNav('/#{controller}/show/#{data_row['id']}');"
title = data_row['name'] ?
"View #{ui_lookup(:model => db)} \"#{data_row['name']}\"" :
"View this #{ui_lookup(:model => db)}"
onclick = "onclick=\"#{donav}\" style='cursor:hand' title='#{title}'"
end
# Handle CI performance report rows
if db.ends_with?("Performance")
if data_row['resource_id'] && data_row['resource_type'] # Base click thru on the related resource
donav = "DoNav('/#{data_row['resource_type'].underscore}/show/#{data_row['resource_id']}');"
onclick = "onclick=\"#{donav}\" style='cursor:hand' title='View #{ui_lookup(:model => data_row['resource_type'])} \"#{data_row['resource_name']}\"'"
end
end
onclick
end
# Generate grouping rows for the passed in grouping value
def build_group_html_rows(group, col_count, label = nil, group_text = nil)
in_a_widget = self.rpt_options[:in_a_widget] || false
html_rows = []
content =
if group == :_total_
"All Rows"
else
group_label = group_text || group
group_label = "<Empty>" if group_label.blank?
"#{label}#{group_label}"
end
if (self.group == 'c') && extras && extras[:grouping] && extras[:grouping][group]
display_count = _("Count: %{number}") % {:number => extras[:grouping][group][:count]}
end
content << " | #{display_count}" unless display_count.blank?
html_rows << "<tr><td class='group' colspan='#{col_count}'>#{CGI.escapeHTML(content)}</td></tr>"
if extras && extras[:grouping] && extras[:grouping][group] # See if group key exists
MiqReport::GROUPINGS.each do |calc| # Add an output row for each group calculation
if extras[:grouping][group].key?(calc.first) # Only add a row if there are calcs of this type for this group value
grp_output = ""
grp_output << "<tr>"
grp_output << "<td#{in_a_widget ? "" : " class='group'"} style='text-align:right'>#{calc.last.pluralize}:</td>"
col_order.each_with_index do |c, c_idx| # Go through the columns
next if c_idx == 0 # Skip first column
grp_output << "<td#{in_a_widget ? "" : " class='group'"} style='text-align:right'>"
grp_output << CGI.escapeHTML(
format(
c.split("__").first, extras[:grouping][group][calc.first][c],
:format => self.col_formats[c_idx] ? self.col_formats[c_idx] : :_default_
)
) if extras[:grouping][group].key?(calc.first)
grp_output << "</td>"
end
grp_output << "</tr>"
html_rows << grp_output
end
end
end
html_rows << "<tr><td class='group_spacer' colspan='#{col_count}'> </td></tr>" unless group == :_total_
html_rows
end
def get_style_class(col, row, tz = nil)
atoms = col_options.fetch_path(col, :style) unless col_options.nil?
return if atoms.nil?
nh = {}; row.each { |k, v| nh[col_to_expression_col(k).sub(/-/, ".")] = v } # Convert keys to match expression fields
field = col_to_expression_col(col)
atoms.each do |atom|
return atom[:class] if atom[:operator].downcase == "default"
exp = expression_for_style_class(field, atom)
return atom[:class] if exp.evaluate(nh, tz)
end
nil
end
def expression_for_style_class(field, atom)
@expression_for_style_class ||= {}
@expression_for_style_class[field] ||= {}
value = atom[:value]
value = [value, atom[:value_suffix]].join(".").to_f_with_method if atom[:value_suffix] && value.to_f.respond_to?(atom[:value_suffix])
@expression_for_style_class[field][atom] ||= MiqExpression.new({atom[:operator] => {"field" => field, "value" => value}}, "hash")
end
end
| mfeifer/manageiq | app/models/miq_report/generator/html.rb | Ruby | apache-2.0 | 8,450 |
/**
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
*/
package com.typesafe.config.impl;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import com.typesafe.config.*;
final class ConfigParser {
static AbstractConfigValue parse(ConfigNodeRoot document,
ConfigOrigin origin, ConfigParseOptions options,
ConfigIncludeContext includeContext) {
ParseContext context = new ParseContext(options.getSyntax(), origin, document,
SimpleIncluder.makeFull(options.getIncluder()), includeContext);
return context.parse();
}
static private final class ParseContext {
private int lineNumber;
final private ConfigNodeRoot document;
final private FullIncluder includer;
final private ConfigIncludeContext includeContext;
final private ConfigSyntax flavor;
final private ConfigOrigin baseOrigin;
final private LinkedList<Path> pathStack;
// the number of lists we are inside; this is used to detect the "cannot
// generate a reference to a list element" problem, and once we fix that
// problem we should be able to get rid of this variable.
int arrayCount;
ParseContext(ConfigSyntax flavor, ConfigOrigin origin, ConfigNodeRoot document,
FullIncluder includer, ConfigIncludeContext includeContext) {
lineNumber = 1;
this.document = document;
this.flavor = flavor;
this.baseOrigin = origin;
this.includer = includer;
this.includeContext = includeContext;
this.pathStack = new LinkedList<Path>();
this.arrayCount = 0;
}
// merge a bunch of adjacent values into one
// value; change unquoted text into a string
// value.
private AbstractConfigValue parseConcatenation(ConfigNodeConcatenation n) {
// this trick is not done in JSON
if (flavor == ConfigSyntax.JSON)
throw new ConfigException.BugOrBroken("Found a concatenation node in JSON");
List<AbstractConfigValue> values = new ArrayList<AbstractConfigValue>();
for (AbstractConfigNode node : n.children()) {
AbstractConfigValue v = null;
if (node instanceof AbstractConfigNodeValue) {
v = parseValue((AbstractConfigNodeValue)node, null);
values.add(v);
}
}
return ConfigConcatenation.concatenate(values);
}
private SimpleConfigOrigin lineOrigin() {
return ((SimpleConfigOrigin) baseOrigin).withLineNumber(lineNumber);
}
private ConfigException parseError(String message) {
return parseError(message, null);
}
private ConfigException parseError(String message, Throwable cause) {
return new ConfigException.Parse(lineOrigin(), message, cause);
}
private Path fullCurrentPath() {
// pathStack has top of stack at front
if (pathStack.isEmpty())
throw new ConfigException.BugOrBroken("Bug in parser; tried to get current path when at root");
else
return new Path(pathStack.descendingIterator());
}
private AbstractConfigValue parseValue(AbstractConfigNodeValue n, List<String> comments) {
AbstractConfigValue v;
int startingArrayCount = arrayCount;
if (n instanceof ConfigNodeSimpleValue) {
v = ((ConfigNodeSimpleValue) n).value();
} else if (n instanceof ConfigNodeObject) {
v = parseObject((ConfigNodeObject)n);
} else if (n instanceof ConfigNodeArray) {
v = parseArray((ConfigNodeArray)n);
} else if (n instanceof ConfigNodeConcatenation) {
v = parseConcatenation((ConfigNodeConcatenation)n);
} else {
throw parseError("Expecting a value but got wrong node type: " + n.getClass());
}
if (comments != null && !comments.isEmpty()) {
v = v.withOrigin(v.origin().prependComments(new ArrayList<String>(comments)));
comments.clear();
}
if (arrayCount != startingArrayCount)
throw new ConfigException.BugOrBroken("Bug in config parser: unbalanced array count");
return v;
}
private static AbstractConfigObject createValueUnderPath(Path path,
AbstractConfigValue value) {
// for path foo.bar, we are creating
// { "foo" : { "bar" : value } }
List<String> keys = new ArrayList<String>();
String key = path.first();
Path remaining = path.remainder();
while (key != null) {
keys.add(key);
if (remaining == null) {
break;
} else {
key = remaining.first();
remaining = remaining.remainder();
}
}
// the withComments(null) is to ensure comments are only
// on the exact leaf node they apply to.
// a comment before "foo.bar" applies to the full setting
// "foo.bar" not also to "foo"
ListIterator<String> i = keys.listIterator(keys.size());
String deepest = i.previous();
AbstractConfigObject o = new SimpleConfigObject(value.origin().withComments(null),
Collections.<String, AbstractConfigValue> singletonMap(
deepest, value));
while (i.hasPrevious()) {
Map<String, AbstractConfigValue> m = Collections.<String, AbstractConfigValue> singletonMap(
i.previous(), o);
o = new SimpleConfigObject(value.origin().withComments(null), m);
}
return o;
}
private void parseInclude(Map<String, AbstractConfigValue> values, ConfigNodeInclude n) {
AbstractConfigObject obj;
switch (n.kind()) {
case URL:
URL url;
try {
url = new URL(n.name());
} catch (MalformedURLException e) {
throw parseError("include url() specifies an invalid URL: " + n.name(), e);
}
obj = (AbstractConfigObject) includer.includeURL(includeContext, url);
break;
case FILE:
obj = (AbstractConfigObject) includer.includeFile(includeContext,
new File(n.name()));
break;
case CLASSPATH:
obj = (AbstractConfigObject) includer.includeResources(includeContext, n.name());
break;
case HEURISTIC:
obj = (AbstractConfigObject) includer
.include(includeContext, n.name());
break;
default:
throw new ConfigException.BugOrBroken("should not be reached");
}
// we really should make this work, but for now throwing an
// exception is better than producing an incorrect result.
// See https://github.com/typesafehub/config/issues/160
if (arrayCount > 0 && obj.resolveStatus() != ResolveStatus.RESOLVED)
throw parseError("Due to current limitations of the config parser, when an include statement is nested inside a list value, "
+ "${} substitutions inside the included file cannot be resolved correctly. Either move the include outside of the list value or "
+ "remove the ${} statements from the included file.");
if (!pathStack.isEmpty()) {
Path prefix = fullCurrentPath();
obj = obj.relativized(prefix);
}
for (String key : obj.keySet()) {
AbstractConfigValue v = obj.get(key);
AbstractConfigValue existing = values.get(key);
if (existing != null) {
values.put(key, v.withFallback(existing));
} else {
values.put(key, v);
}
}
}
private AbstractConfigObject parseObject(ConfigNodeObject n) {
Map<String, AbstractConfigValue> values = new HashMap<String, AbstractConfigValue>();
SimpleConfigOrigin objectOrigin = lineOrigin();
boolean lastWasNewline = false;
ArrayList<AbstractConfigNode> nodes = new ArrayList<AbstractConfigNode>(n.children());
List<String> comments = new ArrayList<String>();
for (int i = 0; i < nodes.size(); i++) {
AbstractConfigNode node = nodes.get(i);
if (node instanceof ConfigNodeComment) {
lastWasNewline = false;
comments.add(((ConfigNodeComment) node).commentText());
} else if (node instanceof ConfigNodeSingleToken && Tokens.isNewline(((ConfigNodeSingleToken) node).token())) {
lineNumber++;
if (lastWasNewline) {
// Drop all comments if there was a blank line and start a new comment block
comments.clear();
}
lastWasNewline = true;
} else if (flavor != ConfigSyntax.JSON && node instanceof ConfigNodeInclude) {
parseInclude(values, (ConfigNodeInclude)node);
lastWasNewline = false;
} else if (node instanceof ConfigNodeField) {
lastWasNewline = false;
Path path = ((ConfigNodeField) node).path().value();
comments.addAll(((ConfigNodeField) node).comments());
// path must be on-stack while we parse the value
pathStack.push(path);
if (((ConfigNodeField) node).separator() == Tokens.PLUS_EQUALS) {
// we really should make this work, but for now throwing
// an exception is better than producing an incorrect
// result. See
// https://github.com/typesafehub/config/issues/160
if (arrayCount > 0)
throw parseError("Due to current limitations of the config parser, += does not work nested inside a list. "
+ "+= expands to a ${} substitution and the path in ${} cannot currently refer to list elements. "
+ "You might be able to move the += outside of the list and then refer to it from inside the list with ${}.");
// because we will put it in an array after the fact so
// we want this to be incremented during the parseValue
// below in order to throw the above exception.
arrayCount += 1;
}
AbstractConfigNodeValue valueNode;
AbstractConfigValue newValue;
valueNode = ((ConfigNodeField) node).value();
// comments from the key token go to the value token
newValue = parseValue(valueNode, comments);
if (((ConfigNodeField) node).separator() == Tokens.PLUS_EQUALS) {
arrayCount -= 1;
List<AbstractConfigValue> concat = new ArrayList<AbstractConfigValue>(2);
AbstractConfigValue previousRef = new ConfigReference(newValue.origin(),
new SubstitutionExpression(fullCurrentPath(), true /* optional */));
AbstractConfigValue list = new SimpleConfigList(newValue.origin(),
Collections.singletonList(newValue));
concat.add(previousRef);
concat.add(list);
newValue = ConfigConcatenation.concatenate(concat);
}
// Grab any trailing comments on the same line
if (i < nodes.size() - 1) {
i++;
while (i < nodes.size()) {
if (nodes.get(i) instanceof ConfigNodeComment) {
ConfigNodeComment comment = (ConfigNodeComment) nodes.get(i);
newValue = newValue.withOrigin(newValue.origin().appendComments(
Collections.singletonList(comment.commentText())));
break;
} else if (nodes.get(i) instanceof ConfigNodeSingleToken) {
ConfigNodeSingleToken curr = (ConfigNodeSingleToken) nodes.get(i);
if (curr.token() == Tokens.COMMA || Tokens.isIgnoredWhitespace(curr.token())) {
// keep searching, as there could still be a comment
} else {
i--;
break;
}
} else {
i--;
break;
}
i++;
}
}
pathStack.pop();
String key = path.first();
Path remaining = path.remainder();
if (remaining == null) {
AbstractConfigValue existing = values.get(key);
if (existing != null) {
// In strict JSON, dups should be an error; while in
// our custom config language, they should be merged
// if the value is an object (or substitution that
// could become an object).
if (flavor == ConfigSyntax.JSON) {
throw parseError("JSON does not allow duplicate fields: '"
+ key
+ "' was already seen at "
+ existing.origin().description());
} else {
newValue = newValue.withFallback(existing);
}
}
values.put(key, newValue);
} else {
if (flavor == ConfigSyntax.JSON) {
throw new ConfigException.BugOrBroken(
"somehow got multi-element path in JSON mode");
}
AbstractConfigObject obj = createValueUnderPath(
remaining, newValue);
AbstractConfigValue existing = values.get(key);
if (existing != null) {
obj = obj.withFallback(existing);
}
values.put(key, obj);
}
}
}
return new SimpleConfigObject(objectOrigin, values);
}
private SimpleConfigList parseArray(ConfigNodeArray n) {
arrayCount += 1;
SimpleConfigOrigin arrayOrigin = lineOrigin();
List<AbstractConfigValue> values = new ArrayList<AbstractConfigValue>();
boolean lastWasNewLine = false;
List<String> comments = new ArrayList<String>();
AbstractConfigValue v = null;
for (AbstractConfigNode node : n.children()) {
if (node instanceof ConfigNodeComment) {
comments.add(((ConfigNodeComment) node).commentText());
lastWasNewLine = false;
} else if (node instanceof ConfigNodeSingleToken && Tokens.isNewline(((ConfigNodeSingleToken) node).token())) {
lineNumber++;
if (lastWasNewLine && v == null) {
comments.clear();
} else if (v != null) {
values.add(v.withOrigin(v.origin().appendComments(new ArrayList<String>(comments))));
comments.clear();
v = null;
}
lastWasNewLine = true;
} else if (node instanceof AbstractConfigNodeValue) {
lastWasNewLine = false;
if (v != null) {
values.add(v.withOrigin(v.origin().appendComments(new ArrayList<String>(comments))));
comments.clear();
}
v = parseValue((AbstractConfigNodeValue)node, comments);
}
}
// There shouldn't be any comments at this point, but add them just in case
if (v != null) {
values.add(v.withOrigin(v.origin().appendComments(new ArrayList<String>(comments))));
}
arrayCount -= 1;
return new SimpleConfigList(arrayOrigin, values);
}
AbstractConfigValue parse() {
AbstractConfigValue result = null;
ArrayList<String> comments = new ArrayList<String>();
boolean lastWasNewLine = false;
for (AbstractConfigNode node : document.children()) {
if (node instanceof ConfigNodeComment) {
comments.add(((ConfigNodeComment) node).commentText());
lastWasNewLine = false;
} else if (node instanceof ConfigNodeSingleToken) {
Token t = ((ConfigNodeSingleToken) node).token();
if (Tokens.isNewline(t)) {
lineNumber++;
if (lastWasNewLine && result == null) {
comments.clear();
} else if (result != null) {
result = result.withOrigin(result.origin().appendComments(new ArrayList<String>(comments)));
comments.clear();
break;
}
lastWasNewLine = true;
}
} else if (node instanceof ConfigNodeComplexValue) {
result = parseValue((ConfigNodeComplexValue)node, comments);
lastWasNewLine = false;
}
}
return result;
}
}
}
| fpringvaldsen/config | config/src/main/java/com/typesafe/config/impl/ConfigParser.java | Java | apache-2.0 | 19,298 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 4.3.2 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2010, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* System Front Controller
*
* Loads the base classes and executes the request.
*
* @package CodeIgniter
* @subpackage codeigniter
* @category Front-controller
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/
*/
// CI Version
define('CI_VERSION', '1.7.3');
/*
* ------------------------------------------------------
* Load the global functions
* ------------------------------------------------------
*/
require(BASEPATH.'codeigniter/Common'.EXT);
/*
* ------------------------------------------------------
* Load the compatibility override functions
* ------------------------------------------------------
*/
require(BASEPATH.'codeigniter/Compat'.EXT);
/*
* ------------------------------------------------------
* Load the framework constants
* ------------------------------------------------------
*/
require(APPPATH.'config/constants'.EXT);
/*
* ------------------------------------------------------
* Define a custom error handler so we can log PHP errors
* ------------------------------------------------------
*/
set_error_handler('_exception_handler');
if ( ! is_php('5.3'))
{
@set_magic_quotes_runtime(0); // Kill magic quotes
}
/*
* ------------------------------------------------------
* Start the timer... tick tock tick tock...
* ------------------------------------------------------
*/
$BM =& load_class('Benchmark');
$BM->mark('total_execution_time_start');
$BM->mark('loading_time_base_classes_start');
/*
* ------------------------------------------------------
* Instantiate the hooks class
* ------------------------------------------------------
*/
$EXT =& load_class('Hooks');
/*
* ------------------------------------------------------
* Is there a "pre_system" hook?
* ------------------------------------------------------
*/
$EXT->_call_hook('pre_system');
/*
* ------------------------------------------------------
* Instantiate the base classes
* ------------------------------------------------------
*/
$CFG =& load_class('Config');
$URI =& load_class('URI');
$RTR =& load_class('Router');
$OUT =& load_class('Output');
/*
* ------------------------------------------------------
* Is there a valid cache file? If so, we're done...
* ------------------------------------------------------
*/
if ($EXT->_call_hook('cache_override') === FALSE)
{
if ($OUT->_display_cache($CFG, $URI) == TRUE)
{
exit;
}
}
/*
* ------------------------------------------------------
* Load the remaining base classes
* ------------------------------------------------------
*/
$IN =& load_class('Input');
$LANG =& load_class('Language');
/*
* ------------------------------------------------------
* Load the app controller and local controller
* ------------------------------------------------------
*
* Note: Due to the poor object handling in PHP 4 we'll
* conditionally load different versions of the base
* class. Retaining PHP 4 compatibility requires a bit of a hack.
*
* Note: The Loader class needs to be included first
*
*/
if ( ! is_php('5.0.0'))
{
load_class('Loader', FALSE);
require(BASEPATH.'codeigniter/Base4'.EXT);
}
else
{
require(BASEPATH.'codeigniter/Base5'.EXT);
}
// Load the base controller class
load_class('Controller', FALSE);
// Load the local application controller
// Note: The Router class automatically validates the controller path. If this include fails it
// means that the default controller in the Routes.php file is not resolving to something valid.
if ( ! file_exists(APPPATH.'controllers/'.$RTR->fetch_directory().$RTR->fetch_class().EXT))
{
show_error('Unable to load your default controller. Please make sure the controller specified in your Routes.php file is valid.');
}
include(APPPATH.'controllers/'.$RTR->fetch_directory().$RTR->fetch_class().EXT);
// Set a mark point for benchmarking
$BM->mark('loading_time_base_classes_end');
/*
* ------------------------------------------------------
* Security check
* ------------------------------------------------------
*
* None of the functions in the app controller or the
* loader class can be called via the URI, nor can
* controller functions that begin with an underscore
*/
$class = $RTR->fetch_class();
$method = $RTR->fetch_method();
if ( ! class_exists($class)
OR $method == 'controller'
OR strncmp($method, '_', 1) == 0
OR in_array(strtolower($method), array_map('strtolower', get_class_methods('Controller')))
)
{
show_404("{$class}/{$method}");
}
/*
* ------------------------------------------------------
* Is there a "pre_controller" hook?
* ------------------------------------------------------
*/
$EXT->_call_hook('pre_controller');
/*
* ------------------------------------------------------
* Instantiate the controller and call requested method
* ------------------------------------------------------
*/
// Mark a start point so we can benchmark the controller
$BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start');
$CI = new $class();
// Is this a scaffolding request?
if ($RTR->scaffolding_request === TRUE)
{
if ($EXT->_call_hook('scaffolding_override') === FALSE)
{
$CI->_ci_scaffolding();
}
}
else
{
/*
* ------------------------------------------------------
* Is there a "post_controller_constructor" hook?
* ------------------------------------------------------
*/
$EXT->_call_hook('post_controller_constructor');
// Is there a "remap" function?
if (method_exists($CI, '_remap'))
{
$CI->_remap($method);
}
else
{
// is_callable() returns TRUE on some versions of PHP 5 for private and protected
// methods, so we'll use this workaround for consistent behavior
if ( ! in_array(strtolower($method), array_map('strtolower', get_class_methods($CI))))
{
show_404("{$class}/{$method}");
}
// Call the requested method.
// Any URI segments present (besides the class/function) will be passed to the method for convenience
call_user_func_array(array(&$CI, $method), array_slice($URI->rsegments, 2));
}
}
// Mark a benchmark end point
$BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end');
/*
* ------------------------------------------------------
* Is there a "post_controller" hook?
* ------------------------------------------------------
*/
$EXT->_call_hook('post_controller');
/*
* ------------------------------------------------------
* Send the final rendered output to the browser
* ------------------------------------------------------
*/
if ($EXT->_call_hook('display_override') === FALSE)
{
$OUT->_display();
}
/*
* ------------------------------------------------------
* Is there a "post_system" hook?
* ------------------------------------------------------
*/
$EXT->_call_hook('post_system');
/*
* ------------------------------------------------------
* Close the DB connection if one exists
* ------------------------------------------------------
*/
if (class_exists('CI_DB') AND isset($CI->db))
{
$CI->db->close();
}
/* End of file CodeIgniter.php */
/* Location: ./system/codeigniter/CodeIgniter.php */ | prashants/webzash-v1-defunct | system/codeigniter/CodeIgniter.php | PHP | apache-2.0 | 7,665 |
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --allow-natives-syntax --harmony-do-expressions
function f(x) {
switch (x) {
case 1: return "one";
case 2: return "two";
case do { for (var i = 0; i < 10; i++) { if (i == 5) %OptimizeOsr(); } }:
case 3: return "WAT";
}
}
assertEquals("one", f(1));
assertEquals("two", f(2));
assertEquals("WAT", f(3));
| macchina-io/macchina.io | platform/JS/V8/v8/test/mjsunit/regress/regress-osr-in-case-label.js | JavaScript | apache-2.0 | 502 |
/*******************************************************************************
* Copyright (c) 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Zend Technologies
*******************************************************************************/
package org.eclipse.php.internal.core.preferences;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* A base class for all the preferences propagators.
*
* @author shalom
*/
public abstract class AbstractPreferencesPropagator {
protected HashMap listenersMap;
protected boolean isInstalled;
protected Object lock = new Object();
/**
* Constructs an AbstractPreferencesPropagator.
*/
public AbstractPreferencesPropagator() {
}
/**
* Adds an IPreferencesPropagatorListener with a preferences key to listen
* to.
*
* @param listener
* An IPreferencesPropagatorListener.
* @param preferencesKey
* The preferences key that will screen the relevant changes.
*/
public void addPropagatorListener(IPreferencesPropagatorListener listener,
String preferencesKey) {
List list = (List) listenersMap.get(preferencesKey);
if (list == null) {
list = new ArrayList(5);
listenersMap.put(preferencesKey, list);
}
if (!list.contains(listener)) {
list.add(listener);
}
}
/**
* Removes an IPreferencesPropagatorListener that was assigned to listen to
* the given preferences key.
*
* @param listener
* An IPreferencesPropagatorListener.
* @param preferencesKey
* The preferences key that is the screening key for the
* IPreferencesPropagatorListener.
*/
public void removePropagatorListener(
IPreferencesPropagatorListener listener, String preferencesKey) {
List list = (List) listenersMap.get(preferencesKey);
if (list != null) {
list.remove(listener);
}
}
/**
* Sets a list of listeners for the given preferences key. This list will
* replace any previous list of listeners for the key.
*
* @param listeners
* A List of listeners.
* @param preferencesKey
* The preferences key that will screen the relevant changes.
*/
public void setPropagatorListeners(List listeners, String preferencesKey) {
listenersMap.put(preferencesKey, listeners);
}
/**
* Returns the list of listeners assigned to the preferences key, or null if
* non exists.
*
* @param preferencesKey
* The key that the listeners listen to.
* @return The list of listeners assigned for the key, or null if non
* exists.
*/
protected List getPropagatorListeners(String preferencesKey) {
synchronized (lock) {
return (List) listenersMap.get(preferencesKey);
}
}
/**
* Install the preferences propagator.
*/
protected synchronized void install() {
if (isInstalled) {
return;
}
listenersMap = new HashMap();
isInstalled = true;
}
/**
* Uninstall the preferences propagator.
*/
protected synchronized void uninstall() {
if (!isInstalled) {
return;
}
listenersMap = null;
isInstalled = false;
}
}
| nwnpallewela/developer-studio | jaggery/plugins/org.eclipse.php.core/src/org/eclipse/php/internal/core/preferences/AbstractPreferencesPropagator.java | Java | apache-2.0 | 3,408 |
/*
* Copyright 2009-2010 WSO2, Inc. (http://wso2.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.eclipse.ds.presentation.custom;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider;
import org.eclipse.ui.views.properties.IPropertySource;
/**
* Custom {@link AdapterFactoryContentProvider} class.
*/
public class CustomAdapterFactoryContentProvider extends AdapterFactoryContentProvider {
/**
* Creates a new {@link CustomAdapterFactoryContentProvider} instance.
*
* @param factory
* {@link AdapterFactory} instance.
*/
public CustomAdapterFactoryContentProvider(AdapterFactory factory) {
super(factory);
}
/**
* {@inheritDoc}
*/
protected IPropertySource createPropertySource(Object object,
IItemPropertySource itemPropertySource) {
return new CustomPropertySource(object, itemPropertySource);
}
}
| nwnpallewela/developer-studio | data-services/plugins/org.wso2.developerstudio.eclipse.ds.editor/src/org/wso2/developerstudio/eclipse/ds/presentation/custom/CustomAdapterFactoryContentProvider.java | Java | apache-2.0 | 1,569 |
/*
* Copyright 2016-present Open Networking Laboratory
*
* 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.onosproject.cpman.cli;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.apache.karaf.shell.console.completer.ArgumentCompleter;
import org.apache.karaf.shell.console.completer.StringsCompleter;
import org.onosproject.cli.AbstractCompleter;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.cluster.NodeId;
import org.onosproject.cpman.ControlPlaneMonitorService;
import org.onosproject.cpman.ControlResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
/**
* Resource name completer.
*/
public class ResourceNameCompleter extends AbstractCompleter {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final String NETWORK = "network";
private static final String DISK = "disk";
private static final String CONTROL_MESSAGE = "control_message";
private final Set<String> resourceTypes = ImmutableSet.of(NETWORK, DISK, CONTROL_MESSAGE);
private static final String INVALID_MSG = "Invalid type name";
@Override
public int complete(String buffer, int cursor, List<String> candidates) {
// delegate string completer
StringsCompleter delegate = new StringsCompleter();
// Resource type is the second argument.
ArgumentCompleter.ArgumentList list = getArgumentList();
String nodeId = list.getArguments()[1];
String type = list.getArguments()[2];
if (resourceTypes.contains(type)) {
ControlPlaneMonitorService monitorService =
AbstractShellCommand.get(ControlPlaneMonitorService.class);
Set<String> set = Sets.newHashSet();
switch (type) {
case NETWORK:
set = monitorService.availableResourcesSync(NodeId.nodeId(nodeId),
ControlResource.Type.NETWORK);
break;
case DISK:
set = monitorService.availableResourcesSync(NodeId.nodeId(nodeId),
ControlResource.Type.DISK);
break;
case CONTROL_MESSAGE:
set = monitorService.availableResourcesSync(NodeId.nodeId(nodeId),
ControlResource.Type.CONTROL_MESSAGE);
break;
default:
log.warn(INVALID_MSG);
break;
}
SortedSet<String> strings = delegate.getStrings();
if (!set.isEmpty()) {
set.forEach(strings::add);
}
}
return delegate.complete(buffer, cursor, candidates);
}
}
| donNewtonAlpha/onos | apps/cpman/app/src/main/java/org/onosproject/cpman/cli/ResourceNameCompleter.java | Java | apache-2.0 | 3,366 |
/*
* Copyright 2014-present Open Networking Laboratory
*
* 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.onosproject.net.provider;
/**
* Base provider implementation.
*/
public abstract class AbstractProvider implements Provider {
private final ProviderId providerId;
/**
* Creates a provider with the supplied identifier.
*
* @param id provider id
*/
protected AbstractProvider(ProviderId id) {
this.providerId = id;
}
@Override
public ProviderId id() {
return providerId;
}
}
| donNewtonAlpha/onos | core/api/src/main/java/org/onosproject/net/provider/AbstractProvider.java | Java | apache-2.0 | 1,074 |
package com.thinkaurelius.titan.graphdb.types.system;
import com.thinkaurelius.titan.graphdb.internal.InternalVertexLabel;
import org.apache.tinkerpop.gremlin.structure.Vertex;
/**
* @author Matthias Broecheler (me@matthiasb.com)
*/
public class BaseVertexLabel extends EmptyVertex implements InternalVertexLabel {
public static final BaseVertexLabel DEFAULT_VERTEXLABEL = new BaseVertexLabel(Vertex.DEFAULT_LABEL);
private final String name;
public BaseVertexLabel(String name) {
this.name = name;
}
@Override
public boolean isPartitioned() {
return false;
}
@Override
public boolean isStatic() {
return false;
}
@Override
public String name() {
return name;
}
@Override
public boolean hasDefaultConfiguration() {
return true;
}
@Override
public int getTTL() {
return 0;
}
@Override
public String toString() {
return name();
}
}
| CYPP/titan | titan-core/src/main/java/com/thinkaurelius/titan/graphdb/types/system/BaseVertexLabel.java | Java | apache-2.0 | 987 |
/*1*/ try /*2*/ { /*3*/
/*4*/ throw /*5*/ "no" /*6*/;
/*7*/} /*8*/ catch /*9*/ ( /*10*/ e /*11*/ ) /*12*/ { /*13*/
/*14*/} /*15*/ finally /*16*/ { /*17*/
/*18*/} /*19*/ | basarat/TypeScript | tests/cases/compiler/tryStatementInternalComments.ts | TypeScript | apache-2.0 | 180 |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'OrderAndItemCharges.code'
db.alter_column(u'shipping_orderanditemcharges', 'code', self.gf('oscar.models.fields.autoslugfield.AutoSlugField')(allow_duplicates=False, max_length=128, separator=u'-', unique=True, populate_from='name', overwrite=False))
# Changing field 'WeightBased.code'
db.alter_column(u'shipping_weightbased', 'code', self.gf('oscar.models.fields.autoslugfield.AutoSlugField')(allow_duplicates=False, max_length=128, separator=u'-', unique=True, populate_from='name', overwrite=False))
def backwards(self, orm):
# Changing field 'OrderAndItemCharges.code'
db.alter_column(u'shipping_orderanditemcharges', 'code', self.gf('django.db.models.fields.SlugField')(max_length=128, unique=True))
# Changing field 'WeightBased.code'
db.alter_column(u'shipping_weightbased', 'code', self.gf('django.db.models.fields.SlugField')(max_length=128, unique=True))
models = {
u'address.country': {
'Meta': {'ordering': "('-display_order', 'name')", 'object_name': 'Country'},
'display_order': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0', 'db_index': 'True'}),
'is_shipping_country': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'iso_3166_1_a2': ('django.db.models.fields.CharField', [], {'max_length': '2', 'primary_key': 'True'}),
'iso_3166_1_a3': ('django.db.models.fields.CharField', [], {'max_length': '3', 'null': 'True', 'db_index': 'True'}),
'iso_3166_1_numeric': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'db_index': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'printable_name': ('django.db.models.fields.CharField', [], {'max_length': '128'})
},
u'shipping.orderanditemcharges': {
'Meta': {'object_name': 'OrderAndItemCharges'},
'code': ('oscar.models.fields.autoslugfield.AutoSlugField', [], {'allow_duplicates': 'False', 'max_length': '128', 'separator': "u'-'", 'blank': 'True', 'unique': 'True', 'populate_from': "'name'", 'overwrite': 'False'}),
'countries': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['address.Country']", 'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'free_shipping_threshold': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '12', 'decimal_places': '2', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}),
'price_per_item': ('django.db.models.fields.DecimalField', [], {'default': "'0.00'", 'max_digits': '12', 'decimal_places': '2'}),
'price_per_order': ('django.db.models.fields.DecimalField', [], {'default': "'0.00'", 'max_digits': '12', 'decimal_places': '2'})
},
u'shipping.weightband': {
'Meta': {'ordering': "['upper_limit']", 'object_name': 'WeightBand'},
'charge': ('django.db.models.fields.DecimalField', [], {'max_digits': '12', 'decimal_places': '2'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'method': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'bands'", 'to': u"orm['shipping.WeightBased']"}),
'upper_limit': ('django.db.models.fields.FloatField', [], {})
},
u'shipping.weightbased': {
'Meta': {'object_name': 'WeightBased'},
'code': ('oscar.models.fields.autoslugfield.AutoSlugField', [], {'allow_duplicates': 'False', 'max_length': '128', 'separator': "u'-'", 'blank': 'True', 'unique': 'True', 'populate_from': "'name'", 'overwrite': 'False'}),
'countries': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['address.Country']", 'null': 'True', 'blank': 'True'}),
'default_weight': ('django.db.models.fields.DecimalField', [], {'default': "'0.00'", 'max_digits': '12', 'decimal_places': '2'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}),
'upper_charge': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '12', 'decimal_places': '2'})
}
}
complete_apps = ['shipping'] | jinnykoo/christmas | src/oscar/apps/shipping/south_migrations/0006_auto__chg_field_orderanditemcharges_code__chg_field_weightbased_code.py | Python | bsd-3-clause | 5,032 |
import imghdr
import json
import logging
from django.conf import settings
from django.db.models import Q
from django.http import (HttpResponse, HttpResponseRedirect,
HttpResponseBadRequest, Http404)
from django.shortcuts import get_object_or_404, render
from django.views.decorators.clickjacking import xframe_options_sameorigin
from django.views.decorators.http import require_POST
from tower import ugettext as _
from kitsune.access.decorators import login_required
from kitsune.gallery import ITEMS_PER_PAGE
from kitsune.gallery.forms import ImageForm
from kitsune.gallery.models import Image, Video
from kitsune.gallery.utils import upload_image, check_media_permissions
from kitsune.sumo.urlresolvers import reverse
from kitsune.sumo.utils import paginate
from kitsune.upload.tasks import compress_image, generate_thumbnail
from kitsune.upload.utils import FileTooLargeError
from kitsune.wiki.tasks import schedule_rebuild_kb
log = logging.getLogger('k.gallery')
def gallery(request, media_type='image'):
"""The media gallery.
Filter can be set to 'images' or 'videos'.
"""
if media_type == 'image':
media_qs = Image.objects.filter(locale=request.LANGUAGE_CODE)
elif media_type == 'video':
media_qs = Video.objects.filter(locale=request.LANGUAGE_CODE)
else:
raise Http404
media = paginate(request, media_qs, per_page=ITEMS_PER_PAGE)
drafts = _get_drafts(request.user)
image = drafts['image'][0] if drafts['image'] else None
image_form = _init_media_form(ImageForm, request, image)
if request.method == 'POST':
image_form.is_valid()
return render(request, 'gallery/gallery.html', {
'media': media,
'media_type': media_type,
'image_form': image_form,
'submitted': request.method == 'POST'})
@login_required
@require_POST
def upload(request, media_type='image'):
"""Finalizes an uploaded draft."""
drafts = _get_drafts(request.user)
if media_type == 'image' and drafts['image']:
# We're publishing an image draft!
image_form = _init_media_form(ImageForm, request, drafts['image'][0])
if image_form.is_valid():
img = image_form.save(is_draft=None)
generate_thumbnail.delay(img, 'file', 'thumbnail')
compress_image.delay(img, 'file')
# Rebuild KB
schedule_rebuild_kb()
return HttpResponseRedirect(img.get_absolute_url())
else:
return gallery(request, media_type='image')
return HttpResponseBadRequest(u'Unrecognized POST request.')
@login_required
@require_POST
def cancel_draft(request, media_type='image'):
"""Delete an existing draft for the user."""
drafts = _get_drafts(request.user)
if media_type == 'image' and drafts['image']:
drafts['image'].delete()
drafts['image'] = None
else:
msg = _(u'Unrecognized request or nothing to cancel.')
content_type = None
if request.is_ajax():
msg = json.dumps({'status': 'error', 'message': msg})
content_type = 'application/json'
return HttpResponseBadRequest(msg, content_type=content_type)
if request.is_ajax():
return HttpResponse(json.dumps({'status': 'success'}),
content_type='application/json')
return HttpResponseRedirect(reverse('gallery.gallery', args=[media_type]))
def gallery_async(request):
"""AJAX endpoint to media gallery.
Returns an HTML list representation of the media.
"""
# Maybe refactor this into existing views and check request.is_ajax?
media_type = request.GET.get('type', 'image')
term = request.GET.get('q')
media_locale = request.GET.get('locale', settings.WIKI_DEFAULT_LANGUAGE)
if media_type == 'image':
media_qs = Image.objects
elif media_type == 'video':
media_qs = Video.objects
else:
raise Http404
media_qs = media_qs.filter(locale=media_locale)
if term:
media_qs = media_qs.filter(Q(title__icontains=term) |
Q(description__icontains=term))
media = paginate(request, media_qs, per_page=ITEMS_PER_PAGE)
return render(request, 'gallery/includes/media_list.html', {
'media_list': media})
def search(request, media_type):
"""Search the media gallery."""
term = request.GET.get('q')
if not term:
url = reverse('gallery.gallery', args=[media_type])
return HttpResponseRedirect(url)
filter = Q(title__icontains=term) | Q(description__icontains=term)
if media_type == 'image':
media_qs = Image.objects.filter(filter, locale=request.LANGUAGE_CODE)
elif media_type == 'video':
media_qs = Video.objects.filter(filter, locale=request.LANGUAGE_CODE)
else:
raise Http404
media = paginate(request, media_qs, per_page=ITEMS_PER_PAGE)
return render(request, 'gallery/search.html', {
'media': media,
'media_type': media_type,
'q': term})
@login_required
def delete_media(request, media_id, media_type='image'):
"""Delete media and redirect to gallery view."""
media, media_format = _get_media_info(media_id, media_type)
check_media_permissions(media, request.user, 'delete')
if request.method == 'GET':
# Render the confirmation page
return render(request, 'gallery/confirm_media_delete.html', {
'media': media,
'media_type': media_type,
'media_format': media_format})
# Handle confirm delete form POST
log.warning('User %s is deleting %s with id=%s' %
(request.user, media_type, media.id))
media.delete()
# Rebuild KB
schedule_rebuild_kb()
return HttpResponseRedirect(reverse('gallery.gallery', args=[media_type]))
@login_required
def edit_media(request, media_id, media_type='image'):
"""Edit media means only changing the description, for now."""
media, media_format = _get_media_info(media_id, media_type)
check_media_permissions(media, request.user, 'change')
if media_type == 'image':
media_form = _init_media_form(ImageForm, request, media,
('locale', 'title'))
else:
raise Http404
if request.method == 'POST' and media_form.is_valid():
media = media_form.save(update_user=request.user, is_draft=False)
return HttpResponseRedirect(
reverse('gallery.media', args=[media_type, media_id]))
return render(request, 'gallery/edit_media.html', {
'media': media,
'media_format': media_format,
'form': media_form,
'media_type': media_type})
def media(request, media_id, media_type='image'):
"""The media page."""
media, media_format = _get_media_info(media_id, media_type)
return render(request, 'gallery/media.html', {
'media': media,
'media_format': media_format,
'media_type': media_type})
@login_required
@require_POST
@xframe_options_sameorigin
def upload_async(request, media_type='image'):
"""Upload images or videos from request.FILES."""
# TODO(paul): validate the Submit File on upload modal async
# even better, use JS validation for title length.
try:
if media_type == 'image':
file_info = upload_image(request)
else:
msg = _(u'Unrecognized media type.')
return HttpResponseBadRequest(
json.dumps({'status': 'error', 'message': msg}))
except FileTooLargeError as e:
return HttpResponseBadRequest(
json.dumps({'status': 'error', 'message': e.args[0]}))
if isinstance(file_info, dict) and 'thumbnail_url' in file_info:
schedule_rebuild_kb()
return HttpResponse(
json.dumps({'status': 'success', 'file': file_info}))
message = _(u'Could not upload your image.')
return HttpResponseBadRequest(
json.dumps({'status': 'error',
'message': unicode(message),
'errors': file_info}))
def _get_media_info(media_id, media_type):
"""Returns an image or video along with media format for the image."""
media_format = None
if media_type == 'image':
media = get_object_or_404(Image, pk=media_id)
try:
media_format = imghdr.what(media.file.path)
except UnicodeEncodeError:
pass
elif media_type == 'video':
media = get_object_or_404(Video, pk=media_id)
else:
raise Http404
return (media, media_format)
def _get_drafts(user):
"""Get video and image drafts for a given user."""
drafts = {'image': None, 'video': None}
if user.is_authenticated():
drafts['image'] = Image.objects.filter(creator=user, is_draft=True)
drafts['video'] = Video.objects.filter(creator=user, is_draft=True)
return drafts
def _init_media_form(form_cls, request=None, obj=None,
ignore_fields=()):
"""Initializes the media form with an Image/Video instance and POSTed data.
form_cls is a django ModelForm
Request method must be POST for POST data to be bound.
exclude_fields contains the list of fields to default to their current
value from the Image/Video object.
"""
post_data = None
initial = None
if request:
initial = {'locale': request.LANGUAGE_CODE}
file_data = None
if request.method == 'POST':
file_data = request.FILES
post_data = request.POST.copy()
if obj and ignore_fields:
for f in ignore_fields:
post_data[f] = getattr(obj, f)
return form_cls(post_data, file_data, instance=obj, initial=initial,
is_ajax=False)
| orvi2014/kitsune | kitsune/gallery/views.py | Python | bsd-3-clause | 9,805 |
// Squarified Treemaps by Mark Bruls, Kees Huizing, and Jarke J. van Wijk
// Modified to support a target aspect ratio by Jeff Heer
d3.layout.treemap = function() {
var hierarchy = d3.layout.hierarchy(),
round = Math.round,
size = [1, 1], // width, height
padding = null,
pad = d3_layout_treemapPadNull,
sticky = false,
stickies,
mode = "squarify",
ratio = 0.5 * (1 + Math.sqrt(5)); // golden ratio
// Compute the area for each child based on value & scale.
function scale(children, k) {
var i = -1,
n = children.length,
child,
area;
while (++i < n) {
area = (child = children[i]).value * (k < 0 ? 0 : k);
child.area = isNaN(area) || area <= 0 ? 0 : area;
}
}
// Recursively arranges the specified node's children into squarified rows.
function squarify(node) {
var children = node.children;
if (children && children.length) {
var rect = pad(node),
row = [],
remaining = children.slice(), // copy-on-write
child,
best = Infinity, // the best row score so far
score, // the current row score
u = mode === "slice" ? rect.dx
: mode === "dice" ? rect.dy
: mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx
: Math.min(rect.dx, rect.dy), // initial orientation
n;
scale(remaining, rect.dx * rect.dy / node.value);
row.area = 0;
while ((n = remaining.length) > 0) {
row.push(child = remaining[n - 1]);
row.area += child.area;
if (mode !== "squarify" || (score = worst(row, u)) <= best) { // continue with this orientation
remaining.pop();
best = score;
} else { // abort, and try a different orientation
row.area -= row.pop().area;
position(row, u, rect, false);
u = Math.min(rect.dx, rect.dy);
row.length = row.area = 0;
best = Infinity;
}
}
if (row.length) {
position(row, u, rect, true);
row.length = row.area = 0;
}
children.forEach(squarify);
}
}
// Recursively resizes the specified node's children into existing rows.
// Preserves the existing layout!
function stickify(node) {
var children = node.children;
if (children && children.length) {
var rect = pad(node),
remaining = children.slice(), // copy-on-write
child,
row = [];
scale(remaining, rect.dx * rect.dy / node.value);
row.area = 0;
while (child = remaining.pop()) {
row.push(child);
row.area += child.area;
if (child.z != null) {
position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length);
row.length = row.area = 0;
}
}
children.forEach(stickify);
}
}
// Computes the score for the specified row, as the worst aspect ratio.
function worst(row, u) {
var s = row.area,
r,
rmax = 0,
rmin = Infinity,
i = -1,
n = row.length;
while (++i < n) {
if (!(r = row[i].area)) continue;
if (r < rmin) rmin = r;
if (r > rmax) rmax = r;
}
s *= s;
u *= u;
return s
? Math.max((u * rmax * ratio) / s, s / (u * rmin * ratio))
: Infinity;
}
// Positions the specified row of nodes. Modifies `rect`.
function position(row, u, rect, flush) {
var i = -1,
n = row.length,
x = rect.x,
y = rect.y,
v = u ? round(row.area / u) : 0,
o;
if (u == rect.dx) { // horizontal subdivision
if (flush || v > rect.dy) v = rect.dy; // over+underflow
while (++i < n) {
o = row[i];
o.x = x;
o.y = y;
o.dy = v;
x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
}
o.z = true;
o.dx += rect.x + rect.dx - x; // rounding error
rect.y += v;
rect.dy -= v;
} else { // vertical subdivision
if (flush || v > rect.dx) v = rect.dx; // over+underflow
while (++i < n) {
o = row[i];
o.x = x;
o.y = y;
o.dx = v;
y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
}
o.z = false;
o.dy += rect.y + rect.dy - y; // rounding error
rect.x += v;
rect.dx -= v;
}
}
function treemap(d) {
var nodes = stickies || hierarchy(d),
root = nodes[0];
root.x = 0;
root.y = 0;
root.dx = size[0];
root.dy = size[1];
if (stickies) hierarchy.revalue(root);
scale([root], root.dx * root.dy / root.value);
(stickies ? stickify : squarify)(root);
if (sticky) stickies = nodes;
return nodes;
}
treemap.size = function(x) {
if (!arguments.length) return size;
size = x;
return treemap;
};
treemap.padding = function(x) {
if (!arguments.length) return padding;
function padFunction(node) {
var p = x.call(treemap, node, node.depth);
return p == null
? d3_layout_treemapPadNull(node)
: d3_layout_treemapPad(node, typeof p === "number" ? [p, p, p, p] : p);
}
function padConstant(node) {
return d3_layout_treemapPad(node, x);
}
var type;
pad = (padding = x) == null ? d3_layout_treemapPadNull
: (type = typeof x) === "function" ? padFunction
: type === "number" ? (x = [x, x, x, x], padConstant)
: padConstant;
return treemap;
};
treemap.round = function(x) {
if (!arguments.length) return round != Number;
round = x ? Math.round : Number;
return treemap;
};
treemap.sticky = function(x) {
if (!arguments.length) return sticky;
sticky = x;
stickies = null;
return treemap;
};
treemap.ratio = function(x) {
if (!arguments.length) return ratio;
ratio = x;
return treemap;
};
treemap.mode = function(x) {
if (!arguments.length) return mode;
mode = x + "";
return treemap;
};
return d3_layout_hierarchyRebind(treemap, hierarchy);
};
function d3_layout_treemapPadNull(node) {
return {x: node.x, y: node.y, dx: node.dx, dy: node.dy};
}
function d3_layout_treemapPad(node, padding) {
var x = node.x + padding[3],
y = node.y + padding[0],
dx = node.dx - padding[1] - padding[3],
dy = node.dy - padding[0] - padding[2];
if (dx < 0) { x += dx / 2; dx = 0; }
if (dy < 0) { y += dy / 2; dy = 0; }
return {x: x, y: y, dx: dx, dy: dy};
}
| zziuni/d3 | src/layout/treemap.js | JavaScript | bsd-3-clause | 6,511 |
#!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test utilities for gtest_xml_output"""
__author__ = 'eefacm@gmail.com (Sean Mcafee)'
import re
from xml.dom import minidom, Node
import gtest_test_utils
GTEST_OUTPUT_FLAG = '--gtest_output'
GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.xml'
class GTestXMLTestCase(gtest_test_utils.TestCase):
"""
Base class for tests of Google Test's XML output functionality.
"""
def AssertEquivalentNodes(self, expected_node, actual_node):
"""
Asserts that actual_node (a DOM node object) is equivalent to
expected_node (another DOM node object), in that either both of
them are CDATA nodes and have the same value, or both are DOM
elements and actual_node meets all of the following conditions:
* It has the same tag name as expected_node.
* It has the same set of attributes as expected_node, each with
the same value as the corresponding attribute of expected_node.
Exceptions are any attribute named "time", which needs only be
convertible to a floating-point number and any attribute named
"type_param" which only has to be non-empty.
* It has an equivalent set of child nodes (including elements and
CDATA sections) as expected_node. Note that we ignore the
order of the children as they are not guaranteed to be in any
particular order.
"""
if expected_node.nodeType == Node.CDATA_SECTION_NODE:
self.assertEquals(Node.CDATA_SECTION_NODE, actual_node.nodeType)
self.assertEquals(expected_node.nodeValue, actual_node.nodeValue)
return
self.assertEquals(Node.ELEMENT_NODE, actual_node.nodeType)
self.assertEquals(Node.ELEMENT_NODE, expected_node.nodeType)
self.assertEquals(expected_node.tagName, actual_node.tagName)
expected_attributes = expected_node.attributes
actual_attributes = actual_node .attributes
self.assertEquals(
expected_attributes.length, actual_attributes.length,
'attribute numbers differ in element %s:\nExpected: %r\nActual: %r' % (
actual_node.tagName, expected_attributes.keys(),
actual_attributes.keys()))
for i in range(expected_attributes.length):
expected_attr = expected_attributes.item(i)
actual_attr = actual_attributes.get(expected_attr.name)
self.assert_(
actual_attr is not None,
'expected attribute %s not found in element %s' %
(expected_attr.name, actual_node.tagName))
self.assertEquals(
expected_attr.value, actual_attr.value,
' values of attribute %s in element %s differ: %s vs %s' %
(expected_attr.name, actual_node.tagName,
expected_attr.value, actual_attr.value))
expected_children = self._GetChildren(expected_node)
actual_children = self._GetChildren(actual_node)
self.assertEquals(
len(expected_children), len(actual_children),
'number of child elements differ in element ' + actual_node.tagName)
for child_id, child in expected_children.iteritems():
self.assert_(child_id in actual_children,
'<%s> is not in <%s> (in element %s)' %
(child_id, actual_children, actual_node.tagName))
self.AssertEquivalentNodes(child, actual_children[child_id])
identifying_attribute = {
'testsuites': 'name',
'testsuite': 'name',
'testcase': 'name',
'failure': 'message',
}
def _GetChildren(self, element):
"""
Fetches all of the child nodes of element, a DOM Element object.
Returns them as the values of a dictionary keyed by the IDs of the
children. For <testsuites>, <testsuite> and <testcase> elements, the ID
is the value of their "name" attribute; for <failure> elements, it is
the value of the "message" attribute; CDATA sections and non-whitespace
text nodes are concatenated into a single CDATA section with ID
"detail". An exception is raised if any element other than the above
four is encountered, if two child elements with the same identifying
attributes are encountered, or if any other type of node is encountered.
"""
children = {}
for child in element.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
self.assert_(child.tagName in self.identifying_attribute,
'Encountered unknown element <%s>' % child.tagName)
childID = child.getAttribute(self.identifying_attribute[child.tagName])
self.assert_(childID not in children)
children[childID] = child
elif child.nodeType in [Node.TEXT_NODE, Node.CDATA_SECTION_NODE]:
if 'detail' not in children:
if (child.nodeType == Node.CDATA_SECTION_NODE or
not child.nodeValue.isspace()):
children['detail'] = child.ownerDocument.createCDATASection(
child.nodeValue)
else:
children['detail'].nodeValue += child.nodeValue
else:
self.fail('Encountered unexpected node type %d' % child.nodeType)
return children
def NormalizeXml(self, element):
"""
Normalizes Google Test's XML output to eliminate references to transient
information that may change from run to run.
* The "time" attribute of <testsuites>, <testsuite> and <testcase>
elements is replaced with a single asterisk, if it contains
only digit characters.
* The "timestamp" attribute of <testsuites> elements is replaced with a
single asterisk, if it contains a valid ISO8601 datetime value.
* The "type_param" attribute of <testcase> elements is replaced with a
single asterisk (if it sn non-empty) as it is the type name returned
by the compiler and is platform dependent.
* The line info reported in the first line of the "message"
attribute and CDATA section of <failure> elements is replaced with the
file's basename and a single asterisk for the line number.
* The directory names in file paths are removed.
* The stack traces are removed.
"""
if element.tagName == 'testsuites':
timestamp = element.getAttributeNode('timestamp')
timestamp.value = re.sub(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d$',
'*', timestamp.value)
if element.tagName in ('testsuites', 'testsuite', 'testcase'):
time = element.getAttributeNode('time')
time.value = re.sub(r'^\d+(\.\d+)?$', '*', time.value)
type_param = element.getAttributeNode('type_param')
if type_param and type_param.value:
type_param.value = '*'
elif element.tagName == 'failure':
source_line_pat = r'^.*[/\\](.*:)\d+\n'
# Replaces the source line information with a normalized form.
message = element.getAttributeNode('message')
message.value = re.sub(source_line_pat, '\\1*\n', message.value)
for child in element.childNodes:
if child.nodeType == Node.CDATA_SECTION_NODE:
# Replaces the source line information with a normalized form.
cdata = re.sub(source_line_pat, '\\1*\n', child.nodeValue)
# Removes the actual stack trace.
child.nodeValue = re.sub(r'\nStack trace:\n(.|\n)*',
'', cdata)
for child in element.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
self.NormalizeXml(child)
| paoloach/zdomus | zigbee_lib/googletest/googletest/test/gtest_xml_test_utils.py | Python | gpl-2.0 | 8,876 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
namespace System.Text.Json
{
public ref partial struct Utf8JsonWriter
{
/// <summary>
/// Writes the <see cref="double"/> value (as a JSON number) as an element of a JSON array.
/// </summary>
/// <param name="value">The value to be written as a JSON number as an element of a JSON array.</param>
/// <exception cref="InvalidOperationException">
/// Thrown if this would result in an invalid JSON to be written (while validation is enabled).
/// </exception>
/// <remarks>
/// Writes the <see cref="double"/> using the default <see cref="StandardFormat"/> (i.e. 'G').
/// </remarks>
public void WriteNumberValue(double value)
{
JsonWriterHelper.ValidateDouble(value);
ValidateWritingValue();
if (_writerOptions.Indented)
{
WriteNumberValueIndented(value);
}
else
{
WriteNumberValueMinimized(value);
}
SetFlagToAddListSeparatorBeforeNextItem();
_tokenType = JsonTokenType.Number;
}
private void WriteNumberValueMinimized(double value)
{
int idx = 0;
WriteListSeparator(ref idx);
WriteNumberValueFormatLoop(value, ref idx);
Advance(idx);
}
private void WriteNumberValueIndented(double value)
{
int idx = WriteCommaAndFormattingPreamble();
WriteNumberValueFormatLoop(value, ref idx);
Advance(idx);
}
}
}
| ptoonen/corefx | src/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Double.cs | C# | mit | 1,839 |
// Type definitions for non-npm package @ember/component 3.0
// Project: https://emberjs.com/api/ember/3.4/modules/@ember%2Fcomponent
// Definitions by: Mike North <https://github.com/mike-north>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
/// <reference types="jquery" />
import CoreView from "@ember/component/-private/core-view";
import ClassNamesSupport from "@ember/component/-private/class-names-support";
import ViewMixin from "@ember/component/-private/view-mixin";
import ActionSupport from "@ember/component/-private/action-support";
// tslint:disable-next-line:strict-export-declare-modifiers
interface TemplateFactory {
__htmlbars_inline_precompile_template_factory: any;
}
/**
* A view that is completely isolated. Property access in its templates go to the view object
* and actions are targeted at the view object. There is no access to the surrounding context or
* outer controller; all contextual information is passed in.
*/
export default class Component extends CoreView.extend(
ViewMixin,
ActionSupport,
ClassNamesSupport
) {
// methods
readDOMAttr(name: string): string;
// properties
/**
* The WAI-ARIA role of the control represented by this view. For example, a button may have a
* role of type 'button', or a pane may have a role of type 'alertdialog'. This property is
* used by assistive software to help visually challenged users navigate rich web applications.
*/
ariaRole: string;
/**
* The HTML id of the component's element in the DOM. You can provide this value yourself but
* it must be unique (just as in HTML):
*
* If not manually set a default value will be provided by the framework. Once rendered an
* element's elementId is considered immutable and you should never change it. If you need
* to compute a dynamic value for the elementId, you should do this when the component or
* element is being instantiated:
*/
elementId: string;
/**
* If false, the view will appear hidden in DOM.
*/
isVisible: boolean;
/**
* A component may contain a layout. A layout is a regular template but supersedes the template
* property during rendering. It is the responsibility of the layout template to retrieve the
* template property from the component (or alternatively, call Handlebars.helpers.yield,
* {{yield}}) to render it in the correct location. This is useful for a component that has a
* shared wrapper, but which delegates the rendering of the contents of the wrapper to the
* template property on a subclass.
*/
layout: TemplateFactory | string;
/**
* Enables components to take a list of parameters as arguments.
*/
static positionalParams: string[] | string;
// events
/**
* Called when the attributes passed into the component have been updated. Called both during the
* initial render of a container and during a rerender. Can be used in place of an observer; code
* placed here will be executed every time any attribute updates.
*/
didReceiveAttrs(): void;
/**
* Called after a component has been rendered, both on initial render and in subsequent rerenders.
*/
didRender(): void;
/**
* Called when the component has updated and rerendered itself. Called only during a rerender,
* not during an initial render.
*/
didUpdate(): void;
/**
* Called when the attributes passed into the component have been changed. Called only during a
* rerender, not during an initial render.
*/
didUpdateAttrs(): void;
/**
* Called before a component has been rendered, both on initial render and in subsequent rerenders.
*/
willRender(): void;
/**
* Called when the component is about to update and rerender itself. Called only during a rerender,
* not during an initial render.
*/
willUpdate(): void;
}
| borisyankov/DefinitelyTyped | types/ember__component/index.d.ts | TypeScript | mit | 4,009 |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""ExportStrategy class that provides strategies to export model so later it
can be used for TensorFlow serving."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
__all__ = ['ExportStrategy']
class ExportStrategy(collections.namedtuple('ExportStrategy',
['name', 'export_fn'])):
def export(self, estimator, export_path):
return self.export_fn(estimator, export_path)
| jjas0nn/solvem | tensorflow/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/export_strategy.py | Python | mit | 1,195 |
version https://git-lfs.github.com/spec/v1
oid sha256:cdaff690080dec73e2f9044eb89e1426fd2645ea6d8b253cd51cd992717b8a06
size 1772
| yogeshsaroya/new-cdnjs | ajax/libs/codemirror/5.1.0/mode/shell/test.js | JavaScript | mit | 129 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
namespace System.Net.NetworkInformation
{
internal class LinuxIPGlobalStatistics : IPGlobalStatistics
{
// MIB-II statistics data.
private readonly IPGlobalStatisticsTable _table;
// Miscellaneous IP information, not defined in MIB-II.
private int _numRoutes;
private int _numInterfaces;
private int _numIPAddresses;
public LinuxIPGlobalStatistics(bool ipv4)
{
if (ipv4)
{
_table = StringParsingHelpers.ParseIPv4GlobalStatisticsFromSnmpFile(NetworkFiles.SnmpV4StatsFile);
_numRoutes = StringParsingHelpers.ParseNumRoutesFromRouteFile(NetworkFiles.Ipv4RouteFile);
_numInterfaces = StringParsingHelpers.ParseNumIPInterfaces(NetworkFiles.Ipv4ConfigFolder);
}
else
{
_table = StringParsingHelpers.ParseIPv6GlobalStatisticsFromSnmp6File(NetworkFiles.SnmpV6StatsFile);
_numRoutes = StringParsingHelpers.ParseNumRoutesFromRouteFile(NetworkFiles.Ipv6RouteFile);
_numInterfaces = StringParsingHelpers.ParseNumIPInterfaces(NetworkFiles.Ipv6ConfigFolder);
// /proc/sys/net/ipv6/conf/default/forwarding
string forwardingConfigFile = Path.Combine(NetworkFiles.Ipv6ConfigFolder,
NetworkFiles.DefaultNetworkInterfaceFileName,
NetworkFiles.ForwardingFileName);
_table.Forwarding = StringParsingHelpers.ParseRawIntFile(forwardingConfigFile) == 1;
// snmp6 does not include Default TTL info. Read it from snmp.
_table.DefaultTtl = StringParsingHelpers.ParseDefaultTtlFromFile(NetworkFiles.SnmpV4StatsFile);
}
_numIPAddresses = GetNumIPAddresses();
}
public override int DefaultTtl { get { return _table.DefaultTtl; } }
public override bool ForwardingEnabled { get { return _table.Forwarding; } }
public override int NumberOfInterfaces { get { return _numInterfaces; } }
public override int NumberOfIPAddresses { get { return _numIPAddresses; } }
public override int NumberOfRoutes { get { return _numRoutes; } }
public override long OutputPacketRequests { get { return _table.OutRequests; } }
public override long OutputPacketRoutingDiscards { get { throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); } }
public override long OutputPacketsDiscarded { get { return _table.OutDiscards; } }
public override long OutputPacketsWithNoRoute { get { return _table.OutNoRoutes; } }
public override long PacketFragmentFailures { get { return _table.FragmentFails; } }
public override long PacketReassembliesRequired { get { return _table.ReassemblyRequireds; } }
public override long PacketReassemblyFailures { get { return _table.ReassemblyFails; } }
public override long PacketReassemblyTimeout { get { return _table.ReassemblyTimeout; } }
public override long PacketsFragmented { get { return _table.FragmentCreates; } }
public override long PacketsReassembled { get { return _table.ReassemblyOKs; } }
public override long ReceivedPackets { get { return _table.InReceives; } }
public override long ReceivedPacketsDelivered { get { return _table.InDelivers; } }
public override long ReceivedPacketsDiscarded { get { return _table.InDiscards; } }
public override long ReceivedPacketsForwarded { get { return _table.ForwardedDatagrams; } }
public override long ReceivedPacketsWithAddressErrors { get { return _table.InAddressErrors; } }
public override long ReceivedPacketsWithHeadersErrors { get { return _table.InHeaderErrors; } }
public override long ReceivedPacketsWithUnknownProtocol { get { return _table.InUnknownProtocols; } }
private static unsafe int GetNumIPAddresses()
{
int count = 0;
Interop.Sys.EnumerateInterfaceAddresses(
(name, ipAddressInfo) =>
{
count++;
},
(name, ipAddressInfo, scopeId) =>
{
count++;
},
// Ignore link-layer addresses that are discovered; don't create a callback.
null);
return count;
}
}
}
| shimingsg/corefx | src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/LinuxIPGlobalStatistics.cs | C# | mit | 4,754 |
package com.wirelesspienetwork.overview.views;
import android.animation.ValueAnimator;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.view.animation.Interpolator;
/* The transform state for a task view */
public class OverviewCardTransform {
public int startDelay = 0;
public int translationY = 0;
public float translationZ = 0;
public float scale = 1f;
public float alpha = 1f;
public boolean visible = false;
public Rect rect = new Rect();
float p = 0f;
public OverviewCardTransform() {
// Do nothing
}
public OverviewCardTransform(OverviewCardTransform o) {
startDelay = o.startDelay;
translationY = o.translationY;
translationZ = o.translationZ;
scale = o.scale;
alpha = o.alpha;
visible = o.visible;
rect.set(o.rect);
p = o.p;
}
/** Resets the current transform */
public void reset() {
startDelay = 0;
translationY = 0;
translationZ = 0;
scale = 1f;
alpha = 1f;
visible = false;
rect.setEmpty();
p = 0f;
}
/** Convenience functions to compare against current property values */
public boolean hasAlphaChangedFrom(float v) {
return (Float.compare(alpha, v) != 0);
}
public boolean hasScaleChangedFrom(float v) {
return (Float.compare(scale, v) != 0);
}
public boolean hasTranslationYChangedFrom(float v) {
return (Float.compare(translationY, v) != 0);
}
public boolean hasTranslationZChangedFrom(float v) {
return (Float.compare(translationZ, v) != 0);
}
/** Applies this transform to a view. */
public void applyToTaskView(View v, int duration, Interpolator interp, boolean allowLayers,
boolean allowShadows, ValueAnimator.AnimatorUpdateListener updateCallback) {
// Check to see if any properties have changed, and update the task view
if (duration > 0) {
ViewPropertyAnimator anim = v.animate();
boolean requiresLayers = false;
// Animate to the final state
if (hasTranslationYChangedFrom(v.getTranslationY())) {
anim.translationY(translationY);
}
if (hasScaleChangedFrom(v.getScaleX())) {
anim.scaleX(scale)
.scaleY(scale);
requiresLayers = true;
}
if (hasAlphaChangedFrom(v.getAlpha())) {
// Use layers if we animate alpha
anim.alpha(alpha);
requiresLayers = true;
}
if (requiresLayers && allowLayers) {
anim.withLayer();
}
anim.setStartDelay(startDelay)
.setDuration(duration)
.setInterpolator(interp)
.start();
} else {
// Set the changed properties
if (hasTranslationYChangedFrom(v.getTranslationY())) {
v.setTranslationY(translationY);
}
if (hasScaleChangedFrom(v.getScaleX())) {
v.setScaleX(scale);
v.setScaleY(scale);
}
if (hasAlphaChangedFrom(v.getAlpha())) {
v.setAlpha(alpha);
}
}
}
/** Reset the transform on a view. */
public static void reset(View v) {
v.setTranslationX(0f);
v.setTranslationY(0f);
v.setScaleX(1f);
v.setScaleY(1f);
v.setAlpha(1f);
}
@Override
public String toString() {
return "TaskViewTransform delay: " + startDelay + " y: " + translationY + " z: " + translationZ +
" scale: " + scale + " alpha: " + alpha + " visible: " + visible + " rect: " + rect +
" p: " + p;
}
}
| ppamorim/StackOverView | lib/src/main/java/com/wirelesspienetwork/overview/views/OverviewCardTransform.java | Java | mit | 3,895 |
#!/usr/bin/env python
import sys
import re
from helpers import *
PROGRAM_USAGE = """
SeqAn script to replace invalid identifiers (previously collected) in the SeqAn
codebase.
USAGE: replace_identifiers.py BASE_PATH [REPLACEMENTS]
BASE_PATH is the root path of all the folders to be searched.
REPLACEMENTS is a file of ``"key:value"`` pairs which contain the invalid
identifier and the replacement string.
If this file is not given, it is attemped to read the replacements from the
standard input stream.
""".strip()
def replace_all(text, subst):
"""
Perform the substitutions given by the dictionary ``subst`` on ``text``.
"""
for old in subst.keys():
text = old.sub(subst[old], text)
return text
def validate_file(file, subst):
"""
Perform the substitutions given by the dictionary ``subst`` on ``file``.
"""
#print file
code = ''
try:
f = open(file, 'r')
finally:
code = f.read()
old_len = len(code)
replaced = replace_all(code, subst)
#assert old_len == len(replaced)
open(file, 'w').write(replaced)
def build_subst_table(file):
"""
Read the substitutions defined in ``file`` and build a substitution table.
"""
table = {}
for line in file:
old, new = line.rstrip('\r\n').split(':')
table[re.compile(r'\b%s\b' % old.strip())] = new.strip()
return table
def main():
# Either read from stdin or expect a file path in the second argument.
# Since there is no reliable way of checking for an attached stdin on
# Windows, just assume good faith if the file name isn't given.
use_stdin = len(sys.argv) == 2
if not (len(sys.argv) == 3 or use_stdin):
print >>sys.stderr, 'ERROR: Invalid number of arguments.'
print >>sys.stderr, PROGRAM_USAGE
return 1
if use_stdin:
print >>sys.stderr, "Attempting to read from stdin ..."
project_path = sys.argv[1]
replacements_file = sys.stdin if use_stdin else open(sys.argv[2], 'r')
substitutions = build_subst_table(replacements_file)
for file in all_files(project_path):
validate_file(file, substitutions)
return 0
if __name__ == '__main__':
sys.exit(main())
| bkahlert/seqan-research | raw/workshop13/workshop2013-data-20130926/trunk/misc/renaming/replace_identifiers.py | Python | mit | 2,256 |
/* This file was generated by SableCC (http://www.sablecc.org/). */
package wolf.node;
import wolf.analysis.*;
@SuppressWarnings("nls")
public final class TStringBody extends Token
{
public TStringBody(String text)
{
setText(text);
}
public TStringBody(String text, int line, int pos)
{
setText(text);
setLine(line);
setPos(pos);
}
@Override
public Object clone()
{
return new TStringBody(getText(), getLine(), getPos());
}
@Override
public void apply(Switch sw)
{
((Analysis) sw).caseTStringBody(this);
}
}
| dittma75/compiler-design | wolf_compiler/wolf/src/wolf/node/TStringBody.java | Java | mit | 616 |
<?php
// vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
/**
* Toc rule end renderer for Xhtml
*
* PHP versions 4 and 5
*
* @category Text
* @package Text_Wiki
* @author Paul M. Jones <pmjones@php.net>
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version CVS: $Id: Toc.php,v 1.9 2005/07/30 08:03:29 toggg Exp $
* @link http://pear.php.net/package/Text_Wiki
*/
/**
* This class inserts a table of content in XHTML.
*
* @category Text
* @package Text_Wiki
* @author Paul M. Jones <pmjones@php.net>
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version Release: @package_version@
* @link http://pear.php.net/package/Text_Wiki
*/
class Text_Wiki_Render_Xhtml_Toc extends Text_Wiki_Render {
var $conf = array(
'css_list' => null,
'css_item' => null,
'title' => '<strong>Table of Contents</strong>',
'div_id' => 'toc',
'collapse' => true
);
var $min = 2;
/**
*
* Renders a token into text matching the requested format.
*
* @access public
*
* @param array $options The "options" portion of the token (second
* element).
*
* @return string The text rendered from the token options.
*
*/
function token($options)
{
// type, id, level, count, attr
extract($options);
switch ($type) {
case 'list_start':
$css = $this->getConf('css_list');
$html = '';
// collapse div within a table?
if ($this->getConf('collapse')) {
$html .= '<table border="0" cellspacing="0" cellpadding="0">';
$html .= "<tr><td>\n";
}
// add the div, class, and id
$html .= '<div';
if ($css) {
$html .= " class=\"$css\"";
}
$div_id = $this->getConf('div_id');
if ($div_id) {
$html .= " id=\"$div_id\"";
}
// add the title, and done
$html .= '>';
$html .= $this->getConf('title');
return $html;
break;
case 'list_end':
if ($this->getConf('collapse')) {
return "\n</div>\n</td></tr></table>\n\n";
} else {
return "\n</div>\n\n";
}
break;
case 'item_start':
$html = "\n\t<div";
$css = $this->getConf('css_item');
if ($css) {
$html .= " class=\"$css\"";
}
$pad = ($level - $this->min);
$html .= " style=\"margin-left: {$pad}em;\">";
$html .= "<a href=\"#$id\">";
return $html;
break;
case 'item_end':
return "</a></div>";
break;
}
}
}
?>
| idoxlr8/HVAC | xataface/lib/Text/Wiki/Render/Xhtml/Toc.php | PHP | gpl-2.0 | 2,899 |
module Rails
module VERSION #:nodoc:
MAJOR = 2
MINOR = 1
TINY = 0
STRING = [MAJOR, MINOR, TINY].join('.')
end
end
| YSATools/The-Ward-Menu | vendor/railties/lib/rails/version.rb | Ruby | gpl-2.0 | 136 |
/*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "Control.h"
#include "LanguageHook.h"
#include "AddonUtils.h"
#include "guilib/GUILabel.h"
#include "guilib/GUIFontManager.h"
#include "guilib/GUILabelControl.h"
#include "guilib/GUIFadeLabelControl.h"
#include "guilib/GUITextBox.h"
#include "guilib/GUIButtonControl.h"
#include "guilib/GUICheckMarkControl.h"
#include "guilib/GUIImage.h"
#include "guilib/GUIListContainer.h"
#include "guilib/GUIProgressControl.h"
#include "guilib/GUISliderControl.h"
#include "guilib/GUIRadioButtonControl.h"
#include "GUIInfoManager.h"
#include "guilib/GUIWindowManager.h"
#include "guilib/GUIEditControl.h"
#include "guilib/GUIControlFactory.h"
#include "listproviders/StaticProvider.h"
#include "utils/XBMCTinyXML.h"
#include "utils/StringUtils.h"
namespace XBMCAddon
{
namespace xbmcgui
{
// ============================================================
// ============================================================
// ============================================================
ControlFadeLabel::ControlFadeLabel(long x, long y, long width, long height,
const char* font, const char* _textColor,
long _alignment) :
strFont("font13"), textColor(0xffffffff), align(_alignment)
{
dwPosX = x;
dwPosY = y;
dwWidth = width;
dwHeight = height;
if (font)
strFont = font;
if (_textColor)
sscanf(_textColor, "%x", &textColor);
pGUIControl = NULL;
}
void ControlFadeLabel::addLabel(const String& label) throw (UnimplementedException)
{
CGUIMessage msg(GUI_MSG_LABEL_ADD, iParentId, iControlId);
msg.SetLabel(label);
g_windowManager.SendThreadMessage(msg, iParentId);
}
void ControlFadeLabel::reset() throw (UnimplementedException)
{
CGUIMessage msg(GUI_MSG_LABEL_RESET, iParentId, iControlId);
vecLabels.clear();
g_windowManager.SendThreadMessage(msg, iParentId);
}
CGUIControl* ControlFadeLabel::Create() throw (WindowException)
{
CLabelInfo label;
label.font = g_fontManager.GetFont(strFont);
label.textColor = label.focusedColor = textColor;
label.align = align;
pGUIControl = new CGUIFadeLabelControl(
iParentId,
iControlId,
(float)dwPosX,
(float)dwPosY,
(float)dwWidth,
(float)dwHeight,
label,
true,
0,
true);
CGUIMessage msg(GUI_MSG_LABEL_RESET, iParentId, iControlId);
pGUIControl->OnMessage(msg);
return pGUIControl;
}
// ============================================================
// ============================================================
// ============================================================
ControlTextBox::ControlTextBox(long x, long y, long width, long height,
const char* font, const char* _textColor) :
strFont("font13"), textColor(0xffffffff)
{
dwPosX = x;
dwPosY = y;
dwWidth = width;
dwHeight = height;
if (font)
strFont = font;
if (_textColor)
sscanf(_textColor, "%x", &textColor);
}
void ControlTextBox::setText(const String& text) throw(UnimplementedException)
{
// create message
CGUIMessage msg(GUI_MSG_LABEL_SET, iParentId, iControlId);
msg.SetLabel(text);
// send message
g_windowManager.SendThreadMessage(msg, iParentId);
}
String ControlTextBox::getText() throw (UnimplementedException)
{
if (!pGUIControl) return NULL;
LOCKGUI;
return ((CGUITextBox*) pGUIControl)->GetDescription();
}
void ControlTextBox::reset() throw(UnimplementedException)
{
// create message
CGUIMessage msg(GUI_MSG_LABEL_RESET, iParentId, iControlId);
g_windowManager.SendThreadMessage(msg, iParentId);
}
void ControlTextBox::scroll(long position) throw(UnimplementedException)
{
static_cast<CGUITextBox*>(pGUIControl)->Scroll((int)position);
}
CGUIControl* ControlTextBox::Create() throw (WindowException)
{
// create textbox
CLabelInfo label;
label.font = g_fontManager.GetFont(strFont);
label.textColor = label.focusedColor = textColor;
pGUIControl = new CGUITextBox(iParentId, iControlId,
(float)dwPosX, (float)dwPosY, (float)dwWidth, (float)dwHeight,
label);
// reset textbox
CGUIMessage msg(GUI_MSG_LABEL_RESET, iParentId, iControlId);
pGUIControl->OnMessage(msg);
return pGUIControl;
}
// ============================================================
// ============================================================
// ============================================================
ControlButton::ControlButton(long x, long y, long width, long height, const String& label,
const char* focusTexture, const char* noFocusTexture,
long _textOffsetX, long _textOffsetY,
long alignment, const char* font, const char* _textColor,
const char* _disabledColor, long angle,
const char* _shadowColor, const char* _focusedColor) :
textOffsetX(_textOffsetX), textOffsetY(_textOffsetY),
align(alignment), strFont("font13"), textColor(0xffffffff), disabledColor(0x60ffffff),
iAngle(angle), shadowColor(0), focusedColor(0xffffffff)
{
dwPosX = x;
dwPosY = y;
dwWidth = width;
dwHeight = height;
strText = label;
// if texture is supplied use it, else get default ones
strTextureFocus = focusTexture ? focusTexture :
XBMCAddonUtils::getDefaultImage((char*)"button", (char*)"texturefocus", (char*)"button-focus.png");
strTextureNoFocus = noFocusTexture ? noFocusTexture :
XBMCAddonUtils::getDefaultImage((char*)"button", (char*)"texturenofocus", (char*)"button-nofocus.jpg");
if (font) strFont = font;
if (_textColor) sscanf( _textColor, "%x", &textColor );
if (_disabledColor) sscanf( _disabledColor, "%x", &disabledColor );
if (_shadowColor) sscanf( _shadowColor, "%x", &shadowColor );
if (_focusedColor) sscanf( _focusedColor, "%x", &focusedColor );
}
void ControlButton::setLabel(const String& label,
const char* font,
const char* _textColor,
const char* _disabledColor,
const char* _shadowColor,
const char* _focusedColor,
const String& label2) throw (UnimplementedException)
{
if (!label.empty()) strText = label;
if (!label2.empty()) strText2 = label2;
if (font) strFont = font;
if (_textColor) sscanf(_textColor, "%x", &textColor);
if (_disabledColor) sscanf( _disabledColor, "%x", &disabledColor );
if (_shadowColor) sscanf(_shadowColor, "%x", &shadowColor);
if (_focusedColor) sscanf(_focusedColor, "%x", &focusedColor);
if (pGUIControl)
{
LOCKGUI;
((CGUIButtonControl*)pGUIControl)->PythonSetLabel(strFont, strText, textColor, shadowColor, focusedColor);
((CGUIButtonControl*)pGUIControl)->SetLabel2(strText2);
((CGUIButtonControl*)pGUIControl)->PythonSetDisabledColor(disabledColor);
}
}
void ControlButton::setDisabledColor(const char* color) throw (UnimplementedException)
{
if (color) sscanf(color, "%x", &disabledColor);
if (pGUIControl)
{
LOCKGUI;
((CGUIButtonControl*)pGUIControl)->PythonSetDisabledColor(disabledColor);
}
}
String ControlButton::getLabel() throw (UnimplementedException)
{
if (!pGUIControl) return NULL;
LOCKGUI;
return ((CGUIButtonControl*) pGUIControl)->GetLabel();
}
String ControlButton::getLabel2() throw (UnimplementedException)
{
if (!pGUIControl) return NULL;
LOCKGUI;
return ((CGUIButtonControl*) pGUIControl)->GetLabel2();
}
CGUIControl* ControlButton::Create() throw (WindowException)
{
CLabelInfo label;
label.font = g_fontManager.GetFont(strFont);
label.textColor = textColor;
label.disabledColor = disabledColor;
label.shadowColor = shadowColor;
label.focusedColor = focusedColor;
label.align = align;
label.offsetX = (float)textOffsetX;
label.offsetY = (float)textOffsetY;
label.angle = (float)-iAngle;
pGUIControl = new CGUIButtonControl(
iParentId,
iControlId,
(float)dwPosX,
(float)dwPosY,
(float)dwWidth,
(float)dwHeight,
CTextureInfo(strTextureFocus),
CTextureInfo(strTextureNoFocus),
label);
CGUIButtonControl* pGuiButtonControl =
(CGUIButtonControl*)pGUIControl;
pGuiButtonControl->SetLabel(strText);
pGuiButtonControl->SetLabel2(strText2);
return pGUIControl;
}
// ============================================================
// ============================================================
// ============================================================
ControlCheckMark::ControlCheckMark(long x, long y, long width, long height, const String& label,
const char* focusTexture, const char* noFocusTexture,
long _checkWidth, long _checkHeight,
long _alignment, const char* font,
const char* _textColor, const char* _disabledColor) :
strFont("font13"), checkWidth(_checkWidth), checkHeight(_checkHeight),
align(_alignment), textColor(0xffffffff), disabledColor(0x60ffffff)
{
dwPosX = x;
dwPosY = y;
dwWidth = width;
dwHeight = height;
strText = label;
if (font) strFont = font;
if (_textColor) sscanf(_textColor, "%x", &textColor);
if (_disabledColor) sscanf( _disabledColor, "%x", &disabledColor );
strTextureFocus = focusTexture ? focusTexture :
XBMCAddonUtils::getDefaultImage((char*)"checkmark", (char*)"texturefocus", (char*)"check-box.png");
strTextureNoFocus = noFocusTexture ? noFocusTexture :
XBMCAddonUtils::getDefaultImage((char*)"checkmark", (char*)"texturenofocus", (char*)"check-boxNF.png");
}
bool ControlCheckMark::getSelected() throw (UnimplementedException)
{
bool isSelected = false;
if (pGUIControl)
{
LOCKGUI;
isSelected = ((CGUICheckMarkControl*)pGUIControl)->GetSelected();
}
return isSelected;
}
void ControlCheckMark::setSelected(bool selected) throw (UnimplementedException)
{
if (pGUIControl)
{
LOCKGUI;
((CGUICheckMarkControl*)pGUIControl)->SetSelected(selected);
}
}
void ControlCheckMark::setLabel(const String& label,
const char* font,
const char* _textColor,
const char* _disabledColor,
const char* _shadowColor,
const char* _focusedColor,
const String& label2) throw (UnimplementedException)
{
if (font) strFont = font;
if (_textColor) sscanf(_textColor, "%x", &textColor);
if (_disabledColor) sscanf(_disabledColor, "%x", &disabledColor);
if (pGUIControl)
{
LOCKGUI;
((CGUICheckMarkControl*)pGUIControl)->PythonSetLabel(strFont,strText,textColor);
((CGUICheckMarkControl*)pGUIControl)->PythonSetDisabledColor(disabledColor);
}
}
void ControlCheckMark::setDisabledColor(const char* color) throw (UnimplementedException)
{
if (color) sscanf(color, "%x", &disabledColor);
if (pGUIControl)
{
LOCKGUI;
((CGUICheckMarkControl*)pGUIControl)->PythonSetDisabledColor( disabledColor );
}
}
CGUIControl* ControlCheckMark::Create() throw (WindowException)
{
CLabelInfo label;
label.disabledColor = disabledColor;
label.textColor = label.focusedColor = textColor;
label.font = g_fontManager.GetFont(strFont);
label.align = align;
CTextureInfo imageFocus(strTextureFocus);
CTextureInfo imageNoFocus(strTextureNoFocus);
pGUIControl = new CGUICheckMarkControl(
iParentId,
iControlId,
(float)dwPosX,
(float)dwPosY,
(float)dwWidth,
(float)dwHeight,
imageFocus, imageNoFocus,
(float)checkWidth,
(float)checkHeight,
label );
CGUICheckMarkControl* pGuiCheckMarkControl = (CGUICheckMarkControl*)pGUIControl;
pGuiCheckMarkControl->SetLabel(strText);
return pGUIControl;
}
// ============================================================
// ============================================================
// ============================================================
ControlImage::ControlImage(long x, long y, long width, long height,
const char* filename, long aRatio,
const char* _colorDiffuse):
aspectRatio(aRatio), colorDiffuse(0)
{
dwPosX = x;
dwPosY = y;
dwWidth = width;
dwHeight = height;
// check if filename exists
strFileName = filename;
if (_colorDiffuse)
sscanf(_colorDiffuse, "%x", &colorDiffuse);
}
void ControlImage::setImage(const char* imageFilename, const bool useCache) throw (UnimplementedException)
{
strFileName = imageFilename;
LOCKGUI;
if (pGUIControl)
((CGUIImage*)pGUIControl)->SetFileName(strFileName, false, useCache);
}
void ControlImage::setColorDiffuse(const char* cColorDiffuse) throw (UnimplementedException)
{
if (cColorDiffuse) sscanf(cColorDiffuse, "%x", &colorDiffuse);
else colorDiffuse = 0;
LOCKGUI;
if (pGUIControl)
((CGUIImage *)pGUIControl)->SetColorDiffuse(colorDiffuse);
}
CGUIControl* ControlImage::Create() throw (WindowException)
{
pGUIControl = new CGUIImage(iParentId, iControlId,
(float)dwPosX, (float)dwPosY, (float)dwWidth, (float)dwHeight,
CTextureInfo(strFileName));
if (pGUIControl && aspectRatio <= CAspectRatio::AR_KEEP)
((CGUIImage *)pGUIControl)->SetAspectRatio((CAspectRatio::ASPECT_RATIO)aspectRatio);
if (pGUIControl && colorDiffuse)
((CGUIImage *)pGUIControl)->SetColorDiffuse(colorDiffuse);
return pGUIControl;
}
// ============================================================
// ============================================================
// ============================================================
ControlProgress::ControlProgress(long x, long y, long width, long height,
const char* texturebg,
const char* textureleft,
const char* texturemid,
const char* textureright,
const char* textureoverlay)
{
dwPosX = x;
dwPosY = y;
dwWidth = width;
dwHeight = height;
// if texture is supplied use it, else get default ones
strTextureBg = texturebg ? texturebg :
XBMCAddonUtils::getDefaultImage((char*)"progress", (char*)"texturebg", (char*)"progress_back.png");
strTextureLeft = textureleft ? textureleft :
XBMCAddonUtils::getDefaultImage((char*)"progress", (char*)"lefttexture", (char*)"progress_left.png");
strTextureMid = texturemid ? texturemid :
XBMCAddonUtils::getDefaultImage((char*)"progress", (char*)"midtexture", (char*)"progress_mid.png");
strTextureRight = textureright ? textureright :
XBMCAddonUtils::getDefaultImage((char*)"progress", (char*)"righttexture", (char*)"progress_right.png");
strTextureOverlay = textureoverlay ? textureoverlay :
XBMCAddonUtils::getDefaultImage((char*)"progress", (char*)"overlaytexture", (char*)"progress_over.png");
}
void ControlProgress::setPercent(float pct) throw (UnimplementedException)
{
if (pGUIControl)
((CGUIProgressControl*)pGUIControl)->SetPercentage(pct);
}
float ControlProgress::getPercent() throw (UnimplementedException)
{
return (pGUIControl) ? ((CGUIProgressControl*)pGUIControl)->GetPercentage() : 0.0f;
}
CGUIControl* ControlProgress::Create() throw (WindowException)
{
pGUIControl = new CGUIProgressControl(iParentId, iControlId,
(float)dwPosX, (float)dwPosY,
(float)dwWidth,(float)dwHeight,
CTextureInfo(strTextureBg), CTextureInfo(strTextureLeft),
CTextureInfo(strTextureMid), CTextureInfo(strTextureRight),
CTextureInfo(strTextureOverlay));
if (pGUIControl && colorDiffuse)
((CGUIProgressControl *)pGUIControl)->SetColorDiffuse(colorDiffuse);
return pGUIControl;
}
// ============================================================
// ============================================================
// ============================================================
ControlSlider::ControlSlider(long x, long y, long width, long height,
const char* textureback,
const char* texture,
const char* texturefocus)
{
dwPosX = x;
dwPosY = y;
dwWidth = width;
dwHeight = height;
// if texture is supplied use it, else get default ones
strTextureBack = textureback ? textureback :
XBMCAddonUtils::getDefaultImage((char*)"slider", (char*)"texturesliderbar", (char*)"osd_slider_bg_2.png");
strTexture = texture ? texture :
XBMCAddonUtils::getDefaultImage((char*)"slider", (char*)"textureslidernib", (char*)"osd_slider_nibNF.png");
strTextureFoc = texturefocus ? texturefocus :
XBMCAddonUtils::getDefaultImage((char*)"slider", (char*)"textureslidernibfocus", (char*)"osd_slider_nib.png");
}
float ControlSlider::getPercent() throw (UnimplementedException)
{
return (pGUIControl) ? ((CGUISliderControl*)pGUIControl)->GetPercentage() : 0.0f;
}
void ControlSlider::setPercent(float pct) throw (UnimplementedException)
{
if (pGUIControl)
((CGUISliderControl*)pGUIControl)->SetPercentage(pct);
}
CGUIControl* ControlSlider::Create () throw (WindowException)
{
pGUIControl = new CGUISliderControl(iParentId, iControlId,(float)dwPosX, (float)dwPosY,
(float)dwWidth,(float)dwHeight,
CTextureInfo(strTextureBack),CTextureInfo(strTexture),
CTextureInfo(strTextureFoc),0);
return pGUIControl;
}
// ============================================================
// ============================================================
// ============================================================
ControlGroup::ControlGroup(long x, long y, long width, long height)
{
dwPosX = x;
dwPosY = y;
dwWidth = width;
dwHeight = height;
}
CGUIControl* ControlGroup::Create() throw (WindowException)
{
pGUIControl = new CGUIControlGroup(iParentId,
iControlId,
(float) dwPosX,
(float) dwPosY,
(float) dwWidth,
(float) dwHeight);
return pGUIControl;
}
// ============================================================
// ============================================================
// ============================================================
ControlRadioButton::ControlRadioButton(long x, long y, long width, long height, const String& label,
const char* focusOnTexture, const char* noFocusOnTexture,
const char* focusOffTexture, const char* noFocusOffTexture,
const char* focusTexture, const char* noFocusTexture,
long _textOffsetX, long _textOffsetY,
long alignment, const char* font, const char* _textColor,
const char* _disabledColor, long angle,
const char* _shadowColor, const char* _focusedColor) :
strFont("font13"), textColor(0xffffffff), disabledColor(0x60ffffff),
textOffsetX(_textOffsetX), textOffsetY(_textOffsetY), align(alignment), iAngle(angle),
shadowColor(0), focusedColor(0xffffffff)
{
dwPosX = x;
dwPosY = y;
dwWidth = width;
dwHeight = height;
strText = label;
// if texture is supplied use it, else get default ones
strTextureFocus = focusTexture ? focusTexture :
XBMCAddonUtils::getDefaultImage((char*)"button", (char*)"texturefocus", (char*)"button-focus.png");
strTextureNoFocus = noFocusTexture ? noFocusTexture :
XBMCAddonUtils::getDefaultImage((char*)"button", (char*)"texturenofocus", (char*)"button-nofocus.jpg");
if (focusOnTexture && noFocusOnTexture)
{
strTextureRadioOnFocus = focusOnTexture;
strTextureRadioOnNoFocus = noFocusOnTexture;
}
else
{
strTextureRadioOnFocus = strTextureRadioOnNoFocus = focusTexture ? focusTexture :
XBMCAddonUtils::getDefaultImage((char*)"radiobutton", (char*)"textureradiofocus", (char*)"radiobutton-focus.png");
}
if (focusOffTexture && noFocusOffTexture)
{
strTextureRadioOffFocus = focusOffTexture;
strTextureRadioOffNoFocus = noFocusOffTexture;
}
else
{
strTextureRadioOffFocus = strTextureRadioOffNoFocus = noFocusTexture ? noFocusTexture :
XBMCAddonUtils::getDefaultImage((char*)"radiobutton", (char*)"textureradiofocus", (char*)"radiobutton-focus.png");
}
if (font) strFont = font;
if (_textColor) sscanf( _textColor, "%x", &textColor );
if (_disabledColor) sscanf( _disabledColor, "%x", &disabledColor );
if (_shadowColor) sscanf( _shadowColor, "%x", &shadowColor );
if (_focusedColor) sscanf( _focusedColor, "%x", &focusedColor );
}
void ControlRadioButton::setSelected(bool selected) throw (UnimplementedException)
{
if (pGUIControl)
{
LOCKGUI;
((CGUIRadioButtonControl*)pGUIControl)->SetSelected(selected);
}
}
bool ControlRadioButton::isSelected() throw (UnimplementedException)
{
bool isSelected = false;
if (pGUIControl)
{
LOCKGUI;
isSelected = ((CGUIRadioButtonControl*)pGUIControl)->IsSelected();
}
return isSelected;
}
void ControlRadioButton::setLabel(const String& label,
const char* font,
const char* _textColor,
const char* _disabledColor,
const char* _shadowColor,
const char* _focusedColor,
const String& label2) throw (UnimplementedException)
{
if (!label.empty()) strText = label;
if (font) strFont = font;
if (_textColor) sscanf(_textColor, "%x", &textColor);
if (_disabledColor) sscanf( _disabledColor, "%x", &disabledColor );
if (_shadowColor) sscanf(_shadowColor, "%x", &shadowColor);
if (_focusedColor) sscanf(_focusedColor, "%x", &focusedColor);
if (pGUIControl)
{
LOCKGUI;
((CGUIRadioButtonControl*)pGUIControl)->PythonSetLabel(strFont, strText, textColor, shadowColor, focusedColor);
((CGUIRadioButtonControl*)pGUIControl)->PythonSetDisabledColor(disabledColor);
}
}
void ControlRadioButton::setRadioDimension(long x, long y, long width, long height)
throw (UnimplementedException)
{
dwPosX = x;
dwPosY = y;
dwWidth = width;
dwHeight = height;
if (pGUIControl)
{
LOCKGUI;
((CGUIRadioButtonControl*)pGUIControl)->SetRadioDimensions((float)dwPosX, (float)dwPosY, (float)dwWidth, (float)dwHeight);
}
}
CGUIControl* ControlRadioButton::Create() throw (WindowException)
{
CLabelInfo label;
label.font = g_fontManager.GetFont(strFont);
label.textColor = textColor;
label.disabledColor = disabledColor;
label.shadowColor = shadowColor;
label.focusedColor = focusedColor;
label.align = align;
label.offsetX = (float)textOffsetX;
label.offsetY = (float)textOffsetY;
label.angle = (float)-iAngle;
pGUIControl = new CGUIRadioButtonControl(
iParentId,
iControlId,
(float)dwPosX,
(float)dwPosY,
(float)dwWidth,
(float)dwHeight,
CTextureInfo(strTextureFocus),
CTextureInfo(strTextureNoFocus),
label,
CTextureInfo(strTextureRadioOnFocus),
CTextureInfo(strTextureRadioOnNoFocus),
CTextureInfo(strTextureRadioOffFocus),
CTextureInfo(strTextureRadioOffNoFocus));
CGUIRadioButtonControl* pGuiButtonControl =
(CGUIRadioButtonControl*)pGUIControl;
pGuiButtonControl->SetLabel(strText);
return pGUIControl;
}
// ============================================================
// ============================================================
// ============================================================
Control::~Control() { deallocating(); }
CGUIControl* Control::Create() throw (WindowException)
{
throw WindowException("Object is a Control, but can't be added to a window");
}
std::vector<int> Control::getPosition()
{
std::vector<int> ret(2);
ret[0] = dwPosX;
ret[1] = dwPosY;
return ret;
}
void Control::setEnabled(bool enabled)
{
DelayedCallGuard dcguard(languageHook);
LOCKGUI;
if (pGUIControl)
pGUIControl->SetEnabled(enabled);
}
void Control::setVisible(bool visible)
{
DelayedCallGuard dcguard(languageHook);
LOCKGUI;
if (pGUIControl)
pGUIControl->SetVisible(visible);
}
void Control::setVisibleCondition(const char* visible, bool allowHiddenFocus)
{
DelayedCallGuard dcguard(languageHook);
LOCKGUI;
if (pGUIControl)
pGUIControl->SetVisibleCondition(visible, allowHiddenFocus ? "true" : "false");
}
void Control::setEnableCondition(const char* enable)
{
DelayedCallGuard dcguard(languageHook);
LOCKGUI;
if (pGUIControl)
pGUIControl->SetEnableCondition(enable);
}
void Control::setAnimations(const std::vector< Tuple<String,String> >& eventAttr) throw (WindowException)
{
CXBMCTinyXML xmlDoc;
TiXmlElement xmlRootElement("control");
TiXmlNode *pRoot = xmlDoc.InsertEndChild(xmlRootElement);
if (!pRoot)
throw WindowException("TiXmlNode creation error");
std::vector<CAnimation> animations;
for (unsigned int anim = 0; anim < eventAttr.size(); anim++)
{
const Tuple<String,String>& pTuple = eventAttr[anim];
if (pTuple.GetNumValuesSet() != 2)
throw WindowException("Error unpacking tuple found in list");
const String& cEvent = pTuple.first();
const String& cAttr = pTuple.second();
TiXmlElement pNode("animation");
std::vector<std::string> attrs = StringUtils::Split(cAttr, " ");
for (std::vector<std::string>::const_iterator i = attrs.begin(); i != attrs.end(); ++i)
{
std::vector<std::string> attrs2 = StringUtils::Split(*i, "=");
if (attrs2.size() == 2)
pNode.SetAttribute(attrs2[0], attrs2[1]);
}
TiXmlText value(cEvent.c_str());
pNode.InsertEndChild(value);
pRoot->InsertEndChild(pNode);
}
const CRect animRect((float)dwPosX, (float)dwPosY, (float)dwPosX + dwWidth, (float)dwPosY + dwHeight);
LOCKGUI;
if (pGUIControl)
{
CGUIControlFactory::GetAnimations(pRoot, animRect, iParentId, animations);
pGUIControl->SetAnimations(animations);
}
}
void Control::setPosition(long x, long y)
{
DelayedCallGuard dcguard(languageHook);
LOCKGUI;
dwPosX = x;
dwPosY = y;
if (pGUIControl)
pGUIControl->SetPosition((float)dwPosX, (float)dwPosY);
}
void Control::setWidth(long width)
{
DelayedCallGuard dcguard(languageHook);
LOCKGUI;
dwWidth = width;
if (pGUIControl)
pGUIControl->SetWidth((float)dwWidth);
}
void Control::setHeight(long height)
{
DelayedCallGuard dcguard(languageHook);
LOCKGUI;
dwHeight = height;
if (pGUIControl)
pGUIControl->SetHeight((float)dwHeight);
}
void Control::setNavigation(const Control* up, const Control* down,
const Control* left, const Control* right)
throw (WindowException)
{
if(iControlId == 0)
throw WindowException("Control has to be added to a window first");
{
LOCKGUI;
if (pGUIControl)
{
pGUIControl->SetNavigationAction(ACTION_MOVE_UP, up->iControlId);
pGUIControl->SetNavigationAction(ACTION_MOVE_DOWN, down->iControlId);
pGUIControl->SetNavigationAction(ACTION_MOVE_LEFT, left->iControlId);
pGUIControl->SetNavigationAction(ACTION_MOVE_RIGHT, right->iControlId);
}
}
}
void Control::controlUp(const Control* control) throw (WindowException)
{
if(iControlId == 0)
throw WindowException("Control has to be added to a window first");
{
LOCKGUI;
if (pGUIControl)
pGUIControl->SetNavigationAction(ACTION_MOVE_UP, control->iControlId);
}
}
void Control::controlDown(const Control* control) throw (WindowException)
{
if(iControlId == 0)
throw WindowException("Control has to be added to a window first");
{
LOCKGUI;
if (pGUIControl)
pGUIControl->SetNavigationAction(ACTION_MOVE_DOWN, control->iControlId);
}
}
void Control::controlLeft(const Control* control) throw (WindowException)
{
if(iControlId == 0)
throw WindowException("Control has to be added to a window first");
{
LOCKGUI;
if (pGUIControl)
pGUIControl->SetNavigationAction(ACTION_MOVE_LEFT, control->iControlId);
}
}
void Control::controlRight(const Control* control) throw (WindowException)
{
if(iControlId == 0)
throw WindowException("Control has to be added to a window first");
{
LOCKGUI;
if (pGUIControl)
pGUIControl->SetNavigationAction(ACTION_MOVE_RIGHT, control->iControlId);
}
}
// ============================================================
// ControlSpin
// ============================================================
ControlSpin::ControlSpin()
{
// default values for spin control
color = 0xffffffff;
dwPosX = 0;
dwPosY = 0;
dwWidth = 16;
dwHeight = 16;
// get default images
strTextureUp = XBMCAddonUtils::getDefaultImage((char*)"listcontrol", (char*)"textureup", (char*)"scroll-up.png");
strTextureDown = XBMCAddonUtils::getDefaultImage((char*)"listcontrol", (char*)"texturedown", (char*)"scroll-down.png");
strTextureUpFocus = XBMCAddonUtils::getDefaultImage((char*)"listcontrol", (char*)"textureupfocus", (char*)"scroll-up-focus.png");
strTextureDownFocus = XBMCAddonUtils::getDefaultImage((char*)"listcontrol", (char*)"texturedownfocus", (char*)"scroll-down-focus.png");
}
void ControlSpin::setTextures(const char* up, const char* down,
const char* upFocus,
const char* downFocus) throw(UnimplementedException)
{
strTextureUp = up;
strTextureDown = down;
strTextureUpFocus = upFocus;
strTextureDownFocus = downFocus;
/*
PyXBMCGUILock();
if (self->pGUIControl)
{
CGUISpinControl* pControl = (CGUISpinControl*)self->pGUIControl;
pControl->se
PyXBMCGUIUnlock();
*/
}
ControlSpin::~ControlSpin() {}
// ============================================================
// ============================================================
// ControlLabel
// ============================================================
ControlLabel::ControlLabel(long x, long y, long width, long height,
const String& label,
const char* font, const char* p_textColor,
const char* p_disabledColor,
long p_alignment,
bool hasPath, long angle) :
strFont("font13"),
textColor(0xffffffff), disabledColor(0x60ffffff),
align(p_alignment), bHasPath(hasPath), iAngle(angle)
{
dwPosX = x;
dwPosY = y;
dwWidth = width;
dwHeight = height;
strText = label;
if (font)
strFont = font;
if (p_textColor)
sscanf(p_textColor, "%x", &textColor);
if (p_disabledColor)
sscanf( p_disabledColor, "%x", &disabledColor );
}
ControlLabel::~ControlLabel() {}
CGUIControl* ControlLabel::Create() throw (WindowException)
{
CLabelInfo label;
label.font = g_fontManager.GetFont(strFont);
label.textColor = label.focusedColor = textColor;
label.disabledColor = disabledColor;
label.align = align;
label.angle = (float)-iAngle;
pGUIControl = new CGUILabelControl(
iParentId,
iControlId,
(float)dwPosX,
(float)dwPosY,
(float)dwWidth,
(float)dwHeight,
label,
false,
bHasPath);
((CGUILabelControl *)pGUIControl)->SetLabel(strText);
return pGUIControl;
}
void ControlLabel::setLabel(const String& label, const char* font,
const char* textColor, const char* disabledColor,
const char* shadowColor, const char* focusedColor,
const String& label2) throw(UnimplementedException)
{
strText = label;
CGUIMessage msg(GUI_MSG_LABEL_SET, iParentId, iControlId);
msg.SetLabel(strText);
g_windowManager.SendThreadMessage(msg, iParentId);
}
String ControlLabel::getLabel() throw(UnimplementedException)
{
if (!pGUIControl)
return NULL;
return strText;
}
// ============================================================
// ============================================================
// ControlEdit
// ============================================================
ControlEdit::ControlEdit(long x, long y, long width, long height, const String& label,
const char* font, const char* _textColor,
const char* _disabledColor,
long _alignment, const char* focusTexture,
const char* noFocusTexture, bool isPassword) :
strFont("font13"), textColor(0xffffffff), disabledColor(0x60ffffff),
align(_alignment), bIsPassword(isPassword)
{
strTextureFocus = focusTexture ? focusTexture :
XBMCAddonUtils::getDefaultImage((char*)"edit", (char*)"texturefocus", (char*)"button-focus.png");
strTextureNoFocus = noFocusTexture ? noFocusTexture :
XBMCAddonUtils::getDefaultImage((char*)"edit", (char*)"texturenofocus", (char*)"button-focus.png");
if (font) strFont = font;
if (_textColor) sscanf( _textColor, "%x", &textColor );
if (_disabledColor) sscanf( _disabledColor, "%x", &disabledColor );
}
CGUIControl* ControlEdit::Create() throw (WindowException)
{
CLabelInfo label;
label.font = g_fontManager.GetFont(strFont);
label.textColor = label.focusedColor = textColor;
label.disabledColor = disabledColor;
label.align = align;
pGUIControl = new CGUIEditControl(
iParentId,
iControlId,
(float)dwPosX,
(float)dwPosY,
(float)dwWidth,
(float)dwHeight,
CTextureInfo(strTextureFocus),
CTextureInfo(strTextureNoFocus),
label,
strText);
if (bIsPassword)
((CGUIEditControl *) pGUIControl)->SetInputType(CGUIEditControl::INPUT_TYPE_PASSWORD, 0);
return pGUIControl;
}
void ControlEdit::setLabel(const String& label, const char* font,
const char* textColor, const char* disabledColor,
const char* shadowColor, const char* focusedColor,
const String& label2) throw(UnimplementedException)
{
strText = label;
CGUIMessage msg(GUI_MSG_LABEL_SET, iParentId, iControlId);
msg.SetLabel(strText);
g_windowManager.SendThreadMessage(msg, iParentId);
}
String ControlEdit::getLabel() throw(UnimplementedException)
{
if (!pGUIControl)
return NULL;
return strText;
}
void ControlEdit::setText(const String& text) throw(UnimplementedException)
{
// create message
CGUIMessage msg(GUI_MSG_LABEL2_SET, iParentId, iControlId);
msg.SetLabel(text);
// send message
g_windowManager.SendThreadMessage(msg, iParentId);
}
String ControlEdit::getText() throw(UnimplementedException)
{
CGUIMessage msg(GUI_MSG_ITEM_SELECTED, iParentId, iControlId);
g_windowManager.SendMessage(msg, iParentId);
return msg.GetLabel();
}
// ============================================================
// ControlList
// ============================================================
ControlList::ControlList(long x, long y, long width, long height, const char* font,
const char* ctextColor, const char* cbuttonTexture,
const char* cbuttonFocusTexture,
const char* cselectedColor,
long _imageWidth, long _imageHeight, long _itemTextXOffset,
long _itemTextYOffset, long _itemHeight, long _space, long _alignmentY) :
strFont("font13"),
textColor(0xe0f0f0f0), selectedColor(0xffffffff),
imageHeight(_imageHeight), imageWidth(_imageWidth),
itemHeight(_itemHeight), space(_space),
itemTextOffsetX(_itemTextXOffset),itemTextOffsetY(_itemTextYOffset),
alignmentY(_alignmentY)
{
dwPosX = x;
dwPosY = y;
dwWidth = width;
dwHeight = height;
// create a python spin control
pControlSpin = new ControlSpin();
// initialize default values
if (font)
strFont = font;
if (ctextColor)
sscanf( ctextColor, "%x", &textColor );
if (cselectedColor)
sscanf( cselectedColor, "%x", &selectedColor );
strTextureButton = cbuttonTexture ? cbuttonTexture :
XBMCAddonUtils::getDefaultImage((char*)"listcontrol", (char*)"texturenofocus", (char*)"list-nofocus.png");
strTextureButtonFocus = cbuttonFocusTexture ? cbuttonFocusTexture :
XBMCAddonUtils::getDefaultImage((char*)"listcontrol", (char*)"texturefocus", (char*)"list-focus.png");
// default values for spin control
pControlSpin->dwPosX = dwWidth - 35;
pControlSpin->dwPosY = dwHeight - 15;
}
ControlList::~ControlList() { }
CGUIControl* ControlList::Create() throw (WindowException)
{
CLabelInfo label;
label.align = alignmentY;
label.font = g_fontManager.GetFont(strFont);
label.textColor = label.focusedColor = textColor;
//label.shadowColor = shadowColor;
label.selectedColor = selectedColor;
label.offsetX = (float)itemTextOffsetX;
label.offsetY = (float)itemTextOffsetY;
// Second label should have the same font, alignment, and colours as the first, but
// the offsets should be 0.
CLabelInfo label2 = label;
label2.offsetX = label2.offsetY = 0;
label2.align |= XBFONT_RIGHT;
pGUIControl = new CGUIListContainer(
iParentId,
iControlId,
(float)dwPosX,
(float)dwPosY,
(float)dwWidth,
(float)dwHeight - pControlSpin->dwHeight - 5,
label, label2,
CTextureInfo(strTextureButton),
CTextureInfo(strTextureButtonFocus),
(float)itemHeight,
(float)imageWidth, (float)imageHeight,
(float)space);
return pGUIControl;
}
void ControlList::addItem(const Alternative<String, const XBMCAddon::xbmcgui::ListItem* > & item, bool sendMessage)
{
XBMC_TRACE;
if (item.which() == first)
internAddListItem(ListItem::fromString(item.former()),sendMessage);
else
internAddListItem(item.later(),sendMessage);
}
void ControlList::addItems(const std::vector<Alternative<String, const XBMCAddon::xbmcgui::ListItem* > > & items)
{
XBMC_TRACE;
for (std::vector<Alternative<String, const XBMCAddon::xbmcgui::ListItem* > >::const_iterator iter = items.begin(); iter != items.end(); ++iter)
addItem(*iter,false);
sendLabelBind(items.size());
}
void ControlList::internAddListItem(AddonClass::Ref<ListItem> pListItem, bool sendMessage) throw (WindowException)
{
if (pListItem.isNull())
throw WindowException("NULL ListItem passed to ControlList::addListItem");
// add item to objects vector
vecItems.push_back(pListItem);
// send all of the items ... this is what it did before.
if (sendMessage)
sendLabelBind(vecItems.size());
}
void ControlList::sendLabelBind(int tail)
{
// construct a CFileItemList to pass 'em on to the list
CGUIListItemPtr items(new CFileItemList());
for (unsigned int i = vecItems.size() - tail; i < vecItems.size(); i++)
((CFileItemList*)items.get())->Add(vecItems[i]->item);
CGUIMessage msg(GUI_MSG_LABEL_BIND, iParentId, iControlId, 0, 0, items);
msg.SetPointer(items.get());
g_windowManager.SendThreadMessage(msg, iParentId);
}
void ControlList::selectItem(long item) throw(UnimplementedException)
{
// create message
CGUIMessage msg(GUI_MSG_ITEM_SELECT, iParentId, iControlId, item);
// send message
g_windowManager.SendThreadMessage(msg, iParentId);
}
void ControlList::removeItem(int index) throw(UnimplementedException,WindowException)
{
if (index < 0 || index >= (int)vecItems.size())
throw WindowException("Index out of range");
vecItems.erase(vecItems.begin() + index);
sendLabelBind(vecItems.size());
}
void ControlList::reset() throw(UnimplementedException)
{
CGUIMessage msg(GUI_MSG_LABEL_RESET, iParentId, iControlId);
g_windowManager.SendThreadMessage(msg, iParentId);
// delete all items from vector
// delete all ListItem from vector
vecItems.clear(); // this should delete all of the objects
}
Control* ControlList::getSpinControl() throw (UnimplementedException)
{
return pControlSpin;
}
long ControlList::getSelectedPosition() throw(UnimplementedException)
{
DelayedCallGuard dcguard(languageHook);
LOCKGUI;
// create message
CGUIMessage msg(GUI_MSG_ITEM_SELECTED, iParentId, iControlId);
long pos = -1;
// send message
if ((vecItems.size() > 0) && pGUIControl)
{
pGUIControl->OnMessage(msg);
pos = msg.GetParam1();
}
return pos;
}
XBMCAddon::xbmcgui::ListItem* ControlList::getSelectedItem() throw (UnimplementedException)
{
DelayedCallGuard dcguard(languageHook);
LOCKGUI;
// create message
CGUIMessage msg(GUI_MSG_ITEM_SELECTED, iParentId, iControlId);
AddonClass::Ref<ListItem> pListItem = NULL;
// send message
if ((vecItems.size() > 0) && pGUIControl)
{
pGUIControl->OnMessage(msg);
if (msg.GetParam1() >= 0 && (size_t)msg.GetParam1() < vecItems.size())
pListItem = vecItems[msg.GetParam1()];
}
return pListItem.get();
}
void ControlList::setImageDimensions(long imageWidth,long imageHeight) throw (UnimplementedException)
{
CLog::Log(LOGWARNING,"ControlList::setImageDimensions was called but ... it currently isn't defined to do anything.");
/*
PyXBMCGUILock();
if (self->pGUIControl)
{
CGUIListControl* pListControl = (CGUIListControl*) self->pGUIControl;
pListControl->SetImageDimensions((float)self->dwImageWidth, (float)self->dwImageHeight );
}
PyXBMCGUIUnlock();
*/
}
void ControlList::setItemHeight(long height) throw (UnimplementedException)
{
CLog::Log(LOGWARNING,"ControlList::setItemHeight was called but ... it currently isn't defined to do anything.");
/*
PyXBMCGUILock();
if (self->pGUIControl)
{
CGUIListControl* pListControl = (CGUIListControl*) self->pGUIControl;
pListControl->SetItemHeight((float)self->dwItemHeight);
}
PyXBMCGUIUnlock();
*/
}
void ControlList::setSpace(int space) throw (UnimplementedException)
{
CLog::Log(LOGWARNING,"ControlList::setSpace was called but ... it currently isn't defined to do anything.");
/*
PyXBMCGUILock();
if (self->pGUIControl)
{
CGUIListControl* pListControl = (CGUIListControl*) self->pGUIControl;
pListControl->SetSpaceBetweenItems((float)self->dwSpace);
}
PyXBMCGUIUnlock();
*/
}
void ControlList::setPageControlVisible(bool visible) throw (UnimplementedException)
{
CLog::Log(LOGWARNING,"ControlList::setPageControlVisible was called but ... it currently isn't defined to do anything.");
// char isOn = true;
/*
PyXBMCGUILock();
if (self->pGUIControl)
{
((CGUIListControl*)self->pGUIControl)->SetPageControlVisible((bool)isOn );
}
PyXBMCGUIUnlock();
*/
}
long ControlList::size() throw (UnimplementedException)
{
return (long)vecItems.size();
}
long ControlList::getItemHeight() throw(UnimplementedException)
{
return (long)itemHeight;
}
long ControlList::getSpace() throw (UnimplementedException)
{
return (long)space;
}
XBMCAddon::xbmcgui::ListItem* ControlList::getListItem(int index) throw (UnimplementedException,WindowException)
{
if (index < 0 || index >= (int)vecItems.size())
throw WindowException("Index out of range");
AddonClass::Ref<ListItem> pListItem = vecItems[index];
return pListItem.get();
}
void ControlList::setStaticContent(const ListItemList* pitems) throw (UnimplementedException)
{
const ListItemList& vecItems = *pitems;
std::vector<CGUIStaticItemPtr> items;
for (unsigned int item = 0; item < vecItems.size(); item++)
{
ListItem* pItem = vecItems[item];
// NOTE: This code has likely not worked fully correctly for some time
// In particular, the click behaviour won't be working.
CGUIStaticItemPtr newItem(new CGUIStaticItem(*pItem->item));
items.push_back(newItem);
}
// set static list
IListProvider *provider = new CStaticListProvider(items);
((CGUIBaseContainer *)pGUIControl)->SetListProvider(provider);
}
// ============================================================
}
}
| onetechgenius/XBMCast2TV | xbmc/interfaces/legacy/Control.cpp | C++ | gpl-2.0 | 49,424 |
namespace WikiFunctions.Profiles
{
partial class AWBLogUploadProfilesForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.lvAccounts = new WikiFunctions.Controls.NoFlickerExtendedListView(true, true);
this.colID = new System.Windows.Forms.ColumnHeader();
this.colAccountName = new System.Windows.Forms.ColumnHeader();
this.colPasswordSaved = new System.Windows.Forms.ColumnHeader();
this.colProfileSettings = new System.Windows.Forms.ColumnHeader();
this.colUsedForUpload = new System.Windows.Forms.ColumnHeader();
this.colNotes = new System.Windows.Forms.ColumnHeader();
this.mnuAccounts = new System.Windows.Forms.ContextMenuStrip(this.components);
this.loginAsThisAccountToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editThisAccountToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.changePasswordToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.addNewAccountToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.deleteThisAccountToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.btnAdd = new System.Windows.Forms.Button();
this.btnDelete = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
this.btnLogin = new System.Windows.Forms.Button();
this.BtnEdit = new System.Windows.Forms.Button();
this.mnuAccounts.SuspendLayout();
this.SuspendLayout();
//
// lvAccounts
//
this.lvAccounts.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lvAccounts.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.colID,
this.colAccountName,
this.colPasswordSaved,
this.colProfileSettings,
this.colUsedForUpload,
this.colNotes});
this.lvAccounts.ContextMenuStrip = this.mnuAccounts;
this.lvAccounts.FullRowSelect = true;
this.lvAccounts.Location = new System.Drawing.Point(12, 12);
this.lvAccounts.Name = "lvAccounts";
this.lvAccounts.Size = new System.Drawing.Size(494, 175);
this.lvAccounts.TabIndex = 0;
this.lvAccounts.UseCompatibleStateImageBehavior = false;
this.lvAccounts.View = System.Windows.Forms.View.Details;
this.lvAccounts.SelectedIndexChanged += new System.EventHandler(this.lvAccounts_SelectedIndexChanged);
this.lvAccounts.DoubleClick += new System.EventHandler(this.lvAccounts_DoubleClick);
//
// colID
//
this.colID.Text = "ID";
this.colID.Width = 32;
//
// colAccountName
//
this.colAccountName.Text = "Username";
this.colAccountName.Width = 89;
//
// colPasswordSaved
//
this.colPasswordSaved.Text = "Password saved?";
this.colPasswordSaved.Width = 107;
//
// colProfileSettings
//
this.colProfileSettings.Text = "Profile default settings";
this.colProfileSettings.Width = 175;
//
// colUsedForUpload
//
this.colUsedForUpload.Text = "Used for Upload?";
this.colUsedForUpload.Width = 98;
//
// colNotes
//
this.colNotes.Text = "Notes";
this.colNotes.Width = 63;
//
// mnuAccounts
//
this.mnuAccounts.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.loginAsThisAccountToolStripMenuItem,
this.editThisAccountToolStripMenuItem,
this.changePasswordToolStripMenuItem,
this.toolStripSeparator1,
this.addNewAccountToolStripMenuItem,
this.toolStripSeparator2,
this.deleteThisAccountToolStripMenuItem});
this.mnuAccounts.Name = "mnuAccounts";
this.mnuAccounts.Size = new System.Drawing.Size(192, 126);
//
// loginAsThisAccountToolStripMenuItem
//
this.loginAsThisAccountToolStripMenuItem.Name = "loginAsThisAccountToolStripMenuItem";
this.loginAsThisAccountToolStripMenuItem.Size = new System.Drawing.Size(191, 22);
this.loginAsThisAccountToolStripMenuItem.Text = "Log-in as this account";
this.loginAsThisAccountToolStripMenuItem.Visible = false;
//
// editThisAccountToolStripMenuItem
//
this.editThisAccountToolStripMenuItem.Name = "editThisAccountToolStripMenuItem";
this.editThisAccountToolStripMenuItem.Size = new System.Drawing.Size(191, 22);
this.editThisAccountToolStripMenuItem.Text = "Edit this account";
this.editThisAccountToolStripMenuItem.Click += new System.EventHandler(this.editThisAccountToolStripMenuItem_Click);
//
// changePasswordToolStripMenuItem
//
this.changePasswordToolStripMenuItem.Name = "changePasswordToolStripMenuItem";
this.changePasswordToolStripMenuItem.Size = new System.Drawing.Size(191, 22);
this.changePasswordToolStripMenuItem.Text = "Change password";
this.changePasswordToolStripMenuItem.Click += new System.EventHandler(this.changePasswordToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(188, 6);
//
// addNewAccountToolStripMenuItem
//
this.addNewAccountToolStripMenuItem.Name = "addNewAccountToolStripMenuItem";
this.addNewAccountToolStripMenuItem.Size = new System.Drawing.Size(191, 22);
this.addNewAccountToolStripMenuItem.Text = "Add new account";
this.addNewAccountToolStripMenuItem.Click += new System.EventHandler(this.addNewAccountToolStripMenuItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(188, 6);
//
// deleteThisAccountToolStripMenuItem
//
this.deleteThisAccountToolStripMenuItem.Name = "deleteThisAccountToolStripMenuItem";
this.deleteThisAccountToolStripMenuItem.Size = new System.Drawing.Size(191, 22);
this.deleteThisAccountToolStripMenuItem.Text = "Delete this account";
this.deleteThisAccountToolStripMenuItem.Click += new System.EventHandler(this.deleteThisSavedAccountToolStripMenuItem_Click);
//
// btnAdd
//
this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnAdd.Location = new System.Drawing.Point(93, 193);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(75, 23);
this.btnAdd.TabIndex = 2;
this.btnAdd.Text = "Add";
this.btnAdd.UseVisualStyleBackColor = true;
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// btnDelete
//
this.btnDelete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnDelete.Enabled = false;
this.btnDelete.Location = new System.Drawing.Point(255, 193);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(75, 23);
this.btnDelete.TabIndex = 4;
this.btnDelete.Text = "Delete";
this.btnDelete.UseVisualStyleBackColor = true;
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
//
// btnClose
//
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.Location = new System.Drawing.Point(431, 193);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(75, 23);
this.btnClose.TabIndex = 5;
this.btnClose.Text = "Close";
this.btnClose.UseVisualStyleBackColor = true;
this.btnClose.Click += new System.EventHandler(this.btnExit_Click);
//
// btnLogin
//
this.btnLogin.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnLogin.Enabled = false;
this.btnLogin.Location = new System.Drawing.Point(12, 193);
this.btnLogin.Name = "btnLogin";
this.btnLogin.Size = new System.Drawing.Size(75, 23);
this.btnLogin.TabIndex = 1;
this.btnLogin.Text = "Login";
this.btnLogin.UseVisualStyleBackColor = true;
this.btnLogin.Visible = false;
//
// BtnEdit
//
this.BtnEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.BtnEdit.Location = new System.Drawing.Point(174, 193);
this.BtnEdit.Name = "BtnEdit";
this.BtnEdit.Size = new System.Drawing.Size(75, 23);
this.BtnEdit.TabIndex = 3;
this.BtnEdit.Text = "Edit";
this.BtnEdit.UseVisualStyleBackColor = true;
this.BtnEdit.Click += new System.EventHandler(this.BtnEdit_Click);
//
// AWBLogUploadProfilesForm
//
this.AcceptButton = this.btnLogin;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnClose;
this.ClientSize = new System.Drawing.Size(518, 223);
this.Controls.Add(this.BtnEdit);
this.Controls.Add(this.lvAccounts);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.btnLogin);
this.Name = "AWBLogUploadProfilesForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Profiles";
this.Load += new System.EventHandler(this.AWBProfiles_Load);
this.mnuAccounts.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
protected WikiFunctions.Controls.NoFlickerExtendedListView lvAccounts;
protected System.Windows.Forms.ColumnHeader colAccountName;
protected System.Windows.Forms.ColumnHeader colPasswordSaved;
protected System.Windows.Forms.ColumnHeader colProfileSettings;
protected System.Windows.Forms.ColumnHeader colNotes;
protected System.Windows.Forms.ContextMenuStrip mnuAccounts;
protected System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
protected System.Windows.Forms.ToolStripMenuItem addNewAccountToolStripMenuItem;
protected System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
protected System.Windows.Forms.ToolStripMenuItem deleteThisAccountToolStripMenuItem;
protected System.Windows.Forms.Button btnAdd;
protected System.Windows.Forms.Button btnDelete;
protected System.Windows.Forms.ToolStripMenuItem changePasswordToolStripMenuItem;
protected System.Windows.Forms.ColumnHeader colID;
protected System.Windows.Forms.ToolStripMenuItem editThisAccountToolStripMenuItem;
protected System.Windows.Forms.Button btnClose;
protected System.Windows.Forms.ColumnHeader colUsedForUpload;
protected System.Windows.Forms.ToolStripMenuItem loginAsThisAccountToolStripMenuItem;
protected System.Windows.Forms.Button btnLogin;
protected System.Windows.Forms.Button BtnEdit;
}
} | svn2github/autowikibrowser | tags/ServerPlugin/WikiFunctions/Profiles/AWBLogUploadProfilesForm.designer.cs | C# | gpl-2.0 | 14,307 |
/*
*------------------------------------------------------------------------------
* Copyright (C) 2006-2014 University of Dundee & Open Microscopy Environment.
* All rights reserved.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*------------------------------------------------------------------------------
*/
package omero.gateway.util;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import omero.log.Logger;
/**
* Checks if the network is still up.
*
* @author Jean-Marie Burel <a
* href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a>
* @since 4.4
*/
public class NetworkChecker {
private final AtomicLong lastCheck = new AtomicLong(
System.currentTimeMillis());
private final AtomicBoolean lastValue = new AtomicBoolean(true);
/**
* The IP Address of the server the client is connected to or
* <code>null</code>.
*/
private InetAddress ipAddress;
/** The address of the server to reach. */
private final String address;
/** Reference to the logger. */
private Logger logger;
/** The list of interfaces when the network checker is initialized. */
private long interfacesCount;
/**
* Creates a new instance.
*
* @param address
* The address of the server the client is connected to or
* <code>null</code>.
* @param logger Reference to the logger.
*/
public NetworkChecker(String address, Logger logger) {
this.address = address;
this.logger = logger;
if (ipAddress != null) {
try {
this.ipAddress = InetAddress.getByName(address);
} catch (UnknownHostException e) {
// Ignored
}
}
interfacesCount = 0;
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface
.getNetworkInterfaces();
if (interfaces != null) {
NetworkInterface ni;
while (interfaces.hasMoreElements()) {
ni = interfaces.nextElement();
if (ni.isLoopback() || !ni.isUp())
continue;
interfacesCount++;
}
}
} catch (Exception e) {
// Ignored
}
}
/**
* Returns <code>true</code> if the network is still up, otherwise throws an
* <code>UnknownHostException</code>. This tests if the adapter is ready.
*
* @param useCachedValue Pass <code>true</code> if we use the cached value,
* <code>false</code> otherwise.
* @return See above.
* @throws Exception
* Thrown if the network is down.
*/
public boolean isNetworkup(boolean useCachedValue) throws Exception {
if (useCachedValue) {
long elapsed = System.currentTimeMillis() - lastCheck.get();
if (elapsed <= 5000) {
return lastValue.get();
}
}
boolean newValue = _isNetworkup();
long stop = System.currentTimeMillis();
lastValue.set(newValue);
lastCheck.set(stop);
return newValue;
}
/**
* Checks the network is available or not.
*
* @return See above.
* @throws Exception
* Thrown if an error occurred if we cannot reach.
*/
public boolean isAvailable() throws Exception {
if (ipAddress != null && ipAddress.isLoopbackAddress()) {
return true;
}
if (address != null) {
try {
URL url = new URL("http://" + address);
HttpURLConnection urlConnect = (HttpURLConnection) url
.openConnection();
urlConnect.setConnectTimeout(1000);
urlConnect.getContent();
} catch (Exception e) {
log("Not available %s", e);
return false;
}
}
return true;
}
/**
* Returns <code>true</code> if the network is still up, otherwise throws an
* <code>UnknownHostException</code>.
*
* @return See above.
* @throws Exception
* Thrown if the network is down.
*/
private boolean _isNetworkup() throws Exception {
if (ipAddress != null && ipAddress.isLoopbackAddress()) {
return true;
}
boolean networkup = false;
Enumeration<NetworkInterface> interfaces = NetworkInterface
.getNetworkInterfaces();
long count = 0;
if (interfaces != null && !networkup) {
NetworkInterface ni;
while (interfaces.hasMoreElements()) {
ni = interfaces.nextElement();
if (ni.isLoopback() || !ni.isUp())
continue;
count++;
}
}
if (count >= interfacesCount) {
networkup = true;
} else {
networkup = isAvailable();
if (networkup) { // one interface was dropped e.g. wireless
interfacesCount = count;
}
}
if (!networkup) {
throw new UnknownHostException("Network is down.");
}
return networkup;
}
/**
* Logs the error.
*
* @param msg
* The message to log
* @param objs
* The objects to add to the message.
*/
void log(String msg, Object... objs) {
if (logger != null) {
logger.debug(this, String.format(msg, objs));
}
}
}
| simleo/openmicroscopy | components/blitz/src/omero/gateway/util/NetworkChecker.java | Java | gpl-2.0 | 6,574 |
/* Delegate.java --
Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package org.omg.CORBA.portable;
import gnu.java.lang.CPStringBuilder;
import org.omg.CORBA.BAD_PARAM;
import org.omg.CORBA.Context;
import org.omg.CORBA.ContextList;
import org.omg.CORBA.DomainManager;
import org.omg.CORBA.ExceptionList;
import org.omg.CORBA.NO_IMPLEMENT;
import org.omg.CORBA.NVList;
import org.omg.CORBA.NamedValue;
import org.omg.CORBA.ORB;
import org.omg.CORBA.Policy;
import org.omg.CORBA.Request;
import org.omg.CORBA.SetOverrideType;
/**
* Specifies a vendor specific implementation of the
* {@link org.omg.CORBA.Object} methods. The calls to these
* methods are forwarded to the object delegate that can be
* replaced, if needed. The first parameter is the actual
* CORBA object to that the operation must be applied.
*
* Some methods in this class are not abstract, but no implemented,
* thowing the {@link NO_IMPLEMENT}. This, however, does not mean that
* they are not implemented in the derived classes as well.
*
* @author Audrius Meskauskas (AudriusA@Bioinformatics.org)
*/
public abstract class Delegate
{
/**
* Explains the reason of throwing the NO_IMPLEMENT.
*/
private static final String WHY =
"Following 1.4 API, this Delegate method must not be implemented. Override.";
/**
* Create a request to invoke the method of this object.
*
* @param target the CORBA object, to that this operation must be applied.
* @param context a list of additional properties.
* @param operation the name of method to be invoked.
* @param parameters the method parameters.
* @param returns the container for tge method returned value.
*
* @return the created reaquest.
*/
public abstract Request create_request(org.omg.CORBA.Object target,
Context context, String operation,
NVList parameters, NamedValue returns
);
/**
* Create a request to invoke the method of this object, specifying
* context list and the list of the expected exception.
*
* @param target the CORBA object, to that this operation must be applied.
* @param context a list of additional properties.
* @param operation the name of method to be invoked.
* @param parameters the method parameters.
* @param returns the container for tge method returned value.
* @param exceptions the list of the possible exceptions that the method
* can throw.
* @param ctx_list the list of the context strings that need to be
* resolved and send as a context instance.
*
* @return the created reaquest.
*/
public abstract Request create_request(org.omg.CORBA.Object target,
Context context, String operation,
NVList parameters, NamedValue returns,
ExceptionList exceptions,
ContextList ctx_list
);
/**
* Duplicate the object reference. This does not make much sense for
* java platform and is just included for the sake of compliance with
* CORBA APIs.
*
* @param target the CORBA object, to that this operation must be applied.
*
* The method may return the object reference itself.
*
* @return as a rule, <code>this</code>.
*/
public abstract org.omg.CORBA.Object duplicate(org.omg.CORBA.Object target);
/**
* Retrieve the domain managers for this object.
*
* @param target the CORBA object, to that this operation must be applied.
*
* @return the domain managers.
*
* @throws NO_IMPLEMENT, always (following the 1.4 specification).
*/
public DomainManager[] get_domain_managers(org.omg.CORBA.Object target)
{
throw new NO_IMPLEMENT(WHY);
}
/**
*
* @param target the CORBA object, to that this operation must be applied.
*
* Get the <code>InterfaceDef</code> for this Object.
*/
public abstract org.omg.CORBA.Object get_interface_def(org.omg.CORBA.Object target);
/**
* Returns the {@link Policy}, applying to this object.
*
* @param target the CORBA object, to that this operation must be applied.
* @param a_policy_type a type of policy to be obtained.
* @return a corresponding Policy object.
*
* @throws NO_IMPLEMENT, always (following the 1.4 specification).
*/
public Policy get_policy(org.omg.CORBA.Object target, int a_policy_type)
throws BAD_PARAM
{
throw new NO_IMPLEMENT(WHY);
}
/**
* Get the hashcode this object reference. The same hashcode still
* does not means that the references are the same. From the other
* side, two different references may still refer to the same CORBA
* object. The returned value must not change during the object
* lifetime.
*
* @param target the CORBA object, to that this operation must be applied.
* @param maximum the maximal value to return.
*
* @return the hashcode.
*/
public abstract int hash(org.omg.CORBA.Object target, int maximum);
/**
* Check if this object can be referenced by the given repository id.
*
* @param target the CORBA object, to that this operation must be applied.
* @param repositoryIdentifer the repository id.
*
* @return true if the passed parameter is a repository id of this
* CORBA object.
*/
public abstract boolean is_a(org.omg.CORBA.Object target,
String repositoryIdentifer
);
/**
* Return true if the other object references are equivalent, so far as
* it is possible to determine this easily.
*
* @param target the CORBA object, to that this operation must be applied.
* @param other the other object reference.
*
* @return true if both references refer the same object, false
* if they probably can refer different objects.
*
*/
public abstract boolean is_equivalent(org.omg.CORBA.Object target,
org.omg.CORBA.Object other
);
/**
* Returns true if the object is local.
*
* @param self the object to check.
*
* @return false, always (following 1.4 specs). Override to get
* functionality.
*/
public boolean is_local(org.omg.CORBA.Object self)
{
return false;
}
/**
* Determines if the server object for this reference has already
* been destroyed.
*
* @param target the CORBA object, to that this operation must be applied.
*
* @return true if the object has been destroyed, false otherwise.
*/
public abstract boolean non_existent(org.omg.CORBA.Object target);
/**
* Compares two objects for equality. The default implementations
* delegated call to {@link java.lang.Object#equals(java.lang.Object)}.
*
* @param self this CORBA object.
* @param other the other CORBA object.
*
* @return true if the objects are equal.
*/
public boolean equals(org.omg.CORBA.Object self, java.lang.Object other)
{
return self==other;
}
/**
* Return the hashcode for this CORBA object. The default implementation
* delegates call to {@link #hash(org.omg.CORBA.Object, int)}, passing Integer.MAX_VALUE as an
* argument.
*
* @param target the object, for that the hash code must be computed.
*
* @return the hashcode.
*/
public int hashCode(org.omg.CORBA.Object target)
{
return hash(target, Integer.MAX_VALUE);
}
/**
* Invoke the operation.
*
* @param target the invocation target.
* @param output the stream, containing the written arguments.
*
* @return the stream, from where the input parameters could be read.
*
* @throws ApplicationException if the application throws an exception,
* defined as a part of its remote method definition.
*
* @throws RemarshalException if reading(remarshalling) fails.
*
* @throws NO_IMPLEMENT, always (following the 1.4 specification).
*/
public InputStream invoke(org.omg.CORBA.Object target,
org.omg.CORBA.portable.OutputStream output
)
throws ApplicationException, RemarshalException
{
throw new NO_IMPLEMENT(WHY);
}
/**
* Provides the reference to ORB.
*
* @param target the object reference.
*
* @return the associated ORB.
*
* @throws NO_IMPLEMENT, always (following the 1.4 specification).
*/
public ORB orb(org.omg.CORBA.Object target)
{
throw new NO_IMPLEMENT(WHY);
}
/**
* Free resoureces, occupied by this reference. The object implementation
* is not notified, and the other references to the same object are not
* affected.
*
* @param target the CORBA object, to that this operation must be applied.
*/
public abstract void release(org.omg.CORBA.Object target);
/**
* Release the reply stream back to ORB after finishing reading the data
* from it.
*
* @param target the CORBA object, to that this operation must be applied.
* @param input the stream, normally returned by {@link #invoke} or
* {@link ApplicationException#getInputStream()}, can be null.
*
* The default method returns without action.
*/
public void releaseReply(org.omg.CORBA.Object target,
org.omg.CORBA.portable.InputStream input
)
{
}
/**
* Create a request to invoke the method of this CORBA object.
*
* @param target the CORBA object, to that this operation must be applied.
* @param operation the name of the method to invoke.
*
* @return the request.
*/
public abstract Request request(org.omg.CORBA.Object target, String operation);
/**
* Create a request to invoke the method of this CORBA object.
*
* @param target the CORBA object, to that this operation must be applied.
* @param operation the name of the method to invoke.
* @param response_expected specifies if this is one way message or the
* response to the message is expected.
*
* @return the stream where the method arguments should be written.
*/
public org.omg.CORBA.portable.OutputStream request(org.omg.CORBA.Object target,
String operation,
boolean response_expected
)
{
throw new NO_IMPLEMENT(WHY);
}
/**
* This method is always called after invoking the operation on the
* local servant.
*
* The default method returns without action.
*
* @param self the object.
* @param servant the servant.
*/
public void servant_postinvoke(org.omg.CORBA.Object self,
ServantObject servant
)
{
}
/**
* Returns a servant that should be used for this request.
* The servant can also be casted to the expected type, calling the
* required method directly.
*
* @param self the object
* @param operation the operation
* @param expectedType the expected type of the servant.
*
* This implementation always returns null; override for different
* behavior.
*
* @return the servant or null if the servant is not an expected type
* of the method is not supported, for example, due security reasons.
*/
public ServantObject servant_preinvoke(org.omg.CORBA.Object self,
String operation, Class expectedType
)
{
return null;
}
/**
* Returns a new object with the new policies either replacing or
* extending the current policies, depending on the second parameter.
*
* @param target the CORBA object, to that this operation must be applied.
* @param policies the policy additions or replacements.
* @param how either {@link SetOverrideType#SET_OVERRIDE} to override the
* current policies of {@link SetOverrideType#ADD_OVERRIDE} to replace
* them.
*
* @throws NO_IMPLEMENT, always (following the 1.4 specification).
*
* @return the new reference with the changed policies.
*/
public org.omg.CORBA.Object set_policy_override(org.omg.CORBA.Object target,
Policy[] policies,
SetOverrideType how
)
{
throw new NO_IMPLEMENT(WHY);
}
/**
* Return a string representation of the passed object.
*
* @param self the CORBA object, to that the string representation must be
* returned. By default, the call is delegated to
* {@link java.lang.Object#toString()}.
*
* @return the string representation.
*/
public String toString(org.omg.CORBA.Object self)
{
if (self instanceof ObjectImpl)
{
ObjectImpl x = (ObjectImpl) self;
CPStringBuilder b = new CPStringBuilder(x.getClass().getName());
b.append(": [");
for (int i = 0; i < x._ids().length; i++)
{
b.append(x._ids() [ i ]);
b.append(" ");
}
b.append("]");
return b.toString();
}
else
return self.getClass().getName();
}
}
| taciano-perez/JamVM-PH | src/classpath/org/omg/CORBA/portable/Delegate.java | Java | gpl-2.0 | 15,054 |
/*
* Copyright (C) 2005-2012 Team XBMC
* http://www.xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "MusicInfoTagLoaderMidi.h"
#include "utils/URIUtils.h"
#include "MusicInfoTag.h"
using namespace XFILE;
using namespace MUSIC_INFO;
CMusicInfoTagLoaderMidi::CMusicInfoTagLoaderMidi()
: IMusicInfoTagLoader()
{
}
CMusicInfoTagLoaderMidi::~CMusicInfoTagLoaderMidi()
{
}
// There is no reliable tag information in MIDI files. There is a 'title' field (@T), but it looks
// like everyone puts there song title, artist name, the name of the person who created the lyrics and
// greetings to their friends and family. Therefore we return the song title as file name, and the
// song artist as parent directory.
// A good intention of creating a pattern-based artist/song recognition engine failed greatly. Simple formats
// like %A-%T fail greatly with artists like A-HA and songs like "Ob-la-Di ob-la-Da.mid". So if anyone has
// a good idea which would include cases from above, I'd be happy to hear about it.
bool CMusicInfoTagLoaderMidi::Load(const CStdString & strFileName, CMusicInfoTag & tag, EmbeddedArt *art)
{
tag.SetURL(strFileName);
CStdString path, title;
URIUtils::Split( strFileName, path, title);
URIUtils::RemoveExtension( title );
tag.SetTitle( title );
URIUtils::RemoveSlashAtEnd(path );
if ( !path.IsEmpty() )
{
CStdString artist = URIUtils::GetFileName( path );
if ( !artist.IsEmpty() )
tag.SetArtist( artist );
}
tag.SetLoaded(true);
return true;
}
| koying/xbmc-pivos | xbmc/music/tags/MusicInfoTagLoaderMidi.cpp | C++ | gpl-2.0 | 2,164 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* 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@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Varien
* @package Varien_Image
* @copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Image handler library
*
* @category Varien
* @package Varien_Image
* @author Magento Core Team <core@magentocommerce.com>
*/
class Varien_Image
{
protected $_adapter;
protected $_fileName;
/**
* Constructor
*
* @param Varien_Image_Adapter $adapter. Default value is GD2
* @param string $fileName
* @return void
*/
function __construct($fileName=null, $adapter=Varien_Image_Adapter::ADAPTER_GD2)
{
$this->_getAdapter($adapter);
$this->_fileName = $fileName;
if( isset($fileName) ) {
$this->open();
}
}
/**
* Opens an image and creates image handle
*
* @access public
* @return void
*/
public function open()
{
$this->_getAdapter()->checkDependencies();
if( !file_exists($this->_fileName) ) {
throw new Exception("File '{$this->_fileName}' does not exists.");
}
$this->_getAdapter()->open($this->_fileName);
}
/**
* Display handled image in your browser
*
* @access public
* @return void
*/
public function display()
{
$this->_getAdapter()->display();
}
/**
* Save handled image into file
*
* @param string $destination. Default value is NULL
* @param string $newFileName. Default value is NULL
* @access public
* @return void
*/
public function save($destination=null, $newFileName=null)
{
$this->_getAdapter()->save($destination, $newFileName);
}
/**
* Rotate an image.
*
* @param int $angle
* @access public
* @return void
*/
public function rotate($angle)
{
$this->_getAdapter()->rotate($angle);
}
/**
* Crop an image.
*
* @param int $top. Default value is 0
* @param int $left. Default value is 0
* @param int $right. Default value is 0
* @param int $bottom. Default value is 0
* @access public
* @return void
*/
public function crop($top=0, $left=0, $right=0, $bottom=0)
{
$this->_getAdapter()->crop($top, $left, $right, $bottom);
}
/**
* Resize an image
*
* @param int $width
* @param int $height
* @access public
* @return void
*/
public function resize($width, $height = null)
{
$this->_getAdapter()->resize($width, $height);
}
public function keepAspectRatio($value)
{
return $this->_getAdapter()->keepAspectRatio($value);
}
public function keepFrame($value)
{
return $this->_getAdapter()->keepFrame($value);
}
public function keepTransparency($value)
{
return $this->_getAdapter()->keepTransparency($value);
}
public function constrainOnly($value)
{
return $this->_getAdapter()->constrainOnly($value);
}
public function backgroundColor($value)
{
return $this->_getAdapter()->backgroundColor($value);
}
/**
* Get/set quality, values in percentage from 0 to 100
*
* @param int $value
* @return int
*/
public function quality($value)
{
return $this->_getAdapter()->quality($value);
}
/**
* Adds watermark to our image.
*
* @param string $watermarkImage. Absolute path to watermark image.
* @param int $positionX. Watermark X position.
* @param int $positionY. Watermark Y position.
* @param int $watermarkImageOpacity. Watermark image opacity.
* @param bool $repeat. Enable or disable watermark brick.
* @access public
* @return void
*/
public function watermark($watermarkImage, $positionX=0, $positionY=0, $watermarkImageOpacity=30, $repeat=false)
{
if( !file_exists($watermarkImage) ) {
throw new Exception("Required file '{$watermarkImage}' does not exists.");
}
$this->_getAdapter()->watermark($watermarkImage, $positionX, $positionY, $watermarkImageOpacity, $repeat);
}
/**
* Get mime type of handled image
*
* @access public
* @return string
*/
public function getMimeType()
{
return $this->_getAdapter()->getMimeType();
}
/**
* process
*
* @access public
* @return void
*/
public function process()
{
}
/**
* instruction
*
* @access public
* @return void
*/
public function instruction()
{
}
/**
* Set image background color
*
* @param int $color
* @access public
* @return void
*/
public function setImageBackgroundColor($color)
{
$this->_getAdapter()->imageBackgroundColor = intval($color);
}
/**
* Set watermark position
*
* @param string $position
* @return Varien_Image
*/
public function setWatermarkPosition($position)
{
$this->_getAdapter()->setWatermarkPosition($position);
return $this;
}
/**
* Set watermark image opacity
*
* @param int $imageOpacity
* @return Varien_Image
*/
public function setWatermarkImageOpacity($imageOpacity)
{
$this->_getAdapter()->setWatermarkImageOpacity($imageOpacity);
return $this;
}
/**
* Set watermark width
*
* @param int $width
* @return Varien_Image
*/
public function setWatermarkWidth($width)
{
$this->_getAdapter()->setWatermarkWidth($width);
return $this;
}
/**
* Set watermark heigth
*
* @param int $heigth
* @return Varien_Image
*/
public function setWatermarkHeigth($heigth)
{
$this->_getAdapter()->setWatermarkHeigth($heigth);
return $this;
}
/**
* Retrieve image adapter object
*
* @param string $adapter
* @return Varien_Image_Adapter_Abstract
*/
protected function _getAdapter($adapter=null)
{
if( !isset($this->_adapter) ) {
$this->_adapter = Varien_Image_Adapter::factory( $adapter );
}
return $this->_adapter;
}
/**
* Retrieve original image width
*
* @return int|null
*/
public function getOriginalWidth()
{
return $this->_getAdapter()->getOriginalWidth();
}
/**
* Retrieve original image height
*
* @return int|null
*/
public function getOriginalHeight()
{
return $this->_getAdapter()->getOriginalHeight();
}
}
| dvh11er/mage-cheatcode | magento/lib/Varien/Image.php | PHP | gpl-2.0 | 7,490 |
/*
* Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_UTILITIES_HISTOGRAM_HPP
#define SHARE_VM_UTILITIES_HISTOGRAM_HPP
#include "memory/allocation.hpp"
#include "runtime/os.hpp"
#include "utilities/growableArray.hpp"
#ifdef TARGET_OS_FAMILY_linux
# include "os_linux.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_solaris
# include "os_solaris.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_windows
# include "os_windows.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_bsd
# include "os_bsd.inline.hpp"
#endif
// This class provides a framework for collecting various statistics.
// The current implementation is oriented towards counting invocations
// of various types, but that can be easily changed.
//
// To use it, you need to declare a Histogram*, and a subtype of
// HistogramElement:
//
// HistogramElement* MyHistogram;
//
// class MyHistogramElement : public HistogramElement {
// public:
// MyHistogramElement(char* name);
// };
//
// MyHistogramElement::MyHistogramElement(char* elementName) {
// _name = elementName;
//
// if(MyHistogram == NULL)
// MyHistogram = new Histogram("My Call Counts",100);
//
// MyHistogram->add_element(this);
// }
//
// #define MyCountWrapper(arg) static MyHistogramElement* e = new MyHistogramElement(arg); e->increment_count()
//
// This gives you a simple way to count invocations of specfic functions:
//
// void a_function_that_is_being_counted() {
// MyCountWrapper("FunctionName");
// ...
// }
//
// To print the results, invoke print() on your Histogram*.
#ifdef ASSERT
class HistogramElement : public CHeapObj<mtInternal> {
protected:
jint _count;
const char* _name;
public:
HistogramElement();
virtual int count();
virtual const char* name();
virtual void increment_count();
void print_on(outputStream* st) const;
virtual int compare(HistogramElement* e1,HistogramElement* e2);
};
class Histogram : public CHeapObj<mtInternal> {
protected:
GrowableArray<HistogramElement*>* _elements;
GrowableArray<HistogramElement*>* elements() { return _elements; }
const char* _title;
const char* title() { return _title; }
static int sort_helper(HistogramElement** e1,HistogramElement** e2);
virtual void print_header(outputStream* st);
virtual void print_elements(outputStream* st);
public:
Histogram(const char* title,int estimatedSize);
virtual void add_element(HistogramElement* element);
void print_on(outputStream* st) const;
};
#endif
#endif // SHARE_VM_UTILITIES_HISTOGRAM_HPP
| BobZhao/HotSpotResearch | src/share/vm/utilities/histogram.hpp | C++ | gpl-2.0 | 3,519 |
/**
* Authentication controller.
*
* Here we just bind together the Docs.Auth and AuthForm component.
*/
Ext.define('Docs.controller.Auth', {
extend: 'Ext.app.Controller',
requires: [
'Docs.Auth',
'Docs.Comments'
],
refs: [
{
ref: "authHeaderForm",
selector: "authHeaderForm"
}
],
init: function() {
this.control({
'authHeaderForm, authForm': {
login: this.login,
logout: this.logout
}
});
// HACK:
// Because the initialization of comments involves adding an
// additional tab, we need to ensure that we do this addition
// after Tabs controller has been launched.
var tabs = this.getController("Tabs");
tabs.onLaunch = Ext.Function.createSequence(tabs.onLaunch, this.afterTabsLaunch, this);
},
afterTabsLaunch: function() {
if (Docs.Comments.isEnabled()) {
if (Docs.Auth.isLoggedIn()) {
this.setLoggedIn();
}
else {
this.setLoggedOut();
}
}
},
login: function(form, username, password, remember) {
Docs.Auth.login({
username: username,
password: password,
remember: remember,
success: this.setLoggedIn,
failure: function(reason) {
form.showMessage(reason);
},
scope: this
});
},
logout: function(form) {
Docs.Auth.logout(this.setLoggedOut, this);
},
setLoggedIn: function() {
Docs.Comments.loadSubscriptions(function() {
this.getAuthHeaderForm().showLoggedIn(Docs.Auth.getUser());
this.eachCmp("commentsListWithForm", function(list) {
list.showCommentingForm();
});
this.eachCmp("commentsList", function(list) {
list.refresh();
});
this.getController("Tabs").showCommentsTab();
}, this);
},
setLoggedOut: function() {
Docs.Comments.clearSubscriptions();
this.getAuthHeaderForm().showLoggedOut();
this.eachCmp("commentsListWithForm", function(list) {
list.showAuthForm();
});
this.eachCmp("commentsList", function(list) {
list.refresh();
});
this.getController("Tabs").hideCommentsTab();
},
eachCmp: function(selector, callback, scope) {
Ext.Array.forEach(Ext.ComponentQuery.query(selector), callback, scope);
}
});
| ckeditor/jsduck | template/app/controller/Auth.js | JavaScript | gpl-3.0 | 2,613 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* Session Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Sessions
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/sessions.html
*/
class CI_Session {
var $sess_encrypt_cookie = FALSE;
var $sess_use_database = FALSE;
var $sess_table_name = '';
var $sess_expiration = 7200;
var $sess_expire_on_close = FALSE;
var $sess_match_ip = FALSE;
var $sess_match_useragent = TRUE;
var $sess_cookie_name = 'ci_session';
var $cookie_prefix = '';
var $cookie_path = '';
var $cookie_domain = '';
var $cookie_secure = FALSE;
var $sess_time_to_update = 300;
var $encryption_key = '';
var $flashdata_key = 'flash';
var $time_reference = 'time';
var $gc_probability = 5;
var $userdata = array();
var $CI;
var $now;
/**
* Session Constructor
*
* The constructor runs the session routines automatically
* whenever the class is instantiated.
*/
public function __construct($params = array())
{
log_message('debug', "Session Class Initialized");
// Set the super object to a local variable for use throughout the class
$this->CI =& get_instance();
// Set all the session preferences, which can either be set
// manually via the $params array above or via the config file
foreach (array('sess_encrypt_cookie', 'sess_use_database', 'sess_table_name', 'sess_expiration', 'sess_expire_on_close', 'sess_match_ip', 'sess_match_useragent', 'sess_cookie_name', 'cookie_path', 'cookie_domain', 'cookie_secure', 'sess_time_to_update', 'time_reference', 'cookie_prefix', 'encryption_key') as $key)
{
$this->$key = (isset($params[$key])) ? $params[$key] : $this->CI->config->item($key);
}
if ($this->encryption_key == '')
{
show_error('In order to use the Session class you are required to set an encryption key in your config file.');
}
// Load the string helper so we can use the strip_slashes() function
$this->CI->load->helper('string');
// Do we need encryption? If so, load the encryption class
if ($this->sess_encrypt_cookie == TRUE)
{
$this->CI->load->library('encrypt');
}
// Are we using a database? If so, load it
if ($this->sess_use_database === TRUE AND $this->sess_table_name != '')
{
$this->CI->load->database();
}
// Set the "now" time. Can either be GMT or server time, based on the
// config prefs. We use this to set the "last activity" time
$this->now = $this->_get_time();
// Set the session length. If the session expiration is
// set to zero we'll set the expiration two years from now.
if ($this->sess_expiration == 0)
{
$this->sess_expiration = (60*60*24*365*2);
}
// Set the cookie name
$this->sess_cookie_name = $this->cookie_prefix.$this->sess_cookie_name;
// Run the Session routine. If a session doesn't exist we'll
// create a new one. If it does, we'll update it.
if ( ! $this->sess_read())
{
$this->sess_create();
}
else
{
$this->sess_update();
}
// Delete 'old' flashdata (from last request)
$this->_flashdata_sweep();
// Mark all new flashdata as old (data will be deleted before next request)
$this->_flashdata_mark();
// Delete expired sessions if necessary
$this->_sess_gc();
log_message('debug', "Session routines successfully run");
}
// --------------------------------------------------------------------
/**
* Fetch the current session data if it exists
*
* @access public
* @return bool
*/
function sess_read()
{
// Fetch the cookie
$session = $this->CI->input->cookie($this->sess_cookie_name);
// No cookie? Goodbye cruel world!...
if ($session === FALSE)
{
log_message('debug', 'A session cookie was not found.');
return FALSE;
}
// HMAC authentication
$len = strlen($session) - 40;
if ($len <= 0)
{
log_message('error', 'Session: The session cookie was not signed.');
return FALSE;
}
// Check cookie authentication
$hmac = substr($session, $len);
$session = substr($session, 0, $len);
// Time-attack-safe comparison
$hmac_check = hash_hmac('sha1', $session, $this->encryption_key);
$diff = 0;
for ($i = 0; $i < 40; $i++)
{
$xor = ord($hmac[$i]) ^ ord($hmac_check[$i]);
$diff |= $xor;
}
if ($diff !== 0)
{
log_message('error', 'Session: HMAC mismatch. The session cookie data did not match what was expected.');
$this->sess_destroy();
return FALSE;
}
// Decrypt the cookie data
if ($this->sess_encrypt_cookie == TRUE)
{
$session = $this->CI->encrypt->decode($session);
}
// Unserialize the session array
$session = $this->_unserialize($session);
// Is the session data we unserialized an array with the correct format?
if ( ! is_array($session) OR ! isset($session['session_id']) OR ! isset($session['ip_address']) OR ! isset($session['user_agent']) OR ! isset($session['last_activity']))
{
$this->sess_destroy();
return FALSE;
}
// Is the session current?
if (($session['last_activity'] + $this->sess_expiration) < $this->now)
{
$this->sess_destroy();
return FALSE;
}
// Does the IP Match?
if ($this->sess_match_ip == TRUE AND $session['ip_address'] != $this->CI->input->ip_address())
{
$this->sess_destroy();
return FALSE;
}
// Does the User Agent Match?
if ($this->sess_match_useragent == TRUE AND trim($session['user_agent']) != trim(substr($this->CI->input->user_agent(), 0, 120)))
{
$this->sess_destroy();
return FALSE;
}
// Is there a corresponding session in the DB?
if ($this->sess_use_database === TRUE)
{
$this->CI->db->where('session_id', $session['session_id']);
if ($this->sess_match_ip == TRUE)
{
$this->CI->db->where('ip_address', $session['ip_address']);
}
if ($this->sess_match_useragent == TRUE)
{
$this->CI->db->where('user_agent', $session['user_agent']);
}
$query = $this->CI->db->get($this->sess_table_name);
// No result? Kill it!
if ($query->num_rows() == 0)
{
$this->sess_destroy();
return FALSE;
}
// Is there custom data? If so, add it to the main session array
$row = $query->row();
if (isset($row->user_data) AND $row->user_data != '')
{
$custom_data = $this->_unserialize($row->user_data);
if (is_array($custom_data))
{
foreach ($custom_data as $key => $val)
{
$session[$key] = $val;
}
}
}
}
// Session is valid!
$this->userdata = $session;
unset($session);
return TRUE;
}
// --------------------------------------------------------------------
/**
* Write the session data
*
* @access public
* @return void
*/
function sess_write()
{
// Are we saving custom data to the DB? If not, all we do is update the cookie
if ($this->sess_use_database === FALSE)
{
$this->_set_cookie();
return;
}
// set the custom userdata, the session data we will set in a second
$custom_userdata = $this->userdata;
$cookie_userdata = array();
// Before continuing, we need to determine if there is any custom data to deal with.
// Let's determine this by removing the default indexes to see if there's anything left in the array
// and set the session data while we're at it
foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
{
unset($custom_userdata[$val]);
$cookie_userdata[$val] = $this->userdata[$val];
}
// Did we find any custom data? If not, we turn the empty array into a string
// since there's no reason to serialize and store an empty array in the DB
if (count($custom_userdata) === 0)
{
$custom_userdata = '';
}
else
{
// Serialize the custom data array so we can store it
$custom_userdata = $this->_serialize($custom_userdata);
}
// Run the update query
$this->CI->db->where('session_id', $this->userdata['session_id']);
$this->CI->db->update($this->sess_table_name, array('last_activity' => $this->userdata['last_activity'], 'user_data' => $custom_userdata));
// Write the cookie. Notice that we manually pass the cookie data array to the
// _set_cookie() function. Normally that function will store $this->userdata, but
// in this case that array contains custom data, which we do not want in the cookie.
$this->_set_cookie($cookie_userdata);
}
// --------------------------------------------------------------------
/**
* Create a new session
*
* @access public
* @return void
*/
function sess_create()
{
$sessid = '';
while (strlen($sessid) < 32)
{
$sessid .= mt_rand(0, mt_getrandmax());
}
// To make the session ID even more secure we'll combine it with the user's IP
$sessid .= $this->CI->input->ip_address();
$this->userdata = array(
'session_id' => md5(uniqid($sessid, TRUE)),
'ip_address' => $this->CI->input->ip_address(),
'user_agent' => substr($this->CI->input->user_agent(), 0, 120),
'last_activity' => $this->now,
'user_data' => ''
);
// Save the data to the DB if needed
if ($this->sess_use_database === TRUE)
{
$this->CI->db->query($this->CI->db->insert_string($this->sess_table_name, $this->userdata));
}
// Write the cookie
$this->_set_cookie();
}
// --------------------------------------------------------------------
/**
* Update an existing session
*
* @access public
* @return void
*/
function sess_update()
{
// We only update the session every five minutes by default
if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now)
{
return;
}
// Save the old session id so we know which record to
// update in the database if we need it
$old_sessid = $this->userdata['session_id'];
$new_sessid = '';
while (strlen($new_sessid) < 32)
{
$new_sessid .= mt_rand(0, mt_getrandmax());
}
// To make the session ID even more secure we'll combine it with the user's IP
$new_sessid .= $this->CI->input->ip_address();
// Turn it into a hash
$new_sessid = md5(uniqid($new_sessid, TRUE));
// Update the session data in the session data array
$this->userdata['session_id'] = $new_sessid;
$this->userdata['last_activity'] = $this->now;
// _set_cookie() will handle this for us if we aren't using database sessions
// by pushing all userdata to the cookie.
$cookie_data = NULL;
// Update the session ID and last_activity field in the DB if needed
if ($this->sess_use_database === TRUE)
{
// set cookie explicitly to only have our session data
$cookie_data = array();
foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
{
$cookie_data[$val] = $this->userdata[$val];
}
$this->CI->db->query($this->CI->db->update_string($this->sess_table_name, array('last_activity' => $this->now, 'session_id' => $new_sessid), array('session_id' => $old_sessid)));
}
// Write the cookie
$this->_set_cookie($cookie_data);
}
// --------------------------------------------------------------------
/**
* Destroy the current session
*
* @access public
* @return void
*/
function sess_destroy()
{
// Kill the session DB row
if ($this->sess_use_database === TRUE && isset($this->userdata['session_id']))
{
$this->CI->db->where('session_id', $this->userdata['session_id']);
$this->CI->db->delete($this->sess_table_name);
}
// Kill the cookie
setcookie(
$this->sess_cookie_name,
addslashes(serialize(array())),
($this->now - 31500000),
$this->cookie_path,
$this->cookie_domain,
0
);
// Kill session data
$this->userdata = array();
}
// --------------------------------------------------------------------
/**
* Fetch a specific item from the session array
*
* @access public
* @param string
* @return string
*/
function userdata($item)
{
return ( ! isset($this->userdata[$item])) ? FALSE : $this->userdata[$item];
}
// --------------------------------------------------------------------
/**
* Fetch all session data
*
* @access public
* @return array
*/
function all_userdata()
{
return $this->userdata;
}
// --------------------------------------------------------------------
/**
* Add or change data in the "userdata" array
*
* @access public
* @param mixed
* @param string
* @return void
*/
function set_userdata($newdata = array(), $newval = '')
{
if (is_string($newdata))
{
$newdata = array($newdata => $newval);
}
if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
$this->userdata[$key] = $val;
}
}
$this->sess_write();
}
// --------------------------------------------------------------------
/**
* Delete a session variable from the "userdata" array
*
* @access array
* @return void
*/
function unset_userdata($newdata = array())
{
if (is_string($newdata))
{
$newdata = array($newdata => '');
}
if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
unset($this->userdata[$key]);
}
}
$this->sess_write();
}
// ------------------------------------------------------------------------
/**
* Add or change flashdata, only available
* until the next request
*
* @access public
* @param mixed
* @param string
* @return void
*/
function set_flashdata($newdata = array(), $newval = '')
{
if (is_string($newdata))
{
$newdata = array($newdata => $newval);
}
if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
$flashdata_key = $this->flashdata_key.':new:'.$key;
$this->set_userdata($flashdata_key, $val);
}
}
}
// ------------------------------------------------------------------------
/**
* Keeps existing flashdata available to next request.
*
* @access public
* @param string
* @return void
*/
function keep_flashdata($key)
{
// 'old' flashdata gets removed. Here we mark all
// flashdata as 'new' to preserve it from _flashdata_sweep()
// Note the function will return FALSE if the $key
// provided cannot be found
$old_flashdata_key = $this->flashdata_key.':old:'.$key;
$value = $this->userdata($old_flashdata_key);
$new_flashdata_key = $this->flashdata_key.':new:'.$key;
$this->set_userdata($new_flashdata_key, $value);
}
// ------------------------------------------------------------------------
/**
* Fetch a specific flashdata item from the session array
*
* @access public
* @param string
* @return string
*/
function flashdata($key)
{
$flashdata_key = $this->flashdata_key.':old:'.$key;
return $this->userdata($flashdata_key);
}
// ------------------------------------------------------------------------
/**
* Identifies flashdata as 'old' for removal
* when _flashdata_sweep() runs.
*
* @access private
* @return void
*/
function _flashdata_mark()
{
$userdata = $this->all_userdata();
foreach ($userdata as $name => $value)
{
$parts = explode(':new:', $name);
if (is_array($parts) && count($parts) === 2)
{
$new_name = $this->flashdata_key.':old:'.$parts[1];
$this->set_userdata($new_name, $value);
$this->unset_userdata($name);
}
}
}
// ------------------------------------------------------------------------
/**
* Removes all flashdata marked as 'old'
*
* @access private
* @return void
*/
function _flashdata_sweep()
{
$userdata = $this->all_userdata();
foreach ($userdata as $key => $value)
{
if (strpos($key, ':old:'))
{
$this->unset_userdata($key);
}
}
}
// --------------------------------------------------------------------
/**
* Get the "now" time
*
* @access private
* @return string
*/
function _get_time()
{
if (strtolower($this->time_reference) == 'gmt')
{
$now = time();
$time = mktime(gmdate("H", $now), gmdate("i", $now), gmdate("s", $now), gmdate("m", $now), gmdate("d", $now), gmdate("Y", $now));
}
else
{
$time = time();
}
return $time;
}
// --------------------------------------------------------------------
/**
* Write the session cookie
*
* @access public
* @return void
*/
function _set_cookie($cookie_data = NULL)
{
if (is_null($cookie_data))
{
$cookie_data = $this->userdata;
}
// Serialize the userdata for the cookie
$cookie_data = $this->_serialize($cookie_data);
if ($this->sess_encrypt_cookie == TRUE)
{
$cookie_data = $this->CI->encrypt->encode($cookie_data);
}
else
{
// if encryption is not used, we provide an md5 hash to prevent userside tampering
$cookie_data .= hash_hmac('sha1', $cookie_data, $this->encryption_key);
}
$expire = ($this->sess_expire_on_close === TRUE) ? 0 : $this->sess_expiration + time();
// Set the cookie
setcookie(
$this->sess_cookie_name,
$cookie_data,
$expire,
$this->cookie_path,
$this->cookie_domain,
$this->cookie_secure
);
}
// --------------------------------------------------------------------
/**
* Serialize an array
*
* This function first converts any slashes found in the array to a temporary
* marker, so when it gets unserialized the slashes will be preserved
*
* @access private
* @param array
* @return string
*/
function _serialize($data)
{
if (is_array($data))
{
foreach ($data as $key => $val)
{
if (is_string($val))
{
$data[$key] = str_replace('\\', '{{slash}}', $val);
}
}
}
else
{
if (is_string($data))
{
$data = str_replace('\\', '{{slash}}', $data);
}
}
return serialize($data);
}
// --------------------------------------------------------------------
/**
* Unserialize
*
* This function unserializes a data string, then converts any
* temporary slash markers back to actual slashes
*
* @access private
* @param array
* @return string
*/
function _unserialize($data)
{
$data = @unserialize(strip_slashes($data));
if (is_array($data))
{
foreach ($data as $key => $val)
{
if (is_string($val))
{
$data[$key] = str_replace('{{slash}}', '\\', $val);
}
}
return $data;
}
return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data;
}
// --------------------------------------------------------------------
/**
* Garbage collection
*
* This deletes expired session rows from database
* if the probability percentage is met
*
* @access public
* @return void
*/
function _sess_gc()
{
if ($this->sess_use_database != TRUE)
{
return;
}
srand(time());
if ((rand() % 100) < $this->gc_probability)
{
$expire = $this->now - $this->sess_expiration;
$this->CI->db->where("last_activity < {$expire}");
$this->CI->db->delete($this->sess_table_name);
log_message('debug', 'Session garbage collection performed.');
}
}
}
// END Session Class
/* End of file Session.php */
/* Location: ./system/libraries/Session.php */
| Karplyak/avtomag.url.ph | system/libraries/Session.php | PHP | gpl-3.0 | 19,399 |
// Copyright (c) 2015 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package model
import (
"strings"
"testing"
)
func TestInitialLoadJson(t *testing.T) {
u := &User{Id: NewId()}
o := InitialLoad{User: u}
json := o.ToJson()
ro := InitialLoadFromJson(strings.NewReader(json))
if o.User.Id != ro.User.Id {
t.Fatal("Ids do not match")
}
}
| rahulltkr/platform | model/initial_load_test.go | GO | agpl-3.0 | 385 |
/***************************************************************************
* Copyright (c) 2009 Jürgen Riegel <juergen.riegel@web.de> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QMessageBox>
#endif
#include "TaskDialog.h"
using namespace Gui::TaskView;
//**************************************************************************
//**************************************************************************
// TaskDialog
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
TaskDialog::TaskDialog()
: QObject(nullptr), pos(North)
, escapeButton(true)
, autoCloseTransaction(false)
{
}
TaskDialog::~TaskDialog()
{
for (std::vector<QWidget*>::iterator it=Content.begin();it!=Content.end();++it) {
delete *it;
*it = 0;
}
}
//==== Slots ===============================================================
const std::vector<QWidget*> &TaskDialog::getDialogContent(void) const
{
return Content;
}
bool TaskDialog::canClose() const
{
QMessageBox msgBox;
msgBox.setText(tr("A dialog is already open in the task panel"));
msgBox.setInformativeText(QObject::tr("Do you want to close this dialog?"));
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
int ret = msgBox.exec();
if (ret == QMessageBox::Yes)
return true;
else
return false;
}
//==== calls from the TaskView ===============================================================
void TaskDialog::open()
{
}
void TaskDialog::closed()
{
}
void TaskDialog::autoClosedOnTransactionChange()
{
}
void TaskDialog::clicked(int)
{
}
bool TaskDialog::accept()
{
return true;
}
bool TaskDialog::reject()
{
return true;
}
void TaskDialog::helpRequested()
{
}
#include "moc_TaskDialog.cpp"
| sanguinariojoe/FreeCAD | src/Gui/TaskView/TaskDialog.cpp | C++ | lgpl-2.1 | 3,435 |
// Copyright 2012 Cloudera 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.
#include "util/metrics.h"
#include <sstream>
#include <boost/algorithm/string/join.hpp>
#include <boost/bind.hpp>
#include <boost/mem_fn.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <gutil/strings/substitute.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/prettywriter.h>
#include "common/logging.h"
#include "util/impalad-metrics.h"
#include "common/names.h"
using namespace impala;
using namespace rapidjson;
using namespace strings;
namespace impala {
template <>
void ToJsonValue<string>(const string& value, const TUnit::type unit,
Document* document, Value* out_val) {
Value val(value.c_str(), document->GetAllocator());
*out_val = val;
}
}
void Metric::AddStandardFields(Document* document, Value* val) {
Value name(key_.c_str(), document->GetAllocator());
val->AddMember("name", name, document->GetAllocator());
Value desc(description_.c_str(), document->GetAllocator());
val->AddMember("description", desc, document->GetAllocator());
Value metric_value(ToHumanReadable().c_str(), document->GetAllocator());
val->AddMember("human_readable", metric_value, document->GetAllocator());
}
MetricDefs* MetricDefs::GetInstance() {
// Note that this is not thread-safe in C++03 (but will be in C++11 see
// http://stackoverflow.com/a/19907903/132034). We don't bother with the double-check
// locking pattern because it introduces complexity whereas a race is very unlikely
// and it doesn't matter if we construct two instances since MetricDefsConstants is
// just a constant map.
static MetricDefs instance;
return &instance;
}
TMetricDef MetricDefs::Get(const string& key, const string& arg) {
MetricDefs* inst = GetInstance();
map<string, TMetricDef>::iterator it = inst->metric_defs_.TMetricDefs.find(key);
if (it == inst->metric_defs_.TMetricDefs.end()) {
DCHECK(false) << "Could not find metric definition for key=" << key << " arg=" << arg;
return TMetricDef();
}
TMetricDef md = it->second;
md.__set_key(Substitute(md.key, arg));
md.__set_description(Substitute(md.description, arg));
return md;
}
MetricGroup::MetricGroup(const string& name)
: obj_pool_(new ObjectPool()), name_(name) { }
Status MetricGroup::Init(Webserver* webserver) {
if (webserver != NULL) {
Webserver::UrlCallback default_callback =
bind<void>(mem_fn(&MetricGroup::CMCompatibleCallback), this, _1, _2);
webserver->RegisterUrlCallback("/jsonmetrics", "legacy-metrics.tmpl",
default_callback, false);
Webserver::UrlCallback json_callback =
bind<void>(mem_fn(&MetricGroup::TemplateCallback), this, _1, _2);
webserver->RegisterUrlCallback("/metrics", "metrics.tmpl", json_callback);
}
return Status::OK();
}
void MetricGroup::CMCompatibleCallback(const Webserver::ArgumentMap& args,
Document* document) {
// If the request has a 'metric' argument, search all top-level metrics for that metric
// only. Otherwise, return document with list of all metrics at the top level.
Webserver::ArgumentMap::const_iterator metric_name = args.find("metric");
lock_guard<SpinLock> l(lock_);
if (metric_name != args.end()) {
MetricMap::const_iterator metric = metric_map_.find(metric_name->second);
if (metric != metric_map_.end()) {
metric->second->ToLegacyJson(document);
}
return;
}
stack<MetricGroup*> groups;
groups.push(this);
do {
// Depth-first traversal of children to flatten all metrics, which is what was
// expected by CM before we introduced metric groups.
MetricGroup* group = groups.top();
groups.pop();
BOOST_FOREACH(const ChildGroupMap::value_type& child, group->children_) {
groups.push(child.second);
}
BOOST_FOREACH(const MetricMap::value_type& m, group->metric_map_) {
m.second->ToLegacyJson(document);
}
} while (!groups.empty());
}
void MetricGroup::TemplateCallback(const Webserver::ArgumentMap& args,
Document* document) {
Webserver::ArgumentMap::const_iterator metric_group = args.find("metric_group");
lock_guard<SpinLock> l(lock_);
// If no particular metric group is requested, render this metric group (and all its
// children).
if (metric_group == args.end()) {
Value container;
ToJson(true, document, &container);
document->AddMember("metric_group", container, document->GetAllocator());
return;
}
// Search all metric groups to find the one we're looking for. In the future, we'll
// change this to support path-based resolution of metric groups.
MetricGroup* found_group = NULL;
stack<MetricGroup*> groups;
groups.push(this);
while (!groups.empty() && found_group == NULL) {
// Depth-first traversal of children to flatten all metrics, which is what was
// expected by CM before we introduced metric groups.
MetricGroup* group = groups.top();
groups.pop();
BOOST_FOREACH(const ChildGroupMap::value_type& child, group->children_) {
if (child.first == metric_group->second) {
found_group = child.second;
break;
}
groups.push(child.second);
}
}
if (found_group != NULL) {
Value container;
found_group->ToJson(false, document, &container);
document->AddMember("metric_group", container, document->GetAllocator());
} else {
Value error(Substitute("Metric group $0 not found", metric_group->second).c_str(),
document->GetAllocator());
document->AddMember("error", error, document->GetAllocator());
}
}
void MetricGroup::ToJson(bool include_children, Document* document, Value* out_val) {
Value metric_list(kArrayType);
BOOST_FOREACH(const MetricMap::value_type& m, metric_map_) {
Value metric_value;
m.second->ToJson(document, &metric_value);
metric_list.PushBack(metric_value, document->GetAllocator());
}
Value container(kObjectType);
container.AddMember("metrics", metric_list, document->GetAllocator());
container.AddMember("name", name_.c_str(), document->GetAllocator());
if (include_children) {
Value child_groups(kArrayType);
BOOST_FOREACH(const ChildGroupMap::value_type& child, children_) {
Value child_value;
child.second->ToJson(true, document, &child_value);
child_groups.PushBack(child_value, document->GetAllocator());
}
container.AddMember("child_groups", child_groups, document->GetAllocator());
}
*out_val = container;
}
MetricGroup* MetricGroup::GetChildGroup(const string& name) {
lock_guard<SpinLock> l(lock_);
ChildGroupMap::iterator it = children_.find(name);
if (it != children_.end()) return it->second;
MetricGroup* group = obj_pool_->Add(new MetricGroup(name));
children_[name] = group;
return group;
}
string MetricGroup::DebugString() {
Webserver::ArgumentMap empty_map;
Document document;
document.SetObject();
TemplateCallback(empty_map, &document);
StringBuffer strbuf;
PrettyWriter<StringBuffer> writer(strbuf);
document.Accept(writer);
return strbuf.GetString();
}
| brightchen/Impala | be/src/util/metrics.cc | C++ | apache-2.0 | 7,566 |
/*
* Copyright 2000-2014 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.openapi.application;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
/**
* Represents the stack of active modal dialogs.
*/
public abstract class ModalityState {
@NotNull public static final ModalityState NON_MODAL;
static {
try {
@SuppressWarnings("unchecked")
final Class<? extends ModalityState> ex = (Class<? extends ModalityState>)Class.forName("com.intellij.openapi.application.impl.ModalityStateEx");
NON_MODAL = ex.newInstance();
}
catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
}
catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
catch (InstantiationException e) {
throw new IllegalStateException(e);
}
}
@NotNull
public static ModalityState current() {
return ApplicationManager.getApplication().getCurrentModalityState();
}
@NotNull
public static ModalityState any() {
return ApplicationManager.getApplication().getAnyModalityState();
}
@NotNull
public static ModalityState stateForComponent(@NotNull Component component){
return ApplicationManager.getApplication().getModalityStateForComponent(component);
}
@NotNull
public static ModalityState defaultModalityState() {
return ApplicationManager.getApplication().getDefaultModalityState();
}
public abstract boolean dominates(@NotNull ModalityState anotherState);
@Override
public abstract String toString();
}
| diorcety/intellij-community | platform/core-api/src/com/intellij/openapi/application/ModalityState.java | Java | apache-2.0 | 2,089 |
/*
* 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.spark.launcher;
import java.io.Closeable;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.apache.spark.launcher.LauncherProtocol.*;
/**
* A server that listens locally for connections from client launched by the library. Each client
* has a secret that it needs to send to the server to identify itself and establish the session.
*
* I/O is currently blocking (one thread per client). Clients have a limited time to connect back
* to the server, otherwise the server will ignore the connection.
*
* === Architecture Overview ===
*
* The launcher server is used when Spark apps are launched as separate processes than the calling
* app. It looks more or less like the following:
*
* ----------------------- -----------------------
* | User App | spark-submit | Spark App |
* | | -------------------> | |
* | ------------| |------------- |
* | | | hello | | |
* | | L. Server |<----------------------| L. Backend | |
* | | | | | |
* | ------------- -----------------------
* | | | ^
* | v | |
* | -------------| |
* | | | <per-app channel> |
* | | App Handle |<------------------------------
* | | |
* -----------------------
*
* The server is started on demand and remains active while there are active or outstanding clients,
* to avoid opening too many ports when multiple clients are launched. Each client is given a unique
* secret, and have a limited amount of time to connect back
* ({@link SparkLauncher#CHILD_CONNECTION_TIMEOUT}), at which point the server will throw away
* that client's state. A client is only allowed to connect back to the server once.
*
* The launcher server listens on the localhost only, so it doesn't need access controls (aside from
* the per-app secret) nor encryption. It thus requires that the launched app has a local process
* that communicates with the server. In cluster mode, this means that the client that launches the
* application must remain alive for the duration of the application (or until the app handle is
* disconnected).
*/
class LauncherServer implements Closeable {
private static final Logger LOG = Logger.getLogger(LauncherServer.class.getName());
private static final String THREAD_NAME_FMT = "LauncherServer-%d";
private static final long DEFAULT_CONNECT_TIMEOUT = 10000L;
/** For creating secrets used for communication with child processes. */
private static final SecureRandom RND = new SecureRandom();
private static volatile LauncherServer serverInstance;
/**
* Creates a handle for an app to be launched. This method will start a server if one hasn't been
* started yet. The server is shared for multiple handles, and once all handles are disposed of,
* the server is shut down.
*/
static synchronized ChildProcAppHandle newAppHandle() throws IOException {
LauncherServer server = serverInstance != null ? serverInstance : new LauncherServer();
server.ref();
serverInstance = server;
String secret = server.createSecret();
while (server.pending.containsKey(secret)) {
secret = server.createSecret();
}
return server.newAppHandle(secret);
}
static LauncherServer getServerInstance() {
return serverInstance;
}
private final AtomicLong refCount;
private final AtomicLong threadIds;
private final ConcurrentMap<String, ChildProcAppHandle> pending;
private final List<ServerConnection> clients;
private final ServerSocket server;
private final Thread serverThread;
private final ThreadFactory factory;
private final Timer timeoutTimer;
private volatile boolean running;
private LauncherServer() throws IOException {
this.refCount = new AtomicLong(0);
ServerSocket server = new ServerSocket();
try {
server.setReuseAddress(true);
server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
this.clients = new ArrayList<>();
this.threadIds = new AtomicLong();
this.factory = new NamedThreadFactory(THREAD_NAME_FMT);
this.pending = new ConcurrentHashMap<>();
this.timeoutTimer = new Timer("LauncherServer-TimeoutTimer", true);
this.server = server;
this.running = true;
this.serverThread = factory.newThread(new Runnable() {
@Override
public void run() {
acceptConnections();
}
});
serverThread.start();
} catch (IOException ioe) {
close();
throw ioe;
} catch (Exception e) {
close();
throw new IOException(e);
}
}
/**
* Creates a new app handle. The handle will wait for an incoming connection for a configurable
* amount of time, and if one doesn't arrive, it will transition to an error state.
*/
ChildProcAppHandle newAppHandle(String secret) {
ChildProcAppHandle handle = new ChildProcAppHandle(secret, this);
ChildProcAppHandle existing = pending.putIfAbsent(secret, handle);
CommandBuilderUtils.checkState(existing == null, "Multiple handles with the same secret.");
return handle;
}
@Override
public void close() throws IOException {
synchronized (this) {
if (running) {
running = false;
timeoutTimer.cancel();
server.close();
synchronized (clients) {
List<ServerConnection> copy = new ArrayList<>(clients);
clients.clear();
for (ServerConnection client : copy) {
client.close();
}
}
}
}
if (serverThread != null) {
try {
serverThread.join();
} catch (InterruptedException ie) {
// no-op
}
}
}
void ref() {
refCount.incrementAndGet();
}
void unref() {
synchronized(LauncherServer.class) {
if (refCount.decrementAndGet() == 0) {
try {
close();
} catch (IOException ioe) {
// no-op.
} finally {
serverInstance = null;
}
}
}
}
int getPort() {
return server.getLocalPort();
}
/**
* Removes the client handle from the pending list (in case it's still there), and unrefs
* the server.
*/
void unregister(ChildProcAppHandle handle) {
pending.remove(handle.getSecret());
unref();
}
private void acceptConnections() {
try {
while (running) {
final Socket client = server.accept();
TimerTask timeout = new TimerTask() {
@Override
public void run() {
LOG.warning("Timed out waiting for hello message from client.");
try {
client.close();
} catch (IOException ioe) {
// no-op.
}
}
};
ServerConnection clientConnection = new ServerConnection(client, timeout);
Thread clientThread = factory.newThread(clientConnection);
synchronized (timeout) {
clientThread.start();
synchronized (clients) {
clients.add(clientConnection);
}
long timeoutMs = getConnectionTimeout();
// 0 is used for testing to avoid issues with clock resolution / thread scheduling,
// and force an immediate timeout.
if (timeoutMs > 0) {
timeoutTimer.schedule(timeout, getConnectionTimeout());
} else {
timeout.run();
}
}
}
} catch (IOException ioe) {
if (running) {
LOG.log(Level.SEVERE, "Error in accept loop.", ioe);
}
}
}
private long getConnectionTimeout() {
String value = SparkLauncher.launcherConfig.get(SparkLauncher.CHILD_CONNECTION_TIMEOUT);
return (value != null) ? Long.parseLong(value) : DEFAULT_CONNECT_TIMEOUT;
}
private String createSecret() {
byte[] secret = new byte[128];
RND.nextBytes(secret);
StringBuilder sb = new StringBuilder();
for (byte b : secret) {
int ival = b >= 0 ? b : Byte.MAX_VALUE - b;
if (ival < 0x10) {
sb.append("0");
}
sb.append(Integer.toHexString(ival));
}
return sb.toString();
}
private class ServerConnection extends LauncherConnection {
private TimerTask timeout;
private ChildProcAppHandle handle;
ServerConnection(Socket socket, TimerTask timeout) throws IOException {
super(socket);
this.timeout = timeout;
}
@Override
protected void handle(Message msg) throws IOException {
try {
if (msg instanceof Hello) {
timeout.cancel();
timeout = null;
Hello hello = (Hello) msg;
ChildProcAppHandle handle = pending.remove(hello.secret);
if (handle != null) {
handle.setConnection(this);
handle.setState(SparkAppHandle.State.CONNECTED);
this.handle = handle;
} else {
throw new IllegalArgumentException("Received Hello for unknown client.");
}
} else {
if (handle == null) {
throw new IllegalArgumentException("Expected hello, got: " +
msg != null ? msg.getClass().getName() : null);
}
if (msg instanceof SetAppId) {
SetAppId set = (SetAppId) msg;
handle.setAppId(set.appId);
} else if (msg instanceof SetState) {
handle.setState(((SetState)msg).state);
} else {
throw new IllegalArgumentException("Invalid message: " +
msg != null ? msg.getClass().getName() : null);
}
}
} catch (Exception e) {
LOG.log(Level.INFO, "Error handling message from client.", e);
if (timeout != null) {
timeout.cancel();
}
close();
} finally {
timeoutTimer.purge();
}
}
@Override
public void close() throws IOException {
synchronized (clients) {
clients.remove(this);
}
super.close();
if (handle != null) {
if (!handle.getState().isFinal()) {
LOG.log(Level.WARNING, "Lost connection to spark application.");
handle.setState(SparkAppHandle.State.LOST);
}
handle.disconnect();
}
}
}
}
| u2009cf/spark-radar | launcher/src/main/java/org/apache/spark/launcher/LauncherServer.java | Java | apache-2.0 | 11,989 |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('estraverse')) :
typeof define === 'function' && define.amd ? define(['estraverse'], factory) :
(global = global || self, global.esquery = factory(global.estraverse));
}(this, (function (estraverse) { 'use strict';
estraverse = estraverse && Object.prototype.hasOwnProperty.call(estraverse, 'default') ? estraverse['default'] : estraverse;
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _createForOfIteratorHelper(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function () {};
return {
s: F,
n: function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function (e) {
throw e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var normalCompletion = true,
didErr = false,
err;
return {
s: function () {
it = o[Symbol.iterator]();
},
n: function () {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function (e) {
didErr = true;
err = e;
},
f: function () {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var parser = createCommonjsModule(function (module) {
/*
* Generated by PEG.js 0.10.0.
*
* http://pegjs.org/
*/
(function (root, factory) {
if ( module.exports) {
module.exports = factory();
}
})(commonjsGlobal, function () {
function peg$subclass(child, parent) {
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
}
function peg$SyntaxError(message, expected, found, location) {
this.message = message;
this.expected = expected;
this.found = found;
this.location = location;
this.name = "SyntaxError";
if (typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(this, peg$SyntaxError);
}
}
peg$subclass(peg$SyntaxError, Error);
peg$SyntaxError.buildMessage = function (expected, found) {
var DESCRIBE_EXPECTATION_FNS = {
literal: function literal(expectation) {
return "\"" + literalEscape(expectation.text) + "\"";
},
"class": function _class(expectation) {
var escapedParts = "",
i;
for (i = 0; i < expectation.parts.length; i++) {
escapedParts += expectation.parts[i] instanceof Array ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) : classEscape(expectation.parts[i]);
}
return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]";
},
any: function any(expectation) {
return "any character";
},
end: function end(expectation) {
return "end of input";
},
other: function other(expectation) {
return expectation.description;
}
};
function hex(ch) {
return ch.charCodeAt(0).toString(16).toUpperCase();
}
function literalEscape(s) {
return s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) {
return '\\x0' + hex(ch);
}).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) {
return '\\x' + hex(ch);
});
}
function classEscape(s) {
return s.replace(/\\/g, '\\\\').replace(/\]/g, '\\]').replace(/\^/g, '\\^').replace(/-/g, '\\-').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) {
return '\\x0' + hex(ch);
}).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) {
return '\\x' + hex(ch);
});
}
function describeExpectation(expectation) {
return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation);
}
function describeExpected(expected) {
var descriptions = new Array(expected.length),
i,
j;
for (i = 0; i < expected.length; i++) {
descriptions[i] = describeExpectation(expected[i]);
}
descriptions.sort();
if (descriptions.length > 0) {
for (i = 1, j = 1; i < descriptions.length; i++) {
if (descriptions[i - 1] !== descriptions[i]) {
descriptions[j] = descriptions[i];
j++;
}
}
descriptions.length = j;
}
switch (descriptions.length) {
case 1:
return descriptions[0];
case 2:
return descriptions[0] + " or " + descriptions[1];
default:
return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1];
}
}
function describeFound(found) {
return found ? "\"" + literalEscape(found) + "\"" : "end of input";
}
return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found.";
};
function peg$parse(input, options) {
options = options !== void 0 ? options : {};
var peg$FAILED = {},
peg$startRuleFunctions = {
start: peg$parsestart
},
peg$startRuleFunction = peg$parsestart,
peg$c0 = function peg$c0(ss) {
return ss.length === 1 ? ss[0] : {
type: 'matches',
selectors: ss
};
},
peg$c1 = function peg$c1() {
return void 0;
},
peg$c2 = " ",
peg$c3 = peg$literalExpectation(" ", false),
peg$c4 = /^[^ [\],():#!=><~+.]/,
peg$c5 = peg$classExpectation([" ", "[", "]", ",", "(", ")", ":", "#", "!", "=", ">", "<", "~", "+", "."], true, false),
peg$c6 = function peg$c6(i) {
return i.join('');
},
peg$c7 = ">",
peg$c8 = peg$literalExpectation(">", false),
peg$c9 = function peg$c9() {
return 'child';
},
peg$c10 = "~",
peg$c11 = peg$literalExpectation("~", false),
peg$c12 = function peg$c12() {
return 'sibling';
},
peg$c13 = "+",
peg$c14 = peg$literalExpectation("+", false),
peg$c15 = function peg$c15() {
return 'adjacent';
},
peg$c16 = function peg$c16() {
return 'descendant';
},
peg$c17 = ",",
peg$c18 = peg$literalExpectation(",", false),
peg$c19 = function peg$c19(s, ss) {
return [s].concat(ss.map(function (s) {
return s[3];
}));
},
peg$c20 = function peg$c20(a, ops) {
return ops.reduce(function (memo, rhs) {
return {
type: rhs[0],
left: memo,
right: rhs[1]
};
}, a);
},
peg$c21 = "!",
peg$c22 = peg$literalExpectation("!", false),
peg$c23 = function peg$c23(subject, as) {
var b = as.length === 1 ? as[0] : {
type: 'compound',
selectors: as
};
if (subject) b.subject = true;
return b;
},
peg$c24 = "*",
peg$c25 = peg$literalExpectation("*", false),
peg$c26 = function peg$c26(a) {
return {
type: 'wildcard',
value: a
};
},
peg$c27 = "#",
peg$c28 = peg$literalExpectation("#", false),
peg$c29 = function peg$c29(i) {
return {
type: 'identifier',
value: i
};
},
peg$c30 = "[",
peg$c31 = peg$literalExpectation("[", false),
peg$c32 = "]",
peg$c33 = peg$literalExpectation("]", false),
peg$c34 = function peg$c34(v) {
return v;
},
peg$c35 = /^[><!]/,
peg$c36 = peg$classExpectation([">", "<", "!"], false, false),
peg$c37 = "=",
peg$c38 = peg$literalExpectation("=", false),
peg$c39 = function peg$c39(a) {
return (a || '') + '=';
},
peg$c40 = /^[><]/,
peg$c41 = peg$classExpectation([">", "<"], false, false),
peg$c42 = ".",
peg$c43 = peg$literalExpectation(".", false),
peg$c44 = function peg$c44(a, as) {
return [].concat.apply([a], as).join('');
},
peg$c45 = function peg$c45(name, op, value) {
return {
type: 'attribute',
name: name,
operator: op,
value: value
};
},
peg$c46 = function peg$c46(name) {
return {
type: 'attribute',
name: name
};
},
peg$c47 = "\"",
peg$c48 = peg$literalExpectation("\"", false),
peg$c49 = /^[^\\"]/,
peg$c50 = peg$classExpectation(["\\", "\""], true, false),
peg$c51 = "\\",
peg$c52 = peg$literalExpectation("\\", false),
peg$c53 = peg$anyExpectation(),
peg$c54 = function peg$c54(a, b) {
return a + b;
},
peg$c55 = function peg$c55(d) {
return {
type: 'literal',
value: strUnescape(d.join(''))
};
},
peg$c56 = "'",
peg$c57 = peg$literalExpectation("'", false),
peg$c58 = /^[^\\']/,
peg$c59 = peg$classExpectation(["\\", "'"], true, false),
peg$c60 = /^[0-9]/,
peg$c61 = peg$classExpectation([["0", "9"]], false, false),
peg$c62 = function peg$c62(a, b) {
// Can use `a.flat().join('')` once supported
var leadingDecimals = a ? [].concat.apply([], a).join('') : '';
return {
type: 'literal',
value: parseFloat(leadingDecimals + b.join(''))
};
},
peg$c63 = function peg$c63(i) {
return {
type: 'literal',
value: i
};
},
peg$c64 = "type(",
peg$c65 = peg$literalExpectation("type(", false),
peg$c66 = /^[^ )]/,
peg$c67 = peg$classExpectation([" ", ")"], true, false),
peg$c68 = ")",
peg$c69 = peg$literalExpectation(")", false),
peg$c70 = function peg$c70(t) {
return {
type: 'type',
value: t.join('')
};
},
peg$c71 = /^[imsu]/,
peg$c72 = peg$classExpectation(["i", "m", "s", "u"], false, false),
peg$c73 = "/",
peg$c74 = peg$literalExpectation("/", false),
peg$c75 = /^[^\/]/,
peg$c76 = peg$classExpectation(["/"], true, false),
peg$c77 = function peg$c77(d, flgs) {
return {
type: 'regexp',
value: new RegExp(d.join(''), flgs ? flgs.join('') : '')
};
},
peg$c78 = function peg$c78(i, is) {
return {
type: 'field',
name: is.reduce(function (memo, p) {
return memo + p[0] + p[1];
}, i)
};
},
peg$c79 = ":not(",
peg$c80 = peg$literalExpectation(":not(", false),
peg$c81 = function peg$c81(ss) {
return {
type: 'not',
selectors: ss
};
},
peg$c82 = ":matches(",
peg$c83 = peg$literalExpectation(":matches(", false),
peg$c84 = function peg$c84(ss) {
return {
type: 'matches',
selectors: ss
};
},
peg$c85 = ":has(",
peg$c86 = peg$literalExpectation(":has(", false),
peg$c87 = function peg$c87(ss) {
return {
type: 'has',
selectors: ss
};
},
peg$c88 = ":first-child",
peg$c89 = peg$literalExpectation(":first-child", false),
peg$c90 = function peg$c90() {
return nth(1);
},
peg$c91 = ":last-child",
peg$c92 = peg$literalExpectation(":last-child", false),
peg$c93 = function peg$c93() {
return nthLast(1);
},
peg$c94 = ":nth-child(",
peg$c95 = peg$literalExpectation(":nth-child(", false),
peg$c96 = function peg$c96(n) {
return nth(parseInt(n.join(''), 10));
},
peg$c97 = ":nth-last-child(",
peg$c98 = peg$literalExpectation(":nth-last-child(", false),
peg$c99 = function peg$c99(n) {
return nthLast(parseInt(n.join(''), 10));
},
peg$c100 = ":",
peg$c101 = peg$literalExpectation(":", false),
peg$c102 = "statement",
peg$c103 = peg$literalExpectation("statement", true),
peg$c104 = "expression",
peg$c105 = peg$literalExpectation("expression", true),
peg$c106 = "declaration",
peg$c107 = peg$literalExpectation("declaration", true),
peg$c108 = "function",
peg$c109 = peg$literalExpectation("function", true),
peg$c110 = "pattern",
peg$c111 = peg$literalExpectation("pattern", true),
peg$c112 = function peg$c112(c) {
return {
type: 'class',
name: c
};
},
peg$currPos = 0,
peg$posDetailsCache = [{
line: 1,
column: 1
}],
peg$maxFailPos = 0,
peg$maxFailExpected = [],
peg$resultsCache = {},
peg$result;
if ("startRule" in options) {
if (!(options.startRule in peg$startRuleFunctions)) {
throw new Error("Can't start parsing from rule \"" + options.startRule + "\".");
}
peg$startRuleFunction = peg$startRuleFunctions[options.startRule];
}
function peg$literalExpectation(text, ignoreCase) {
return {
type: "literal",
text: text,
ignoreCase: ignoreCase
};
}
function peg$classExpectation(parts, inverted, ignoreCase) {
return {
type: "class",
parts: parts,
inverted: inverted,
ignoreCase: ignoreCase
};
}
function peg$anyExpectation() {
return {
type: "any"
};
}
function peg$endExpectation() {
return {
type: "end"
};
}
function peg$computePosDetails(pos) {
var details = peg$posDetailsCache[pos],
p;
if (details) {
return details;
} else {
p = pos - 1;
while (!peg$posDetailsCache[p]) {
p--;
}
details = peg$posDetailsCache[p];
details = {
line: details.line,
column: details.column
};
while (p < pos) {
if (input.charCodeAt(p) === 10) {
details.line++;
details.column = 1;
} else {
details.column++;
}
p++;
}
peg$posDetailsCache[pos] = details;
return details;
}
}
function peg$computeLocation(startPos, endPos) {
var startPosDetails = peg$computePosDetails(startPos),
endPosDetails = peg$computePosDetails(endPos);
return {
start: {
offset: startPos,
line: startPosDetails.line,
column: startPosDetails.column
},
end: {
offset: endPos,
line: endPosDetails.line,
column: endPosDetails.column
}
};
}
function peg$fail(expected) {
if (peg$currPos < peg$maxFailPos) {
return;
}
if (peg$currPos > peg$maxFailPos) {
peg$maxFailPos = peg$currPos;
peg$maxFailExpected = [];
}
peg$maxFailExpected.push(expected);
}
function peg$buildStructuredError(expected, found, location) {
return new peg$SyntaxError(peg$SyntaxError.buildMessage(expected, found), expected, found, location);
}
function peg$parsestart() {
var s0, s1, s2, s3;
var key = peg$currPos * 30 + 0,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parse_();
if (s1 !== peg$FAILED) {
s2 = peg$parseselectors();
if (s2 !== peg$FAILED) {
s3 = peg$parse_();
if (s3 !== peg$FAILED) {
s1 = peg$c0(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parse_();
if (s1 !== peg$FAILED) {
s1 = peg$c1();
}
s0 = s1;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parse_() {
var s0, s1;
var key = peg$currPos * 30 + 1,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = [];
if (input.charCodeAt(peg$currPos) === 32) {
s1 = peg$c2;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c3);
}
}
while (s1 !== peg$FAILED) {
s0.push(s1);
if (input.charCodeAt(peg$currPos) === 32) {
s1 = peg$c2;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c3);
}
}
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseidentifierName() {
var s0, s1, s2;
var key = peg$currPos * 30 + 2,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
if (peg$c4.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c5);
}
}
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
if (peg$c4.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c5);
}
}
}
} else {
s1 = peg$FAILED;
}
if (s1 !== peg$FAILED) {
s1 = peg$c6(s1);
}
s0 = s1;
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsebinaryOp() {
var s0, s1, s2, s3;
var key = peg$currPos * 30 + 3,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parse_();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 62) {
s2 = peg$c7;
peg$currPos++;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c8);
}
}
if (s2 !== peg$FAILED) {
s3 = peg$parse_();
if (s3 !== peg$FAILED) {
s1 = peg$c9();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parse_();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 126) {
s2 = peg$c10;
peg$currPos++;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c11);
}
}
if (s2 !== peg$FAILED) {
s3 = peg$parse_();
if (s3 !== peg$FAILED) {
s1 = peg$c12();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parse_();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 43) {
s2 = peg$c13;
peg$currPos++;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c14);
}
}
if (s2 !== peg$FAILED) {
s3 = peg$parse_();
if (s3 !== peg$FAILED) {
s1 = peg$c15();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 32) {
s1 = peg$c2;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c3);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s1 = peg$c16();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
}
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseselectors() {
var s0, s1, s2, s3, s4, s5, s6, s7;
var key = peg$currPos * 30 + 4,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parseselector();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s5 = peg$c17;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c18);
}
}
if (s5 !== peg$FAILED) {
s6 = peg$parse_();
if (s6 !== peg$FAILED) {
s7 = peg$parseselector();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s5 = peg$c17;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c18);
}
}
if (s5 !== peg$FAILED) {
s6 = peg$parse_();
if (s6 !== peg$FAILED) {
s7 = peg$parseselector();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
if (s2 !== peg$FAILED) {
s1 = peg$c19(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseselector() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 5,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parsesequence();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parsebinaryOp();
if (s4 !== peg$FAILED) {
s5 = peg$parsesequence();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parsebinaryOp();
if (s4 !== peg$FAILED) {
s5 = peg$parsesequence();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
if (s2 !== peg$FAILED) {
s1 = peg$c20(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsesequence() {
var s0, s1, s2, s3;
var key = peg$currPos * 30 + 6,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 33) {
s1 = peg$c21;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c22);
}
}
if (s1 === peg$FAILED) {
s1 = null;
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseatom();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseatom();
}
} else {
s2 = peg$FAILED;
}
if (s2 !== peg$FAILED) {
s1 = peg$c23(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseatom() {
var s0;
var key = peg$currPos * 30 + 7,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$parsewildcard();
if (s0 === peg$FAILED) {
s0 = peg$parseidentifier();
if (s0 === peg$FAILED) {
s0 = peg$parseattr();
if (s0 === peg$FAILED) {
s0 = peg$parsefield();
if (s0 === peg$FAILED) {
s0 = peg$parsenegation();
if (s0 === peg$FAILED) {
s0 = peg$parsematches();
if (s0 === peg$FAILED) {
s0 = peg$parsehas();
if (s0 === peg$FAILED) {
s0 = peg$parsefirstChild();
if (s0 === peg$FAILED) {
s0 = peg$parselastChild();
if (s0 === peg$FAILED) {
s0 = peg$parsenthChild();
if (s0 === peg$FAILED) {
s0 = peg$parsenthLastChild();
if (s0 === peg$FAILED) {
s0 = peg$parseclass();
}
}
}
}
}
}
}
}
}
}
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsewildcard() {
var s0, s1;
var key = peg$currPos * 30 + 8,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 42) {
s1 = peg$c24;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c25);
}
}
if (s1 !== peg$FAILED) {
s1 = peg$c26(s1);
}
s0 = s1;
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseidentifier() {
var s0, s1, s2;
var key = peg$currPos * 30 + 9,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 35) {
s1 = peg$c27;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c28);
}
}
if (s1 === peg$FAILED) {
s1 = null;
}
if (s1 !== peg$FAILED) {
s2 = peg$parseidentifierName();
if (s2 !== peg$FAILED) {
s1 = peg$c29(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseattr() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 10,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 91) {
s1 = peg$c30;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c31);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = peg$parseattrValue();
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s5 = peg$c32;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c33);
}
}
if (s5 !== peg$FAILED) {
s1 = peg$c34(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseattrOps() {
var s0, s1, s2;
var key = peg$currPos * 30 + 11,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (peg$c35.test(input.charAt(peg$currPos))) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c36);
}
}
if (s1 === peg$FAILED) {
s1 = null;
}
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s2 = peg$c37;
peg$currPos++;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c38);
}
}
if (s2 !== peg$FAILED) {
s1 = peg$c39(s1);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
if (peg$c40.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
{
peg$fail(peg$c41);
}
}
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseattrEqOps() {
var s0, s1, s2;
var key = peg$currPos * 30 + 12,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 33) {
s1 = peg$c21;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c22);
}
}
if (s1 === peg$FAILED) {
s1 = null;
}
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s2 = peg$c37;
peg$currPos++;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c38);
}
}
if (s2 !== peg$FAILED) {
s1 = peg$c39(s1);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseattrName() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 13,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parseidentifierName();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c42;
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c43);
}
}
if (s4 !== peg$FAILED) {
s5 = peg$parseidentifierName();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c42;
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c43);
}
}
if (s4 !== peg$FAILED) {
s5 = peg$parseidentifierName();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
if (s2 !== peg$FAILED) {
s1 = peg$c44(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseattrValue() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 14,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parseattrName();
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = peg$parseattrEqOps();
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
s5 = peg$parsetype();
if (s5 === peg$FAILED) {
s5 = peg$parseregex();
}
if (s5 !== peg$FAILED) {
s1 = peg$c45(s1, s3, s5);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parseattrName();
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = peg$parseattrOps();
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
s5 = peg$parsestring();
if (s5 === peg$FAILED) {
s5 = peg$parsenumber();
if (s5 === peg$FAILED) {
s5 = peg$parsepath();
}
}
if (s5 !== peg$FAILED) {
s1 = peg$c45(s1, s3, s5);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parseattrName();
if (s1 !== peg$FAILED) {
s1 = peg$c46(s1);
}
s0 = s1;
}
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsestring() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 15,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 34) {
s1 = peg$c47;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c48);
}
}
if (s1 !== peg$FAILED) {
s2 = [];
if (peg$c49.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c50);
}
}
if (s3 === peg$FAILED) {
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 92) {
s4 = peg$c51;
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c52);
}
}
if (s4 !== peg$FAILED) {
if (input.length > peg$currPos) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c53);
}
}
if (s5 !== peg$FAILED) {
s4 = peg$c54(s4, s5);
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
while (s3 !== peg$FAILED) {
s2.push(s3);
if (peg$c49.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c50);
}
}
if (s3 === peg$FAILED) {
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 92) {
s4 = peg$c51;
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c52);
}
}
if (s4 !== peg$FAILED) {
if (input.length > peg$currPos) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c53);
}
}
if (s5 !== peg$FAILED) {
s4 = peg$c54(s4, s5);
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 34) {
s3 = peg$c47;
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c48);
}
}
if (s3 !== peg$FAILED) {
s1 = peg$c55(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 39) {
s1 = peg$c56;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c57);
}
}
if (s1 !== peg$FAILED) {
s2 = [];
if (peg$c58.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c59);
}
}
if (s3 === peg$FAILED) {
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 92) {
s4 = peg$c51;
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c52);
}
}
if (s4 !== peg$FAILED) {
if (input.length > peg$currPos) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c53);
}
}
if (s5 !== peg$FAILED) {
s4 = peg$c54(s4, s5);
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
while (s3 !== peg$FAILED) {
s2.push(s3);
if (peg$c58.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c59);
}
}
if (s3 === peg$FAILED) {
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 92) {
s4 = peg$c51;
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c52);
}
}
if (s4 !== peg$FAILED) {
if (input.length > peg$currPos) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c53);
}
}
if (s5 !== peg$FAILED) {
s4 = peg$c54(s4, s5);
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 39) {
s3 = peg$c56;
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c57);
}
}
if (s3 !== peg$FAILED) {
s1 = peg$c55(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsenumber() {
var s0, s1, s2, s3;
var key = peg$currPos * 30 + 16,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$currPos;
s2 = [];
if (peg$c60.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c61);
}
}
while (s3 !== peg$FAILED) {
s2.push(s3);
if (peg$c60.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c61);
}
}
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s3 = peg$c42;
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c43);
}
}
if (s3 !== peg$FAILED) {
s2 = [s2, s3];
s1 = s2;
} else {
peg$currPos = s1;
s1 = peg$FAILED;
}
} else {
peg$currPos = s1;
s1 = peg$FAILED;
}
if (s1 === peg$FAILED) {
s1 = null;
}
if (s1 !== peg$FAILED) {
s2 = [];
if (peg$c60.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c61);
}
}
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
if (peg$c60.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c61);
}
}
}
} else {
s2 = peg$FAILED;
}
if (s2 !== peg$FAILED) {
s1 = peg$c62(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsepath() {
var s0, s1;
var key = peg$currPos * 30 + 17,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parseidentifierName();
if (s1 !== peg$FAILED) {
s1 = peg$c63(s1);
}
s0 = s1;
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsetype() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 18,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 5) === peg$c64) {
s1 = peg$c64;
peg$currPos += 5;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c65);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = [];
if (peg$c66.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c67);
}
}
if (s4 !== peg$FAILED) {
while (s4 !== peg$FAILED) {
s3.push(s4);
if (peg$c66.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c67);
}
}
}
} else {
s3 = peg$FAILED;
}
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s5 = peg$c68;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c69);
}
}
if (s5 !== peg$FAILED) {
s1 = peg$c70(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseflags() {
var s0, s1;
var key = peg$currPos * 30 + 19,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = [];
if (peg$c71.test(input.charAt(peg$currPos))) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c72);
}
}
if (s1 !== peg$FAILED) {
while (s1 !== peg$FAILED) {
s0.push(s1);
if (peg$c71.test(input.charAt(peg$currPos))) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c72);
}
}
}
} else {
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseregex() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 30 + 20,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 47) {
s1 = peg$c73;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c74);
}
}
if (s1 !== peg$FAILED) {
s2 = [];
if (peg$c75.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c76);
}
}
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
if (peg$c75.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c76);
}
}
}
} else {
s2 = peg$FAILED;
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 47) {
s3 = peg$c73;
peg$currPos++;
} else {
s3 = peg$FAILED;
{
peg$fail(peg$c74);
}
}
if (s3 !== peg$FAILED) {
s4 = peg$parseflags();
if (s4 === peg$FAILED) {
s4 = null;
}
if (s4 !== peg$FAILED) {
s1 = peg$c77(s2, s4);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsefield() {
var s0, s1, s2, s3, s4, s5, s6;
var key = peg$currPos * 30 + 21,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s1 = peg$c42;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c43);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parseidentifierName();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s5 = peg$c42;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c43);
}
}
if (s5 !== peg$FAILED) {
s6 = peg$parseidentifierName();
if (s6 !== peg$FAILED) {
s5 = [s5, s6];
s4 = s5;
} else {
peg$currPos = s4;
s4 = peg$FAILED;
}
} else {
peg$currPos = s4;
s4 = peg$FAILED;
}
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s5 = peg$c42;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c43);
}
}
if (s5 !== peg$FAILED) {
s6 = peg$parseidentifierName();
if (s6 !== peg$FAILED) {
s5 = [s5, s6];
s4 = s5;
} else {
peg$currPos = s4;
s4 = peg$FAILED;
}
} else {
peg$currPos = s4;
s4 = peg$FAILED;
}
}
if (s3 !== peg$FAILED) {
s1 = peg$c78(s2, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsenegation() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 22,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 5) === peg$c79) {
s1 = peg$c79;
peg$currPos += 5;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c80);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = peg$parseselectors();
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s5 = peg$c68;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c69);
}
}
if (s5 !== peg$FAILED) {
s1 = peg$c81(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsematches() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 23,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 9) === peg$c82) {
s1 = peg$c82;
peg$currPos += 9;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c83);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = peg$parseselectors();
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s5 = peg$c68;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c69);
}
}
if (s5 !== peg$FAILED) {
s1 = peg$c84(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsehas() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 24,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 5) === peg$c85) {
s1 = peg$c85;
peg$currPos += 5;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c86);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = peg$parseselectors();
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s5 = peg$c68;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c69);
}
}
if (s5 !== peg$FAILED) {
s1 = peg$c87(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsefirstChild() {
var s0, s1;
var key = peg$currPos * 30 + 25,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 12) === peg$c88) {
s1 = peg$c88;
peg$currPos += 12;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c89);
}
}
if (s1 !== peg$FAILED) {
s1 = peg$c90();
}
s0 = s1;
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parselastChild() {
var s0, s1;
var key = peg$currPos * 30 + 26,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 11) === peg$c91) {
s1 = peg$c91;
peg$currPos += 11;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c92);
}
}
if (s1 !== peg$FAILED) {
s1 = peg$c93();
}
s0 = s1;
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsenthChild() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 27,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 11) === peg$c94) {
s1 = peg$c94;
peg$currPos += 11;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c95);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = [];
if (peg$c60.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c61);
}
}
if (s4 !== peg$FAILED) {
while (s4 !== peg$FAILED) {
s3.push(s4);
if (peg$c60.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c61);
}
}
}
} else {
s3 = peg$FAILED;
}
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s5 = peg$c68;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c69);
}
}
if (s5 !== peg$FAILED) {
s1 = peg$c96(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parsenthLastChild() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 30 + 28,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 16) === peg$c97) {
s1 = peg$c97;
peg$currPos += 16;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c98);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = [];
if (peg$c60.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c61);
}
}
if (s4 !== peg$FAILED) {
while (s4 !== peg$FAILED) {
s3.push(s4);
if (peg$c60.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
{
peg$fail(peg$c61);
}
}
}
} else {
s3 = peg$FAILED;
}
if (s3 !== peg$FAILED) {
s4 = peg$parse_();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s5 = peg$c68;
peg$currPos++;
} else {
s5 = peg$FAILED;
{
peg$fail(peg$c69);
}
}
if (s5 !== peg$FAILED) {
s1 = peg$c99(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function peg$parseclass() {
var s0, s1, s2;
var key = peg$currPos * 30 + 29,
cached = peg$resultsCache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 58) {
s1 = peg$c100;
peg$currPos++;
} else {
s1 = peg$FAILED;
{
peg$fail(peg$c101);
}
}
if (s1 !== peg$FAILED) {
if (input.substr(peg$currPos, 9).toLowerCase() === peg$c102) {
s2 = input.substr(peg$currPos, 9);
peg$currPos += 9;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c103);
}
}
if (s2 === peg$FAILED) {
if (input.substr(peg$currPos, 10).toLowerCase() === peg$c104) {
s2 = input.substr(peg$currPos, 10);
peg$currPos += 10;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c105);
}
}
if (s2 === peg$FAILED) {
if (input.substr(peg$currPos, 11).toLowerCase() === peg$c106) {
s2 = input.substr(peg$currPos, 11);
peg$currPos += 11;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c107);
}
}
if (s2 === peg$FAILED) {
if (input.substr(peg$currPos, 8).toLowerCase() === peg$c108) {
s2 = input.substr(peg$currPos, 8);
peg$currPos += 8;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c109);
}
}
if (s2 === peg$FAILED) {
if (input.substr(peg$currPos, 7).toLowerCase() === peg$c110) {
s2 = input.substr(peg$currPos, 7);
peg$currPos += 7;
} else {
s2 = peg$FAILED;
{
peg$fail(peg$c111);
}
}
}
}
}
}
if (s2 !== peg$FAILED) {
s1 = peg$c112(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
peg$resultsCache[key] = {
nextPos: peg$currPos,
result: s0
};
return s0;
}
function nth(n) {
return {
type: 'nth-child',
index: {
type: 'literal',
value: n
}
};
}
function nthLast(n) {
return {
type: 'nth-last-child',
index: {
type: 'literal',
value: n
}
};
}
function strUnescape(s) {
return s.replace(/\\(.)/g, function (match, ch) {
switch (ch) {
case 'b':
return '\b';
case 'f':
return '\f';
case 'n':
return '\n';
case 'r':
return '\r';
case 't':
return '\t';
case 'v':
return '\v';
default:
return ch;
}
});
}
peg$result = peg$startRuleFunction();
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
return peg$result;
} else {
if (peg$result !== peg$FAILED && peg$currPos < input.length) {
peg$fail(peg$endExpectation());
}
throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos));
}
}
return {
SyntaxError: peg$SyntaxError,
parse: peg$parse
};
});
});
function _objectEntries(obj) {
var entries = [];
var keys = Object.keys(obj);
for (var k = 0; k < keys.length; k++) entries.push([keys[k], obj[keys[k]]]);
return entries;
}
/**
* @typedef {"LEFT_SIDE"|"RIGHT_SIDE"} Side
*/
var LEFT_SIDE = 'LEFT_SIDE';
var RIGHT_SIDE = 'RIGHT_SIDE';
/**
* @external AST
* @see https://esprima.readthedocs.io/en/latest/syntax-tree-format.html
*/
/**
* One of the rules of `grammar.pegjs`
* @typedef {PlainObject} SelectorAST
* @see grammar.pegjs
*/
/**
* The `sequence` production of `grammar.pegjs`
* @typedef {PlainObject} SelectorSequenceAST
*/
/**
* Get the value of a property which may be multiple levels down
* in the object.
* @param {?PlainObject} obj
* @param {string} key
* @returns {undefined|boolean|string|number|external:AST}
*/
function getPath(obj, key) {
var keys = key.split('.');
var _iterator = _createForOfIteratorHelper(keys),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _key = _step.value;
if (obj == null) {
return obj;
}
obj = obj[_key];
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return obj;
}
/**
* Determine whether `node` can be reached by following `path`,
* starting at `ancestor`.
* @param {?external:AST} node
* @param {?external:AST} ancestor
* @param {string[]} path
* @returns {boolean}
*/
function inPath(node, ancestor, path) {
if (path.length === 0) {
return node === ancestor;
}
if (ancestor == null) {
return false;
}
var field = ancestor[path[0]];
var remainingPath = path.slice(1);
if (Array.isArray(field)) {
var _iterator2 = _createForOfIteratorHelper(field),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var component = _step2.value;
if (inPath(node, component, remainingPath)) {
return true;
}
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
return false;
} else {
return inPath(node, field, remainingPath);
}
}
/**
* @callback TraverseOptionFallback
* @param {external:AST} node The given node.
* @returns {string[]} An array of visitor keys for the given node.
*/
/**
* @typedef {object} ESQueryOptions
* @property { { [nodeType: string]: string[] } } [visitorKeys] By passing `visitorKeys` mapping, we can extend the properties of the nodes that traverse the node.
* @property {TraverseOptionFallback} [fallback] By passing `fallback` option, we can control the properties of traversing nodes when encountering unknown nodes.
*/
/**
* Given a `node` and its ancestors, determine if `node` is matched
* by `selector`.
* @param {?external:AST} node
* @param {?SelectorAST} selector
* @param {external:AST[]} [ancestry=[]]
* @param {ESQueryOptions} [options]
* @throws {Error} Unknowns (operator, class name, selector type, or
* selector value type)
* @returns {boolean}
*/
function matches(node, selector, ancestry, options) {
if (!selector) {
return true;
}
if (!node) {
return false;
}
if (!ancestry) {
ancestry = [];
}
switch (selector.type) {
case 'wildcard':
return true;
case 'identifier':
return selector.value.toLowerCase() === node.type.toLowerCase();
case 'field':
{
var path = selector.name.split('.');
var ancestor = ancestry[path.length - 1];
return inPath(node, ancestor, path);
}
case 'matches':
var _iterator3 = _createForOfIteratorHelper(selector.selectors),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var sel = _step3.value;
if (matches(node, sel, ancestry, options)) {
return true;
}
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
return false;
case 'compound':
var _iterator4 = _createForOfIteratorHelper(selector.selectors),
_step4;
try {
for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
var _sel = _step4.value;
if (!matches(node, _sel, ancestry, options)) {
return false;
}
}
} catch (err) {
_iterator4.e(err);
} finally {
_iterator4.f();
}
return true;
case 'not':
var _iterator5 = _createForOfIteratorHelper(selector.selectors),
_step5;
try {
for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
var _sel2 = _step5.value;
if (matches(node, _sel2, ancestry, options)) {
return false;
}
}
} catch (err) {
_iterator5.e(err);
} finally {
_iterator5.f();
}
return true;
case 'has':
{
var _ret = function () {
var collector = [];
var _iterator6 = _createForOfIteratorHelper(selector.selectors),
_step6;
try {
var _loop = function _loop() {
var sel = _step6.value;
var a = [];
estraverse.traverse(node, {
enter: function enter(node, parent) {
if (parent != null) {
a.unshift(parent);
}
if (matches(node, sel, a, options)) {
collector.push(node);
}
},
leave: function leave() {
a.shift();
},
keys: options && options.visitorKeys,
fallback: options && options.fallback || 'iteration'
});
};
for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
_loop();
}
} catch (err) {
_iterator6.e(err);
} finally {
_iterator6.f();
}
return {
v: collector.length !== 0
};
}();
if (_typeof(_ret) === "object") return _ret.v;
}
case 'child':
if (matches(node, selector.right, ancestry, options)) {
return matches(ancestry[0], selector.left, ancestry.slice(1), options);
}
return false;
case 'descendant':
if (matches(node, selector.right, ancestry, options)) {
for (var i = 0, l = ancestry.length; i < l; ++i) {
if (matches(ancestry[i], selector.left, ancestry.slice(i + 1), options)) {
return true;
}
}
}
return false;
case 'attribute':
{
var p = getPath(node, selector.name);
switch (selector.operator) {
case void 0:
return p != null;
case '=':
switch (selector.value.type) {
case 'regexp':
return typeof p === 'string' && selector.value.value.test(p);
case 'literal':
return "".concat(selector.value.value) === "".concat(p);
case 'type':
return selector.value.value === _typeof(p);
}
throw new Error("Unknown selector value type: ".concat(selector.value.type));
case '!=':
switch (selector.value.type) {
case 'regexp':
return !selector.value.value.test(p);
case 'literal':
return "".concat(selector.value.value) !== "".concat(p);
case 'type':
return selector.value.value !== _typeof(p);
}
throw new Error("Unknown selector value type: ".concat(selector.value.type));
case '<=':
return p <= selector.value.value;
case '<':
return p < selector.value.value;
case '>':
return p > selector.value.value;
case '>=':
return p >= selector.value.value;
}
throw new Error("Unknown operator: ".concat(selector.operator));
}
case 'sibling':
return matches(node, selector.right, ancestry, options) && sibling(node, selector.left, ancestry, LEFT_SIDE, options) || selector.left.subject && matches(node, selector.left, ancestry, options) && sibling(node, selector.right, ancestry, RIGHT_SIDE, options);
case 'adjacent':
return matches(node, selector.right, ancestry, options) && adjacent(node, selector.left, ancestry, LEFT_SIDE, options) || selector.right.subject && matches(node, selector.left, ancestry, options) && adjacent(node, selector.right, ancestry, RIGHT_SIDE, options);
case 'nth-child':
return matches(node, selector.right, ancestry, options) && nthChild(node, ancestry, function () {
return selector.index.value - 1;
}, options);
case 'nth-last-child':
return matches(node, selector.right, ancestry, options) && nthChild(node, ancestry, function (length) {
return length - selector.index.value;
}, options);
case 'class':
switch (selector.name.toLowerCase()) {
case 'statement':
if (node.type.slice(-9) === 'Statement') return true;
// fallthrough: interface Declaration <: Statement { }
case 'declaration':
return node.type.slice(-11) === 'Declaration';
case 'pattern':
if (node.type.slice(-7) === 'Pattern') return true;
// fallthrough: interface Expression <: Node, Pattern { }
case 'expression':
return node.type.slice(-10) === 'Expression' || node.type.slice(-7) === 'Literal' || node.type === 'Identifier' && (ancestry.length === 0 || ancestry[0].type !== 'MetaProperty') || node.type === 'MetaProperty';
case 'function':
return node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression';
}
throw new Error("Unknown class name: ".concat(selector.name));
}
throw new Error("Unknown selector type: ".concat(selector.type));
}
/**
* Get visitor keys of a given node.
* @param {external:AST} node The AST node to get keys.
* @param {ESQueryOptions|undefined} options
* @returns {string[]} Visitor keys of the node.
*/
function getVisitorKeys(node, options) {
var nodeType = node.type;
if (options && options.visitorKeys && options.visitorKeys[nodeType]) {
return options.visitorKeys[nodeType];
}
if (estraverse.VisitorKeys[nodeType]) {
return estraverse.VisitorKeys[nodeType];
}
if (options && typeof options.fallback === 'function') {
return options.fallback(node);
} // 'iteration' fallback
return Object.keys(node).filter(function (key) {
return key !== 'type';
});
}
/**
* Check whether the given value is an ASTNode or not.
* @param {any} node The value to check.
* @returns {boolean} `true` if the value is an ASTNode.
*/
function isNode(node) {
return node !== null && _typeof(node) === 'object' && typeof node.type === 'string';
}
/**
* Determines if the given node has a sibling that matches the
* given selector.
* @param {external:AST} node
* @param {SelectorSequenceAST} selector
* @param {external:AST[]} ancestry
* @param {Side} side
* @param {ESQueryOptions|undefined} options
* @returns {boolean}
*/
function sibling(node, selector, ancestry, side, options) {
var _ancestry = _slicedToArray(ancestry, 1),
parent = _ancestry[0];
if (!parent) {
return false;
}
var keys = getVisitorKeys(parent, options);
var _iterator7 = _createForOfIteratorHelper(keys),
_step7;
try {
for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
var key = _step7.value;
var listProp = parent[key];
if (Array.isArray(listProp)) {
var startIndex = listProp.indexOf(node);
if (startIndex < 0) {
continue;
}
var lowerBound = void 0,
upperBound = void 0;
if (side === LEFT_SIDE) {
lowerBound = 0;
upperBound = startIndex;
} else {
lowerBound = startIndex + 1;
upperBound = listProp.length;
}
for (var k = lowerBound; k < upperBound; ++k) {
if (isNode(listProp[k]) && matches(listProp[k], selector, ancestry, options)) {
return true;
}
}
}
}
} catch (err) {
_iterator7.e(err);
} finally {
_iterator7.f();
}
return false;
}
/**
* Determines if the given node has an adjacent sibling that matches
* the given selector.
* @param {external:AST} node
* @param {SelectorSequenceAST} selector
* @param {external:AST[]} ancestry
* @param {Side} side
* @param {ESQueryOptions|undefined} options
* @returns {boolean}
*/
function adjacent(node, selector, ancestry, side, options) {
var _ancestry2 = _slicedToArray(ancestry, 1),
parent = _ancestry2[0];
if (!parent) {
return false;
}
var keys = getVisitorKeys(parent, options);
var _iterator8 = _createForOfIteratorHelper(keys),
_step8;
try {
for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
var key = _step8.value;
var listProp = parent[key];
if (Array.isArray(listProp)) {
var idx = listProp.indexOf(node);
if (idx < 0) {
continue;
}
if (side === LEFT_SIDE && idx > 0 && isNode(listProp[idx - 1]) && matches(listProp[idx - 1], selector, ancestry, options)) {
return true;
}
if (side === RIGHT_SIDE && idx < listProp.length - 1 && isNode(listProp[idx + 1]) && matches(listProp[idx + 1], selector, ancestry, options)) {
return true;
}
}
}
} catch (err) {
_iterator8.e(err);
} finally {
_iterator8.f();
}
return false;
}
/**
* @callback IndexFunction
* @param {Integer} len Containing list's length
* @returns {Integer}
*/
/**
* Determines if the given node is the nth child, determined by
* `idxFn`, which is given the containing list's length.
* @param {external:AST} node
* @param {external:AST[]} ancestry
* @param {IndexFunction} idxFn
* @param {ESQueryOptions|undefined} options
* @returns {boolean}
*/
function nthChild(node, ancestry, idxFn, options) {
var _ancestry3 = _slicedToArray(ancestry, 1),
parent = _ancestry3[0];
if (!parent) {
return false;
}
var keys = getVisitorKeys(parent, options);
var _iterator9 = _createForOfIteratorHelper(keys),
_step9;
try {
for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
var key = _step9.value;
var listProp = parent[key];
if (Array.isArray(listProp)) {
var idx = listProp.indexOf(node);
if (idx >= 0 && idx === idxFn(listProp.length)) {
return true;
}
}
}
} catch (err) {
_iterator9.e(err);
} finally {
_iterator9.f();
}
return false;
}
/**
* For each selector node marked as a subject, find the portion of the
* selector that the subject must match.
* @param {SelectorAST} selector
* @param {SelectorAST} [ancestor] Defaults to `selector`
* @returns {SelectorAST[]}
*/
function subjects(selector, ancestor) {
if (selector == null || _typeof(selector) != 'object') {
return [];
}
if (ancestor == null) {
ancestor = selector;
}
var results = selector.subject ? [ancestor] : [];
for (var _i = 0, _Object$entries = _objectEntries(selector); _i < _Object$entries.length; _i++) {
var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
p = _Object$entries$_i[0],
sel = _Object$entries$_i[1];
results.push.apply(results, _toConsumableArray(subjects(sel, p === 'left' ? sel : ancestor)));
}
return results;
}
/**
* @callback TraverseVisitor
* @param {?external:AST} node
* @param {?external:AST} parent
* @param {external:AST[]} ancestry
*/
/**
* From a JS AST and a selector AST, collect all JS AST nodes that
* match the selector.
* @param {external:AST} ast
* @param {?SelectorAST} selector
* @param {TraverseVisitor} visitor
* @param {ESQueryOptions} [options]
* @returns {external:AST[]}
*/
function traverse(ast, selector, visitor, options) {
if (!selector) {
return;
}
var ancestry = [];
var altSubjects = subjects(selector);
estraverse.traverse(ast, {
enter: function enter(node, parent) {
if (parent != null) {
ancestry.unshift(parent);
}
if (matches(node, selector, ancestry, options)) {
if (altSubjects.length) {
for (var i = 0, l = altSubjects.length; i < l; ++i) {
if (matches(node, altSubjects[i], ancestry, options)) {
visitor(node, parent, ancestry);
}
for (var k = 0, m = ancestry.length; k < m; ++k) {
var succeedingAncestry = ancestry.slice(k + 1);
if (matches(ancestry[k], altSubjects[i], succeedingAncestry, options)) {
visitor(ancestry[k], parent, succeedingAncestry);
}
}
}
} else {
visitor(node, parent, ancestry);
}
}
},
leave: function leave() {
ancestry.shift();
},
keys: options && options.visitorKeys,
fallback: options && options.fallback || 'iteration'
});
}
/**
* From a JS AST and a selector AST, collect all JS AST nodes that
* match the selector.
* @param {external:AST} ast
* @param {?SelectorAST} selector
* @param {ESQueryOptions} [options]
* @returns {external:AST[]}
*/
function match(ast, selector, options) {
var results = [];
traverse(ast, selector, function (node) {
results.push(node);
}, options);
return results;
}
/**
* Parse a selector string and return its AST.
* @param {string} selector
* @returns {SelectorAST}
*/
function parse(selector) {
return parser.parse(selector);
}
/**
* Query the code AST using the selector string.
* @param {external:AST} ast
* @param {string} selector
* @param {ESQueryOptions} [options]
* @returns {external:AST[]}
*/
function query(ast, selector, options) {
return match(ast, parse(selector), options);
}
query.parse = parse;
query.match = match;
query.traverse = traverse;
query.matches = matches;
query.query = query;
return query;
})));
| GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/esquery/dist/esquery.lite.js | JavaScript | apache-2.0 | 105,133 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* The production x ^= y is the same as x = x ^ y
*
* @path ch11/11.13/11.13.2/S11.13.2_A4.10_T2.2.js
* @description Type(x) is different from Type(y) and both types vary between Number (primitive or object) and String (primitive and object)
*/
//CHECK#1
x = "1";
x ^= 1;
if (x !== 0) {
$ERROR('#1: x = "1"; x ^= 1; x === 0. Actual: ' + (x));
}
//CHECK#2
x = 1;
x ^= "1";
if (x !== 0) {
$ERROR('#2: x = 1; x ^= "1"; x === 0. Actual: ' + (x));
}
//CHECK#3
x = new String("1");
x ^= 1;
if (x !== 0) {
$ERROR('#3: x = new String("1"); x ^= 1; x === 0. Actual: ' + (x));
}
//CHECK#4
x = 1;
x ^= new String("1");
if (x !== 0) {
$ERROR('#4: x = 1; x ^= new String("1"); x === 0. Actual: ' + (x));
}
//CHECK#5
x = "1";
x ^= new Number(1);
if (x !== 0) {
$ERROR('#5: x = "1"; x ^= new Number(1); x === 0. Actual: ' + (x));
}
//CHECK#6
x = new Number(1);
x ^= "1";
if (x !== 0) {
$ERROR('#6: x = new Number(1); x ^= "1"; x === 0. Actual: ' + (x));
}
//CHECK#7
x = new String("1");
x ^= new Number(1);
if (x !== 0) {
$ERROR('#7: x = new String("1"); x ^= new Number(1); x === 0. Actual: ' + (x));
}
//CHECK#8
x = new Number(1);
x ^= new String("1");
if (x !== 0) {
$ERROR('#8: x = new Number(1); x ^= new String("1"); x === 0. Actual: ' + (x));
}
//CHECK#9
x = "x";
x ^= 1;
if (x !== 1) {
$ERROR('#9: x = "x"; x ^= 1; x === 1. Actual: ' + (x));
}
//CHECK#10
x = 1;
x ^= "x";
if (x !== 1) {
$ERROR('#10: x = 1; x ^= "x"; x === 1. Actual: ' + (x));
}
| hippich/typescript | tests/Fidelity/test262/suite/ch11/11.13/11.13.2/S11.13.2_A4.10_T2.2.js | JavaScript | apache-2.0 | 1,611 |
/**
* Copyright 2011, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.floodlightcontroller.topology.web;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.floodlightcontroller.core.internal.IOFSwitchService;
import net.floodlightcontroller.topology.ITopologyService;
import org.projectfloodlight.openflow.types.DatapathId;
import org.restlet.data.Form;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
/**
* Returns a JSON map of <ClusterId, List<SwitchDpids>>
*/
public class SwitchClustersResource extends ServerResource {
@Get("json")
public Map<String, List<String>> retrieve() {
IOFSwitchService switchService =
(IOFSwitchService) getContext().getAttributes().
get(IOFSwitchService.class.getCanonicalName());
ITopologyService topologyService =
(ITopologyService) getContext().getAttributes().
get(ITopologyService.class.getCanonicalName());
Form form = getQuery();
String queryType = form.getFirstValue("type", true);
boolean openflowDomain = true;
if (queryType != null && "l2".equals(queryType)) {
openflowDomain = false;
}
Map<String, List<String>> switchClusterMap = new HashMap<String, List<String>>();
for (DatapathId dpid: switchService.getAllSwitchDpids()) {
DatapathId clusterDpid =
(openflowDomain
? topologyService.getOpenflowDomainId(dpid)
:topologyService.getOpenflowDomainId(dpid));
List<String> switchesInCluster = switchClusterMap.get(clusterDpid.toString());
if (switchesInCluster != null) {
switchesInCluster.add(dpid.toString());
} else {
List<String> l = new ArrayList<String>();
l.add(dpid.toString());
switchClusterMap.put(clusterDpid.toString(), l);
}
}
return switchClusterMap;
}
}
| alberthitanaya/floodlight-dnscollector | src/main/java/net/floodlightcontroller/topology/web/SwitchClustersResource.java | Java | apache-2.0 | 2,712 |
cask "lynx" do
version "7.5.2.0"
sha256 :no_check
url "https://download.saharasupport.com/lynx#{version.major}/production/macx/Lynx#{version.major}-install.dmg",
verified: "download.saharasupport.com"
name "LYNX Whiteboard by Clevertouch"
desc "Cross platform presentation and productivity app"
homepage "https://www.lynxcloud.app/"
livecheck do
url "https://downloads.saharasupport.com/lynx#{version.major}/production/macx/version.txt"
regex(/(\d+(?:[._-]\d+)+)/)
end
auto_updates true
pkg "Lynx#{version.major}.pkg"
uninstall pkgutil: [
"com.clevertouch.lynx",
"uk.co.cleverproducts.lynx",
]
end
| nrlquaker/homebrew-cask | Casks/lynx.rb | Ruby | bsd-2-clause | 649 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.modules.i18nmanager;
import android.content.Context;
import android.content.SharedPreferences;
import androidx.core.text.TextUtilsCompat;
import androidx.core.view.ViewCompat;
import java.util.Locale;
public class I18nUtil {
private static I18nUtil sharedI18nUtilInstance = null;
private static final String SHARED_PREFS_NAME = "com.facebook.react.modules.i18nmanager.I18nUtil";
private static final String KEY_FOR_PREFS_ALLOWRTL = "RCTI18nUtil_allowRTL";
private static final String KEY_FOR_PREFS_FORCERTL = "RCTI18nUtil_forceRTL";
private static final String KEY_FOR_PERFS_MAKE_RTL_FLIP_LEFT_AND_RIGHT_STYLES =
"RCTI18nUtil_makeRTLFlipLeftAndRightStyles";
private I18nUtil() {
// Exists only to defeat instantiation.
}
public static I18nUtil getInstance() {
if (sharedI18nUtilInstance == null) {
sharedI18nUtilInstance = new I18nUtil();
}
return sharedI18nUtilInstance;
}
/**
* Check if the device is currently running on an RTL locale. This only happens when the app:
*
* <ul>
* <li>is forcing RTL layout, regardless of the active language (for development purpose)
* <li>allows RTL layout when using RTL locale
* </ul>
*/
public boolean isRTL(Context context) {
if (isRTLForced(context)) {
return true;
}
return isRTLAllowed(context) && isDevicePreferredLanguageRTL();
}
/**
* Should be used very early during app start up Before the bridge is initialized
*
* @return whether the app allows RTL layout, default is true
*/
private boolean isRTLAllowed(Context context) {
return isPrefSet(context, KEY_FOR_PREFS_ALLOWRTL, true);
}
public void allowRTL(Context context, boolean allowRTL) {
setPref(context, KEY_FOR_PREFS_ALLOWRTL, allowRTL);
}
public boolean doLeftAndRightSwapInRTL(Context context) {
return isPrefSet(context, KEY_FOR_PERFS_MAKE_RTL_FLIP_LEFT_AND_RIGHT_STYLES, true);
}
public void swapLeftAndRightInRTL(Context context, boolean flip) {
setPref(context, KEY_FOR_PERFS_MAKE_RTL_FLIP_LEFT_AND_RIGHT_STYLES, flip);
}
/** Could be used to test RTL layout with English Used for development and testing purpose */
private boolean isRTLForced(Context context) {
return isPrefSet(context, KEY_FOR_PREFS_FORCERTL, false);
}
public void forceRTL(Context context, boolean forceRTL) {
setPref(context, KEY_FOR_PREFS_FORCERTL, forceRTL);
}
// Check if the current device language is RTL
private boolean isDevicePreferredLanguageRTL() {
final int directionality = TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault());
return directionality == ViewCompat.LAYOUT_DIRECTION_RTL;
}
private boolean isPrefSet(Context context, String key, boolean defaultValue) {
SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
return prefs.getBoolean(key, defaultValue);
}
private void setPref(Context context, String key, boolean value) {
SharedPreferences.Editor editor =
context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE).edit();
editor.putBoolean(key, value);
editor.apply();
}
}
| exponent/exponent | android/ReactAndroid/src/main/java/com/facebook/react/modules/i18nmanager/I18nUtil.java | Java | bsd-3-clause | 3,388 |
cdb.admin.overlays.LayerSelector = cdb.core.View.extend({
tagName: 'div',
className: 'cartodb-layer-selector-box',
events: {
"click": '_openDropdown',
"dblclick": 'killEvent',
"mousedown": 'killEvent'
},
default_options: {
timeout: 0,
msg: ''
},
initialize: function() {
_.bindAll(this, "_close");
this.map = this.options.mapView.map;
this.mapView = this.options.mapView;
this.mapView.bind('click zoomstart drag', function() {
this.dropdown && this.dropdown.hide()
}, this);
this.add_related_model(this.mapView);
this.layers = [];
this.map = this.options.map;
_.defaults(this.options, this.default_options);
this._setupModels();
},
_killEvent: function(e) {
e && e.preventDefault();
e && e.stopPropagation();
},
// Setup the internal and custom model
_setupModels: function() {
this.model = this.options.model;
this.model.on("change:display", this._onChangeDisplay, this);
this.model.on("change:y", this._onChangeY, this);
this.model.on("change:x", this._onChangeX, this);
this.model.on("destroy", function() {
this.$el.remove();
}, this);
},
_onChangeX: function() {
var x = this.model.get("x");
this.$el.animate({ right: x }, 150);
this.trigger("change_x", this);
//this.model.save();
},
_onChangeY: function() {
var y = this.model.get("y");
this.$el.animate({ top: y }, 150);
this.trigger("change_y", this);
//this.model.save();
},
_onChangeDisplay: function() {
var display = this.model.get("display");
if (display) {
this.show();
} else {
this.hide();
}
},
_checkZoom: function() {
var zoom = this.map.get('zoom');
this.$('.zoom_in')[ zoom < this.map.get('maxZoom') ? 'removeClass' : 'addClass' ]('disabled')
this.$('.zoom_out')[ zoom > this.map.get('minZoom') ? 'removeClass' : 'addClass' ]('disabled')
},
zoom_in: function(ev) {
if (this.map.get("maxZoom") > this.map.getZoom()) {
this.map.setZoom(this.map.getZoom() + 1);
}
ev.preventDefault();
ev.stopPropagation();
},
zoom_out: function(ev) {
if (this.map.get("minZoom") < this.map.getZoom()) {
this.map.setZoom(this.map.getZoom() - 1);
}
ev.preventDefault();
ev.stopPropagation();
},
_onMouseDown: function() { },
_onMouseEnterText: function() { },
_onMouseLeaveText: function() { },
_onMouseEnter: function() { },
_onMouseLeave: function() { },
show: function() {
this.$el.fadeIn(250);
},
hide: function(callback) {
var self = this;
callback && callback();
this.$el.fadeOut(250);
},
_close: function(e) {
this._killEvent(e);
var self = this;
this.hide(function() {
self.trigger("remove", self);
});
},
_toggleFullScreen: function(ev) {
ev.stopPropagation();
ev.preventDefault();
var doc = window.document;
var docEl = doc.documentElement;
if (this.options.doc) { // we use a custom element
docEl = $(this.options.doc)[0];
}
var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen;
var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen;
var mapView = this.options.mapView;
if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement) {
requestFullScreen.call(docEl);
if (mapView) {
if (this.model.get("allowWheelOnFullscreen")) {
mapView.options.map.set("scrollwheel", true);
}
}
} else {
cancelFullScreen.call(doc);
}
},
_getLayers: function() {
var self = this;
this.layers = [];
_.each(this.mapView.map.layers.models, function(layer) {
if (layer.get("type") == 'layergroup' || layer.get('type') === 'namedmap') {
var layerGroupView = self.mapView.getLayerByCid(layer.cid);
for (var i = 0 ; i < layerGroupView.getLayerCount(); ++i) {
var l = layerGroupView.getLayer(i);
var m = new cdb.core.Model(l);
m.set('order', i);
m.set('type', 'layergroup');
m.set('visible', !layerGroupView.getSubLayer(i).get('hidden'));
m.bind('change:visible', function(model) {
this.trigger("change:visible", model.get('visible'), model.get('order'), model);
model.save();
}, self);
if(self.options.layer_names) {
m.set('layer_name', self.options.layer_names[i]);
} else {
m.set('layer_name', l.options.layer_name);
}
var layerView = self._createLayer('LayerViewFromLayerGroup', {
model: m,
layerView: layerGroupView,
layerIndex: i
});
layerView.bind('switchChanged', self._setCount, self);
self.layers.push(layerView);
}
} else if (layer.get("type") === "CartoDB" || layer.get('type') === 'torque') {
var layerView = self._createLayer('LayerView', { model: layer });
layerView.bind('switchChanged', self._setCount, self);
self.layers.push(layerView);
layerView.model.bind('change:visible', function(model) {
this.trigger("change:visible", model.get('visible'), model.get('order'), model);
model.save();
}, self);
}
});
},
_createLayer: function(_class, opts) {
var layerView = new cdb.geo.ui[_class](opts);
this.$("ul").append(layerView.render().el);
this.addView(layerView);
return layerView;
},
_setCount: function() {
var count = 0;
for (var i = 0, l = this.layers.length; i < l; ++i) {
var lyr = this.layers[i];
if (lyr.model.get('visible')) {
count++;
}
}
this.$('.count').text(count);
this.trigger("switchChanged", this);
},
_openDropdown: function() {
this.dropdown.open();
},
render: function() {
var self = this;
this.$el.html(this.options.template(this.options));
this.$el.css({ right: this.model.get("x"), top: this.model.get("y") });
this.dropdown = new cdb.ui.common.Dropdown({
className:"cartodb-dropdown border",
template: this.options.dropdown_template,
target: this.$el.find("a"),
speedIn: 300,
speedOut: 200,
position: "position",
tick: "right",
vertical_position: "down",
horizontal_position: "right",
vertical_offset: 7,
horizontal_offset: 13
});
if (cdb.god) cdb.god.bind("closeDialogs", this.dropdown.hide, this.dropdown);
this.$el.append(this.dropdown.render().el);
this._getLayers();
this._setCount();
return this;
}
});
| nyimbi/cartodb | lib/assets/javascripts/cartodb/table/overlays/layer_selector.js | JavaScript | bsd-3-clause | 6,825 |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
const React = require('react');
const ReactDOM = require('react-dom');
describe('ReactMount', () => {
it('should destroy a react root upon request', () => {
const mainContainerDiv = document.createElement('div');
document.body.appendChild(mainContainerDiv);
const instanceOne = <div className="firstReactDiv" />;
const firstRootDiv = document.createElement('div');
mainContainerDiv.appendChild(firstRootDiv);
ReactDOM.render(instanceOne, firstRootDiv);
const instanceTwo = <div className="secondReactDiv" />;
const secondRootDiv = document.createElement('div');
mainContainerDiv.appendChild(secondRootDiv);
ReactDOM.render(instanceTwo, secondRootDiv);
// Test that two react roots are rendered in isolation
expect(firstRootDiv.firstChild.className).toBe('firstReactDiv');
expect(secondRootDiv.firstChild.className).toBe('secondReactDiv');
// Test that after unmounting each, they are no longer in the document.
ReactDOM.unmountComponentAtNode(firstRootDiv);
expect(firstRootDiv.firstChild).toBeNull();
ReactDOM.unmountComponentAtNode(secondRootDiv);
expect(secondRootDiv.firstChild).toBeNull();
});
it('should warn when unmounting a non-container root node', () => {
const mainContainerDiv = document.createElement('div');
const component = (
<div>
<div />
</div>
);
ReactDOM.render(component, mainContainerDiv);
// Test that unmounting at a root node gives a helpful warning
const rootDiv = mainContainerDiv.firstChild;
expect(() => ReactDOM.unmountComponentAtNode(rootDiv)).toWarnDev(
"Warning: unmountComponentAtNode(): The node you're attempting to " +
'unmount was rendered by React and is not a top-level container. You ' +
'may have accidentally passed in a React root node instead of its ' +
'container.',
{withoutStack: true},
);
});
it('should warn when unmounting a non-container, non-root node', () => {
const mainContainerDiv = document.createElement('div');
const component = (
<div>
<div>
<div />
</div>
</div>
);
ReactDOM.render(component, mainContainerDiv);
// Test that unmounting at a non-root node gives a different warning
const nonRootDiv = mainContainerDiv.firstChild.firstChild;
expect(() => ReactDOM.unmountComponentAtNode(nonRootDiv)).toWarnDev(
"Warning: unmountComponentAtNode(): The node you're attempting to " +
'unmount was rendered by React and is not a top-level container. ' +
'Instead, have the parent component update its state and rerender in ' +
'order to remove this component.',
{withoutStack: true},
);
});
});
| jdlehman/react | packages/react-dom/src/__tests__/ReactMountDestruction-test.js | JavaScript | mit | 2,971 |
//------------------------------------------------------------------------------
// <copyright file="XmlReservedNS.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml {
/// <summary>
/// This class defines a set of common XML namespaces for sharing across multiple source files.
/// </summary>
internal static class XmlReservedNs {
internal const string NsXml = "http://www.w3.org/XML/1998/namespace";
internal const string NsXmlNs = "http://www.w3.org/2000/xmlns/";
#if !SILVERLIGHT // These strings are not needed in Silverlight
internal const string NsDataType = "urn:schemas-microsoft-com:datatypes";
internal const string NsDataTypeAlias = "uuid:C2F41010-65B3-11D1-A29F-00AA00C14882";
internal const string NsDataTypeOld = "urn:uuid:C2F41010-65B3-11D1-A29F-00AA00C14882/";
internal const string NsMsxsl = "urn:schemas-microsoft-com:xslt";
internal const string NsXdr = "urn:schemas-microsoft-com:xml-data";
internal const string NsXslDebug = "urn:schemas-microsoft-com:xslt-debug";
internal const string NsXdrAlias = "uuid:BDC6E3F0-6DA3-11D1-A2A3-00AA00C14882";
internal const string NsWdXsl = "http://www.w3.org/TR/WD-xsl";
internal const string NsXs = "http://www.w3.org/2001/XMLSchema";
internal const string NsXsd = "http://www.w3.org/2001/XMLSchema-datatypes";
internal const string NsXsi = "http://www.w3.org/2001/XMLSchema-instance";
internal const string NsXslt = "http://www.w3.org/1999/XSL/Transform";
internal const string NsExsltCommon = "http://exslt.org/common";
internal const string NsExsltDates = "http://exslt.org/dates-and-times";
internal const string NsExsltMath = "http://exslt.org/math";
internal const string NsExsltRegExps = "http://exslt.org/regular-expressions";
internal const string NsExsltSets = "http://exslt.org/sets";
internal const string NsExsltStrings = "http://exslt.org/strings";
internal const string NsXQueryFunc = "http://www.w3.org/2003/11/xpath-functions";
internal const string NsXQueryDataType = "http://www.w3.org/2003/11/xpath-datatypes";
internal const string NsCollationBase = "http://collations.microsoft.com";
internal const string NsCollCodePoint = "http://www.w3.org/2004/10/xpath-functions/collation/codepoint";
internal const string NsXsltInternal = "http://schemas.microsoft.com/framework/2003/xml/xslt/internal";
#endif
};
}
| sekcheong/referencesource | System.Xml/System/Xml/XmlReservedNs.cs | C# | mit | 2,890 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ReflectiveInjector, ɵglobal as global} from '@angular/core';
import {ApplicationRef, ApplicationRef_} from '@angular/core/src/application_ref';
import {SpyObject} from '@angular/core/testing/src/testing_internal';
export class SpyApplicationRef extends SpyObject {
constructor() { super(ApplicationRef_); }
}
export class SpyComponentRef extends SpyObject {
injector: any /** TODO #9100 */;
constructor() {
super();
this.injector = ReflectiveInjector.resolveAndCreate(
[{provide: ApplicationRef, useClass: SpyApplicationRef}]);
}
}
export function callNgProfilerTimeChangeDetection(config?: any /** TODO #9100 */): void {
(<any>global).ng.profiler.timeChangeDetection(config);
}
| souvikbasu/angular | packages/platform-browser/test/browser/tools/spies.ts | TypeScript | mit | 921 |
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com>
#include "Debug.h"
#include "Array.inl"
#include "StrLib.h" // StringBuilder
#include "StdStream.h" // fileOpen
#include <stdlib.h>
// Extern
#if NV_OS_WIN32 //&& NV_CC_MSVC
# define WIN32_LEAN_AND_MEAN
# define VC_EXTRALEAN
# include <windows.h>
# include <direct.h>
# if NV_CC_MSVC
# include <crtdbg.h>
# if _MSC_VER < 1300
# define DECLSPEC_DEPRECATED
// VC6: change this path to your Platform SDK headers
# include <dbghelp.h> // must be XP version of file
// include "M:\\dev7\\vs\\devtools\\common\\win32sdk\\include\\dbghelp.h"
# else
// VC7: ships with updated headers
# include <dbghelp.h>
# endif
# endif
# pragma comment(lib,"dbghelp.lib")
#endif
#if NV_OS_XBOX
# include <Xtl.h>
# ifdef _DEBUG
# include <xbdm.h>
# endif //_DEBUG
#endif //NV_OS_XBOX
#if !NV_OS_WIN32 && defined(HAVE_SIGNAL_H)
# include <signal.h>
#endif
#if NV_OS_UNIX
# include <unistd.h> // getpid
#endif
#if NV_OS_LINUX && defined(HAVE_EXECINFO_H)
# include <execinfo.h> // backtrace
# if NV_CC_GNUC // defined(HAVE_CXXABI_H)
# include <cxxabi.h>
# endif
#endif
#if NV_OS_DARWIN || NV_OS_FREEBSD || NV_OS_OPENBSD
# include <sys/types.h>
# include <sys/param.h>
# include <sys/sysctl.h> // sysctl
# if !defined(NV_OS_OPENBSD)
# include <sys/ucontext.h>
# endif
# if defined(HAVE_EXECINFO_H) // only after OSX 10.5
# include <execinfo.h> // backtrace
# if NV_CC_GNUC // defined(HAVE_CXXABI_H)
# include <cxxabi.h>
# endif
# endif
#endif
#if NV_OS_ORBIS
#include <libdbg.h>
#endif
#define NV_USE_SEPARATE_THREAD 1
using namespace nv;
namespace
{
static MessageHandler * s_message_handler = NULL;
static AssertHandler * s_assert_handler = NULL;
static bool s_sig_handler_enabled = false;
static bool s_interactive = true;
#if NV_OS_WIN32 && NV_CC_MSVC
// Old exception filter.
static LPTOP_LEVEL_EXCEPTION_FILTER s_old_exception_filter = NULL;
#elif !NV_OS_WIN32 && defined(HAVE_SIGNAL_H)
// Old signal handlers.
struct sigaction s_old_sigsegv;
struct sigaction s_old_sigtrap;
struct sigaction s_old_sigfpe;
struct sigaction s_old_sigbus;
#endif
#if NV_OS_WIN32 && NV_CC_MSVC
// We should try to simplify the top level filter as much as possible.
// http://www.nynaeve.net/?p=128
#if NV_USE_SEPARATE_THREAD
// The critical section enforcing the requirement that only one exception be
// handled by a handler at a time.
static CRITICAL_SECTION s_handler_critical_section;
// Semaphores used to move exception handling between the exception thread
// and the handler thread. handler_start_semaphore_ is signalled by the
// exception thread to wake up the handler thread when an exception occurs.
// handler_finish_semaphore_ is signalled by the handler thread to wake up
// the exception thread when handling is complete.
static HANDLE s_handler_start_semaphore = NULL;
static HANDLE s_handler_finish_semaphore = NULL;
// The exception handler thread.
static HANDLE s_handler_thread = NULL;
static DWORD s_requesting_thread_id = 0;
static EXCEPTION_POINTERS * s_exception_info = NULL;
#endif // NV_USE_SEPARATE_THREAD
struct MinidumpCallbackContext {
ULONG64 memory_base;
ULONG memory_size;
bool finished;
};
// static
static BOOL CALLBACK miniDumpWriteDumpCallback(PVOID context, const PMINIDUMP_CALLBACK_INPUT callback_input, PMINIDUMP_CALLBACK_OUTPUT callback_output)
{
switch (callback_input->CallbackType)
{
case MemoryCallback: {
MinidumpCallbackContext* callback_context = reinterpret_cast<MinidumpCallbackContext*>(context);
if (callback_context->finished)
return FALSE;
// Include the specified memory region.
callback_output->MemoryBase = callback_context->memory_base;
callback_output->MemorySize = callback_context->memory_size;
callback_context->finished = true;
return TRUE;
}
// Include all modules.
case IncludeModuleCallback:
case ModuleCallback:
return TRUE;
// Include all threads.
case IncludeThreadCallback:
case ThreadCallback:
return TRUE;
// Stop receiving cancel callbacks.
case CancelCallback:
callback_output->CheckCancel = FALSE;
callback_output->Cancel = FALSE;
return TRUE;
}
// Ignore other callback types.
return FALSE;
}
static bool writeMiniDump(EXCEPTION_POINTERS * pExceptionInfo)
{
// create the file
HANDLE hFile = CreateFileA("crash.dmp", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
//nvDebug("*** Failed to create dump file.\n");
return false;
}
MINIDUMP_EXCEPTION_INFORMATION * pExInfo = NULL;
MINIDUMP_CALLBACK_INFORMATION * pCallback = NULL;
if (pExceptionInfo != NULL) {
MINIDUMP_EXCEPTION_INFORMATION ExInfo;
ExInfo.ThreadId = ::GetCurrentThreadId();
ExInfo.ExceptionPointers = pExceptionInfo;
ExInfo.ClientPointers = NULL;
pExInfo = &ExInfo;
MINIDUMP_CALLBACK_INFORMATION callback;
MinidumpCallbackContext context;
// Find a memory region of 256 bytes centered on the
// faulting instruction pointer.
const ULONG64 instruction_pointer =
#if defined(_M_IX86)
pExceptionInfo->ContextRecord->Eip;
#elif defined(_M_AMD64)
pExceptionInfo->ContextRecord->Rip;
#else
#error Unsupported platform
#endif
MEMORY_BASIC_INFORMATION info;
if (VirtualQuery(reinterpret_cast<LPCVOID>(instruction_pointer), &info, sizeof(MEMORY_BASIC_INFORMATION)) != 0 && info.State == MEM_COMMIT)
{
// Attempt to get 128 bytes before and after the instruction
// pointer, but settle for whatever's available up to the
// boundaries of the memory region.
const ULONG64 kIPMemorySize = 256;
context.memory_base = max(reinterpret_cast<ULONG64>(info.BaseAddress), instruction_pointer - (kIPMemorySize / 2));
ULONG64 end_of_range = min(instruction_pointer + (kIPMemorySize / 2), reinterpret_cast<ULONG64>(info.BaseAddress) + info.RegionSize);
context.memory_size = static_cast<ULONG>(end_of_range - context.memory_base);
context.finished = false;
callback.CallbackRoutine = miniDumpWriteDumpCallback;
callback.CallbackParam = reinterpret_cast<void*>(&context);
pCallback = &callback;
}
}
MINIDUMP_TYPE miniDumpType = (MINIDUMP_TYPE)(MiniDumpNormal|MiniDumpWithHandleData|MiniDumpWithThreadInfo);
// write the dump
BOOL ok = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, miniDumpType, pExInfo, NULL, pCallback) != 0;
CloseHandle(hFile);
if (ok == FALSE) {
//nvDebug("*** Failed to save dump file.\n");
return false;
}
//nvDebug("\nDump file saved.\n");
return true;
}
#if NV_USE_SEPARATE_THREAD
static DWORD WINAPI ExceptionHandlerThreadMain(void* lpParameter) {
nvDebugCheck(s_handler_start_semaphore != NULL);
nvDebugCheck(s_handler_finish_semaphore != NULL);
while (true) {
if (WaitForSingleObject(s_handler_start_semaphore, INFINITE) == WAIT_OBJECT_0) {
writeMiniDump(s_exception_info);
// Allow the requesting thread to proceed.
ReleaseSemaphore(s_handler_finish_semaphore, 1, NULL);
}
}
// This statement is not reached when the thread is unconditionally
// terminated by the ExceptionHandler destructor.
return 0;
}
#endif // NV_USE_SEPARATE_THREAD
static bool hasStackTrace() {
return true;
}
/*static NV_NOINLINE int backtrace(void * trace[], int maxcount) {
// In Windows XP and Windows Server 2003, the sum of the FramesToSkip and FramesToCapture parameters must be less than 63.
int xp_maxcount = min(63-1, maxcount);
int count = RtlCaptureStackBackTrace(1, xp_maxcount, trace, NULL);
nvDebugCheck(count <= maxcount);
return count;
}*/
static NV_NOINLINE int backtraceWithSymbols(CONTEXT * ctx, void * trace[], int maxcount, int skip = 0) {
// Init the stack frame for this function
STACKFRAME64 stackFrame = { 0 };
#if NV_CPU_X86_64
DWORD dwMachineType = IMAGE_FILE_MACHINE_AMD64;
stackFrame.AddrPC.Offset = ctx->Rip;
stackFrame.AddrFrame.Offset = ctx->Rbp;
stackFrame.AddrStack.Offset = ctx->Rsp;
#elif NV_CPU_X86
DWORD dwMachineType = IMAGE_FILE_MACHINE_I386;
stackFrame.AddrPC.Offset = ctx->Eip;
stackFrame.AddrFrame.Offset = ctx->Ebp;
stackFrame.AddrStack.Offset = ctx->Esp;
#else
#error "Platform not supported!"
#endif
stackFrame.AddrPC.Mode = AddrModeFlat;
stackFrame.AddrFrame.Mode = AddrModeFlat;
stackFrame.AddrStack.Mode = AddrModeFlat;
// Walk up the stack
const HANDLE hThread = GetCurrentThread();
const HANDLE hProcess = GetCurrentProcess();
int i;
for (i = 0; i < maxcount; i++)
{
// walking once first makes us skip self
if (!StackWalk64(dwMachineType, hProcess, hThread, &stackFrame, ctx, NULL, &SymFunctionTableAccess64, &SymGetModuleBase64, NULL)) {
break;
}
/*if (stackFrame.AddrPC.Offset == stackFrame.AddrReturn.Offset || stackFrame.AddrPC.Offset == 0) {
break;
}*/
if (i >= skip) {
trace[i - skip] = (PVOID)stackFrame.AddrPC.Offset;
}
}
return i - skip;
}
#pragma warning(push)
#pragma warning(disable:4748)
static NV_NOINLINE int backtrace(void * trace[], int maxcount) {
CONTEXT ctx = { 0 };
#if NV_CPU_X86 && !NV_CPU_X86_64
ctx.ContextFlags = CONTEXT_CONTROL;
_asm {
call x
x: pop eax
mov ctx.Eip, eax
mov ctx.Ebp, ebp
mov ctx.Esp, esp
}
#else
RtlCaptureContext(&ctx); // Not implemented correctly in x86.
#endif
return backtraceWithSymbols(&ctx, trace, maxcount, 1);
}
#pragma warning(pop)
static NV_NOINLINE void writeStackTrace(void * trace[], int size, int start, Array<const char *> & lines)
{
StringBuilder builder(512);
HANDLE hProcess = GetCurrentProcess();
// Resolve PC to function names
for (int i = start; i < size; i++)
{
// Check for end of stack walk
DWORD64 ip = (DWORD64)trace[i];
if (ip == NULL)
break;
// Get function name
#define MAX_STRING_LEN (512)
unsigned char byBuffer[sizeof(IMAGEHLP_SYMBOL64) + MAX_STRING_LEN] = { 0 };
IMAGEHLP_SYMBOL64 * pSymbol = (IMAGEHLP_SYMBOL64*)byBuffer;
pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
pSymbol->MaxNameLength = MAX_STRING_LEN;
DWORD64 dwDisplacement;
if (SymGetSymFromAddr64(hProcess, ip, &dwDisplacement, pSymbol))
{
pSymbol->Name[MAX_STRING_LEN-1] = 0;
/*
// Make the symbol readable for humans
UnDecorateSymbolName( pSym->Name, lpszNonUnicodeUnDSymbol, BUFFERSIZE,
UNDNAME_COMPLETE |
UNDNAME_NO_THISTYPE |
UNDNAME_NO_SPECIAL_SYMS |
UNDNAME_NO_MEMBER_TYPE |
UNDNAME_NO_MS_KEYWORDS |
UNDNAME_NO_ACCESS_SPECIFIERS );
*/
// pSymbol->Name
const char * pFunc = pSymbol->Name;
// Get file/line number
IMAGEHLP_LINE64 theLine = { 0 };
theLine.SizeOfStruct = sizeof(theLine);
DWORD dwDisplacement;
if (!SymGetLineFromAddr64(hProcess, ip, &dwDisplacement, &theLine))
{
// Do not print unknown symbols anymore.
break;
//builder.format("unknown(%08X) : %s\n", (uint32)ip, pFunc);
}
else
{
/*
const char* pFile = strrchr(theLine.FileName, '\\');
if ( pFile == NULL ) pFile = theLine.FileName;
else pFile++;
*/
const char * pFile = theLine.FileName;
int line = theLine.LineNumber;
builder.format("%s(%d) : %s\n", pFile, line, pFunc);
}
lines.append(builder.release());
if (pFunc != NULL && strcmp(pFunc, "WinMain") == 0) {
break;
}
}
}
}
// Write mini dump and print stack trace.
static LONG WINAPI handleException(EXCEPTION_POINTERS * pExceptionInfo)
{
EnterCriticalSection(&s_handler_critical_section);
#if NV_USE_SEPARATE_THREAD
s_requesting_thread_id = GetCurrentThreadId();
s_exception_info = pExceptionInfo;
// This causes the handler thread to call writeMiniDump.
ReleaseSemaphore(s_handler_start_semaphore, 1, NULL);
// Wait until WriteMinidumpWithException is done and collect its return value.
WaitForSingleObject(s_handler_finish_semaphore, INFINITE);
//bool status = s_handler_return_value;
// Clean up.
s_requesting_thread_id = 0;
s_exception_info = NULL;
#else
// First of all, write mini dump.
writeMiniDump(pExceptionInfo);
#endif
LeaveCriticalSection(&s_handler_critical_section);
nvDebug("\nDump file saved.\n");
// Try to attach to debugger.
if (s_interactive && debug::attachToDebugger()) {
nvDebugBreak();
return EXCEPTION_CONTINUE_EXECUTION;
}
// If that fails, then try to pretty print a stack trace and terminate.
void * trace[64];
int size = backtraceWithSymbols(pExceptionInfo->ContextRecord, trace, 64);
// @@ Use win32's CreateFile?
FILE * fp = fileOpen("crash.txt", "wb");
if (fp != NULL) {
Array<const char *> lines;
writeStackTrace(trace, size, 0, lines);
for (uint i = 0; i < lines.count(); i++) {
fputs(lines[i], fp);
delete lines[i];
}
// @@ Add more info to crash.txt?
fclose(fp);
}
// This should terminate the process and set the error exit code.
TerminateProcess(GetCurrentProcess(), EXIT_FAILURE + 2);
return EXCEPTION_EXECUTE_HANDLER; // Terminate app. In case terminate process did not succeed.
}
static void handlePureVirtualCall() {
nvDebugBreak();
TerminateProcess(GetCurrentProcess(), EXIT_FAILURE + 8);
}
static void handleInvalidParameter(const wchar_t * wexpresion, const wchar_t * wfunction, const wchar_t * wfile, unsigned int line, uintptr_t reserved) {
size_t convertedCharCount = 0;
StringBuilder expresion;
if (wexpresion != NULL) {
uint size = U32(wcslen(wexpresion) + 1);
expresion.reserve(size);
wcstombs_s(&convertedCharCount, expresion.str(), size, wexpresion, _TRUNCATE);
}
StringBuilder file;
if (wfile != NULL) {
uint size = U32(wcslen(wfile) + 1);
file.reserve(size);
wcstombs_s(&convertedCharCount, file.str(), size, wfile, _TRUNCATE);
}
StringBuilder function;
if (wfunction != NULL) {
uint size = U32(wcslen(wfunction) + 1);
function.reserve(size);
wcstombs_s(&convertedCharCount, function.str(), size, wfunction, _TRUNCATE);
}
int result = nvAbort(expresion.str(), file.str(), line, function.str());
if (result == NV_ABORT_DEBUG) {
nvDebugBreak();
}
}
#elif !NV_OS_WIN32 && defined(HAVE_SIGNAL_H) // NV_OS_LINUX || NV_OS_DARWIN
#if defined(HAVE_EXECINFO_H)
static bool hasStackTrace() {
#if NV_OS_DARWIN
return backtrace != NULL;
#else
return true;
#endif
}
static void writeStackTrace(void * trace[], int size, int start, Array<const char *> & lines) {
StringBuilder builder(512);
char ** string_array = backtrace_symbols(trace, size);
for(int i = start; i < size-1; i++ ) {
# if NV_CC_GNUC // defined(HAVE_CXXABI_H)
// @@ Write a better parser for the possible formats.
char * begin = strchr(string_array[i], '(');
char * end = strrchr(string_array[i], '+');
char * module = string_array[i];
if (begin == 0 && end != 0) {
*(end - 1) = '\0';
begin = strrchr(string_array[i], ' ');
module = NULL; // Ignore module.
}
if (begin != 0 && begin < end) {
int stat;
*end = '\0';
*begin = '\0';
char * name = abi::__cxa_demangle(begin+1, 0, 0, &stat);
if (module == NULL) {
if (name == NULL || stat != 0) {
builder.format(" In: '%s'\n", begin+1);
}
else {
builder.format(" In: '%s'\n", name);
}
}
else {
if (name == NULL || stat != 0) {
builder.format(" In: [%s] '%s'\n", module, begin+1);
}
else {
builder.format(" In: [%s] '%s'\n", module, name);
}
}
free(name);
}
else {
builder.format(" In: '%s'\n", string_array[i]);
}
# else
builder.format(" In: '%s'\n", string_array[i]);
# endif
lines.append(builder.release());
}
free(string_array);
}
static void printStackTrace(void * trace[], int size, int start=0) {
nvDebug( "\nDumping stacktrace:\n" );
Array<const char *> lines;
writeStackTrace(trace, size, 1, lines);
for (uint i = 0; i < lines.count(); i++) {
nvDebug(lines[i]);
delete lines[i];
}
nvDebug("\n");
}
#endif // defined(HAVE_EXECINFO_H)
static void * callerAddress(void * secret)
{
#if NV_OS_DARWIN
# if defined(_STRUCT_MCONTEXT)
# if NV_CPU_PPC
ucontext_t * ucp = (ucontext_t *)secret;
return (void *) ucp->uc_mcontext->__ss.__srr0;
# elif NV_CPU_X86_64
ucontext_t * ucp = (ucontext_t *)secret;
return (void *) ucp->uc_mcontext->__ss.__rip;
# elif NV_CPU_X86
ucontext_t * ucp = (ucontext_t *)secret;
return (void *) ucp->uc_mcontext->__ss.__eip;
# elif NV_CPU_ARM
ucontext_t * ucp = (ucontext_t *)secret;
return (void *) ucp->uc_mcontext->__ss.__pc;
# else
# error "Unknown CPU"
# endif
# else
# if NV_CPU_PPC
ucontext_t * ucp = (ucontext_t *)secret;
return (void *) ucp->uc_mcontext->ss.srr0;
# elif NV_CPU_X86
ucontext_t * ucp = (ucontext_t *)secret;
return (void *) ucp->uc_mcontext->ss.eip;
# else
# error "Unknown CPU"
# endif
# endif
#elif NV_OS_FREEBSD
# if NV_CPU_X86_64
ucontext_t * ucp = (ucontext_t *)secret;
return (void *)ucp->uc_mcontext.mc_rip;
# elif NV_CPU_X86
ucontext_t * ucp = (ucontext_t *)secret;
return (void *)ucp->uc_mcontext.mc_eip;
# else
# error "Unknown CPU"
# endif
#elif NV_OS_OPENBSD
# if NV_CPU_X86_64
ucontext_t * ucp = (ucontext_t *)secret;
return (void *)ucp->sc_rip;
# elif NV_CPU_X86
ucontext_t * ucp = (ucontext_t *)secret;
return (void *)ucp->sc_eip;
# else
# error "Unknown CPU"
# endif
#else
# if NV_CPU_X86_64
// #define REG_RIP REG_INDEX(rip) // seems to be 16
ucontext_t * ucp = (ucontext_t *)secret;
return (void *)ucp->uc_mcontext.gregs[REG_RIP];
# elif NV_CPU_X86
ucontext_t * ucp = (ucontext_t *)secret;
return (void *)ucp->uc_mcontext.gregs[14/*REG_EIP*/];
# elif NV_CPU_PPC
ucontext_t * ucp = (ucontext_t *)secret;
return (void *) ucp->uc_mcontext.regs->nip;
# else
# error "Unknown CPU"
# endif
#endif
// How to obtain the instruction pointers in different platforms, from mlton's source code.
// http://mlton.org/
// OpenBSD && NetBSD
// ucp->sc_eip
// FreeBSD:
// ucp->uc_mcontext.mc_eip
// HPUX:
// ucp->uc_link
// Solaris:
// ucp->uc_mcontext.gregs[REG_PC]
// Linux hppa:
// uc->uc_mcontext.sc_iaoq[0] & ~0x3UL
// Linux sparc:
// ((struct sigcontext*) secret)->sigc_regs.tpc
// Linux sparc64:
// ((struct sigcontext*) secret)->si_regs.pc
// potentially correct for other archs:
// Linux alpha: ucp->m_context.sc_pc
// Linux arm: ucp->m_context.ctx.arm_pc
// Linux ia64: ucp->m_context.sc_ip & ~0x3UL
// Linux mips: ucp->m_context.sc_pc
// Linux s390: ucp->m_context.sregs->regs.psw.addr
}
static void nvSigHandler(int sig, siginfo_t *info, void *secret)
{
void * pnt = callerAddress(secret);
// Do something useful with siginfo_t
if (sig == SIGSEGV) {
if (pnt != NULL) nvDebug("Got signal %d, faulty address is %p, from %p\n", sig, info->si_addr, pnt);
else nvDebug("Got signal %d, faulty address is %p\n", sig, info->si_addr);
}
else if(sig == SIGTRAP) {
nvDebug("Breakpoint hit.\n");
}
else {
nvDebug("Got signal %d\n", sig);
}
#if defined(HAVE_EXECINFO_H)
if (hasStackTrace()) // in case of weak linking
{
void * trace[64];
int size = backtrace(trace, 64);
if (pnt != NULL) {
// Overwrite sigaction with caller's address.
trace[1] = pnt;
}
printStackTrace(trace, size, 1);
}
#endif // defined(HAVE_EXECINFO_H)
exit(0);
}
#endif // defined(HAVE_SIGNAL_H)
#if NV_OS_WIN32 //&& NV_CC_MSVC
/** Win32 assert handler. */
struct Win32AssertHandler : public AssertHandler
{
// Flush the message queue. This is necessary for the message box to show up.
static void flushMessageQueue()
{
MSG msg;
while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) {
//if( msg.message == WM_QUIT ) break;
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
// Assert handler method.
virtual int assertion(const char * exp, const char * file, int line, const char * func, const char * msg, va_list arg)
{
int ret = NV_ABORT_EXIT;
StringBuilder error_string;
error_string.format("*** Assertion failed: %s\n On file: %s\n On line: %d\n", exp, file, line );
if (func != NULL) {
error_string.appendFormat(" On function: %s\n", func);
}
if (msg != NULL) {
error_string.append(" Message: ");
va_list tmp;
va_copy(tmp, arg);
error_string.appendFormatList(msg, tmp);
va_end(tmp);
error_string.append("\n");
}
nvDebug( error_string.str() );
// Print stack trace:
debug::dumpInfo();
if (debug::isDebuggerPresent()) {
return NV_ABORT_DEBUG;
}
if (s_interactive) {
flushMessageQueue();
int action = MessageBoxA(NULL, error_string.str(), "Assertion failed", MB_ABORTRETRYIGNORE | MB_ICONERROR | MB_TOPMOST);
switch( action ) {
case IDRETRY:
ret = NV_ABORT_DEBUG;
break;
case IDIGNORE:
ret = NV_ABORT_IGNORE;
break;
case IDABORT:
default:
ret = NV_ABORT_EXIT;
break;
}
/*if( _CrtDbgReport( _CRT_ASSERT, file, line, module, exp ) == 1 ) {
return NV_ABORT_DEBUG;
}*/
}
if (ret == NV_ABORT_EXIT) {
// Exit cleanly.
exit(EXIT_FAILURE + 1);
}
return ret;
}
};
#elif NV_OS_XBOX
/** Xbox360 assert handler. */
struct Xbox360AssertHandler : public AssertHandler
{
// Assert handler method.
virtual int assertion(const char * exp, const char * file, int line, const char * func, const char * msg, va_list arg)
{
int ret = NV_ABORT_EXIT;
StringBuilder error_string;
if( func != NULL ) {
error_string.format( "*** Assertion failed: %s\n On file: %s\n On function: %s\n On line: %d\n ", exp, file, func, line );
nvDebug( error_string.str() );
}
else {
error_string.format( "*** Assertion failed: %s\n On file: %s\n On line: %d\n ", exp, file, line );
nvDebug( error_string.str() );
}
if (debug::isDebuggerPresent()) {
return NV_ABORT_DEBUG;
}
if( ret == NV_ABORT_EXIT ) {
// Exit cleanly.
exit(EXIT_FAILURE + 1);
}
return ret;
}
};
#elif NV_OS_ORBIS
/** Orbis assert handler. */
struct OrbisAssertHandler : public AssertHandler
{
// Assert handler method.
virtual int assertion(const char * exp, const char * file, int line, const char * func, const char * msg, va_list arg)
{
if( func != NULL ) {
nvDebug( "*** Assertion failed: %s\n On file: %s\n On function: %s\n On line: %d\n ", exp, file, func, line );
}
else {
nvDebug( "*** Assertion failed: %s\n On file: %s\n On line: %d\n ", exp, file, line );
}
//SBtodoORBIS print stack trace
/*if (hasStackTrace())
{
void * trace[64];
int size = backtrace(trace, 64);
printStackTrace(trace, size, 2);
}*/
if (debug::isDebuggerPresent())
return NV_ABORT_DEBUG;
return NV_ABORT_IGNORE;
}
};
#else
/** Unix assert handler. */
struct UnixAssertHandler : public AssertHandler
{
// Assert handler method.
virtual int assertion(const char * exp, const char * file, int line, const char * func, const char * msg, va_list arg)
{
int ret = NV_ABORT_EXIT;
if( func != NULL ) {
nvDebug( "*** Assertion failed: %s\n On file: %s\n On function: %s\n On line: %d\n ", exp, file, func, line );
}
else {
nvDebug( "*** Assertion failed: %s\n On file: %s\n On line: %d\n ", exp, file, line );
}
#if _DEBUG
if (debug::isDebuggerPresent()) {
return NV_ABORT_DEBUG;
}
#endif
#if defined(HAVE_EXECINFO_H)
if (hasStackTrace())
{
void * trace[64];
int size = backtrace(trace, 64);
printStackTrace(trace, size, 2);
}
#endif
if( ret == NV_ABORT_EXIT ) {
// Exit cleanly.
exit(EXIT_FAILURE + 1);
}
return ret;
}
};
#endif
} // namespace
/// Handle assertion through the assert handler.
int nvAbort(const char * exp, const char * file, int line, const char * func/*=NULL*/, const char * msg/*= NULL*/, ...)
{
#if NV_OS_WIN32 //&& NV_CC_MSVC
static Win32AssertHandler s_default_assert_handler;
#elif NV_OS_XBOX
static Xbox360AssertHandler s_default_assert_handler;
#elif NV_OS_ORBIS
static OrbisAssertHandler s_default_assert_handler;
#else
static UnixAssertHandler s_default_assert_handler;
#endif
va_list arg;
va_start(arg,msg);
AssertHandler * handler = s_assert_handler != NULL ? s_assert_handler : &s_default_assert_handler;
int result = handler->assertion(exp, file, line, func, msg, arg);
va_end(arg);
return result;
}
// Abnormal termination. Create mini dump and output call stack.
void debug::terminate(int code)
{
#if NV_OS_WIN32
EnterCriticalSection(&s_handler_critical_section);
writeMiniDump(NULL);
const int max_stack_size = 64;
void * trace[max_stack_size];
int size = backtrace(trace, max_stack_size);
// @@ Use win32's CreateFile?
FILE * fp = fileOpen("crash.txt", "wb");
if (fp != NULL) {
Array<const char *> lines;
writeStackTrace(trace, size, 0, lines);
for (uint i = 0; i < lines.count(); i++) {
fputs(lines[i], fp);
delete lines[i];
}
// @@ Add more info to crash.txt?
fclose(fp);
}
LeaveCriticalSection(&s_handler_critical_section);
#endif
exit(code);
}
/// Shows a message through the message handler.
void NV_CDECL nvDebugPrint(const char *msg, ...)
{
va_list arg;
va_start(arg,msg);
if (s_message_handler != NULL) {
s_message_handler->log( msg, arg );
}
va_end(arg);
}
/// Dump debug info.
void debug::dumpInfo()
{
#if (NV_OS_WIN32 && NV_CC_MSVC) || (defined(HAVE_SIGNAL_H) && defined(HAVE_EXECINFO_H))
if (hasStackTrace())
{
void * trace[64];
int size = backtrace(trace, 64);
nvDebug( "\nDumping stacktrace:\n" );
Array<const char *> lines;
writeStackTrace(trace, size, 1, lines);
for (uint i = 0; i < lines.count(); i++) {
nvDebug(lines[i]);
delete lines[i];
}
}
#endif
}
/// Dump callstack using the specified handler.
void debug::dumpCallstack(MessageHandler *messageHandler, int callstackLevelsToSkip /*= 0*/)
{
#if (NV_OS_WIN32 && NV_CC_MSVC) || (defined(HAVE_SIGNAL_H) && defined(HAVE_EXECINFO_H))
if (hasStackTrace())
{
void * trace[64];
int size = backtrace(trace, 64);
Array<const char *> lines;
writeStackTrace(trace, size, callstackLevelsToSkip + 1, lines); // + 1 to skip the call to dumpCallstack
for (uint i = 0; i < lines.count(); i++) {
messageHandler->log(lines[i], NULL);
delete lines[i];
}
}
#endif
}
/// Set the debug message handler.
void debug::setMessageHandler(MessageHandler * message_handler)
{
s_message_handler = message_handler;
}
/// Reset the debug message handler.
void debug::resetMessageHandler()
{
s_message_handler = NULL;
}
/// Set the assert handler.
void debug::setAssertHandler(AssertHandler * assert_handler)
{
s_assert_handler = assert_handler;
}
/// Reset the assert handler.
void debug::resetAssertHandler()
{
s_assert_handler = NULL;
}
#if NV_OS_WIN32
#if NV_USE_SEPARATE_THREAD
static void initHandlerThread()
{
static const int kExceptionHandlerThreadInitialStackSize = 64 * 1024;
// Set synchronization primitives and the handler thread. Each
// ExceptionHandler object gets its own handler thread because that's the
// only way to reliably guarantee sufficient stack space in an exception,
// and it allows an easy way to get a snapshot of the requesting thread's
// context outside of an exception.
InitializeCriticalSection(&s_handler_critical_section);
s_handler_start_semaphore = CreateSemaphore(NULL, 0, 1, NULL);
nvDebugCheck(s_handler_start_semaphore != NULL);
s_handler_finish_semaphore = CreateSemaphore(NULL, 0, 1, NULL);
nvDebugCheck(s_handler_finish_semaphore != NULL);
// Don't attempt to create the thread if we could not create the semaphores.
if (s_handler_finish_semaphore != NULL && s_handler_start_semaphore != NULL) {
DWORD thread_id;
s_handler_thread = CreateThread(NULL, // lpThreadAttributes
kExceptionHandlerThreadInitialStackSize,
ExceptionHandlerThreadMain,
NULL, // lpParameter
0, // dwCreationFlags
&thread_id);
nvDebugCheck(s_handler_thread != NULL);
}
/* @@ We should avoid loading modules in the exception handler!
dbghelp_module_ = LoadLibrary(L"dbghelp.dll");
if (dbghelp_module_) {
minidump_write_dump_ = reinterpret_cast<MiniDumpWriteDump_type>(GetProcAddress(dbghelp_module_, "MiniDumpWriteDump"));
}
*/
}
static void shutHandlerThread() {
// @@ Free stuff. Terminate thread.
}
#endif // NV_USE_SEPARATE_THREAD
#endif // NV_OS_WIN32
// Enable signal handler.
void debug::enableSigHandler(bool interactive)
{
nvCheck(s_sig_handler_enabled != true);
s_sig_handler_enabled = true;
s_interactive = interactive;
#if NV_OS_WIN32 && NV_CC_MSVC
if (interactive) {
// Do not display message boxes on error.
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621(v=vs.85).aspx
SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX);
// CRT reports errors to debug output only.
// http://msdn.microsoft.com/en-us/library/1y71x448(v=vs.80).aspx
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
}
#if NV_USE_SEPARATE_THREAD
initHandlerThread();
#endif
s_old_exception_filter = ::SetUnhandledExceptionFilter( handleException );
#if _MSC_VER >= 1400 // MSVC 2005/8
_set_invalid_parameter_handler(handleInvalidParameter);
#endif // _MSC_VER >= 1400
_set_purecall_handler(handlePureVirtualCall);
// SYMOPT_DEFERRED_LOADS make us not take a ton of time unless we actual log traces
SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_FAIL_CRITICAL_ERRORS|SYMOPT_LOAD_LINES|SYMOPT_UNDNAME);
if (!SymInitialize(GetCurrentProcess(), NULL, TRUE)) {
DWORD error = GetLastError();
nvDebug("SymInitialize returned error : %d\n", error);
}
#elif !NV_OS_WIN32 && defined(HAVE_SIGNAL_H)
// Install our signal handler
struct sigaction sa;
sa.sa_sigaction = nvSigHandler;
sigemptyset (&sa.sa_mask);
sa.sa_flags = SA_ONSTACK | SA_RESTART | SA_SIGINFO;
sigaction(SIGSEGV, &sa, &s_old_sigsegv);
sigaction(SIGTRAP, &sa, &s_old_sigtrap);
sigaction(SIGFPE, &sa, &s_old_sigfpe);
sigaction(SIGBUS, &sa, &s_old_sigbus);
#endif
}
/// Disable signal handler.
void debug::disableSigHandler()
{
nvCheck(s_sig_handler_enabled == true);
s_sig_handler_enabled = false;
#if NV_OS_WIN32 && NV_CC_MSVC
::SetUnhandledExceptionFilter( s_old_exception_filter );
s_old_exception_filter = NULL;
SymCleanup(GetCurrentProcess());
#elif !NV_OS_WIN32 && defined(HAVE_SIGNAL_H)
sigaction(SIGSEGV, &s_old_sigsegv, NULL);
sigaction(SIGTRAP, &s_old_sigtrap, NULL);
sigaction(SIGFPE, &s_old_sigfpe, NULL);
sigaction(SIGBUS, &s_old_sigbus, NULL);
#endif
}
bool debug::isDebuggerPresent()
{
#if NV_OS_WIN32
HINSTANCE kernel32 = GetModuleHandleA("kernel32.dll");
if (kernel32) {
FARPROC IsDebuggerPresent = GetProcAddress(kernel32, "IsDebuggerPresent");
if (IsDebuggerPresent != NULL && IsDebuggerPresent()) {
return true;
}
}
return false;
#elif NV_OS_XBOX
#ifdef _DEBUG
return DmIsDebuggerPresent() == TRUE;
#else
return false;
#endif
#elif NV_OS_ORBIS
#if PS4_FINAL_REQUIREMENTS
return false;
#else
return sceDbgIsDebuggerAttached() == 1;
#endif
#elif NV_OS_DARWIN
int mib[4];
struct kinfo_proc info;
size_t size;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PID;
mib[3] = getpid();
size = sizeof(info);
info.kp_proc.p_flag = 0;
sysctl(mib,4,&info,&size,NULL,0);
return ((info.kp_proc.p_flag & P_TRACED) == P_TRACED);
#else
// if ppid != sid, some process spawned our app, probably a debugger.
return getsid(getpid()) != getppid();
#endif
}
bool debug::attachToDebugger()
{
#if NV_OS_WIN32
if (isDebuggerPresent() == FALSE) {
Path process(1024);
process.copy("\"");
GetSystemDirectoryA(process.str() + 1, 1024 - 1);
process.appendSeparator();
process.appendFormat("VSJitDebugger.exe\" -p %lu", ::GetCurrentProcessId());
STARTUPINFOA sSi;
memset(&sSi, 0, sizeof(sSi));
PROCESS_INFORMATION sPi;
memset(&sPi, 0, sizeof(sPi));
BOOL b = CreateProcessA(NULL, process.str(), NULL, NULL, FALSE, 0, NULL, NULL, &sSi, &sPi);
if (b != FALSE) {
::WaitForSingleObject(sPi.hProcess, INFINITE);
DWORD dwExitCode;
::GetExitCodeProcess(sPi.hProcess, &dwExitCode);
if (dwExitCode != 0) //if exit code is zero, a debugger was selected
b = FALSE;
}
if (sPi.hThread != NULL) ::CloseHandle(sPi.hThread);
if (sPi.hProcess != NULL) ::CloseHandle(sPi.hProcess);
if (b == FALSE)
return false;
for (int i = 0; i < 5*60; i++) {
if (isDebuggerPresent())
break;
::Sleep(200);
}
}
#endif // NV_OS_WIN32
return true;
}
| dmsovetov/nvidia-texture-tools | src/nvcore/Debug.cpp | C++ | mit | 40,281 |
module Fog
module Compute
class XenServer
module Models
class Vlans < Collection
model Fog::Compute::XenServer::Models::Vlan
end
end
end
end
end | jonpstone/portfolio-project-rails-mean-movie-reviews | vendor/bundle/ruby/2.3.0/gems/fog-xenserver-0.3.0/lib/fog/compute/xen_server/models/vlans.rb | Ruby | mit | 194 |
/**
@module ember-data
*/
import Ember from 'ember';
import Model from "ember-data/model";
var get = Ember.get;
var capitalize = Ember.String.capitalize;
var underscore = Ember.String.underscore;
const { assert } = Ember;
/*
Extend `Ember.DataAdapter` with ED specific code.
@class DebugAdapter
@namespace DS
@extends Ember.DataAdapter
@private
*/
export default Ember.DataAdapter.extend({
getFilters() {
return [
{ name: 'isNew', desc: 'New' },
{ name: 'isModified', desc: 'Modified' },
{ name: 'isClean', desc: 'Clean' }
];
},
detect(typeClass) {
return typeClass !== Model && Model.detect(typeClass);
},
columnsForType(typeClass) {
var columns = [{
name: 'id',
desc: 'Id'
}];
var count = 0;
var self = this;
get(typeClass, 'attributes').forEach((meta, name) => {
if (count++ > self.attributeLimit) { return false; }
var desc = capitalize(underscore(name).replace('_', ' '));
columns.push({ name: name, desc: desc });
});
return columns;
},
getRecords(modelClass, modelName) {
if (arguments.length < 2) {
// Legacy Ember.js < 1.13 support
let containerKey = modelClass._debugContainerKey;
if (containerKey) {
let match = containerKey.match(/model:(.*)/);
if (match) {
modelName = match[1];
}
}
}
assert("Cannot find model name. Please upgrade to Ember.js >= 1.13 for Ember Inspector support", !!modelName);
return this.get('store').peekAll(modelName);
},
getRecordColumnValues(record) {
var count = 0;
var columnValues = { id: get(record, 'id') };
record.eachAttribute((key) => {
if (count++ > this.attributeLimit) {
return false;
}
var value = get(record, key);
columnValues[key] = value;
});
return columnValues;
},
getRecordKeywords(record) {
var keywords = [];
var keys = Ember.A(['id']);
record.eachAttribute((key) => keys.push(key));
keys.forEach((key) => keywords.push(get(record, key)));
return keywords;
},
getRecordFilterValues(record) {
return {
isNew: record.get('isNew'),
isModified: record.get('hasDirtyAttributes') && !record.get('isNew'),
isClean: !record.get('hasDirtyAttributes')
};
},
getRecordColor(record) {
var color = 'black';
if (record.get('isNew')) {
color = 'green';
} else if (record.get('hasDirtyAttributes')) {
color = 'blue';
}
return color;
},
observeRecord(record, recordUpdated) {
var releaseMethods = Ember.A();
var keysToObserve = Ember.A(['id', 'isNew', 'hasDirtyAttributes']);
record.eachAttribute((key) => keysToObserve.push(key));
var adapter = this;
keysToObserve.forEach(function(key) {
var handler = function() {
recordUpdated(adapter.wrapRecord(record));
};
Ember.addObserver(record, key, handler);
releaseMethods.push(function() {
Ember.removeObserver(record, key, handler);
});
});
var release = function() {
releaseMethods.forEach((fn) => fn());
};
return release;
}
});
| r0zar/ember-rails-stocks | stocks/node_modules/ember-data/addon/-private/system/debug/debug-adapter.js | JavaScript | mit | 3,163 |
<?php
/**
* @package wpml-core
* @subpackage wpml-user-language
*/
class WPML_User_Language_Switcher_UI {
/**
* WPML_User_Language_Switcher_UI constructor.
*
* @param WPML_User_Language_Switcher $WPML_User_Language_Switcher
* @param WPML_User_Language_Switcher_Resources $WPML_User_Language_Switcher_Resources
*/
public function __construct( &$WPML_User_Language_Switcher, &$WPML_User_Language_Switcher_Resources ) {
$this->user_language_switcher = &$WPML_User_Language_Switcher;
$this->resources = &$WPML_User_Language_Switcher_Resources;
}
public function language_switcher( $args, $model ) {
$this->resources->enqueue_scripts( $args );
return $this->get_view( $model );
}
/**
* @param array $model
*
* @return string
*/
protected function get_view( $model ) {
$template_paths = array(
ICL_PLUGIN_PATH . '/templates/user-language/',
);
$template = 'language-switcher.twig';
$loader = new Twig_Loader_Filesystem( $template_paths );
$environment_args = array();
if ( WP_DEBUG ) {
$environment_args['debug'] = true;
}
$twig = new Twig_Environment( $loader, $environment_args );
return $twig->render( $template, $model );
}
}
| Bamboo3000/searchit | wp-content/plugins/sitepress-multilingual-cms/classes/user-language/class-wpml-user-language-switcher-ui.php | PHP | gpl-2.0 | 1,231 |
from PyQt5.uic import properties
| drnextgis/QGIS | python/PyQt/PyQt5/uic/properties.py | Python | gpl-2.0 | 33 |
<?php
/**
* Date Exception
*
* PHP version 5
*
* Copyright (C) Villanova University 2011.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Exceptions
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development Wiki
*/
namespace VuFind\Exception;
/**
* Date Exception
*
* @category VuFind
* @package Exceptions
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development Wiki
*/
class Date extends \Exception
{
}
| ubtue/KrimDok | module/VuFind/src/VuFind/Exception/Date.php | PHP | gpl-2.0 | 1,319 |
<?php
/**
* This class is used for Manages all the options related With Magic Fields
*
*/
class RCCWP_Options {
/**
* Update the options of Magic Fields
*
* @params array $options is a array with the options of Magic Fields
*/
function Update($options) {
$options = serialize($options);
update_option(RC_CWP_OPTION_KEY, $options);
}
/**
* Get the options of magic fields
*
* if is not specified a key is return a array with all the options of magic fields
*
* @param string $key is the name of the option.
*
*/
function Get($key = null) {
if (get_option(RC_CWP_OPTION_KEY) == "") return "";
if (is_array(get_option(RC_CWP_OPTION_KEY)))
$options = get_option(RC_CWP_OPTION_KEY);
else
$options = unserialize(get_option(RC_CWP_OPTION_KEY));
if (!empty($key)){
if( isset($options[$key]) ) return $options[$key];
return false;
}else{
return $options;
}
}
/**
* Save a new value in the options
*
* @param string $key is the name of the option to will be updated
* @param string $val is the new value of the option
*/
function Set($key, $val) {
$options = RCCWP_Options::Get();
$options[$key] = $val;
RCCWP_Options::Update($options);
}
}
| matthewbirtch/birtchfarms.com | wp-content/plugins/magic-fields/RCCWP_Options.php | PHP | gpl-2.0 | 1,237 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2013-2014 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::PhaseIncompressibleTurbulenceModel
Description
Templated abstract base class for multiphase incompressible
turbulence models.
SourceFiles
PhaseIncompressibleTurbulenceModel.C
\*---------------------------------------------------------------------------*/
#ifndef PhaseIncompressibleTurbulenceModel_H
#define PhaseIncompressibleTurbulenceModel_H
#include "TurbulenceModel.H"
#include "incompressibleTurbulenceModel.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class PhaseIncompressibleTurbulenceModel Declaration
\*---------------------------------------------------------------------------*/
template<class TransportModel>
class PhaseIncompressibleTurbulenceModel
:
public TurbulenceModel
<
volScalarField,
geometricOneField,
incompressibleTurbulenceModel,
TransportModel
>
{
public:
typedef volScalarField alphaField;
typedef geometricOneField rhoField;
typedef TransportModel transportModel;
// Constructors
//- Construct
PhaseIncompressibleTurbulenceModel
(
const alphaField& alpha,
const geometricOneField& rho,
const volVectorField& U,
const surfaceScalarField& alphaRhoPhi,
const surfaceScalarField& phi,
const TransportModel& trasportModel,
const word& propertiesName
);
// Selectors
//- Return a reference to the selected turbulence model
static autoPtr<PhaseIncompressibleTurbulenceModel> New
(
const alphaField& alpha,
const volVectorField& U,
const surfaceScalarField& alphaRhoPhi,
const surfaceScalarField& phi,
const TransportModel& trasportModel,
const word& propertiesName = turbulenceModel::propertiesName
);
//- Destructor
virtual ~PhaseIncompressibleTurbulenceModel()
{}
// Member Functions
//- Return the phase-pressure'
// (derivative of phase-pressure w.r.t. phase-fraction)
virtual tmp<volScalarField> pPrime() const;
//- Return the face-phase-pressure'
// (derivative of phase-pressure w.r.t. phase-fraction)
virtual tmp<surfaceScalarField> pPrimef() const;
//- Return the effective stress tensor
virtual tmp<volSymmTensorField> devReff() const;
//- Return the source term for the momentum equation
virtual tmp<fvVectorMatrix> divDevReff(volVectorField& U) const;
//- Return the effective stress tensor
virtual tmp<volSymmTensorField> devRhoReff() const;
//- Return the source term for the momentum equation
virtual tmp<fvVectorMatrix> divDevRhoReff(volVectorField& U) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#ifdef NoRepository
# include "PhaseIncompressibleTurbulenceModel.C"
#endif
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| Atizar/RapidCFD-dev | src/TurbulenceModels/phaseIncompressible/PhaseIncompressibleTurbulenceModel/PhaseIncompressibleTurbulenceModel.H | C++ | gpl-3.0 | 4,433 |
/*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function () {
describe('startFromFilter', function() {
var startFrom;
beforeEach(module('piwikApp.filter'));
beforeEach(inject(function($injector) {
var $filter = $injector.get('$filter');
startFrom = $filter('startFrom');
}));
describe('#startFrom()', function() {
it('should return all entries if index is zero', function() {
var result = startFrom([1,2,3], 0);
expect(result).to.eql([1,2,3]);
});
it('should return only partial entries if filter is higher than zero', function() {
var result = startFrom([1,2,3], 2);
expect(result).to.eql([3]);
});
it('should return no entries if start is higher than input length', function() {
var result = startFrom([1,2,3], 11);
expect(result).to.eql([]);
});
});
});
})(); | befair/soulShape | wp/soulshape.earth/piwik/plugins/CoreHome/angularjs/common/filters/startfrom.spec.js | JavaScript | agpl-3.0 | 1,121 |
// AForge Image Processing Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © Andrew Kirillov, 2005-2010
// andrew.kirillov@aforgenet.com
//
namespace AForge.Imaging.Filters
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using AForge;
/// <summary>
/// Linear correction of RGB channels.
/// </summary>
///
/// <remarks><para>The filter performs linear correction of RGB channels by mapping specified
/// channels' input ranges to output ranges. It is similar to the
/// <see cref="ColorRemapping"/>, but the remapping is linear.</para>
///
/// <para>The filter accepts 8 bpp grayscale and 24/32 bpp color images for processing.</para>
///
/// <para>Sample usage:</para>
/// <code>
/// // create filter
/// LevelsLinear filter = new LevelsLinear( );
/// // set ranges
/// filter.InRed = new IntRange( 30, 230 );
/// filter.InGreen = new IntRange( 50, 240 );
/// filter.InBlue = new IntRange( 10, 210 );
/// // apply the filter
/// filter.ApplyInPlace( image );
/// </code>
///
/// <para><b>Initial image:</b></para>
/// <img src="img/imaging/sample1.jpg" width="480" height="361" />
/// <para><b>Result image:</b></para>
/// <img src="img/imaging/levels_linear.jpg" width="480" height="361" />
/// </remarks>
///
/// <seealso cref="HSLLinear"/>
/// <seealso cref="YCbCrLinear"/>
///
public class LevelsLinear : BaseInPlacePartialFilter
{
private IntRange inRed = new IntRange(0, 255);
private IntRange inGreen = new IntRange(0, 255);
private IntRange inBlue = new IntRange(0, 255);
private IntRange outRed = new IntRange(0, 255);
private IntRange outGreen = new IntRange(0, 255);
private IntRange outBlue = new IntRange(0, 255);
private byte[] mapRed = new byte[256];
private byte[] mapGreen = new byte[256];
private byte[] mapBlue = new byte[256];
// private format translation dictionary
private Dictionary<PixelFormat, PixelFormat> formatTranslations = new Dictionary<PixelFormat, PixelFormat>();
/// <summary>
/// Format translations dictionary.
/// </summary>
public override Dictionary<PixelFormat, PixelFormat> FormatTranslations
{
get { return formatTranslations; }
}
#region Public Propertis
/// <summary>
/// Red component's input range.
/// </summary>
public IntRange InRed
{
get { return inRed; }
set
{
inRed = value;
CalculateMap(inRed, outRed, mapRed);
}
}
/// <summary>
/// Green component's input range.
/// </summary>
public IntRange InGreen
{
get { return inGreen; }
set
{
inGreen = value;
CalculateMap(inGreen, outGreen, mapGreen);
}
}
/// <summary>
/// Blue component's input range.
/// </summary>
public IntRange InBlue
{
get { return inBlue; }
set
{
inBlue = value;
CalculateMap(inBlue, outBlue, mapBlue);
}
}
/// <summary>
/// Gray component's input range.
/// </summary>
public IntRange InGray
{
get { return inGreen; }
set
{
inGreen = value;
CalculateMap(inGreen, outGreen, mapGreen);
}
}
/// <summary>
/// Input range for RGB components.
/// </summary>
///
/// <remarks>The property allows to set red, green and blue input ranges to the same value.</remarks>
///
public IntRange Input
{
set
{
inRed = inGreen = inBlue = value;
CalculateMap(inRed, outRed, mapRed);
CalculateMap(inGreen, outGreen, mapGreen);
CalculateMap(inBlue, outBlue, mapBlue);
}
}
/// <summary>
/// Red component's output range.
/// </summary>
public IntRange OutRed
{
get { return outRed; }
set
{
outRed = value;
CalculateMap(inRed, outRed, mapRed);
}
}
/// <summary>
/// Green component's output range.
/// </summary>
public IntRange OutGreen
{
get { return outGreen; }
set
{
outGreen = value;
CalculateMap(inGreen, outGreen, mapGreen);
}
}
/// <summary>
/// Blue component's output range.
/// </summary>
public IntRange OutBlue
{
get { return outBlue; }
set
{
outBlue = value;
CalculateMap(inBlue, outBlue, mapBlue);
}
}
/// <summary>
/// Gray component's output range.
/// </summary>
public IntRange OutGray
{
get { return outGreen; }
set
{
outGreen = value;
CalculateMap(inGreen, outGreen, mapGreen);
}
}
/// <summary>
/// Output range for RGB components.
/// </summary>
///
/// <remarks>The property allows to set red, green and blue output ranges to the same value.</remarks>
///
public IntRange Output
{
set
{
outRed = outGreen = outBlue = value;
CalculateMap(inRed, outRed, mapRed);
CalculateMap(inGreen, outGreen, mapGreen);
CalculateMap(inBlue, outBlue, mapBlue);
}
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="LevelsLinear"/> class.
/// </summary>
public LevelsLinear()
{
CalculateMap(inRed, outRed, mapRed);
CalculateMap(inGreen, outGreen, mapGreen);
CalculateMap(inBlue, outBlue, mapBlue);
formatTranslations[PixelFormat.Format8bppIndexed] = PixelFormat.Format8bppIndexed;
formatTranslations[PixelFormat.Format24bppRgb] = PixelFormat.Format24bppRgb;
formatTranslations[PixelFormat.Format32bppRgb] = PixelFormat.Format32bppRgb;
formatTranslations[PixelFormat.Format32bppArgb] = PixelFormat.Format32bppArgb;
}
/// <summary>
/// Process the filter on the specified image.
/// </summary>
///
/// <param name="image">Source image data.</param>
/// <param name="rect">Image rectangle for processing by the filter.</param>
///
protected override unsafe void ProcessFilter(UnmanagedImage image, Rectangle rect)
{
int pixelSize = Image.GetPixelFormatSize(image.PixelFormat) / 8;
// processing start and stop X,Y positions
int startX = rect.Left;
int startY = rect.Top;
int stopX = startX + rect.Width;
int stopY = startY + rect.Height;
int offset = image.Stride - rect.Width * pixelSize;
// do the job
byte* ptr = (byte*)image.ImageData.ToPointer();
// allign pointer to the first pixel to process
ptr += (startY * image.Stride + startX * pixelSize);
if (image.PixelFormat == PixelFormat.Format8bppIndexed)
{
// grayscale image
for (int y = startY; y < stopY; y++)
{
for (int x = startX; x < stopX; x++, ptr++)
{
// gray
*ptr = mapGreen[*ptr];
}
ptr += offset;
}
}
else
{
// RGB image
for (int y = startY; y < stopY; y++)
{
for (int x = startX; x < stopX; x++, ptr += pixelSize)
{
// red
ptr[RGB.R] = mapRed[ptr[RGB.R]];
// green
ptr[RGB.G] = mapGreen[ptr[RGB.G]];
// blue
ptr[RGB.B] = mapBlue[ptr[RGB.B]];
}
ptr += offset;
}
}
}
/// <summary>
/// Calculate conversion map.
/// </summary>
///
/// <param name="inRange">Input range.</param>
/// <param name="outRange">Output range.</param>
/// <param name="map">Conversion map.</param>
///
private static void CalculateMap(IntRange inRange, IntRange outRange, byte[] map)
{
double k = 0, b = 0;
if (inRange.Max != inRange.Min)
{
k = (double)(outRange.Max - outRange.Min) / (double)(inRange.Max - inRange.Min);
b = (double)(outRange.Min) - k * inRange.Min;
}
for (int i = 0; i < 256; i++)
{
byte v = (byte)i;
if (v >= inRange.Max)
v = (byte)outRange.Max;
else if (v <= inRange.Min)
v = (byte)outRange.Min;
else
v = (byte)(k * v + b);
map[i] = v;
}
}
}
}
| AnnaPeng/framework | Sources/Accord.Imaging/AForge/Filters/Color Filters/LevelsLinear.cs | C# | lgpl-2.1 | 10,124 |
/**
* Vosao CMS. Simple CMS for Google App Engine.
*
* Copyright (C) 2009-2010 Vosao development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* email: vosao.dev@gmail.com
*/
package org.vosao.business;
import java.util.Date;
import java.util.List;
import org.apache.velocity.VelocityContext;
import org.vosao.business.decorators.TreeItemDecorator;
import org.vosao.business.page.PageRenderDecorator;
import org.vosao.entity.ContentEntity;
import org.vosao.entity.FolderEntity;
import org.vosao.entity.PageEntity;
import org.vosao.entity.StructureTemplateEntity;
import org.vosao.entity.UserEntity;
import org.vosao.velocity.VelocityPluginService;
import org.vosao.velocity.VelocityService;
public interface PageBusiness {
/**
* Security filtered dao version.
* @return found page.
*/
PageEntity getById(final Long id);
/**
* Security filtered dao version.
* @return list of pages.
*/
List<PageEntity> select();
/**
* Security filtered dao version.
* @return found page.
*/
PageEntity getByUrl(final String url);
/**
* Security filtered dao version.
* @return list of pages.
*/
List<PageEntity> getByParent(final String url);
/**
* Security filtered dao version.
* @return list of pages.
*/
List<PageEntity> getByParentApproved(final String url);
/**
* Security filtered dao version.
* @return list of pages.
*/
List<PageEntity> getByParentApproved(final String url, Date startDate,
Date endDate);
/**
* Security filtered dao version.
*/
void remove(final List<Long> ids);
/**
* Security filtered dao version.
*/
void removeVersion(Long id);
/**
* Security filtered dao version.
*/
List<ContentEntity> getContents(final Long pageId);
/**
* Security filtered dao version.
*/
List<PageEntity> selectByUrl(final String url);
/**
* With added business processing dao version.
*/
void save(PageEntity page);
TreeItemDecorator<PageEntity> getTree(final List<PageEntity> pages);
TreeItemDecorator<PageEntity> getTree();
/**
* Render page with page bound template. With applied postProcessing and
* using PageRenderDecorator.
* @param page - page to render.
* @param languageCode - language code.
* @return rendered html.
*/
String render(final PageEntity page, final String languageCode);
/**
* Render page using provided template. With applied postProcessing and
* using PageRenderDecorator.
* @param page - page to render.
* @param template - page template.
* @param languageCode - language code.
* @return rendered html.
*/
String render(final PageEntity page, final String tempate,
final String languageCode);
VelocityContext createContext(final String languageCode, PageEntity page);
PageRenderDecorator createPageRenderDecorator(final PageEntity page,
final String languageCode);
PageRenderDecorator createStructuredPageRenderDecorator(
final PageEntity page, final String languageCode,
StructureTemplateEntity template);
List<String> validateBeforeUpdate(final PageEntity page);
ContentEntity getPageContent(final PageEntity page,
final String languageCode);
/**
* Add new version of specified page.
* @param oldPage - page to create version from.
*/
PageEntity addVersion(final PageEntity oldPage, final Integer version,
final String versionTitle, final UserEntity user);
boolean canChangeContent(String url, String languageCode);
/**
* Save page content and update search index.
* @param page
* @param content
* @param language
*/
void saveContent(PageEntity page, String language, String content);
/**
* Get next sort index for new page.
* @param friendlyURL - new page url.
*/
Integer getNextSortIndex(final String friendlyURL);
/**
* Move page down in sort order.
* @param page
*/
void moveDown(PageEntity page);
/**
* Move page up in sort order.
* @param page
*/
void moveUp(PageEntity page);
/**
* Place page after refPage in sort order.
* @param page
* @param refPage
*/
void moveAfter(PageEntity page, PageEntity refPage);
/**
* Place page before refPage in sort order.
* @param page
* @param refPage
*/
void moveBefore(PageEntity page, PageEntity refPage);
VelocityService getVelocityService();
VelocityPluginService getVelocityPluginService();
/**
* Remove page by URL with all subpages and page resouces.
*/
void remove(String pageURL);
/**
* Check for free url and if not then add suffix number.
* @param url - url to check
* @return - free page friendly URL.
*/
String makeUniquePageURL(String url);
/**
* Move page to new friendlyURL. Also change friendlyURL recursively
* for all children pages.
* @param page - page to change.
* @param friendlyURL - new friendlyURL.
*/
void move(PageEntity page, String friendlyURL);
/**
* Copy page with subpages to new parent URL.
*/
void copy(PageEntity page, String parentURL);
void addVelocityTools(VelocityContext context);
/**
* Find or create default child page for given parent page url. Every page has default
* settings page for children with url "/_default".
* @param url - parent page url.
* @return - found or created default page.
*/
PageEntity getPageDefaultSettings(String url);
/**
* Set default values from parent default page.
* @param page - page to set default values from parent.
*/
void setDefaultValues(PageEntity page);
/**
* Create/update page content to parent default content.
* @param page - page to set/update content.
*/
void updateDefaultContent(PageEntity page);
FolderEntity getPageFolder(String pageURL);
PageEntity getRestPage(String url);
}
| vosaocms/vosao | api/src/org/vosao/business/PageBusiness.java | Java | lgpl-2.1 | 6,389 |
namespace AForge.Video.DirectShow
{
partial class VideoCaptureDeviceForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cancelButton = new System.Windows.Forms.Button();
this.okButton = new System.Windows.Forms.Button();
this.devicesCombo = new System.Windows.Forms.ComboBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.videoInputsCombo = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.snapshotsLabel = new System.Windows.Forms.Label();
this.snapshotResolutionsCombo = new System.Windows.Forms.ComboBox();
this.videoResolutionsCombo = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.SuspendLayout();
//
// cancelButton
//
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.cancelButton.Location = new System.Drawing.Point(358, 292);
this.cancelButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(112, 35);
this.cancelButton.TabIndex = 11;
this.cancelButton.Text = "Cancel";
//
// okButton
//
this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.okButton.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.okButton.Location = new System.Drawing.Point(224, 292);
this.okButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(112, 35);
this.okButton.TabIndex = 10;
this.okButton.Text = "OK";
this.okButton.Click += new System.EventHandler(this.okButton_Click);
//
// devicesCombo
//
this.devicesCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.devicesCombo.FormattingEnabled = true;
this.devicesCombo.Location = new System.Drawing.Point(150, 62);
this.devicesCombo.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.devicesCombo.Name = "devicesCombo";
this.devicesCombo.Size = new System.Drawing.Size(486, 28);
this.devicesCombo.TabIndex = 9;
this.devicesCombo.SelectedIndexChanged += new System.EventHandler(this.devicesCombo_SelectedIndexChanged);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.videoInputsCombo);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.snapshotsLabel);
this.groupBox1.Controls.Add(this.snapshotResolutionsCombo);
this.groupBox1.Controls.Add(this.videoResolutionsCombo);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.pictureBox);
this.groupBox1.Controls.Add(this.devicesCombo);
this.groupBox1.Location = new System.Drawing.Point(15, 15);
this.groupBox1.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.groupBox1.Size = new System.Drawing.Size(660, 254);
this.groupBox1.TabIndex = 12;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Video capture device settings";
//
// videoInputsCombo
//
this.videoInputsCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.videoInputsCombo.FormattingEnabled = true;
this.videoInputsCombo.Location = new System.Drawing.Point(150, 200);
this.videoInputsCombo.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.videoInputsCombo.Name = "videoInputsCombo";
this.videoInputsCombo.Size = new System.Drawing.Size(223, 28);
this.videoInputsCombo.TabIndex = 17;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(150, 177);
this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(93, 20);
this.label3.TabIndex = 16;
this.label3.Text = "Video input:";
//
// snapshotsLabel
//
this.snapshotsLabel.AutoSize = true;
this.snapshotsLabel.Location = new System.Drawing.Point(412, 108);
this.snapshotsLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.snapshotsLabel.Name = "snapshotsLabel";
this.snapshotsLabel.Size = new System.Drawing.Size(152, 20);
this.snapshotsLabel.TabIndex = 15;
this.snapshotsLabel.Text = "Snapshot resoluton:";
//
// snapshotResolutionsCombo
//
this.snapshotResolutionsCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.snapshotResolutionsCombo.FormattingEnabled = true;
this.snapshotResolutionsCombo.Location = new System.Drawing.Point(412, 131);
this.snapshotResolutionsCombo.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.snapshotResolutionsCombo.Name = "snapshotResolutionsCombo";
this.snapshotResolutionsCombo.Size = new System.Drawing.Size(223, 28);
this.snapshotResolutionsCombo.TabIndex = 14;
//
// videoResolutionsCombo
//
this.videoResolutionsCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.videoResolutionsCombo.FormattingEnabled = true;
this.videoResolutionsCombo.Location = new System.Drawing.Point(150, 131);
this.videoResolutionsCombo.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.videoResolutionsCombo.Name = "videoResolutionsCombo";
this.videoResolutionsCombo.Size = new System.Drawing.Size(223, 28);
this.videoResolutionsCombo.TabIndex = 13;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(150, 108);
this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(124, 20);
this.label2.TabIndex = 12;
this.label2.Text = "Video resoluton:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(150, 38);
this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(103, 20);
this.label1.TabIndex = 11;
this.label1.Text = "Video device:";
//
// pictureBox
//
this.pictureBox.Image = global::Accord.Video.DirectShow.Properties.Resources.camera;
this.pictureBox.Location = new System.Drawing.Point(30, 43);
this.pictureBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(96, 98);
this.pictureBox.TabIndex = 10;
this.pictureBox.TabStop = false;
//
// VideoCaptureDeviceForm
//
this.AcceptButton = this.okButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(144F, 144F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.CancelButton = this.cancelButton;
this.ClientSize = new System.Drawing.Size(693, 340);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.okButton);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.Name = "VideoCaptureDeviceForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Open local video capture device";
this.Load += new System.EventHandler(this.VideoCaptureDeviceForm_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.ComboBox devicesCombo;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.PictureBox pictureBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label snapshotsLabel;
private System.Windows.Forms.ComboBox snapshotResolutionsCombo;
private System.Windows.Forms.ComboBox videoResolutionsCombo;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox videoInputsCombo;
private System.Windows.Forms.Label label3;
}
} | AnnaPeng/framework | Sources/Accord.Video.DirectShow/VideoCaptureDeviceForm.Designer.cs | C# | lgpl-2.1 | 11,285 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* 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@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Adminhtml
* @copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Product attribute add/edit form main tab
*
* @category Mage
* @package Mage_Adminhtml
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_Adminhtml_Block_Catalog_Product_Attribute_Edit_Tab_Main extends Mage_Eav_Block_Adminhtml_Attribute_Edit_Main_Abstract
{
/**
* Adding product form elements for editing attribute
*
* @return Mage_Adminhtml_Block_Catalog_Product_Attribute_Edit_Tab_Main
*/
protected function _prepareForm()
{
parent::_prepareForm();
$attributeObject = $this->getAttributeObject();
/* @var $form Varien_Data_Form */
$form = $this->getForm();
/* @var $fieldset Varien_Data_Form_Element_Fieldset */
$fieldset = $form->getElement('base_fieldset');
$frontendInputElm = $form->getElement('frontend_input');
$additionalTypes = array(
array(
'value' => 'price',
'label' => Mage::helper('catalog')->__('Price')
),
array(
'value' => 'media_image',
'label' => Mage::helper('catalog')->__('Media Image')
)
);
if ($attributeObject->getFrontendInput() == 'gallery') {
$additionalTypes[] = array(
'value' => 'gallery',
'label' => Mage::helper('catalog')->__('Gallery')
);
}
$response = new Varien_Object();
$response->setTypes(array());
Mage::dispatchEvent('adminhtml_product_attribute_types', array('response'=>$response));
$_disabledTypes = array();
$_hiddenFields = array();
foreach ($response->getTypes() as $type) {
$additionalTypes[] = $type;
if (isset($type['hide_fields'])) {
$_hiddenFields[$type['value']] = $type['hide_fields'];
}
if (isset($type['disabled_types'])) {
$_disabledTypes[$type['value']] = $type['disabled_types'];
}
}
Mage::register('attribute_type_hidden_fields', $_hiddenFields);
Mage::register('attribute_type_disabled_types', $_disabledTypes);
$frontendInputValues = array_merge($frontendInputElm->getValues(), $additionalTypes);
$frontendInputElm->setValues($frontendInputValues);
$yesnoSource = Mage::getModel('adminhtml/system_config_source_yesno')->toOptionArray();
$scopes = array(
Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE =>Mage::helper('catalog')->__('Store View'),
Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_WEBSITE =>Mage::helper('catalog')->__('Website'),
Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL =>Mage::helper('catalog')->__('Global'),
);
if ($attributeObject->getAttributeCode() == 'status' || $attributeObject->getAttributeCode() == 'tax_class_id') {
unset($scopes[Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE]);
}
$fieldset->addField('is_global', 'select', array(
'name' => 'is_global',
'label' => Mage::helper('catalog')->__('Scope'),
'title' => Mage::helper('catalog')->__('Scope'),
'note' => Mage::helper('catalog')->__('Declare attribute value saving scope'),
'values'=> $scopes
), 'attribute_code');
$fieldset->addField('apply_to', 'apply', array(
'name' => 'apply_to[]',
'label' => Mage::helper('catalog')->__('Apply To'),
'values' => Mage_Catalog_Model_Product_Type::getOptions(),
'mode_labels' => array(
'all' => Mage::helper('catalog')->__('All Product Types'),
'custom' => Mage::helper('catalog')->__('Selected Product Types')
),
'required' => true
), 'frontend_class');
$fieldset->addField('is_configurable', 'select', array(
'name' => 'is_configurable',
'label' => Mage::helper('catalog')->__('Use To Create Configurable Product'),
'values' => $yesnoSource,
), 'apply_to');
// frontend properties fieldset
$fieldset = $form->addFieldset('front_fieldset', array('legend'=>Mage::helper('catalog')->__('Frontend Properties')));
$fieldset->addField('is_searchable', 'select', array(
'name' => 'is_searchable',
'label' => Mage::helper('catalog')->__('Use in Quick Search'),
'title' => Mage::helper('catalog')->__('Use in Quick Search'),
'values' => $yesnoSource,
));
$fieldset->addField('is_visible_in_advanced_search', 'select', array(
'name' => 'is_visible_in_advanced_search',
'label' => Mage::helper('catalog')->__('Use in Advanced Search'),
'title' => Mage::helper('catalog')->__('Use in Advanced Search'),
'values' => $yesnoSource,
));
$fieldset->addField('is_comparable', 'select', array(
'name' => 'is_comparable',
'label' => Mage::helper('catalog')->__('Comparable on Front-end'),
'title' => Mage::helper('catalog')->__('Comparable on Front-end'),
'values' => $yesnoSource,
));
$fieldset->addField('is_filterable', 'select', array(
'name' => 'is_filterable',
'label' => Mage::helper('catalog')->__("Use In Layered Navigation"),
'title' => Mage::helper('catalog')->__('Can be used only with catalog input type Dropdown, Multiple Select and Price'),
'note' => Mage::helper('catalog')->__('Can be used only with catalog input type Dropdown, Multiple Select and Price'),
'values' => array(
array('value' => '0', 'label' => Mage::helper('catalog')->__('No')),
array('value' => '1', 'label' => Mage::helper('catalog')->__('Filterable (with results)')),
array('value' => '2', 'label' => Mage::helper('catalog')->__('Filterable (no results)')),
),
));
$fieldset->addField('is_filterable_in_search', 'select', array(
'name' => 'is_filterable_in_search',
'label' => Mage::helper('catalog')->__("Use In Search Results Layered Navigation"),
'title' => Mage::helper('catalog')->__('Can be used only with catalog input type Dropdown, Multiple Select and Price'),
'note' => Mage::helper('catalog')->__('Can be used only with catalog input type Dropdown, Multiple Select and Price'),
'values' => $yesnoSource,
));
$fieldset->addField('is_used_for_promo_rules', 'select', array(
'name' => 'is_used_for_promo_rules',
'label' => Mage::helper('catalog')->__('Use for Promo Rule Conditions'),
'title' => Mage::helper('catalog')->__('Use for Promo Rule Conditions'),
'values' => $yesnoSource,
));
$fieldset->addField('position', 'text', array(
'name' => 'position',
'label' => Mage::helper('catalog')->__('Position'),
'title' => Mage::helper('catalog')->__('Position in Layered Navigation'),
'note' => Mage::helper('catalog')->__('Position of attribute in layered navigation block'),
'class' => 'validate-digits',
));
$fieldset->addField('is_wysiwyg_enabled', 'select', array(
'name' => 'is_wysiwyg_enabled',
'label' => Mage::helper('catalog')->__('Enable WYSIWYG'),
'title' => Mage::helper('catalog')->__('Enable WYSIWYG'),
'values' => $yesnoSource,
));
$htmlAllowed = $fieldset->addField('is_html_allowed_on_front', 'select', array(
'name' => 'is_html_allowed_on_front',
'label' => Mage::helper('catalog')->__('Allow HTML Tags on Frontend'),
'title' => Mage::helper('catalog')->__('Allow HTML Tags on Frontend'),
'values' => $yesnoSource,
));
if (!$attributeObject->getId() || $attributeObject->getIsWysiwygEnabled()) {
$attributeObject->setIsHtmlAllowedOnFront(1);
}
$fieldset->addField('is_visible_on_front', 'select', array(
'name' => 'is_visible_on_front',
'label' => Mage::helper('catalog')->__('Visible on Product View Page on Front-end'),
'title' => Mage::helper('catalog')->__('Visible on Product View Page on Front-end'),
'values' => $yesnoSource,
));
$fieldset->addField('used_in_product_listing', 'select', array(
'name' => 'used_in_product_listing',
'label' => Mage::helper('catalog')->__('Used in Product Listing'),
'title' => Mage::helper('catalog')->__('Used in Product Listing'),
'note' => Mage::helper('catalog')->__('Depends on design theme'),
'values' => $yesnoSource,
));
$fieldset->addField('used_for_sort_by', 'select', array(
'name' => 'used_for_sort_by',
'label' => Mage::helper('catalog')->__('Used for Sorting in Product Listing'),
'title' => Mage::helper('catalog')->__('Used for Sorting in Product Listing'),
'note' => Mage::helper('catalog')->__('Depends on design theme'),
'values' => $yesnoSource,
));
$form->getElement('apply_to')->setSize(5);
if ($applyTo = $attributeObject->getApplyTo()) {
$applyTo = is_array($applyTo) ? $applyTo : explode(',', $applyTo);
$form->getElement('apply_to')->setValue($applyTo);
} else {
$form->getElement('apply_to')->addClass('no-display ignore-validate');
}
// define field dependencies
$this->setChild('form_after', $this->getLayout()->createBlock('adminhtml/widget_form_element_dependence')
->addFieldMap("is_wysiwyg_enabled", 'wysiwyg_enabled')
->addFieldMap("is_html_allowed_on_front", 'html_allowed_on_front')
->addFieldMap("frontend_input", 'frontend_input_type')
->addFieldDependence('wysiwyg_enabled', 'frontend_input_type', 'textarea')
->addFieldDependence('html_allowed_on_front', 'wysiwyg_enabled', '0')
);
Mage::dispatchEvent('adminhtml_catalog_product_attribute_edit_prepare_form', array(
'form' => $form,
'attribute' => $attributeObject
));
return $this;
}
/**
* Retrieve additional element types for product attributes
*
* @return array
*/
protected function _getAdditionalElementTypes()
{
return array(
'apply' => Mage::getConfig()->getBlockClassName('adminhtml/catalog_product_helper_form_apply'),
);
}
}
| dbashyal/MagentoStarterBase | trunk/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Edit/Tab/Main.php | PHP | lgpl-3.0 | 11,823 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OfficeDevPnP.Core;
using Contoso.Provisioning.Hybrid.Contract;
using System.IO;
using System.Diagnostics;
using Microsoft.SharePoint.Client;
using OfficeDevPnP.Core.Entities;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Configuration;
namespace Contoso.Provisioning.Hybrid.Core.SiteTemplates
{
public abstract class SiteProvisioningBase
{
ClientContext appOnlyClientContext = null;
ClientContext createdSiteContext = null;
ClientContext siteDirectorySiteContext = null;
/// <summary>
/// Returns the app only client context (the one with tenant level permissions)
/// </summary>
public ClientContext AppOnlyClientContext
{
get
{
return this.appOnlyClientContext;
}
}
/// <summary>
/// Returns the client context to manipulate the created site (collection)
/// </summary>
public ClientContext CreatedSiteContext
{
get
{
return this.createdSiteContext;
}
}
/// <summary>
/// Returns the client context to manipulate the site directory in the site directory site
/// </summary>
public ClientContext SiteDirectorySiteContext
{
get
{
return this.siteDirectorySiteContext;
}
}
/// <summary>
/// Class instance that will be used for on-premises specific provisioning code
/// </summary>
public ISiteProvisioningOnPremises SiteProvisioningOnPremises
{
get;
set;
}
/// <summary>
/// Information about the site to be provisioned
/// </summary>
public SharePointProvisioningData SharePointProvisioningData
{
get;
set;
}
/// <summary>
/// We're creating on-premises
/// </summary>
public bool CreateOnPremises
{
get
{
return SharePointProvisioningData.DataClassification.Equals("HBI", StringComparison.InvariantCultureIgnoreCase);
}
}
/// <summary>
/// Returns the root directory of the current deployment
/// </summary>
public string AppRootPath
{
get
{
string roleRoot = Environment.GetEnvironmentVariable("RoleRoot");
if (null != roleRoot && roleRoot.Length > 0)
{
// We're running on azure (real or emulated)
return roleRoot + @"\approot";
}
else
{
Process process = Process.GetCurrentProcess();
string fullPath = Path.GetDirectoryName(process.MainModule.FileName);
return fullPath;
}
}
}
/// <summary>
/// Realm to use for the access token's nameid and audience. In Office 365 use MSOL PowerShell (Get-MsolCompanyInformation).ObjectID to obtain Target/Tenant realm
/// </summary>
public string Realm
{
get;
set;
}
/// <summary>
/// The Application ID generated when you deploy an app (Visual Studio) or when you register an app via the appregnew.aspx page
/// </summary>
public string AppId
{
get;
set;
}
/// <summary>
/// The Application Secret generated when you deploy an app (Visual Studio) or when you register an app via the appregnew.aspx page
/// </summary>
public string AppSecret
{
get;
set;
}
/// <summary>
/// Triggers the provisioning
/// </summary>
/// <returns>True if OK, false otherwise</returns>
public virtual bool Execute()
{
bool result = false;
return result;
}
/// <summary>
/// Instantiate an app only client context (the one with tenant level permissions)
/// </summary>
/// <param name="siteUrl">Url of the tenant admin site</param>
public void InstantiateAppOnlyClientContext(string siteUrl)
{
this.appOnlyClientContext = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, this.Realm, this.AppId, this.AppSecret);
}
/// <summary>
/// Instantiate an app only client context (the one with tenant level permissions)
/// </summary>
/// <param name="siteUrl">Url of the tenant admin site</param>
public void InstantiateCreatedSiteClientContext(string siteUrl)
{
this.createdSiteContext = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, this.Realm, this.AppId, this.AppSecret);
}
/// <summary>
/// Instantiate an app only client context (the one with tenant level permissions)
/// </summary>
/// <param name="siteUrl">Url of the tenant admin site</param>
public void InstantiateSiteDirectorySiteClientContext(string siteUrl)
{
this.siteDirectorySiteContext = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, this.Realm, this.AppId, this.AppSecret);
}
public string GetNextSiteCollectionUrl(string siteDirectoryUrl, string siteDirectoryListName, string baseSiteUrl)
{
if (this.CreateOnPremises)
{
return this.SiteProvisioningOnPremises.GetNextSiteCollectionUrl(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, siteDirectoryUrl, siteDirectoryListName, baseSiteUrl);
}
else
{
return new SiteDirectoryManager().GetNextSiteCollectionUrlTenant(this.AppOnlyClientContext, this.AppOnlyClientContext.Web, this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, siteDirectoryUrl, siteDirectoryListName, baseSiteUrl);
}
}
/// <summary>
/// Launches a site collection creation and waits for the creation to finish
/// </summary>
/// <param name="properties">Describes the site collection to be created</param>
public void AddSiteCollection(SharePointProvisioningData properties)
{
if (this.CreateOnPremises)
{
this.SiteProvisioningOnPremises.CreateSiteCollectionOnPremises(this.SharePointProvisioningData);
this.createdSiteContext = this.SiteProvisioningOnPremises.SpOnPremiseAuthentication(this.SharePointProvisioningData.Url);
}
else
{
SiteEntity newSite = new SiteEntity
{
Description = properties.Description,
Title = properties.Title,
Url = properties.Url,
Template = properties.Template,
Lcid = properties.Lcid,
SiteOwnerLogin = properties.SiteOwner.Login,
StorageMaximumLevel = properties.StorageMaximumLevel,
StorageWarningLevel = properties.StorageWarningLevel,
TimeZoneId = properties.TimeZoneId,
UserCodeMaximumLevel = properties.UserCodeMaximumLevel,
UserCodeWarningLevel = properties.UserCodeWarningLevel,
};
this.AppOnlyClientContext.Web.AddSiteCollectionTenant(newSite);
InstantiateCreatedSiteClientContext(newSite.Url);
}
}
internal string GetConfiguration(string key)
{
string value = "";
if (this.CreateOnPremises)
{
value = ConfigurationManager.AppSettings[key];
}
else
{
value = RoleEnvironment.GetConfigurationSettingValue(key);
}
return value;
}
}
}
| stijnneirinckx/PnP | Solutions/Provisioning.Hybrid/Provisioning.Hybrid.Core/SiteTemplates/SiteProvisioningBase.cs | C# | apache-2.0 | 8,236 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto_test
import (
"math"
"reflect"
"testing"
. "./testdata"
. "github.com/coreos/etcd/third_party/code.google.com/p/gogoprotobuf/proto"
)
type UnmarshalTextTest struct {
in string
err string // if "", no error expected
out *MyMessage
}
func buildExtStructTest(text string) UnmarshalTextTest {
msg := &MyMessage{
Count: Int32(42),
}
SetExtension(msg, E_Ext_More, &Ext{
Data: String("Hello, world!"),
})
return UnmarshalTextTest{in: text, out: msg}
}
func buildExtDataTest(text string) UnmarshalTextTest {
msg := &MyMessage{
Count: Int32(42),
}
SetExtension(msg, E_Ext_Text, String("Hello, world!"))
SetExtension(msg, E_Ext_Number, Int32(1729))
return UnmarshalTextTest{in: text, out: msg}
}
func buildExtRepStringTest(text string) UnmarshalTextTest {
msg := &MyMessage{
Count: Int32(42),
}
if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil {
panic(err)
}
return UnmarshalTextTest{in: text, out: msg}
}
var unMarshalTextTests = []UnmarshalTextTest{
// Basic
{
in: " count:42\n name:\"Dave\" ",
out: &MyMessage{
Count: Int32(42),
Name: String("Dave"),
},
},
// Empty quoted string
{
in: `count:42 name:""`,
out: &MyMessage{
Count: Int32(42),
Name: String(""),
},
},
// Quoted string concatenation
{
in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`,
out: &MyMessage{
Count: Int32(42),
Name: String("My name is elsewhere"),
},
},
// Quoted string with escaped apostrophe
{
in: `count:42 name: "HOLIDAY - New Year\'s Day"`,
out: &MyMessage{
Count: Int32(42),
Name: String("HOLIDAY - New Year's Day"),
},
},
// Quoted string with single quote
{
in: `count:42 name: 'Roger "The Ramster" Ramjet'`,
out: &MyMessage{
Count: Int32(42),
Name: String(`Roger "The Ramster" Ramjet`),
},
},
// Quoted string with all the accepted special characters from the C++ test
{
in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"",
out: &MyMessage{
Count: Int32(42),
Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"),
},
},
// Quoted string with quoted backslash
{
in: `count:42 name: "\\'xyz"`,
out: &MyMessage{
Count: Int32(42),
Name: String(`\'xyz`),
},
},
// Quoted string with UTF-8 bytes.
{
in: "count:42 name: '\303\277\302\201\xAB'",
out: &MyMessage{
Count: Int32(42),
Name: String("\303\277\302\201\xAB"),
},
},
// Bad quoted string
{
in: `inner: < host: "\0" >` + "\n",
err: `line 1.15: invalid quoted string "\0"`,
},
// Number too large for int64
{
in: "count: 123456789012345678901",
err: "line 1.7: invalid int32: 123456789012345678901",
},
// Number too large for int32
{
in: "count: 1234567890123",
err: "line 1.7: invalid int32: 1234567890123",
},
// Number in hexadecimal
{
in: "count: 0x2beef",
out: &MyMessage{
Count: Int32(0x2beef),
},
},
// Number in octal
{
in: "count: 024601",
out: &MyMessage{
Count: Int32(024601),
},
},
// Floating point number with "f" suffix
{
in: "count: 4 others:< weight: 17.0f >",
out: &MyMessage{
Count: Int32(4),
Others: []*OtherMessage{
{
Weight: Float32(17),
},
},
},
},
// Floating point positive infinity
{
in: "count: 4 bigfloat: inf",
out: &MyMessage{
Count: Int32(4),
Bigfloat: Float64(math.Inf(1)),
},
},
// Floating point negative infinity
{
in: "count: 4 bigfloat: -inf",
out: &MyMessage{
Count: Int32(4),
Bigfloat: Float64(math.Inf(-1)),
},
},
// Number too large for float32
{
in: "others:< weight: 12345678901234567890123456789012345678901234567890 >",
err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890",
},
// Number posing as a quoted string
{
in: `inner: < host: 12 >` + "\n",
err: `line 1.15: invalid string: 12`,
},
// Quoted string posing as int32
{
in: `count: "12"`,
err: `line 1.7: invalid int32: "12"`,
},
// Quoted string posing a float32
{
in: `others:< weight: "17.4" >`,
err: `line 1.17: invalid float32: "17.4"`,
},
// Enum
{
in: `count:42 bikeshed: BLUE`,
out: &MyMessage{
Count: Int32(42),
Bikeshed: MyMessage_BLUE.Enum(),
},
},
// Repeated field
{
in: `count:42 pet: "horsey" pet:"bunny"`,
out: &MyMessage{
Count: Int32(42),
Pet: []string{"horsey", "bunny"},
},
},
// Repeated message with/without colon and <>/{}
{
in: `count:42 others:{} others{} others:<> others:{}`,
out: &MyMessage{
Count: Int32(42),
Others: []*OtherMessage{
{},
{},
{},
{},
},
},
},
// Missing colon for inner message
{
in: `count:42 inner < host: "cauchy.syd" >`,
out: &MyMessage{
Count: Int32(42),
Inner: &InnerMessage{
Host: String("cauchy.syd"),
},
},
},
// Missing colon for string field
{
in: `name "Dave"`,
err: `line 1.5: expected ':', found "\"Dave\""`,
},
// Missing colon for int32 field
{
in: `count 42`,
err: `line 1.6: expected ':', found "42"`,
},
// Missing required field
{
in: ``,
err: `line 1.0: message testdata.MyMessage missing required field "count"`,
},
// Repeated non-repeated field
{
in: `name: "Rob" name: "Russ"`,
err: `line 1.12: non-repeated field "name" was repeated`,
},
// Group
{
in: `count: 17 SomeGroup { group_field: 12 }`,
out: &MyMessage{
Count: Int32(17),
Somegroup: &MyMessage_SomeGroup{
GroupField: Int32(12),
},
},
},
// Semicolon between fields
{
in: `count:3;name:"Calvin"`,
out: &MyMessage{
Count: Int32(3),
Name: String("Calvin"),
},
},
// Comma between fields
{
in: `count:4,name:"Ezekiel"`,
out: &MyMessage{
Count: Int32(4),
Name: String("Ezekiel"),
},
},
// Extension
buildExtStructTest(`count: 42 [testdata.Ext.more]:<data:"Hello, world!" >`),
buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`),
buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`),
buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`),
// Big all-in-one
{
in: "count:42 # Meaning\n" +
`name:"Dave" ` +
`quote:"\"I didn't want to go.\"" ` +
`pet:"bunny" ` +
`pet:"kitty" ` +
`pet:"horsey" ` +
`inner:<` +
` host:"footrest.syd" ` +
` port:7001 ` +
` connected:true ` +
`> ` +
`others:<` +
` key:3735928559 ` +
` value:"\x01A\a\f" ` +
`> ` +
`others:<` +
" weight:58.9 # Atomic weight of Co\n" +
` inner:<` +
` host:"lesha.mtv" ` +
` port:8002 ` +
` >` +
`>`,
out: &MyMessage{
Count: Int32(42),
Name: String("Dave"),
Quote: String(`"I didn't want to go."`),
Pet: []string{"bunny", "kitty", "horsey"},
Inner: &InnerMessage{
Host: String("footrest.syd"),
Port: Int32(7001),
Connected: Bool(true),
},
Others: []*OtherMessage{
{
Key: Int64(3735928559),
Value: []byte{0x1, 'A', '\a', '\f'},
},
{
Weight: Float32(58.9),
Inner: &InnerMessage{
Host: String("lesha.mtv"),
Port: Int32(8002),
},
},
},
},
},
}
func TestUnmarshalText(t *testing.T) {
for i, test := range unMarshalTextTests {
pb := new(MyMessage)
err := UnmarshalText(test.in, pb)
if test.err == "" {
// We don't expect failure.
if err != nil {
t.Errorf("Test %d: Unexpected error: %v", i, err)
} else if !reflect.DeepEqual(pb, test.out) {
t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v",
i, pb, test.out)
}
} else {
// We do expect failure.
if err == nil {
t.Errorf("Test %d: Didn't get expected error: %v", i, test.err)
} else if err.Error() != test.err {
t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v",
i, err.Error(), test.err)
}
}
}
}
func TestUnmarshalTextCustomMessage(t *testing.T) {
msg := &textMessage{}
if err := UnmarshalText("custom", msg); err != nil {
t.Errorf("Unexpected error from custom unmarshal: %v", err)
}
if UnmarshalText("not custom", msg) == nil {
t.Errorf("Didn't get expected error from custom unmarshal")
}
}
// Regression test; this caused a panic.
func TestRepeatedEnum(t *testing.T) {
pb := new(RepeatedEnum)
if err := UnmarshalText("color: RED", pb); err != nil {
t.Fatal(err)
}
exp := &RepeatedEnum{
Color: []RepeatedEnum_Color{RepeatedEnum_RED},
}
if !Equal(pb, exp) {
t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp)
}
}
var benchInput string
func init() {
benchInput = "count: 4\n"
for i := 0; i < 1000; i++ {
benchInput += "pet: \"fido\"\n"
}
// Check it is valid input.
pb := new(MyMessage)
err := UnmarshalText(benchInput, pb)
if err != nil {
panic("Bad benchmark input: " + err.Error())
}
}
func BenchmarkUnmarshalText(b *testing.B) {
pb := new(MyMessage)
for i := 0; i < b.N; i++ {
UnmarshalText(benchInput, pb)
}
b.SetBytes(int64(len(benchInput)))
}
| cvik/etcd | third_party/code.google.com/p/gogoprotobuf/proto/text_parser_test.go | GO | apache-2.0 | 10,773 |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Automation;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools.VSTestHost;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
using Task = System.Threading.Tasks.Task;
namespace TestUtilities.UI {
/// <summary>
/// Provides wrappers for automating the VisualStudio UI.
/// </summary>
public class VisualStudioApp : AutomationWrapper, IDisposable {
private SolutionExplorerTree _solutionExplorerTreeView;
private ObjectBrowser _objectBrowser, _resourceView;
private AzureCloudServiceActivityLog _azureActivityLog;
private IntPtr _mainWindowHandle;
private readonly DTE _dte;
private IServiceProvider _provider;
private List<Action> _onDispose;
private bool _isDisposed, _skipCloseAll;
public VisualStudioApp(DTE dte = null)
: this(new IntPtr((dte ?? VSTestContext.DTE).MainWindow.HWnd)) {
_dte = dte ?? VSTestContext.DTE;
foreach (var p in ((DTE2)_dte).ToolWindows.OutputWindow.OutputWindowPanes.OfType<OutputWindowPane>()) {
p.Clear();
}
}
private VisualStudioApp(IntPtr windowHandle)
: base(AutomationElement.FromHandle(windowHandle)) {
_mainWindowHandle = windowHandle;
}
public bool IsDisposed {
get { return _isDisposed; }
}
public void OnDispose(Action action) {
Debug.Assert(action != null);
if (_onDispose == null) {
_onDispose = new List<Action> { action };
} else {
_onDispose.Add(action);
}
}
protected virtual void Dispose(bool disposing) {
if (!_isDisposed) {
_isDisposed = true;
try {
if (_onDispose != null) {
foreach (var action in _onDispose) {
action();
}
}
if (_dte != null && _dte.Debugger.CurrentMode != dbgDebugMode.dbgDesignMode) {
_dte.Debugger.TerminateAll();
_dte.Debugger.Stop();
}
DismissAllDialogs();
for (int i = 0; i < 100 && !_skipCloseAll; i++) {
try {
_dte.Solution.Close(false);
break;
} catch {
_dte.Documents.CloseAll(EnvDTE.vsSaveChanges.vsSaveChangesNo);
System.Threading.Thread.Sleep(200);
}
}
} catch (Exception ex) {
Debug.WriteLine("Exception disposing VisualStudioApp: {0}", ex);
}
}
}
public void Dispose() {
Dispose(true);
}
public void SuppressCloseAllOnDispose() {
_skipCloseAll = true;
}
public IComponentModel ComponentModel {
get {
return GetService<IComponentModel>(typeof(SComponentModel));
}
}
public IServiceProvider ServiceProvider {
get {
if (_provider == null) {
if (_dte == null) {
_provider = VSTestContext.ServiceProvider;
} else {
_provider = new ServiceProvider((IOleServiceProvider)_dte);
OnDispose(() => ((ServiceProvider)_provider).Dispose());
}
}
return _provider;
}
}
public T GetService<T>(Type type = null) {
return (T)ServiceProvider.GetService(type ?? typeof(T));
}
/// <summary>
/// File->Save
/// </summary>
public void SaveSelection() {
Dte.ExecuteCommand("File.SaveSelectedItems");
}
/// <summary>
/// Opens and activates the solution explorer window.
/// </summary>
public SolutionExplorerTree OpenSolutionExplorer() {
_solutionExplorerTreeView = null;
Dte.ExecuteCommand("View.SolutionExplorer");
return SolutionExplorerTreeView;
}
/// <summary>
/// Opens and activates the object browser window.
/// </summary>
public void OpenObjectBrowser() {
Dte.ExecuteCommand("View.ObjectBrowser");
}
/// <summary>
/// Opens and activates the Resource View window.
/// </summary>
public void OpenResourceView() {
Dte.ExecuteCommand("View.ResourceView");
}
public IntPtr OpenDialogWithDteExecuteCommand(string commandName, string commandArgs = "") {
Task task = Task.Factory.StartNew(() => {
Dte.ExecuteCommand(commandName, commandArgs);
Console.WriteLine("Successfully executed command {0} {1}", commandName, commandArgs);
});
IntPtr dialog = IntPtr.Zero;
try {
dialog = WaitForDialog(task);
} finally {
if (dialog == IntPtr.Zero) {
if (task.IsFaulted && task.Exception != null) {
Assert.Fail("Unexpected Exception - VSTestContext.DTE.ExecuteCommand({0},{1}){2}{3}",
commandName, commandArgs, Environment.NewLine, task.Exception.ToString());
}
Assert.Fail("Task failed - VSTestContext.DTE.ExecuteCommand({0},{1})",
commandName, commandArgs);
}
}
return dialog;
}
public void ExecuteCommand(string commandName, string commandArgs = "", int timeout = 25000) {
Task task = Task.Factory.StartNew(() => {
Console.WriteLine("Executing command {0} {1}", commandName, commandArgs);
Dte.ExecuteCommand(commandName, commandArgs);
Console.WriteLine("Successfully executed command {0} {1}", commandName, commandArgs);
});
bool timedOut = false;
try {
timedOut = !task.Wait(timeout);
} catch (AggregateException ae) {
foreach (var ex in ae.InnerExceptions) {
Console.WriteLine(ex.ToString());
}
throw ae.InnerException;
}
if (timedOut) {
string msg = String.Format("Command {0} failed to execute in specified timeout", commandName);
Console.WriteLine(msg);
DumpVS();
Assert.Fail(msg);
}
}
/// <summary>
/// Opens and activates the Navigate To window.
/// </summary>
public NavigateToDialog OpenNavigateTo() {
Task task = Task.Factory.StartNew(() => {
Dte.ExecuteCommand("Edit.NavigateTo");
Console.WriteLine("Successfully executed Edit.NavigateTo");
});
for (int retries = 10; retries > 0; --retries) {
#if DEV12_OR_LATER
foreach (var element in Element.FindAll(
TreeScope.Descendants,
new PropertyCondition(AutomationElement.ClassNameProperty, "Window")
).OfType<AutomationElement>()) {
if (element.FindAll(TreeScope.Children, new OrCondition(
new PropertyCondition(AutomationElement.AutomationIdProperty, "PART_SearchHost"),
new PropertyCondition(AutomationElement.AutomationIdProperty, "PART_ResultList")
)).Count == 2) {
return new NavigateToDialog(element);
}
}
#else
var element = Element.FindFirst(
TreeScope.Descendants,
new AndCondition(
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window),
new PropertyCondition(AutomationElement.NameProperty, "Navigate To")
)
);
if (element != null) {
return new NavigateToDialog(element);
}
#endif
System.Threading.Thread.Sleep(500);
}
Assert.Fail("Could not find Navigate To window");
return null;
}
public SaveDialog SaveAs() {
return SaveDialog.FromDte(this);
}
/// <summary>
/// Gets the specified document. Filename should be fully qualified filename.
/// </summary>
public EditorWindow GetDocument(string filename) {
Debug.Assert(Path.IsPathRooted(filename));
string windowName = Path.GetFileName(filename);
var elem = GetDocumentTab(windowName);
elem = elem.FindFirst(TreeScope.Descendants,
new PropertyCondition(
AutomationElement.ClassNameProperty,
"WpfTextView"
)
);
return new EditorWindow(filename, elem);
}
public AutomationElement GetDocumentTab(string windowName) {
var elem = Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(
AutomationElement.ClassNameProperty,
"TabItem"
),
new PropertyCondition(
AutomationElement.NameProperty,
windowName
)
)
);
if (elem == null) {
// maybe the file has been modified, try again with a *
elem = Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(
AutomationElement.ClassNameProperty,
"TabItem"
),
new PropertyCondition(
AutomationElement.NameProperty,
windowName + "*"
)
)
);
}
return elem;
}
/// <summary>
/// Selects the given source control provider. Name merely needs to be
/// enough text to disambiguate from other source control providers.
/// </summary>
public void SelectSourceControlProvider(string providerName) {
Element.SetFocus();
using (var dialog = ToolsOptionsDialog.FromDte(this)) {
dialog.SelectedView = "Source Control/Plug-in Selection";
var currentSourceControl = new ComboBox(
dialog.FindByAutomationId("2001") // Current source control plug-in
);
currentSourceControl.SelectItem(providerName);
dialog.OK();
}
}
public NewProjectDialog FileNewProject() {
var dialog = OpenDialogWithDteExecuteCommand("File.NewProject");
return new NewProjectDialog(this, AutomationElement.FromHandle(dialog));
}
public AttachToProcessDialog OpenDebugAttach() {
var dialog = OpenDialogWithDteExecuteCommand("Debug.AttachtoProcess");
return new AttachToProcessDialog(dialog);
}
public OutputWindowPane GetOutputWindow(string name) {
return ((DTE2)Dte).ToolWindows.OutputWindow.OutputWindowPanes.Item(name);
}
public IEnumerable<Window> OpenDocumentWindows {
get {
return Dte.Windows.OfType<Window>().Where(w => w.Document != null);
}
}
public void WaitForBuildComplete(int timeout) {
for (int i = 0; i < timeout; i += 500) {
if (Dte.Solution.SolutionBuild.BuildState == vsBuildState.vsBuildStateDone) {
return;
}
System.Threading.Thread.Sleep(500);
}
throw new TimeoutException("Timeout waiting for build to complete");
}
public string GetOutputWindowText(string name) {
var window = GetOutputWindow(name);
var doc = window.TextDocument;
doc.Selection.SelectAll();
return doc.Selection.Text;
}
public void WaitForOutputWindowText(string name, string containsText, int timeout=5000) {
for (int i = 0; i < timeout; i += 500) {
var text = GetOutputWindowText(name);
if (text.Contains(containsText)) {
return;
}
System.Threading.Thread.Sleep(500);
}
Assert.Fail("Failed to find {0} in output window {1}, found:\r\n{2}", containsText, name, GetOutputWindowText(name));
}
public void DismissAllDialogs() {
int foundWindow = 2;
while (foundWindow != 0) {
IVsUIShell uiShell = GetService<IVsUIShell>(typeof(IVsUIShell));
if (uiShell == null) {
return;
}
IntPtr hwnd;
uiShell.GetDialogOwnerHwnd(out hwnd);
for (int j = 0; j < 10 && hwnd == _mainWindowHandle; j++) {
System.Threading.Thread.Sleep(100);
uiShell.GetDialogOwnerHwnd(out hwnd);
}
//We didn't see any dialogs
if (hwnd == IntPtr.Zero || hwnd == _mainWindowHandle) {
foundWindow--;
continue;
}
//MessageBoxButton.Abort
//MessageBoxButton.Cancel
//MessageBoxButton.No
//MessageBoxButton.Ok
//MessageBoxButton.Yes
//The second parameter is going to be the value returned... We always send Ok
Debug.WriteLine("Dismissing dialog");
AutomationWrapper.DumpElement(AutomationElement.FromHandle(hwnd));
NativeMethods.EndDialog(hwnd, new IntPtr(1));
}
}
/// <summary>
/// Waits for a modal dialog to take over VS's main window and returns the HWND for the dialog.
/// </summary>
/// <returns></returns>
public IntPtr WaitForDialog(Task task) {
return WaitForDialogToReplace(_mainWindowHandle, task);
}
public IntPtr WaitForDialog() {
return WaitForDialogToReplace(_mainWindowHandle, null);
}
public ExceptionHelperDialog WaitForException() {
var window = FindByName("Exception Helper Indicator Window");
if (window != null) {
var innerPane = window.FindFirst(TreeScope.Descendants,
new PropertyCondition(
AutomationElement.ControlTypeProperty,
ControlType.Pane
)
);
Assert.IsNotNull(innerPane);
return new ExceptionHelperDialog(innerPane);
}
Assert.Fail("Failed to find exception helper window");
return null;
}
/// <summary>
/// Waits for a modal dialog to take over a given window and returns the HWND for the new dialog.
/// </summary>
/// <returns>An IntPtr which should be interpreted as an HWND</returns>
public IntPtr WaitForDialogToReplace(IntPtr originalHwnd) {
return WaitForDialogToReplace(originalHwnd, null);
}
/// <summary>
/// Waits for a modal dialog to take over a given window and returns the HWND for the new dialog.
/// </summary>
/// <returns>An IntPtr which should be interpreted as an HWND</returns>
public IntPtr WaitForDialogToReplace(AutomationElement element) {
return WaitForDialogToReplace(new IntPtr(element.Current.NativeWindowHandle), null);
}
private IntPtr WaitForDialogToReplace(IntPtr originalHwnd, Task task) {
IVsUIShell uiShell = GetService<IVsUIShell>(typeof(IVsUIShell));
IntPtr hwnd;
uiShell.GetDialogOwnerHwnd(out hwnd);
int timeout = task == null ? 10000 : 60000;
while (timeout > 0 && hwnd == originalHwnd && (task == null || !(task.IsFaulted || task.IsCanceled))) {
timeout -= 500;
System.Threading.Thread.Sleep(500);
uiShell.GetDialogOwnerHwnd(out hwnd);
}
if (task != null && (task.IsFaulted || task.IsCanceled)) {
return IntPtr.Zero;
}
if (hwnd == originalHwnd) {
DumpElement(AutomationElement.FromHandle(hwnd));
}
Assert.AreNotEqual(IntPtr.Zero, hwnd);
Assert.AreNotEqual(originalHwnd, hwnd, "Main window still has focus");
return hwnd;
}
/// <summary>
/// Waits for the VS main window to receive the focus.
/// </summary>
/// <returns>
/// True if the main window has the focus. Otherwise, false.
/// </returns>
public bool WaitForDialogDismissed(bool assertIfFailed = true, int timeout = 100000) {
IVsUIShell uiShell = GetService<IVsUIShell>(typeof(IVsUIShell));
IntPtr hwnd;
uiShell.GetDialogOwnerHwnd(out hwnd);
for (int i = 0; i < (timeout / 100) && hwnd != _mainWindowHandle; i++) {
System.Threading.Thread.Sleep(100);
uiShell.GetDialogOwnerHwnd(out hwnd);
}
if (assertIfFailed) {
Assert.AreEqual(_mainWindowHandle, hwnd);
return true;
}
return _mainWindowHandle == hwnd;
}
/// <summary>
/// Waits for no dialog. If a dialog appears before the timeout expires
/// then the test fails and the dialog is closed.
/// </summary>
public void WaitForNoDialog(TimeSpan timeout) {
IVsUIShell uiShell = GetService<IVsUIShell>(typeof(IVsUIShell));
IntPtr hwnd;
uiShell.GetDialogOwnerHwnd(out hwnd);
for (int i = 0; i < 100 && hwnd == _mainWindowHandle; i++) {
System.Threading.Thread.Sleep((int)timeout.TotalMilliseconds / 100);
uiShell.GetDialogOwnerHwnd(out hwnd);
}
if (hwnd != (IntPtr)_mainWindowHandle) {
AutomationWrapper.DumpElement(AutomationElement.FromHandle(hwnd));
NativeMethods.EndDialog(hwnd, (IntPtr)(int)MessageBoxButton.Cancel);
Assert.Fail("Dialog appeared - see output for details");
}
}
public static void CheckMessageBox(params string[] text) {
CheckMessageBox(MessageBoxButton.Cancel, text);
}
public static void CheckMessageBox(MessageBoxButton button, params string[] text) {
CheckAndDismissDialog(text, 65535, new IntPtr((int)button));
}
/// <summary>
/// Checks the text of a dialog and dismisses it.
///
/// dlgField is the field to check the text of.
/// buttonId is the button to press to dismiss.
/// </summary>
private static void CheckAndDismissDialog(string[] text, int dlgField, IntPtr buttonId) {
var handle = new IntPtr(VSTestContext.DTE.MainWindow.HWnd);
IVsUIShell uiShell = VSTestContext.ServiceProvider.GetService(typeof(IVsUIShell)) as IVsUIShell;
IntPtr hwnd;
uiShell.GetDialogOwnerHwnd(out hwnd);
for (int i = 0; i < 20 && hwnd == handle; i++) {
System.Threading.Thread.Sleep(500);
uiShell.GetDialogOwnerHwnd(out hwnd);
}
Assert.AreNotEqual(IntPtr.Zero, hwnd, "hwnd is null, We failed to get the dialog");
Assert.AreNotEqual(handle, hwnd, "hwnd is Dte.MainWindow, We failed to get the dialog");
Console.WriteLine("Ending dialog: ");
AutomationWrapper.DumpElement(AutomationElement.FromHandle(hwnd));
Console.WriteLine("--------");
try {
StringBuilder title = new StringBuilder(4096);
Assert.AreNotEqual(NativeMethods.GetDlgItemText(hwnd, dlgField, title, title.Capacity), (uint)0);
string t = title.ToString();
AssertUtil.Contains(t, text);
} finally {
NativeMethods.EndDialog(hwnd, buttonId);
}
}
/// <summary>
/// Provides access to Visual Studio's solution explorer tree view.
/// </summary>
public SolutionExplorerTree SolutionExplorerTreeView {
get {
if (_solutionExplorerTreeView == null) {
AutomationElement element = null;
for (int i = 0; i < 20 && element == null; i++) {
element = Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(
AutomationElement.ControlTypeProperty,
ControlType.Pane
),
new PropertyCondition(
AutomationElement.NameProperty,
"Solution Explorer"
)
)
);
if (element == null) {
System.Threading.Thread.Sleep(500);
}
}
AutomationElement treeElement = null;
if (element != null) {
for (int i = 0; i < 20 && treeElement == null; i++) {
treeElement = element.FindFirst(TreeScope.Descendants,
new PropertyCondition(
AutomationElement.ControlTypeProperty,
ControlType.Tree
)
);
if (treeElement == null) {
System.Threading.Thread.Sleep(500);
}
}
}
_solutionExplorerTreeView = new SolutionExplorerTree(treeElement);
}
return _solutionExplorerTreeView;
}
}
/// <summary>
/// Provides access to Visual Studio's object browser.
/// </summary>
public ObjectBrowser ObjectBrowser {
get {
if (_objectBrowser == null) {
AutomationElement element = null;
for (int i = 0; i < 10 && element == null; i++) {
element = Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(
AutomationElement.ClassNameProperty,
"ViewPresenter"
),
new PropertyCondition(
AutomationElement.NameProperty,
"Object Browser"
)
)
);
if (element == null) {
System.Threading.Thread.Sleep(500);
}
}
_objectBrowser = new ObjectBrowser(element);
}
return _objectBrowser;
}
}
/// <summary>
/// Provides access to Visual Studio's resource view.
/// </summary>
public ObjectBrowser ResourceView {
get {
if (_resourceView == null) {
AutomationElement element = null;
for (int i = 0; i < 10 && element == null; i++) {
element = Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(
AutomationElement.ClassNameProperty,
"ViewPresenter"
),
new PropertyCondition(
AutomationElement.NameProperty,
"Resource View"
)
)
);
if (element == null) {
System.Threading.Thread.Sleep(500);
}
}
_resourceView = new ObjectBrowser(element);
}
return _resourceView;
}
}
/// <summary>
/// Provides access to Azure's VS Activity Log window.
/// </summary>
public AzureCloudServiceActivityLog AzureActivityLog {
get {
if (_azureActivityLog == null) {
AutomationElement element = null;
for (int i = 0; i < 10 && element == null; i++) {
element = Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(
AutomationElement.ClassNameProperty,
"GenericPane"
),
new OrCondition(
new PropertyCondition(
AutomationElement.NameProperty,
"Microsoft Azure Activity Log"
),
new PropertyCondition(
AutomationElement.NameProperty,
"Windows Azure Activity Log"
)
)
)
);
if (element == null) {
System.Threading.Thread.Sleep(500);
}
}
_azureActivityLog = new AzureCloudServiceActivityLog(element);
}
return _azureActivityLog;
}
}
/// <summary>
/// Produces a name which is compatible with x:Name requirements (starts with a letter/underscore, contains
/// only letter, numbers, or underscores).
/// </summary>
public static string GetName(string title) {
if (title.Length == 0) {
return "InteractiveWindowHost";
}
StringBuilder res = new StringBuilder();
if (!Char.IsLetter(title[0])) {
res.Append('_');
}
foreach (char c in title) {
if (Char.IsLetter(c) || Char.IsDigit(c) || c == '_') {
res.Append(c);
}
}
res.Append("Host");
return res.ToString();
}
public DTE Dte {
get {
return _dte;
}
}
public void WaitForMode(dbgDebugMode mode) {
for (int i = 0; i < 60 && Dte.Debugger.CurrentMode != mode; i++) {
System.Threading.Thread.Sleep(500);
}
Assert.AreEqual(mode, VSTestContext.DTE.Debugger.CurrentMode);
}
public virtual Project CreateProject(
string languageName,
string templateName,
string createLocation,
string projectName,
bool newSolution = true,
bool suppressUI = true
) {
var sln = (Solution2)Dte.Solution;
var templatePath = sln.GetProjectTemplate(templateName, languageName);
Assert.IsTrue(File.Exists(templatePath) || Directory.Exists(templatePath), string.Format("Cannot find template '{0}' for language '{1}'", templateName, languageName));
var origName = projectName;
var projectDir = Path.Combine(createLocation, projectName);
for (int i = 1; Directory.Exists(projectDir); ++i) {
projectName = string.Format("{0}{1}", origName, i);
projectDir = Path.Combine(createLocation, projectName);
}
var previousSuppressUI = Dte.SuppressUI;
try {
Dte.SuppressUI = suppressUI;
sln.AddFromTemplate(templatePath, projectDir, projectName, newSolution);
} finally {
Dte.SuppressUI = previousSuppressUI;
}
return sln.Projects.Cast<Project>().FirstOrDefault(p => p.Name == projectName);
}
public Project OpenProject(
string projName,
string startItem = null,
int? expectedProjects = null,
string projectName = null,
bool setStartupItem = true,
Func<AutomationDialog, bool> onDialog = null
) {
string fullPath = TestData.GetPath(projName);
Assert.IsTrue(File.Exists(fullPath), "Cannot find " + fullPath);
Console.WriteLine("Opening {0}", fullPath);
// If there is a .suo file, delete that so that there is no state carried over from another test.
for (int i = 10; i <= 14; ++i) {
string suoPath = Path.ChangeExtension(fullPath, ".v" + i + ".suo");
if (File.Exists(suoPath)) {
File.Delete(suoPath);
}
}
var t = Task.Run(() => Dte.Solution.Open(fullPath));
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30))) {
try {
if (!t.Wait(1000, cts.Token)) {
// Load has taken a while, start checking whether a dialog has
// appeared
IVsUIShell uiShell = GetService<IVsUIShell>(typeof(IVsUIShell));
IntPtr hwnd;
while (!t.Wait(1000, cts.Token)) {
ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out hwnd));
if (hwnd != _mainWindowHandle) {
using (var dlg = new AutomationDialog(this, AutomationElement.FromHandle(hwnd))) {
if (onDialog == null || onDialog(dlg) == false) {
Console.WriteLine("Unexpected dialog");
DumpElement(dlg.Element);
Assert.Fail("Unexpected dialog while loading project");
}
}
}
}
}
} catch (OperationCanceledException) {
Assert.Fail("Failed to open project quickly enough");
}
}
Assert.IsTrue(Dte.Solution.IsOpen, "The solution is not open");
// Force all projects to load before running any tests.
var solution = GetService<IVsSolution4>(typeof(SVsSolution));
Assert.IsNotNull(solution, "Failed to obtain SVsSolution service");
solution.EnsureSolutionIsLoaded((uint)__VSBSLFLAGS.VSBSLFLAGS_None);
int count = Dte.Solution.Projects.Count;
if (expectedProjects != null && expectedProjects.Value != count) {
// if we have other files open we can end up with a bonus project...
int i = 0;
foreach (EnvDTE.Project proj in Dte.Solution.Projects) {
if (proj.Name != "Miscellaneous Files") {
i++;
}
}
Assert.AreEqual(expectedProjects, i, "Wrong number of loaded projects");
}
Project project = GetProject(projectName);
string outputText = "(unable to get Solution output)";
try {
outputText = GetOutputWindowText("Solution");
} catch (Exception) {
}
Assert.IsNotNull(project, "No project loaded: " + outputText);
// HACK: Testing whether Properties is just slow to initialize
for (int retries = 10; retries > 0 && project.Properties == null; --retries) {
Trace.TraceWarning("Waiting for project.Properties to become non-null");
System.Threading.Thread.Sleep(250);
}
Assert.IsNotNull(project.Properties, "No project properties: " + outputText);
Assert.IsTrue(project.Properties.GetEnumerator().MoveNext(), "No items in project properties: " + outputText);
if (startItem != null && setStartupItem) {
project.SetStartupFile(startItem);
for (var i = 0; i < 20; i++) {
//Wait for the startupItem to be set before returning from the project creation
try {
if (((string)project.Properties.Item("StartupFile").Value) == startItem) {
break;
}
} catch { }
System.Threading.Thread.Sleep(250);
}
}
DeleteAllBreakPoints();
return project;
}
public Project GetProject(string projectName) {
var iter = Dte.Solution.Projects.GetEnumerator();
if (!iter.MoveNext()) {
return null;
}
Project project = (Project)iter.Current;
if (projectName != null) {
while (project.Name != projectName) {
Assert.IsTrue(iter.MoveNext(), "Failed to find project named " + projectName);
project = (Project)iter.Current;
}
}
return project;
}
public void DeleteAllBreakPoints() {
var debug3 = (EnvDTE90.Debugger3)Dte.Debugger;
if (debug3.Breakpoints != null) {
foreach (var bp in debug3.Breakpoints) {
((EnvDTE90a.Breakpoint3)bp).Delete();
}
}
}
public Uri PublishToAzureCloudService(string serviceName, string subscriptionPublishSettingsFilePath) {
using (var publishDialog = AzureCloudServicePublishDialog.FromDte(this)) {
using (var manageSubscriptionsDialog = publishDialog.SelectManageSubscriptions()) {
LoadPublishSettings(manageSubscriptionsDialog, subscriptionPublishSettingsFilePath);
manageSubscriptionsDialog.Close();
}
publishDialog.ClickNext();
using (var createServiceDialog = publishDialog.SelectCreateNewService()) {
createServiceDialog.ServiceName = serviceName;
createServiceDialog.Location = "West US";
createServiceDialog.ClickCreate();
}
publishDialog.ClickPublish();
}
return new Uri(string.Format("http://{0}.cloudapp.net", serviceName));
}
public Uri PublishToAzureWebSite(string siteName, string subscriptionPublishSettingsFilePath) {
using (var publishDialog = AzureWebSitePublishDialog.FromDte(this)) {
using (var importSettingsDialog = publishDialog.ClickImportSettings()) {
importSettingsDialog.ClickImportFromWindowsAzureWebSite();
using (var manageSubscriptionsDialog = importSettingsDialog.ClickImportOrManageSubscriptions()) {
LoadPublishSettings(manageSubscriptionsDialog, subscriptionPublishSettingsFilePath);
manageSubscriptionsDialog.Close();
}
using (var createSiteDialog = importSettingsDialog.ClickNew()) {
createSiteDialog.SiteName = siteName;
createSiteDialog.ClickCreate();
}
importSettingsDialog.ClickOK();
}
publishDialog.ClickPublish();
}
return new Uri(string.Format("http://{0}.azurewebsites.net", siteName));
}
private void LoadPublishSettings(AzureManageSubscriptionsDialog manageSubscriptionsDialog, string publishSettingsFilePath) {
manageSubscriptionsDialog.ClickCertificates();
while (manageSubscriptionsDialog.SubscriptionsListBox.Count > 0) {
manageSubscriptionsDialog.SubscriptionsListBox[0].Select();
manageSubscriptionsDialog.ClickRemove();
WaitForDialogToReplace(manageSubscriptionsDialog.Element);
VisualStudioApp.CheckMessageBox(TestUtilities.MessageBoxButton.Yes);
}
using (var importSubscriptionDialog = manageSubscriptionsDialog.ClickImport()) {
importSubscriptionDialog.FileName = publishSettingsFilePath;
importSubscriptionDialog.ClickImport();
}
}
public List<IVsTaskItem> WaitForErrorListItems(int expectedCount) {
return WaitForTaskListItems(typeof(SVsErrorList), expectedCount, exactMatch: false);
}
public List<IVsTaskItem> WaitForTaskListItems(Type taskListService, int expectedCount, bool exactMatch = true) {
Console.Write("Waiting for {0} items on {1} ... ", expectedCount, taskListService.Name);
var errorList = GetService<IVsTaskList>(taskListService);
var allItems = new List<IVsTaskItem>();
if (expectedCount == 0) {
// Allow time for errors to appear. Otherwise when we expect 0
// errors we will get a false pass.
System.Threading.Thread.Sleep(5000);
}
for (int retries = 20; retries > 0; --retries) {
allItems.Clear();
IVsEnumTaskItems items;
ErrorHandler.ThrowOnFailure(errorList.EnumTaskItems(out items));
IVsTaskItem[] taskItems = new IVsTaskItem[1];
uint[] itemCnt = new uint[1];
while (ErrorHandler.Succeeded(items.Next(1, taskItems, itemCnt)) && itemCnt[0] == 1) {
allItems.Add(taskItems[0]);
}
if (allItems.Count >= expectedCount) {
break;
}
// give time for errors to process...
System.Threading.Thread.Sleep(1000);
}
if (exactMatch) {
Assert.AreEqual(expectedCount, allItems.Count);
}
return allItems;
}
internal ProjectItem AddItem(Project project, string language, string template, string filename) {
var fullTemplate = ((Solution2)project.DTE.Solution).GetProjectItemTemplate(template, language);
return project.ProjectItems.AddFromTemplate(fullTemplate, filename);
}
}
}
| dut3062796s/PTVS | Common/Tests/Utilities.UI/UI/VisualStudioApp.cs | C# | apache-2.0 | 42,155 |
/* ------------------------------------------------------------------
* Copyright (C) 1998-2009 PacketVideo
*
* 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.
* -------------------------------------------------------------------
*/
/****************************************************************************************
Portions of this file are derived from the following 3GPP standard:
3GPP TS 26.073
ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
Available from http://www.3gpp.org
(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
Permission to distribute, modify and use this file under the standard license
terms listed above has been obtained from the copyright holder.
****************************************************************************************/
/*
------------------------------------------------------------------------------
Pathname: ./audio/gsm-amr/c/src/d_gain_p.c
Functions: d_gain_p
Date: 01/31/2002
------------------------------------------------------------------------------
REVISION HISTORY
Description:
(1) Removed extra includes
(2) Replaced function calls to basic math operations with ANSI C standard
mathemtical operations.
(3) Placed code in the proper software template.
Description: Replaced "int" and/or "char" with OSCL defined types.
Description: Added #ifdef __cplusplus around extern'ed table.
Description:
------------------------------------------------------------------------------
INPUT AND OUTPUT DEFINITIONS
Inputs:
mode -- enumerated type -- AMR mode
index -- Word16 -- index of quantization
Outputs:
None
Returns:
Word16 gain -- (Q14)
Global Variables Used:
None
Local Variables Needed:
None
------------------------------------------------------------------------------
FUNCTION DESCRIPTION
Function : d_gain_pitch
Purpose : Decodes the pitch gain using the received index.
output is in Q14
------------------------------------------------------------------------------
REQUIREMENTS
------------------------------------------------------------------------------
REFERENCES
d_gain_p.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
------------------------------------------------------------------------------
PSEUDO-CODE
------------------------------------------------------------------------------
RESOURCES USED
When the code is written for a specific target processor the
the resources used should be documented below.
STACK USAGE: [stack count for this module] + [variable to represent
stack usage for each subroutine called]
where: [stack usage variable] = stack usage for [subroutine
name] (see [filename].ext)
DATA MEMORY USED: x words
PROGRAM MEMORY USED: x words
CLOCK CYCLES: [cycle count equation for this module] + [variable
used to represent cycle count for each subroutine
called]
where: [cycle count variable] = cycle count for [subroutine
name] (see [filename].ext)
------------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------
; INCLUDES
----------------------------------------------------------------------------*/
#include "d_gain_p.h"
#include "typedef.h"
#include "mode.h"
/*--------------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C"
{
#endif
/*----------------------------------------------------------------------------
; MACROS
; Define module specific macros here
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; DEFINES
; Include all pre-processor statements here. Include conditional
; compile variables also.
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; LOCAL FUNCTION DEFINITIONS
; Function Prototype declaration
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; LOCAL STORE/BUFFER/POINTER DEFINITIONS
; Variable declaration - defined here and used outside this module
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; EXTERNAL FUNCTION REFERENCES
; Declare functions defined elsewhere and referenced in this module
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
; Declare variables used in this module but defined elsewhere
----------------------------------------------------------------------------*/
extern const Word16 qua_gain_pitch[];
/*--------------------------------------------------------------------------*/
#ifdef __cplusplus
}
#endif
/*----------------------------------------------------------------------------
; FUNCTION CODE
----------------------------------------------------------------------------*/
Word16 d_gain_pitch( /* return value: gain (Q14) */
enum Mode mode, /* i : AMR mode */
Word16 index /* i : index of quantization */
)
{
Word16 gain;
gain = qua_gain_pitch[index];
if (mode == MR122)
{
/* clear 2 LSBits */
gain &= 0xFFFC;
}
return gain;
}
| dAck2cC2/m3e | src/frameworks/av/media/libstagefright/codecs/amrnb/dec/src/d_gain_p.cpp | C++ | apache-2.0 | 6,349 |
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubelet
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
utilfeature "k8s.io/apiserver/pkg/util/feature"
utilfeaturetesting "k8s.io/apiserver/pkg/util/feature/testing"
core "k8s.io/client-go/testing"
"k8s.io/client-go/tools/record"
// TODO: remove this import if
// api.Registry.GroupOrDie(v1.GroupName).GroupVersions[0].String() is changed
// to "v1"?
_ "k8s.io/kubernetes/pkg/apis/core/install"
"k8s.io/kubernetes/pkg/features"
kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
containertest "k8s.io/kubernetes/pkg/kubelet/container/testing"
"k8s.io/kubernetes/pkg/kubelet/server/portforward"
"k8s.io/kubernetes/pkg/kubelet/server/remotecommand"
"k8s.io/kubernetes/pkg/util/mount"
"k8s.io/kubernetes/pkg/volume/util/subpath"
)
func TestDisabledSubpath(t *testing.T) {
fm := &mount.FakeMounter{}
fsp := &subpath.FakeSubpath{}
pod := v1.Pod{
Spec: v1.PodSpec{
HostNetwork: true,
},
}
podVolumes := kubecontainer.VolumeMap{
"disk": kubecontainer.VolumeInfo{Mounter: &stubVolume{path: "/mnt/disk"}},
}
cases := map[string]struct {
container v1.Container
expectError bool
}{
"subpath not specified": {
v1.Container{
VolumeMounts: []v1.VolumeMount{
{
MountPath: "/mnt/path3",
Name: "disk",
ReadOnly: true,
},
},
},
false,
},
"subpath specified": {
v1.Container{
VolumeMounts: []v1.VolumeMount{
{
MountPath: "/mnt/path3",
SubPath: "/must/not/be/absolute",
Name: "disk",
ReadOnly: true,
},
},
},
true,
},
}
defer utilfeaturetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.VolumeSubpath, false)()
for name, test := range cases {
_, _, err := makeMounts(&pod, "/pod", &test.container, "fakepodname", "", "", podVolumes, fm, fsp, nil)
if err != nil && !test.expectError {
t.Errorf("test %v failed: %v", name, err)
}
if err == nil && test.expectError {
t.Errorf("test %v failed: expected error", name)
}
}
}
func TestNodeHostsFileContent(t *testing.T) {
testCases := []struct {
hostsFileName string
hostAliases []v1.HostAlias
rawHostsFileContent string
expectedHostsFileContent string
}{
{
"hosts_test_file1",
[]v1.HostAlias{},
`# hosts file for testing.
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
123.45.67.89 some.domain
`,
`# Kubernetes-managed hosts file (host network).
# hosts file for testing.
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
123.45.67.89 some.domain
`,
},
{
"hosts_test_file2",
[]v1.HostAlias{},
`# another hosts file for testing.
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
12.34.56.78 another.domain
`,
`# Kubernetes-managed hosts file (host network).
# another hosts file for testing.
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
12.34.56.78 another.domain
`,
},
{
"hosts_test_file1_with_host_aliases",
[]v1.HostAlias{
{IP: "123.45.67.89", Hostnames: []string{"foo", "bar", "baz"}},
},
`# hosts file for testing.
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
123.45.67.89 some.domain
`,
`# Kubernetes-managed hosts file (host network).
# hosts file for testing.
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
123.45.67.89 some.domain
# Entries added by HostAliases.
123.45.67.89 foo bar baz
`,
},
{
"hosts_test_file2_with_host_aliases",
[]v1.HostAlias{
{IP: "123.45.67.89", Hostnames: []string{"foo", "bar", "baz"}},
{IP: "456.78.90.123", Hostnames: []string{"park", "doo", "boo"}},
},
`# another hosts file for testing.
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
12.34.56.78 another.domain
`,
`# Kubernetes-managed hosts file (host network).
# another hosts file for testing.
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
12.34.56.78 another.domain
# Entries added by HostAliases.
123.45.67.89 foo bar baz
456.78.90.123 park doo boo
`,
},
}
for _, testCase := range testCases {
tmpdir, err := writeHostsFile(testCase.hostsFileName, testCase.rawHostsFileContent)
require.NoError(t, err, "could not create a temp hosts file")
defer os.RemoveAll(tmpdir)
actualContent, fileReadErr := nodeHostsFileContent(filepath.Join(tmpdir, testCase.hostsFileName), testCase.hostAliases)
require.NoError(t, fileReadErr, "could not create read hosts file")
assert.Equal(t, testCase.expectedHostsFileContent, string(actualContent), "hosts file content not expected")
}
}
// writeHostsFile will write a hosts file into a temporary dir, and return that dir.
// Caller is responsible for deleting the dir and its contents.
func writeHostsFile(filename string, cfg string) (string, error) {
tmpdir, err := ioutil.TempDir("", "kubelet=kubelet_pods_test.go=")
if err != nil {
return "", err
}
return tmpdir, ioutil.WriteFile(filepath.Join(tmpdir, filename), []byte(cfg), 0644)
}
func TestManagedHostsFileContent(t *testing.T) {
testCases := []struct {
hostIP string
hostName string
hostDomainName string
hostAliases []v1.HostAlias
expectedContent string
}{
{
"123.45.67.89",
"podFoo",
"",
[]v1.HostAlias{},
`# Kubernetes-managed hosts file.
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
123.45.67.89 podFoo
`,
},
{
"203.0.113.1",
"podFoo",
"domainFoo",
[]v1.HostAlias{},
`# Kubernetes-managed hosts file.
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
203.0.113.1 podFoo.domainFoo podFoo
`,
},
{
"203.0.113.1",
"podFoo",
"domainFoo",
[]v1.HostAlias{
{IP: "123.45.67.89", Hostnames: []string{"foo", "bar", "baz"}},
},
`# Kubernetes-managed hosts file.
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
203.0.113.1 podFoo.domainFoo podFoo
# Entries added by HostAliases.
123.45.67.89 foo bar baz
`,
},
{
"203.0.113.1",
"podFoo",
"domainFoo",
[]v1.HostAlias{
{IP: "123.45.67.89", Hostnames: []string{"foo", "bar", "baz"}},
{IP: "456.78.90.123", Hostnames: []string{"park", "doo", "boo"}},
},
`# Kubernetes-managed hosts file.
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
203.0.113.1 podFoo.domainFoo podFoo
# Entries added by HostAliases.
123.45.67.89 foo bar baz
456.78.90.123 park doo boo
`,
},
}
for _, testCase := range testCases {
actualContent := managedHostsFileContent(testCase.hostIP, testCase.hostName, testCase.hostDomainName, testCase.hostAliases)
assert.Equal(t, testCase.expectedContent, string(actualContent), "hosts file content not expected")
}
}
func TestRunInContainerNoSuchPod(t *testing.T) {
testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */)
defer testKubelet.Cleanup()
kubelet := testKubelet.kubelet
fakeRuntime := testKubelet.fakeRuntime
fakeRuntime.PodList = []*containertest.FakePod{}
podName := "podFoo"
podNamespace := "nsFoo"
containerName := "containerFoo"
output, err := kubelet.RunInContainer(
kubecontainer.GetPodFullName(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: podName, Namespace: podNamespace}}),
"",
containerName,
[]string{"ls"})
assert.Error(t, err)
assert.Nil(t, output, "output should be nil")
}
func TestRunInContainer(t *testing.T) {
for _, testError := range []error{nil, errors.New("bar")} {
testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */)
defer testKubelet.Cleanup()
kubelet := testKubelet.kubelet
fakeRuntime := testKubelet.fakeRuntime
fakeCommandRunner := containertest.FakeContainerCommandRunner{
Err: testError,
Stdout: "foo",
}
kubelet.runner = &fakeCommandRunner
containerID := kubecontainer.ContainerID{Type: "test", ID: "abc1234"}
fakeRuntime.PodList = []*containertest.FakePod{
{Pod: &kubecontainer.Pod{
ID: "12345678",
Name: "podFoo",
Namespace: "nsFoo",
Containers: []*kubecontainer.Container{
{Name: "containerFoo",
ID: containerID,
},
},
}},
}
cmd := []string{"ls"}
actualOutput, err := kubelet.RunInContainer("podFoo_nsFoo", "", "containerFoo", cmd)
assert.Equal(t, containerID, fakeCommandRunner.ContainerID, "(testError=%v) ID", testError)
assert.Equal(t, cmd, fakeCommandRunner.Cmd, "(testError=%v) command", testError)
// this isn't 100% foolproof as a bug in a real ContainerCommandRunner where it fails to copy to stdout/stderr wouldn't be caught by this test
assert.Equal(t, "foo", string(actualOutput), "(testError=%v) output", testError)
assert.Equal(t, err, testError, "(testError=%v) err", testError)
}
}
type testServiceLister struct {
services []*v1.Service
}
func (ls testServiceLister) List(labels.Selector) ([]*v1.Service, error) {
return ls.services, nil
}
type envs []kubecontainer.EnvVar
func (e envs) Len() int {
return len(e)
}
func (e envs) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
func (e envs) Less(i, j int) bool { return e[i].Name < e[j].Name }
func buildService(name, namespace, clusterIP, protocol string, port int) *v1.Service {
return &v1.Service{
ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Protocol: v1.Protocol(protocol),
Port: int32(port),
}},
ClusterIP: clusterIP,
},
}
}
func TestMakeEnvironmentVariables(t *testing.T) {
trueVal := true
services := []*v1.Service{
buildService("kubernetes", metav1.NamespaceDefault, "1.2.3.1", "TCP", 8081),
buildService("test", "test1", "1.2.3.3", "TCP", 8083),
buildService("kubernetes", "test2", "1.2.3.4", "TCP", 8084),
buildService("test", "test2", "1.2.3.5", "TCP", 8085),
buildService("test", "test2", "None", "TCP", 8085),
buildService("test", "test2", "", "TCP", 8085),
buildService("kubernetes", "kubernetes", "1.2.3.6", "TCP", 8086),
buildService("not-special", "kubernetes", "1.2.3.8", "TCP", 8088),
buildService("not-special", "kubernetes", "None", "TCP", 8088),
buildService("not-special", "kubernetes", "", "TCP", 8088),
}
trueValue := true
falseValue := false
testCases := []struct {
name string // the name of the test case
ns string // the namespace to generate environment for
enableServiceLinks *bool // enabling service links
container *v1.Container // the container to use
masterServiceNs string // the namespace to read master service info from
nilLister bool // whether the lister should be nil
configMap *v1.ConfigMap // an optional ConfigMap to pull from
secret *v1.Secret // an optional Secret to pull from
expectedEnvs []kubecontainer.EnvVar // a set of expected environment vars
expectedError bool // does the test fail
expectedEvent string // does the test emit an event
}{
{
name: "api server = Y, kubelet = Y",
ns: "test1",
enableServiceLinks: &falseValue,
container: &v1.Container{
Env: []v1.EnvVar{
{Name: "FOO", Value: "BAR"},
{Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"},
{Name: "TEST_SERVICE_PORT", Value: "8083"},
{Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"},
{Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"},
{Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"},
{Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"},
{Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"},
},
},
masterServiceNs: metav1.NamespaceDefault,
nilLister: false,
expectedEnvs: []kubecontainer.EnvVar{
{Name: "FOO", Value: "BAR"},
{Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"},
{Name: "TEST_SERVICE_PORT", Value: "8083"},
{Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"},
{Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"},
{Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"},
{Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"},
{Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"},
{Name: "KUBERNETES_SERVICE_PORT", Value: "8081"},
{Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.1"},
{Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.1:8081"},
{Name: "KUBERNETES_PORT_8081_TCP", Value: "tcp://1.2.3.1:8081"},
{Name: "KUBERNETES_PORT_8081_TCP_PROTO", Value: "tcp"},
{Name: "KUBERNETES_PORT_8081_TCP_PORT", Value: "8081"},
{Name: "KUBERNETES_PORT_8081_TCP_ADDR", Value: "1.2.3.1"},
},
},
{
name: "api server = Y, kubelet = N",
ns: "test1",
enableServiceLinks: &falseValue,
container: &v1.Container{
Env: []v1.EnvVar{
{Name: "FOO", Value: "BAR"},
{Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"},
{Name: "TEST_SERVICE_PORT", Value: "8083"},
{Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"},
{Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"},
{Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"},
{Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"},
{Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"},
},
},
masterServiceNs: metav1.NamespaceDefault,
nilLister: true,
expectedEnvs: []kubecontainer.EnvVar{
{Name: "FOO", Value: "BAR"},
{Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"},
{Name: "TEST_SERVICE_PORT", Value: "8083"},
{Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"},
{Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"},
{Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"},
{Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"},
{Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"},
},
},
{
name: "api server = N; kubelet = Y",
ns: "test1",
enableServiceLinks: &falseValue,
container: &v1.Container{
Env: []v1.EnvVar{
{Name: "FOO", Value: "BAZ"},
},
},
masterServiceNs: metav1.NamespaceDefault,
nilLister: false,
expectedEnvs: []kubecontainer.EnvVar{
{Name: "FOO", Value: "BAZ"},
{Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.1"},
{Name: "KUBERNETES_SERVICE_PORT", Value: "8081"},
{Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.1:8081"},
{Name: "KUBERNETES_PORT_8081_TCP", Value: "tcp://1.2.3.1:8081"},
{Name: "KUBERNETES_PORT_8081_TCP_PROTO", Value: "tcp"},
{Name: "KUBERNETES_PORT_8081_TCP_PORT", Value: "8081"},
{Name: "KUBERNETES_PORT_8081_TCP_ADDR", Value: "1.2.3.1"},
},
},
{
name: "api server = N; kubelet = Y; service env vars",
ns: "test1",
enableServiceLinks: &trueValue,
container: &v1.Container{
Env: []v1.EnvVar{
{Name: "FOO", Value: "BAZ"},
},
},
masterServiceNs: metav1.NamespaceDefault,
nilLister: false,
expectedEnvs: []kubecontainer.EnvVar{
{Name: "FOO", Value: "BAZ"},
{Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"},
{Name: "TEST_SERVICE_PORT", Value: "8083"},
{Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"},
{Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"},
{Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"},
{Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"},
{Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"},
{Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.1"},
{Name: "KUBERNETES_SERVICE_PORT", Value: "8081"},
{Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.1:8081"},
{Name: "KUBERNETES_PORT_8081_TCP", Value: "tcp://1.2.3.1:8081"},
{Name: "KUBERNETES_PORT_8081_TCP_PROTO", Value: "tcp"},
{Name: "KUBERNETES_PORT_8081_TCP_PORT", Value: "8081"},
{Name: "KUBERNETES_PORT_8081_TCP_ADDR", Value: "1.2.3.1"},
},
},
{
name: "master service in pod ns",
ns: "test2",
enableServiceLinks: &falseValue,
container: &v1.Container{
Env: []v1.EnvVar{
{Name: "FOO", Value: "ZAP"},
},
},
masterServiceNs: "kubernetes",
nilLister: false,
expectedEnvs: []kubecontainer.EnvVar{
{Name: "FOO", Value: "ZAP"},
{Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.6"},
{Name: "KUBERNETES_SERVICE_PORT", Value: "8086"},
{Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.6:8086"},
{Name: "KUBERNETES_PORT_8086_TCP", Value: "tcp://1.2.3.6:8086"},
{Name: "KUBERNETES_PORT_8086_TCP_PROTO", Value: "tcp"},
{Name: "KUBERNETES_PORT_8086_TCP_PORT", Value: "8086"},
{Name: "KUBERNETES_PORT_8086_TCP_ADDR", Value: "1.2.3.6"},
},
},
{
name: "master service in pod ns, service env vars",
ns: "test2",
enableServiceLinks: &trueValue,
container: &v1.Container{
Env: []v1.EnvVar{
{Name: "FOO", Value: "ZAP"},
},
},
masterServiceNs: "kubernetes",
nilLister: false,
expectedEnvs: []kubecontainer.EnvVar{
{Name: "FOO", Value: "ZAP"},
{Name: "TEST_SERVICE_HOST", Value: "1.2.3.5"},
{Name: "TEST_SERVICE_PORT", Value: "8085"},
{Name: "TEST_PORT", Value: "tcp://1.2.3.5:8085"},
{Name: "TEST_PORT_8085_TCP", Value: "tcp://1.2.3.5:8085"},
{Name: "TEST_PORT_8085_TCP_PROTO", Value: "tcp"},
{Name: "TEST_PORT_8085_TCP_PORT", Value: "8085"},
{Name: "TEST_PORT_8085_TCP_ADDR", Value: "1.2.3.5"},
{Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.4"},
{Name: "KUBERNETES_SERVICE_PORT", Value: "8084"},
{Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.4:8084"},
{Name: "KUBERNETES_PORT_8084_TCP", Value: "tcp://1.2.3.4:8084"},
{Name: "KUBERNETES_PORT_8084_TCP_PROTO", Value: "tcp"},
{Name: "KUBERNETES_PORT_8084_TCP_PORT", Value: "8084"},
{Name: "KUBERNETES_PORT_8084_TCP_ADDR", Value: "1.2.3.4"},
},
},
{
name: "pod in master service ns",
ns: "kubernetes",
enableServiceLinks: &falseValue,
container: &v1.Container{},
masterServiceNs: "kubernetes",
nilLister: false,
expectedEnvs: []kubecontainer.EnvVar{
{Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.6"},
{Name: "KUBERNETES_SERVICE_PORT", Value: "8086"},
{Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.6:8086"},
{Name: "KUBERNETES_PORT_8086_TCP", Value: "tcp://1.2.3.6:8086"},
{Name: "KUBERNETES_PORT_8086_TCP_PROTO", Value: "tcp"},
{Name: "KUBERNETES_PORT_8086_TCP_PORT", Value: "8086"},
{Name: "KUBERNETES_PORT_8086_TCP_ADDR", Value: "1.2.3.6"},
},
},
{
name: "pod in master service ns, service env vars",
ns: "kubernetes",
enableServiceLinks: &trueValue,
container: &v1.Container{},
masterServiceNs: "kubernetes",
nilLister: false,
expectedEnvs: []kubecontainer.EnvVar{
{Name: "NOT_SPECIAL_SERVICE_HOST", Value: "1.2.3.8"},
{Name: "NOT_SPECIAL_SERVICE_PORT", Value: "8088"},
{Name: "NOT_SPECIAL_PORT", Value: "tcp://1.2.3.8:8088"},
{Name: "NOT_SPECIAL_PORT_8088_TCP", Value: "tcp://1.2.3.8:8088"},
{Name: "NOT_SPECIAL_PORT_8088_TCP_PROTO", Value: "tcp"},
{Name: "NOT_SPECIAL_PORT_8088_TCP_PORT", Value: "8088"},
{Name: "NOT_SPECIAL_PORT_8088_TCP_ADDR", Value: "1.2.3.8"},
{Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.6"},
{Name: "KUBERNETES_SERVICE_PORT", Value: "8086"},
{Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.6:8086"},
{Name: "KUBERNETES_PORT_8086_TCP", Value: "tcp://1.2.3.6:8086"},
{Name: "KUBERNETES_PORT_8086_TCP_PROTO", Value: "tcp"},
{Name: "KUBERNETES_PORT_8086_TCP_PORT", Value: "8086"},
{Name: "KUBERNETES_PORT_8086_TCP_ADDR", Value: "1.2.3.6"},
},
},
{
name: "downward api pod",
ns: "downward-api",
enableServiceLinks: &falseValue,
container: &v1.Container{
Env: []v1.EnvVar{
{
Name: "POD_NAME",
ValueFrom: &v1.EnvVarSource{
FieldRef: &v1.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.name",
},
},
},
{
Name: "POD_NAMESPACE",
ValueFrom: &v1.EnvVarSource{
FieldRef: &v1.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.namespace",
},
},
},
{
Name: "POD_NODE_NAME",
ValueFrom: &v1.EnvVarSource{
FieldRef: &v1.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "spec.nodeName",
},
},
},
{
Name: "POD_SERVICE_ACCOUNT_NAME",
ValueFrom: &v1.EnvVarSource{
FieldRef: &v1.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "spec.serviceAccountName",
},
},
},
{
Name: "POD_IP",
ValueFrom: &v1.EnvVarSource{
FieldRef: &v1.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "status.podIP",
},
},
},
{
Name: "HOST_IP",
ValueFrom: &v1.EnvVarSource{
FieldRef: &v1.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "status.hostIP",
},
},
},
},
},
masterServiceNs: "nothing",
nilLister: true,
expectedEnvs: []kubecontainer.EnvVar{
{Name: "POD_NAME", Value: "dapi-test-pod-name"},
{Name: "POD_NAMESPACE", Value: "downward-api"},
{Name: "POD_NODE_NAME", Value: "node-name"},
{Name: "POD_SERVICE_ACCOUNT_NAME", Value: "special"},
{Name: "POD_IP", Value: "1.2.3.4"},
{Name: "HOST_IP", Value: testKubeletHostIP},
},
},
{
name: "env expansion",
ns: "test1",
enableServiceLinks: &falseValue,
container: &v1.Container{
Env: []v1.EnvVar{
{
Name: "TEST_LITERAL",
Value: "test-test-test",
},
{
Name: "POD_NAME",
ValueFrom: &v1.EnvVarSource{
FieldRef: &v1.ObjectFieldSelector{
APIVersion: "v1", //legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(),
FieldPath: "metadata.name",
},
},
},
{
Name: "OUT_OF_ORDER_TEST",
Value: "$(OUT_OF_ORDER_TARGET)",
},
{
Name: "OUT_OF_ORDER_TARGET",
Value: "FOO",
},
{
Name: "EMPTY_VAR",
},
{
Name: "EMPTY_TEST",
Value: "foo-$(EMPTY_VAR)",
},
{
Name: "POD_NAME_TEST2",
Value: "test2-$(POD_NAME)",
},
{
Name: "POD_NAME_TEST3",
Value: "$(POD_NAME_TEST2)-3",
},
{
Name: "LITERAL_TEST",
Value: "literal-$(TEST_LITERAL)",
},
{
Name: "TEST_UNDEFINED",
Value: "$(UNDEFINED_VAR)",
},
},
},
masterServiceNs: "nothing",
nilLister: false,
expectedEnvs: []kubecontainer.EnvVar{
{
Name: "TEST_LITERAL",
Value: "test-test-test",
},
{
Name: "POD_NAME",
Value: "dapi-test-pod-name",
},
{
Name: "POD_NAME_TEST2",
Value: "test2-dapi-test-pod-name",
},
{
Name: "POD_NAME_TEST3",
Value: "test2-dapi-test-pod-name-3",
},
{
Name: "LITERAL_TEST",
Value: "literal-test-test-test",
},
{
Name: "OUT_OF_ORDER_TEST",
Value: "$(OUT_OF_ORDER_TARGET)",
},
{
Name: "OUT_OF_ORDER_TARGET",
Value: "FOO",
},
{
Name: "TEST_UNDEFINED",
Value: "$(UNDEFINED_VAR)",
},
{
Name: "EMPTY_VAR",
},
{
Name: "EMPTY_TEST",
Value: "foo-",
},
},
},
{
name: "env expansion, service env vars",
ns: "test1",
enableServiceLinks: &trueValue,
container: &v1.Container{
Env: []v1.EnvVar{
{
Name: "TEST_LITERAL",
Value: "test-test-test",
},
{
Name: "POD_NAME",
ValueFrom: &v1.EnvVarSource{
FieldRef: &v1.ObjectFieldSelector{
APIVersion: "v1",
FieldPath: "metadata.name",
},
},
},
{
Name: "OUT_OF_ORDER_TEST",
Value: "$(OUT_OF_ORDER_TARGET)",
},
{
Name: "OUT_OF_ORDER_TARGET",
Value: "FOO",
},
{
Name: "EMPTY_VAR",
},
{
Name: "EMPTY_TEST",
Value: "foo-$(EMPTY_VAR)",
},
{
Name: "POD_NAME_TEST2",
Value: "test2-$(POD_NAME)",
},
{
Name: "POD_NAME_TEST3",
Value: "$(POD_NAME_TEST2)-3",
},
{
Name: "LITERAL_TEST",
Value: "literal-$(TEST_LITERAL)",
},
{
Name: "SERVICE_VAR_TEST",
Value: "$(TEST_SERVICE_HOST):$(TEST_SERVICE_PORT)",
},
{
Name: "TEST_UNDEFINED",
Value: "$(UNDEFINED_VAR)",
},
},
},
masterServiceNs: "nothing",
nilLister: false,
expectedEnvs: []kubecontainer.EnvVar{
{
Name: "TEST_LITERAL",
Value: "test-test-test",
},
{
Name: "POD_NAME",
Value: "dapi-test-pod-name",
},
{
Name: "POD_NAME_TEST2",
Value: "test2-dapi-test-pod-name",
},
{
Name: "POD_NAME_TEST3",
Value: "test2-dapi-test-pod-name-3",
},
{
Name: "LITERAL_TEST",
Value: "literal-test-test-test",
},
{
Name: "TEST_SERVICE_HOST",
Value: "1.2.3.3",
},
{
Name: "TEST_SERVICE_PORT",
Value: "8083",
},
{
Name: "TEST_PORT",
Value: "tcp://1.2.3.3:8083",
},
{
Name: "TEST_PORT_8083_TCP",
Value: "tcp://1.2.3.3:8083",
},
{
Name: "TEST_PORT_8083_TCP_PROTO",
Value: "tcp",
},
{
Name: "TEST_PORT_8083_TCP_PORT",
Value: "8083",
},
{
Name: "TEST_PORT_8083_TCP_ADDR",
Value: "1.2.3.3",
},
{
Name: "SERVICE_VAR_TEST",
Value: "1.2.3.3:8083",
},
{
Name: "OUT_OF_ORDER_TEST",
Value: "$(OUT_OF_ORDER_TARGET)",
},
{
Name: "OUT_OF_ORDER_TARGET",
Value: "FOO",
},
{
Name: "TEST_UNDEFINED",
Value: "$(UNDEFINED_VAR)",
},
{
Name: "EMPTY_VAR",
},
{
Name: "EMPTY_TEST",
Value: "foo-",
},
},
},
{
name: "configmapkeyref_missing_optional",
ns: "test",
enableServiceLinks: &falseValue,
container: &v1.Container{
Env: []v1.EnvVar{
{
Name: "POD_NAME",
ValueFrom: &v1.EnvVarSource{
ConfigMapKeyRef: &v1.ConfigMapKeySelector{
LocalObjectReference: v1.LocalObjectReference{Name: "missing-config-map"},
Key: "key",
Optional: &trueVal,
},
},
},
},
},
masterServiceNs: "nothing",
expectedEnvs: nil,
},
{
name: "configmapkeyref_missing_key_optional",
ns: "test",
enableServiceLinks: &falseValue,
container: &v1.Container{
Env: []v1.EnvVar{
{
Name: "POD_NAME",
ValueFrom: &v1.EnvVarSource{
ConfigMapKeyRef: &v1.ConfigMapKeySelector{
LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"},
Key: "key",
Optional: &trueVal,
},
},
},
},
},
masterServiceNs: "nothing",
nilLister: true,
configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: "test1",
Name: "test-configmap",
},
Data: map[string]string{
"a": "b",
},
},
expectedEnvs: nil,
},
{
name: "secretkeyref_missing_optional",
ns: "test",
enableServiceLinks: &falseValue,
container: &v1.Container{
Env: []v1.EnvVar{
{
Name: "POD_NAME",
ValueFrom: &v1.EnvVarSource{
SecretKeyRef: &v1.SecretKeySelector{
LocalObjectReference: v1.LocalObjectReference{Name: "missing-secret"},
Key: "key",
Optional: &trueVal,
},
},
},
},
},
masterServiceNs: "nothing",
expectedEnvs: nil,
},
{
name: "secretkeyref_missing_key_optional",
ns: "test",
enableServiceLinks: &falseValue,
container: &v1.Container{
Env: []v1.EnvVar{
{
Name: "POD_NAME",
ValueFrom: &v1.EnvVarSource{
SecretKeyRef: &v1.SecretKeySelector{
LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"},
Key: "key",
Optional: &trueVal,
},
},
},
},
},
masterServiceNs: "nothing",
nilLister: true,
secret: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: "test1",
Name: "test-secret",
},
Data: map[string][]byte{
"a": []byte("b"),
},
},
expectedEnvs: nil,
},
{
name: "configmap",
ns: "test1",
enableServiceLinks: &falseValue,
container: &v1.Container{
EnvFrom: []v1.EnvFromSource{
{
ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}},
},
{
Prefix: "p_",
ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}},
},
},
Env: []v1.EnvVar{
{
Name: "TEST_LITERAL",
Value: "test-test-test",
},
{
Name: "EXPANSION_TEST",
Value: "$(REPLACE_ME)",
},
{
Name: "DUPE_TEST",
Value: "ENV_VAR",
},
},
},
masterServiceNs: "nothing",
nilLister: false,
configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: "test1",
Name: "test-configmap",
},
Data: map[string]string{
"REPLACE_ME": "FROM_CONFIG_MAP",
"DUPE_TEST": "CONFIG_MAP",
},
},
expectedEnvs: []kubecontainer.EnvVar{
{
Name: "TEST_LITERAL",
Value: "test-test-test",
},
{
Name: "REPLACE_ME",
Value: "FROM_CONFIG_MAP",
},
{
Name: "EXPANSION_TEST",
Value: "FROM_CONFIG_MAP",
},
{
Name: "DUPE_TEST",
Value: "ENV_VAR",
},
{
Name: "p_REPLACE_ME",
Value: "FROM_CONFIG_MAP",
},
{
Name: "p_DUPE_TEST",
Value: "CONFIG_MAP",
},
},
},
{
name: "configmap, service env vars",
ns: "test1",
enableServiceLinks: &trueValue,
container: &v1.Container{
EnvFrom: []v1.EnvFromSource{
{
ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}},
},
{
Prefix: "p_",
ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}},
},
},
Env: []v1.EnvVar{
{
Name: "TEST_LITERAL",
Value: "test-test-test",
},
{
Name: "EXPANSION_TEST",
Value: "$(REPLACE_ME)",
},
{
Name: "DUPE_TEST",
Value: "ENV_VAR",
},
},
},
masterServiceNs: "nothing",
nilLister: false,
configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: "test1",
Name: "test-configmap",
},
Data: map[string]string{
"REPLACE_ME": "FROM_CONFIG_MAP",
"DUPE_TEST": "CONFIG_MAP",
},
},
expectedEnvs: []kubecontainer.EnvVar{
{
Name: "TEST_LITERAL",
Value: "test-test-test",
},
{
Name: "TEST_SERVICE_HOST",
Value: "1.2.3.3",
},
{
Name: "TEST_SERVICE_PORT",
Value: "8083",
},
{
Name: "TEST_PORT",
Value: "tcp://1.2.3.3:8083",
},
{
Name: "TEST_PORT_8083_TCP",
Value: "tcp://1.2.3.3:8083",
},
{
Name: "TEST_PORT_8083_TCP_PROTO",
Value: "tcp",
},
{
Name: "TEST_PORT_8083_TCP_PORT",
Value: "8083",
},
{
Name: "TEST_PORT_8083_TCP_ADDR",
Value: "1.2.3.3",
},
{
Name: "REPLACE_ME",
Value: "FROM_CONFIG_MAP",
},
{
Name: "EXPANSION_TEST",
Value: "FROM_CONFIG_MAP",
},
{
Name: "DUPE_TEST",
Value: "ENV_VAR",
},
{
Name: "p_REPLACE_ME",
Value: "FROM_CONFIG_MAP",
},
{
Name: "p_DUPE_TEST",
Value: "CONFIG_MAP",
},
},
},
{
name: "configmap_missing",
ns: "test1",
enableServiceLinks: &falseValue,
container: &v1.Container{
EnvFrom: []v1.EnvFromSource{
{ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}}},
},
},
masterServiceNs: "nothing",
expectedError: true,
},
{
name: "configmap_missing_optional",
ns: "test",
enableServiceLinks: &falseValue,
container: &v1.Container{
EnvFrom: []v1.EnvFromSource{
{ConfigMapRef: &v1.ConfigMapEnvSource{
Optional: &trueVal,
LocalObjectReference: v1.LocalObjectReference{Name: "missing-config-map"}}},
},
},
masterServiceNs: "nothing",
expectedEnvs: nil,
},
{
name: "configmap_invalid_keys",
ns: "test",
enableServiceLinks: &falseValue,
container: &v1.Container{
EnvFrom: []v1.EnvFromSource{
{ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}}},
},
},
masterServiceNs: "nothing",
configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: "test1",
Name: "test-configmap",
},
Data: map[string]string{
"1234": "abc",
"1z": "abc",
"key": "value",
},
},
expectedEnvs: []kubecontainer.EnvVar{
{
Name: "key",
Value: "value",
},
},
expectedEvent: "Warning InvalidEnvironmentVariableNames Keys [1234, 1z] from the EnvFrom configMap test/test-config-map were skipped since they are considered invalid environment variable names.",
},
{
name: "configmap_invalid_keys_valid",
ns: "test",
enableServiceLinks: &falseValue,
container: &v1.Container{
EnvFrom: []v1.EnvFromSource{
{
Prefix: "p_",
ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}},
},
},
},
masterServiceNs: "",
configMap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: "test1",
Name: "test-configmap",
},
Data: map[string]string{
"1234": "abc",
},
},
expectedEnvs: []kubecontainer.EnvVar{
{
Name: "p_1234",
Value: "abc",
},
},
},
{
name: "secret",
ns: "test1",
enableServiceLinks: &falseValue,
container: &v1.Container{
EnvFrom: []v1.EnvFromSource{
{
SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}},
},
{
Prefix: "p_",
SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}},
},
},
Env: []v1.EnvVar{
{
Name: "TEST_LITERAL",
Value: "test-test-test",
},
{
Name: "EXPANSION_TEST",
Value: "$(REPLACE_ME)",
},
{
Name: "DUPE_TEST",
Value: "ENV_VAR",
},
},
},
masterServiceNs: "nothing",
nilLister: false,
secret: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: "test1",
Name: "test-secret",
},
Data: map[string][]byte{
"REPLACE_ME": []byte("FROM_SECRET"),
"DUPE_TEST": []byte("SECRET"),
},
},
expectedEnvs: []kubecontainer.EnvVar{
{
Name: "TEST_LITERAL",
Value: "test-test-test",
},
{
Name: "REPLACE_ME",
Value: "FROM_SECRET",
},
{
Name: "EXPANSION_TEST",
Value: "FROM_SECRET",
},
{
Name: "DUPE_TEST",
Value: "ENV_VAR",
},
{
Name: "p_REPLACE_ME",
Value: "FROM_SECRET",
},
{
Name: "p_DUPE_TEST",
Value: "SECRET",
},
},
},
{
name: "secret, service env vars",
ns: "test1",
enableServiceLinks: &trueValue,
container: &v1.Container{
EnvFrom: []v1.EnvFromSource{
{
SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}},
},
{
Prefix: "p_",
SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}},
},
},
Env: []v1.EnvVar{
{
Name: "TEST_LITERAL",
Value: "test-test-test",
},
{
Name: "EXPANSION_TEST",
Value: "$(REPLACE_ME)",
},
{
Name: "DUPE_TEST",
Value: "ENV_VAR",
},
},
},
masterServiceNs: "nothing",
nilLister: false,
secret: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: "test1",
Name: "test-secret",
},
Data: map[string][]byte{
"REPLACE_ME": []byte("FROM_SECRET"),
"DUPE_TEST": []byte("SECRET"),
},
},
expectedEnvs: []kubecontainer.EnvVar{
{
Name: "TEST_LITERAL",
Value: "test-test-test",
},
{
Name: "TEST_SERVICE_HOST",
Value: "1.2.3.3",
},
{
Name: "TEST_SERVICE_PORT",
Value: "8083",
},
{
Name: "TEST_PORT",
Value: "tcp://1.2.3.3:8083",
},
{
Name: "TEST_PORT_8083_TCP",
Value: "tcp://1.2.3.3:8083",
},
{
Name: "TEST_PORT_8083_TCP_PROTO",
Value: "tcp",
},
{
Name: "TEST_PORT_8083_TCP_PORT",
Value: "8083",
},
{
Name: "TEST_PORT_8083_TCP_ADDR",
Value: "1.2.3.3",
},
{
Name: "REPLACE_ME",
Value: "FROM_SECRET",
},
{
Name: "EXPANSION_TEST",
Value: "FROM_SECRET",
},
{
Name: "DUPE_TEST",
Value: "ENV_VAR",
},
{
Name: "p_REPLACE_ME",
Value: "FROM_SECRET",
},
{
Name: "p_DUPE_TEST",
Value: "SECRET",
},
},
},
{
name: "secret_missing",
ns: "test1",
enableServiceLinks: &falseValue,
container: &v1.Container{
EnvFrom: []v1.EnvFromSource{
{SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}}},
},
},
masterServiceNs: "nothing",
expectedError: true,
},
{
name: "secret_missing_optional",
ns: "test",
enableServiceLinks: &falseValue,
container: &v1.Container{
EnvFrom: []v1.EnvFromSource{
{SecretRef: &v1.SecretEnvSource{
LocalObjectReference: v1.LocalObjectReference{Name: "missing-secret"},
Optional: &trueVal}},
},
},
masterServiceNs: "nothing",
expectedEnvs: nil,
},
{
name: "secret_invalid_keys",
ns: "test",
enableServiceLinks: &falseValue,
container: &v1.Container{
EnvFrom: []v1.EnvFromSource{
{SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}}},
},
},
masterServiceNs: "nothing",
secret: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: "test1",
Name: "test-secret",
},
Data: map[string][]byte{
"1234": []byte("abc"),
"1z": []byte("abc"),
"key.1": []byte("value"),
},
},
expectedEnvs: []kubecontainer.EnvVar{
{
Name: "key.1",
Value: "value",
},
},
expectedEvent: "Warning InvalidEnvironmentVariableNames Keys [1234, 1z] from the EnvFrom secret test/test-secret were skipped since they are considered invalid environment variable names.",
},
{
name: "secret_invalid_keys_valid",
ns: "test",
enableServiceLinks: &falseValue,
container: &v1.Container{
EnvFrom: []v1.EnvFromSource{
{
Prefix: "p_",
SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}},
},
},
},
masterServiceNs: "",
secret: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: "test1",
Name: "test-secret",
},
Data: map[string][]byte{
"1234.name": []byte("abc"),
},
},
expectedEnvs: []kubecontainer.EnvVar{
{
Name: "p_1234.name",
Value: "abc",
},
},
},
{
name: "nil_enableServiceLinks",
ns: "test",
enableServiceLinks: nil,
container: &v1.Container{
EnvFrom: []v1.EnvFromSource{
{
Prefix: "p_",
SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}},
},
},
},
masterServiceNs: "",
secret: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: "test1",
Name: "test-secret",
},
Data: map[string][]byte{
"1234.name": []byte("abc"),
},
},
expectedError: true,
},
}
for _, tc := range testCases {
fakeRecorder := record.NewFakeRecorder(1)
testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */)
testKubelet.kubelet.recorder = fakeRecorder
defer testKubelet.Cleanup()
kl := testKubelet.kubelet
kl.masterServiceNamespace = tc.masterServiceNs
if tc.nilLister {
kl.serviceLister = nil
} else {
kl.serviceLister = testServiceLister{services}
}
testKubelet.fakeKubeClient.AddReactor("get", "configmaps", func(action core.Action) (bool, runtime.Object, error) {
var err error
if tc.configMap == nil {
err = apierrors.NewNotFound(action.GetResource().GroupResource(), "configmap-name")
}
return true, tc.configMap, err
})
testKubelet.fakeKubeClient.AddReactor("get", "secrets", func(action core.Action) (bool, runtime.Object, error) {
var err error
if tc.secret == nil {
err = apierrors.NewNotFound(action.GetResource().GroupResource(), "secret-name")
}
return true, tc.secret, err
})
testKubelet.fakeKubeClient.AddReactor("get", "secrets", func(action core.Action) (bool, runtime.Object, error) {
var err error
if tc.secret == nil {
err = errors.New("no secret defined")
}
return true, tc.secret, err
})
testPod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Namespace: tc.ns,
Name: "dapi-test-pod-name",
},
Spec: v1.PodSpec{
ServiceAccountName: "special",
NodeName: "node-name",
EnableServiceLinks: tc.enableServiceLinks,
},
}
podIP := "1.2.3.4"
result, err := kl.makeEnvironmentVariables(testPod, tc.container, podIP)
select {
case e := <-fakeRecorder.Events:
assert.Equal(t, tc.expectedEvent, e)
default:
assert.Equal(t, "", tc.expectedEvent)
}
if tc.expectedError {
assert.Error(t, err, tc.name)
} else {
assert.NoError(t, err, "[%s]", tc.name)
sort.Sort(envs(result))
sort.Sort(envs(tc.expectedEnvs))
assert.Equal(t, tc.expectedEnvs, result, "[%s] env entries", tc.name)
}
}
}
func waitingState(cName string) v1.ContainerStatus {
return v1.ContainerStatus{
Name: cName,
State: v1.ContainerState{
Waiting: &v1.ContainerStateWaiting{},
},
}
}
func waitingStateWithLastTermination(cName string) v1.ContainerStatus {
return v1.ContainerStatus{
Name: cName,
State: v1.ContainerState{
Waiting: &v1.ContainerStateWaiting{},
},
LastTerminationState: v1.ContainerState{
Terminated: &v1.ContainerStateTerminated{
ExitCode: 0,
},
},
}
}
func runningState(cName string) v1.ContainerStatus {
return v1.ContainerStatus{
Name: cName,
State: v1.ContainerState{
Running: &v1.ContainerStateRunning{},
},
}
}
func stoppedState(cName string) v1.ContainerStatus {
return v1.ContainerStatus{
Name: cName,
State: v1.ContainerState{
Terminated: &v1.ContainerStateTerminated{},
},
}
}
func succeededState(cName string) v1.ContainerStatus {
return v1.ContainerStatus{
Name: cName,
State: v1.ContainerState{
Terminated: &v1.ContainerStateTerminated{
ExitCode: 0,
},
},
}
}
func failedState(cName string) v1.ContainerStatus {
return v1.ContainerStatus{
Name: cName,
State: v1.ContainerState{
Terminated: &v1.ContainerStateTerminated{
ExitCode: -1,
},
},
}
}
func TestPodPhaseWithRestartAlways(t *testing.T) {
desiredState := v1.PodSpec{
NodeName: "machine",
Containers: []v1.Container{
{Name: "containerA"},
{Name: "containerB"},
},
RestartPolicy: v1.RestartPolicyAlways,
}
tests := []struct {
pod *v1.Pod
status v1.PodPhase
test string
}{
{&v1.Pod{Spec: desiredState, Status: v1.PodStatus{}}, v1.PodPending, "waiting"},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
runningState("containerA"),
runningState("containerB"),
},
},
},
v1.PodRunning,
"all running",
},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
stoppedState("containerA"),
stoppedState("containerB"),
},
},
},
v1.PodRunning,
"all stopped with restart always",
},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
runningState("containerA"),
stoppedState("containerB"),
},
},
},
v1.PodRunning,
"mixed state #1 with restart always",
},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
runningState("containerA"),
},
},
},
v1.PodPending,
"mixed state #2 with restart always",
},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
runningState("containerA"),
waitingState("containerB"),
},
},
},
v1.PodPending,
"mixed state #3 with restart always",
},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
runningState("containerA"),
waitingStateWithLastTermination("containerB"),
},
},
},
v1.PodRunning,
"backoff crashloop container with restart always",
},
}
for _, test := range tests {
status := getPhase(&test.pod.Spec, test.pod.Status.ContainerStatuses)
assert.Equal(t, test.status, status, "[test %s]", test.test)
}
}
func TestPodPhaseWithRestartNever(t *testing.T) {
desiredState := v1.PodSpec{
NodeName: "machine",
Containers: []v1.Container{
{Name: "containerA"},
{Name: "containerB"},
},
RestartPolicy: v1.RestartPolicyNever,
}
tests := []struct {
pod *v1.Pod
status v1.PodPhase
test string
}{
{&v1.Pod{Spec: desiredState, Status: v1.PodStatus{}}, v1.PodPending, "waiting"},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
runningState("containerA"),
runningState("containerB"),
},
},
},
v1.PodRunning,
"all running with restart never",
},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
succeededState("containerA"),
succeededState("containerB"),
},
},
},
v1.PodSucceeded,
"all succeeded with restart never",
},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
failedState("containerA"),
failedState("containerB"),
},
},
},
v1.PodFailed,
"all failed with restart never",
},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
runningState("containerA"),
succeededState("containerB"),
},
},
},
v1.PodRunning,
"mixed state #1 with restart never",
},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
runningState("containerA"),
},
},
},
v1.PodPending,
"mixed state #2 with restart never",
},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
runningState("containerA"),
waitingState("containerB"),
},
},
},
v1.PodPending,
"mixed state #3 with restart never",
},
}
for _, test := range tests {
status := getPhase(&test.pod.Spec, test.pod.Status.ContainerStatuses)
assert.Equal(t, test.status, status, "[test %s]", test.test)
}
}
func TestPodPhaseWithRestartOnFailure(t *testing.T) {
desiredState := v1.PodSpec{
NodeName: "machine",
Containers: []v1.Container{
{Name: "containerA"},
{Name: "containerB"},
},
RestartPolicy: v1.RestartPolicyOnFailure,
}
tests := []struct {
pod *v1.Pod
status v1.PodPhase
test string
}{
{&v1.Pod{Spec: desiredState, Status: v1.PodStatus{}}, v1.PodPending, "waiting"},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
runningState("containerA"),
runningState("containerB"),
},
},
},
v1.PodRunning,
"all running with restart onfailure",
},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
succeededState("containerA"),
succeededState("containerB"),
},
},
},
v1.PodSucceeded,
"all succeeded with restart onfailure",
},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
failedState("containerA"),
failedState("containerB"),
},
},
},
v1.PodRunning,
"all failed with restart never",
},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
runningState("containerA"),
succeededState("containerB"),
},
},
},
v1.PodRunning,
"mixed state #1 with restart onfailure",
},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
runningState("containerA"),
},
},
},
v1.PodPending,
"mixed state #2 with restart onfailure",
},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
runningState("containerA"),
waitingState("containerB"),
},
},
},
v1.PodPending,
"mixed state #3 with restart onfailure",
},
{
&v1.Pod{
Spec: desiredState,
Status: v1.PodStatus{
ContainerStatuses: []v1.ContainerStatus{
runningState("containerA"),
waitingStateWithLastTermination("containerB"),
},
},
},
v1.PodRunning,
"backoff crashloop container with restart onfailure",
},
}
for _, test := range tests {
status := getPhase(&test.pod.Spec, test.pod.Status.ContainerStatuses)
assert.Equal(t, test.status, status, "[test %s]", test.test)
}
}
type fakeReadWriteCloser struct{}
func (f *fakeReadWriteCloser) Write(data []byte) (int, error) {
return 0, nil
}
func (f *fakeReadWriteCloser) Read(data []byte) (int, error) {
return 0, nil
}
func (f *fakeReadWriteCloser) Close() error {
return nil
}
func TestGetExec(t *testing.T) {
const (
podName = "podFoo"
podNamespace = "nsFoo"
podUID types.UID = "12345678"
containerID = "containerFoo"
tty = true
)
var (
podFullName = kubecontainer.GetPodFullName(podWithUIDNameNs(podUID, podName, podNamespace))
command = []string{"ls"}
)
testcases := []struct {
description string
podFullName string
container string
expectError bool
}{{
description: "success case",
podFullName: podFullName,
container: containerID,
}, {
description: "no such pod",
podFullName: "bar" + podFullName,
container: containerID,
expectError: true,
}, {
description: "no such container",
podFullName: podFullName,
container: "containerBar",
expectError: true,
}}
for _, tc := range testcases {
testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */)
defer testKubelet.Cleanup()
kubelet := testKubelet.kubelet
testKubelet.fakeRuntime.PodList = []*containertest.FakePod{
{Pod: &kubecontainer.Pod{
ID: podUID,
Name: podName,
Namespace: podNamespace,
Containers: []*kubecontainer.Container{
{Name: containerID,
ID: kubecontainer.ContainerID{Type: "test", ID: containerID},
},
},
}},
}
description := "streaming - " + tc.description
fakeRuntime := &containertest.FakeStreamingRuntime{FakeRuntime: testKubelet.fakeRuntime}
kubelet.containerRuntime = fakeRuntime
kubelet.streamingRuntime = fakeRuntime
redirect, err := kubelet.GetExec(tc.podFullName, podUID, tc.container, command, remotecommand.Options{})
if tc.expectError {
assert.Error(t, err, description)
} else {
assert.NoError(t, err, description)
assert.Equal(t, containertest.FakeHost, redirect.Host, description+": redirect")
}
}
}
func TestGetPortForward(t *testing.T) {
const (
podName = "podFoo"
podNamespace = "nsFoo"
podUID types.UID = "12345678"
port int32 = 5000
)
testcases := []struct {
description string
podName string
expectError bool
}{{
description: "success case",
podName: podName,
}, {
description: "no such pod",
podName: "bar",
expectError: true,
}}
for _, tc := range testcases {
testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */)
defer testKubelet.Cleanup()
kubelet := testKubelet.kubelet
testKubelet.fakeRuntime.PodList = []*containertest.FakePod{
{Pod: &kubecontainer.Pod{
ID: podUID,
Name: podName,
Namespace: podNamespace,
Containers: []*kubecontainer.Container{
{Name: "foo",
ID: kubecontainer.ContainerID{Type: "test", ID: "foo"},
},
},
}},
}
description := "streaming - " + tc.description
fakeRuntime := &containertest.FakeStreamingRuntime{FakeRuntime: testKubelet.fakeRuntime}
kubelet.containerRuntime = fakeRuntime
kubelet.streamingRuntime = fakeRuntime
redirect, err := kubelet.GetPortForward(tc.podName, podNamespace, podUID, portforward.V4Options{})
if tc.expectError {
assert.Error(t, err, description)
} else {
assert.NoError(t, err, description)
assert.Equal(t, containertest.FakeHost, redirect.Host, description+": redirect")
}
}
}
func TestHasHostMountPVC(t *testing.T) {
tests := map[string]struct {
pvError error
pvcError error
expected bool
podHasPVC bool
pvcIsHostPath bool
}{
"no pvc": {podHasPVC: false, expected: false},
"error fetching pvc": {
podHasPVC: true,
pvcError: fmt.Errorf("foo"),
expected: false,
},
"error fetching pv": {
podHasPVC: true,
pvError: fmt.Errorf("foo"),
expected: false,
},
"host path pvc": {
podHasPVC: true,
pvcIsHostPath: true,
expected: true,
},
"non host path pvc": {
podHasPVC: true,
pvcIsHostPath: false,
expected: false,
},
}
for k, v := range tests {
testKubelet := newTestKubelet(t, false)
defer testKubelet.Cleanup()
pod := &v1.Pod{
Spec: v1.PodSpec{},
}
volumeToReturn := &v1.PersistentVolume{
Spec: v1.PersistentVolumeSpec{},
}
if v.podHasPVC {
pod.Spec.Volumes = []v1.Volume{
{
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{},
},
},
}
if v.pvcIsHostPath {
volumeToReturn.Spec.PersistentVolumeSource = v1.PersistentVolumeSource{
HostPath: &v1.HostPathVolumeSource{},
}
}
}
testKubelet.fakeKubeClient.AddReactor("get", "persistentvolumeclaims", func(action core.Action) (bool, runtime.Object, error) {
return true, &v1.PersistentVolumeClaim{
Spec: v1.PersistentVolumeClaimSpec{
VolumeName: "foo",
},
}, v.pvcError
})
testKubelet.fakeKubeClient.AddReactor("get", "persistentvolumes", func(action core.Action) (bool, runtime.Object, error) {
return true, volumeToReturn, v.pvError
})
actual := testKubelet.kubelet.hasHostMountPVC(pod)
if actual != v.expected {
t.Errorf("%s expected %t but got %t", k, v.expected, actual)
}
}
}
func TestHasNonNamespacedCapability(t *testing.T) {
createPodWithCap := func(caps []v1.Capability) *v1.Pod {
pod := &v1.Pod{
Spec: v1.PodSpec{
Containers: []v1.Container{{}},
},
}
if len(caps) > 0 {
pod.Spec.Containers[0].SecurityContext = &v1.SecurityContext{
Capabilities: &v1.Capabilities{
Add: caps,
},
}
}
return pod
}
nilCaps := createPodWithCap([]v1.Capability{v1.Capability("foo")})
nilCaps.Spec.Containers[0].SecurityContext = nil
tests := map[string]struct {
pod *v1.Pod
expected bool
}{
"nil security contxt": {createPodWithCap(nil), false},
"nil caps": {nilCaps, false},
"namespaced cap": {createPodWithCap([]v1.Capability{v1.Capability("foo")}), false},
"non-namespaced cap MKNOD": {createPodWithCap([]v1.Capability{v1.Capability("MKNOD")}), true},
"non-namespaced cap SYS_TIME": {createPodWithCap([]v1.Capability{v1.Capability("SYS_TIME")}), true},
"non-namespaced cap SYS_MODULE": {createPodWithCap([]v1.Capability{v1.Capability("SYS_MODULE")}), true},
}
for k, v := range tests {
actual := hasNonNamespacedCapability(v.pod)
if actual != v.expected {
t.Errorf("%s failed, expected %t but got %t", k, v.expected, actual)
}
}
}
func TestHasHostVolume(t *testing.T) {
pod := &v1.Pod{
Spec: v1.PodSpec{
Volumes: []v1.Volume{
{
VolumeSource: v1.VolumeSource{
HostPath: &v1.HostPathVolumeSource{},
},
},
},
},
}
result := hasHostVolume(pod)
if !result {
t.Errorf("expected host volume to enable host user namespace")
}
pod.Spec.Volumes[0].VolumeSource.HostPath = nil
result = hasHostVolume(pod)
if result {
t.Errorf("expected nil host volume to not enable host user namespace")
}
}
func TestHasHostNamespace(t *testing.T) {
tests := map[string]struct {
ps v1.PodSpec
expected bool
}{
"nil psc": {
ps: v1.PodSpec{},
expected: false},
"host pid true": {
ps: v1.PodSpec{
HostPID: true,
SecurityContext: &v1.PodSecurityContext{},
},
expected: true,
},
"host ipc true": {
ps: v1.PodSpec{
HostIPC: true,
SecurityContext: &v1.PodSecurityContext{},
},
expected: true,
},
"host net true": {
ps: v1.PodSpec{
HostNetwork: true,
SecurityContext: &v1.PodSecurityContext{},
},
expected: true,
},
"no host ns": {
ps: v1.PodSpec{
SecurityContext: &v1.PodSecurityContext{},
},
expected: false,
},
}
for k, v := range tests {
pod := &v1.Pod{
Spec: v.ps,
}
actual := hasHostNamespace(pod)
if actual != v.expected {
t.Errorf("%s failed, expected %t but got %t", k, v.expected, actual)
}
}
}
func TestTruncatePodHostname(t *testing.T) {
for c, test := range map[string]struct {
input string
output string
}{
"valid hostname": {
input: "test.pod.hostname",
output: "test.pod.hostname",
},
"too long hostname": {
input: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.1234567.1234567.", // 8*9=72 chars
output: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.1234567", //8*8-1=63 chars
},
"hostname end with .": {
input: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.123456.1234567.", // 8*9-1=71 chars
output: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.123456", //8*8-2=62 chars
},
"hostname end with -": {
input: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.123456-1234567.", // 8*9-1=71 chars
output: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.123456", //8*8-2=62 chars
},
} {
t.Logf("TestCase: %q", c)
output, err := truncatePodHostnameIfNeeded("test-pod", test.input)
assert.NoError(t, err)
assert.Equal(t, test.output, output)
}
}
| Stackdriver/heapster | vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_pods_test.go | GO | apache-2.0 | 61,774 |
package org.keycloak.provider;
import org.jboss.logging.Logger;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class ProviderManager {
private static final Logger log = Logger.getLogger(ProviderManager.class);
private List<ProviderLoader> loaders = new LinkedList<ProviderLoader>();
private Map<String, List<ProviderFactory>> cache = new HashMap<String, List<ProviderFactory>>();
public ProviderManager(ClassLoader baseClassLoader, String... resources) {
List<ProviderLoaderFactory> factories = new LinkedList<ProviderLoaderFactory>();
for (ProviderLoaderFactory f : ServiceLoader.load(ProviderLoaderFactory.class, getClass().getClassLoader())) {
factories.add(f);
}
log.debugv("Provider loaders {0}", factories);
loaders.add(new DefaultProviderLoader(baseClassLoader));
if (resources != null) {
for (String r : resources) {
String type = r.substring(0, r.indexOf(':'));
String resource = r.substring(r.indexOf(':') + 1, r.length());
boolean found = false;
for (ProviderLoaderFactory f : factories) {
if (f.supports(type)) {
loaders.add(f.create(baseClassLoader, resource));
found = true;
break;
}
}
if (!found) {
throw new RuntimeException("Provider loader for " + r + " not found");
}
}
}
}
public synchronized List<ProviderFactory> load(Spi spi) {
List<ProviderFactory> factories = cache.get(spi.getName());
if (factories == null) {
factories = new LinkedList<ProviderFactory>();
for (ProviderLoader loader : loaders) {
List<ProviderFactory> f = loader.load(spi);
if (f != null) {
factories.addAll(f);
}
}
}
return factories;
}
public synchronized ProviderFactory load(Spi spi, String providerId) {
for (ProviderFactory f : load(spi)) {
if (f.getId().equals(providerId)) {
return f;
}
}
return null;
}
}
| matzew/keycloak | services/src/main/java/org/keycloak/provider/ProviderManager.java | Java | apache-2.0 | 2,461 |
/*
* 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.sql.tree;
import com.google.common.collect.ImmutableList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.collectingAndThen;
public final class GroupingSets
extends GroupingElement
{
private final List<List<QualifiedName>> sets;
public GroupingSets(List<List<QualifiedName>> groupingSetList)
{
this(Optional.empty(), groupingSetList);
}
public GroupingSets(NodeLocation location, List<List<QualifiedName>> sets)
{
this(Optional.of(location), sets);
}
private GroupingSets(Optional<NodeLocation> location, List<List<QualifiedName>> sets)
{
super(location);
requireNonNull(sets, "sets is null");
checkArgument(!sets.isEmpty(), "grouping sets cannot be empty");
this.sets = ImmutableList.copyOf(sets.stream().map(ImmutableList::copyOf).collect(Collectors.toList()));
}
public List<List<QualifiedName>> getSets()
{
return sets;
}
@Override
public List<Set<Expression>> enumerateGroupingSets()
{
return sets.stream()
.map(groupingSet -> groupingSet.stream()
.map(DereferenceExpression::from)
.collect(Collectors.<Expression>toSet()))
.collect(collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
}
@Override
protected <R, C> R accept(AstVisitor<R, C> visitor, C context)
{
return visitor.visitGroupingSets(this, context);
}
@Override
public List<Node> getChildren()
{
return ImmutableList.of();
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GroupingSets groupingSets = (GroupingSets) o;
return Objects.equals(sets, groupingSets.sets);
}
@Override
public int hashCode()
{
return Objects.hash(sets);
}
@Override
public String toString()
{
return toStringHelper(this)
.add("sets", sets)
.toString();
}
}
| marsorp/blog | presto166/presto-parser/src/main/java/com/facebook/presto/sql/tree/GroupingSets.java | Java | apache-2.0 | 3,087 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.cache.store.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;
import javax.cache.Cache;
import javax.cache.configuration.Factory;
import javax.cache.integration.CacheLoaderException;
import javax.cache.integration.CacheWriterException;
import org.apache.ignite.cache.store.CacheStore;
import org.apache.ignite.cache.store.CacheStoreAdapter;
import org.apache.ignite.cache.store.CacheStoreSession;
import org.apache.ignite.cache.store.CacheStoreSessionListener;
import org.apache.ignite.cache.store.CacheStoreSessionListenerAbstractSelfTest;
import org.apache.ignite.lang.IgniteBiInClosure;
import org.apache.ignite.resources.CacheStoreSessionResource;
import org.apache.ignite.testframework.MvccFeatureChecker;
import org.h2.jdbcx.JdbcConnectionPool;
import org.junit.Before;
/**
* Tests for {@link CacheJdbcStoreSessionListener}.
*/
public class CacheJdbcStoreSessionListenerSelfTest extends CacheStoreSessionListenerAbstractSelfTest {
/** */
@Before
public void beforeCacheJdbcStoreSessionListenerSelfTest() {
MvccFeatureChecker.skipIfNotSupported(MvccFeatureChecker.Feature.CACHE_STORE);
}
/** {@inheritDoc} */
@Override protected Factory<? extends CacheStore<Integer, Integer>> storeFactory() {
return new Factory<CacheStore<Integer, Integer>>() {
@Override public CacheStore<Integer, Integer> create() {
return new Store();
}
};
}
/** {@inheritDoc} */
@Override protected Factory<CacheStoreSessionListener> sessionListenerFactory() {
return new Factory<CacheStoreSessionListener>() {
@Override public CacheStoreSessionListener create() {
CacheJdbcStoreSessionListener lsnr = new CacheJdbcStoreSessionListener();
lsnr.setDataSource(JdbcConnectionPool.create(URL, "", ""));
return lsnr;
}
};
}
/**
*/
private static class Store extends CacheStoreAdapter<Integer, Integer> {
/** */
private static String SES_CONN_KEY = "ses_conn";
/** */
@CacheStoreSessionResource
private CacheStoreSession ses;
/** {@inheritDoc} */
@Override public void loadCache(IgniteBiInClosure<Integer, Integer> clo, Object... args) {
loadCacheCnt.incrementAndGet();
checkConnection();
}
/** {@inheritDoc} */
@Override public Integer load(Integer key) throws CacheLoaderException {
loadCnt.incrementAndGet();
checkConnection();
return null;
}
/** {@inheritDoc} */
@Override public void write(Cache.Entry<? extends Integer, ? extends Integer> entry)
throws CacheWriterException {
writeCnt.incrementAndGet();
checkConnection();
if (write.get()) {
Connection conn = ses.attachment();
try {
String table;
switch (ses.cacheName()) {
case "cache1":
table = "Table1";
break;
case "cache2":
if (fail.get())
throw new CacheWriterException("Expected failure.");
table = "Table2";
break;
default:
throw new CacheWriterException("Wring cache: " + ses.cacheName());
}
PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO " + table + " (key, value) VALUES (?, ?)");
stmt.setInt(1, entry.getKey());
stmt.setInt(2, entry.getValue());
stmt.executeUpdate();
}
catch (SQLException e) {
throw new CacheWriterException(e);
}
}
}
/** {@inheritDoc} */
@Override public void delete(Object key) throws CacheWriterException {
deleteCnt.incrementAndGet();
checkConnection();
}
/** {@inheritDoc} */
@Override public void sessionEnd(boolean commit) {
assertNull(ses.attachment());
}
/**
*/
private void checkConnection() {
Connection conn = ses.attachment();
assertNotNull(conn);
try {
assertFalse(conn.isClosed());
assertFalse(conn.getAutoCommit());
}
catch (SQLException e) {
throw new RuntimeException(e);
}
verifySameInstance(conn);
}
/**
* @param conn Connection.
*/
private void verifySameInstance(Connection conn) {
Map<String, Connection> props = ses.properties();
Connection sesConn = props.get(SES_CONN_KEY);
if (sesConn == null)
props.put(SES_CONN_KEY, conn);
else {
assertSame(conn, sesConn);
reuseCnt.incrementAndGet();
}
}
}
}
| samaitra/ignite | modules/core/src/test/java/org/apache/ignite/cache/store/jdbc/CacheJdbcStoreSessionListenerSelfTest.java | Java | apache-2.0 | 6,111 |
// +build !windows
package devices
import (
"errors"
"golang.org/x/sys/unix"
)
func (d *Rule) Mkdev() (uint64, error) {
if d.Major == Wildcard || d.Minor == Wildcard {
return 0, errors.New("cannot mkdev() device with wildcards")
}
return unix.Mkdev(uint32(d.Major), uint32(d.Minor)), nil
}
| xychu/kubernetes | vendor/github.com/opencontainers/runc/libcontainer/devices/device_unix.go | GO | apache-2.0 | 301 |
package com.salesmanager.web.entity.shop;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
public class ContactForm {
@NotEmpty
private String name;
@NotEmpty
private String subject;
@Email
private String email;
@NotEmpty
private String comment;
private String captchaResponseField;
private String captchaChallengeField;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getCaptchaResponseField() {
return captchaResponseField;
}
public void setCaptchaResponseField(String captchaResponseField) {
this.captchaResponseField = captchaResponseField;
}
public String getCaptchaChallengeField() {
return captchaChallengeField;
}
public void setCaptchaChallengeField(String captchaChallengeField) {
this.captchaChallengeField = captchaChallengeField;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
}
| asheshsaraf/ecommerce-simple | sm-shop/src/main/java/com/salesmanager/web/entity/shop/ContactForm.java | Java | apache-2.0 | 1,264 |
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInitcdf72ff6e7f034c7d87f9bb5bd53f8da::getLoader();
| ThreePeple/xjqjsjpgldjkkuiloojjloj | vendor/autoload.php | PHP | bsd-3-clause | 183 |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
#include "platform/platform.h"
#include "platformWin32/platformWin32.h"
#include "time.h"
void Platform::sleep(U32 ms)
{
Sleep(ms);
}
//--------------------------------------
void Platform::getLocalTime(LocalTime <)
{
struct tm *systime;
time_t long_time;
time( &long_time ); // Get time as long integer.
systime = localtime( &long_time ); // Convert to local time.
lt.sec = systime->tm_sec;
lt.min = systime->tm_min;
lt.hour = systime->tm_hour;
lt.month = systime->tm_mon;
lt.monthday = systime->tm_mday;
lt.weekday = systime->tm_wday;
lt.year = systime->tm_year;
lt.yearday = systime->tm_yday;
lt.isdst = systime->tm_isdst;
}
String Platform::localTimeToString( const LocalTime < )
{
// Converting a LocalTime to SYSTEMTIME
// requires a few annoying adjustments.
SYSTEMTIME st;
st.wMilliseconds = 0;
st.wSecond = lt.sec;
st.wMinute = lt.min;
st.wHour = lt.hour;
st.wDay = lt.monthday;
st.wDayOfWeek = lt.weekday;
st.wMonth = lt.month + 1;
st.wYear = lt.year + 1900;
TCHAR buffer[1024] = {0};
S32 result = 0;
String outStr;
// Note: The 'Ex' version of GetDateFormat and GetTimeFormat are preferred
// and have better support for supplemental locales but are not supported
// for version of windows prior to Vista.
//
// Would be nice if Torque was more aware of the OS version and
// take full advantage of it.
result = GetDateFormat( LOCALE_USER_DEFAULT,
DATE_SHORTDATE,
&st,
NULL,
(LPTSTR)buffer,
1024 );
// Also would be nice to have a standard system for torque to
// retrieve and display windows level errors using GetLastError and
// FormatMessage...
AssertWarn( result != 0, "Platform::getLocalTime" );
outStr += buffer;
outStr += "\t";
result = GetTimeFormat( LOCALE_USER_DEFAULT,
0,
&st,
NULL,
(LPTSTR)buffer,
1024 );
AssertWarn( result != 0, "Platform::localTimeToString, error occured!" );
outStr += buffer;
return outStr;
}
U32 Platform::getTime()
{
time_t long_time;
time( &long_time );
return long_time;
}
void Platform::fileToLocalTime(const FileTime & ft, LocalTime * lt)
{
if(!lt)
return;
dMemset(lt, 0, sizeof(LocalTime));
FILETIME winFileTime;
winFileTime.dwLowDateTime = ft.v1;
winFileTime.dwHighDateTime = ft.v2;
SYSTEMTIME winSystemTime;
// convert the filetime to local time
FILETIME convertedFileTime;
if(::FileTimeToLocalFileTime(&winFileTime, &convertedFileTime))
{
// get the time into system time struct
if(::FileTimeToSystemTime((const FILETIME *)&convertedFileTime, &winSystemTime))
{
SYSTEMTIME * time = &winSystemTime;
// fill it in...
lt->sec = time->wSecond;
lt->min = time->wMinute;
lt->hour = time->wHour;
lt->month = time->wMonth - 1;
lt->monthday = time->wDay;
lt->weekday = time->wDayOfWeek;
lt->year = (time->wYear < 1900) ? 1900 : (time->wYear - 1900);
// not calculated
lt->yearday = 0;
lt->isdst = false;
}
}
}
U32 Platform::getRealMilliseconds()
{
return GetTickCount();
}
U32 Platform::getVirtualMilliseconds()
{
return winState.currentTime;
}
void Platform::advanceTime(U32 delta)
{
winState.currentTime += delta;
}
| elfprince13/Torque3D | Engine/source/platformWin32/winTime.cpp | C++ | mit | 4,979 |
require 'spec_helper'
describe SCSSLint::Linter::DeclarationOrder do
context 'when rule is empty' do
let(:scss) { <<-SCSS }
p {
}
SCSS
it { should_not report_lint }
end
context 'when rule contains only properties' do
let(:scss) { <<-SCSS }
p {
background: #000;
margin: 5px;
}
SCSS
it { should_not report_lint }
end
context 'when rule contains only mixins' do
let(:scss) { <<-SCSS }
p {
@include border-radius(5px);
@include box-shadow(5px);
}
SCSS
it { should_not report_lint }
end
context 'when rule contains no mixins or properties' do
let(:scss) { <<-SCSS }
p {
a {
color: #f00;
}
}
SCSS
it { should_not report_lint }
end
context 'when rule contains properties after nested rules' do
let(:scss) { <<-SCSS }
p {
a {
color: #f00;
}
color: #f00;
margin: 5px;
}
SCSS
it { should report_lint }
end
context 'when @extend appears before any properties or rules' do
let(:scss) { <<-SCSS }
.warn {
font-weight: bold;
}
.error {
@extend .warn;
color: #f00;
a {
color: #ccc;
}
}
SCSS
it { should_not report_lint }
end
context 'when @extend appears after a property' do
let(:scss) { <<-SCSS }
.warn {
font-weight: bold;
}
.error {
color: #f00;
@extend .warn;
a {
color: #ccc;
}
}
SCSS
it { should report_lint line: 6 }
end
context 'when nested rule set' do
context 'contains @extend before a property' do
let(:scss) { <<-SCSS }
p {
a {
@extend foo;
color: #f00;
}
}
SCSS
it { should_not report_lint }
end
context 'contains @extend after a property' do
let(:scss) { <<-SCSS }
p {
a {
color: #f00;
@extend foo;
}
}
SCSS
it { should report_lint line: 4 }
end
context 'contains @extend after nested rule set' do
let(:scss) { <<-SCSS }
p {
a {
span {
color: #000;
}
@extend foo;
}
}
SCSS
it { should report_lint line: 6 }
end
end
context 'when @include appears' do
context 'before a property and rule set' do
let(:scss) { <<-SCSS }
.error {
@include warn;
color: #f00;
a {
color: #ccc;
}
}
SCSS
it { should_not report_lint }
end
context 'after a property and before a rule set' do
let(:scss) { <<-SCSS }
.error {
color: #f00;
@include warn;
a {
color: #ccc;
}
}
SCSS
it { should report_lint line: 3 }
end
end
context 'when @include that features @content appears' do
context 'before a property' do
let(:scss) { <<-SCSS }
.foo {
@include breakpoint("phone") {
color: #ccc;
}
color: #f00;
}
SCSS
it { should report_lint line: 5 }
end
context 'after a property' do
let(:scss) { <<-SCSS }
.foo {
color: #f00;
@include breakpoint("phone") {
color: #ccc;
}
}
SCSS
it { should_not report_lint }
end
context 'before an @extend' do
let(:scss) { <<-SCSS }
.foo {
@include breakpoint("phone") {
color: #ccc;
}
@extend .bar;
}
SCSS
it { should report_lint line: 5 }
end
context 'before a rule set' do
let(:scss) { <<-SCSS }
.foo {
@include breakpoint("phone") {
color: #ccc;
}
a {
color: #fff;
}
}
SCSS
it { should_not report_lint }
end
context 'after a rule set' do
let(:scss) { <<-SCSS }
.foo {
a {
color: #fff;
}
@include breakpoint("phone") {
color: #ccc;
}
}
SCSS
it { should report_lint line: 5 }
end
context 'with its own nested rule set' do
context 'before a property' do
let(:scss) { <<-SCSS }
@include breakpoint("phone") {
a {
color: #000;
}
color: #ccc;
}
SCSS
it { should report_lint line: 5 }
end
context 'after a property' do
let(:scss) { <<-SCSS }
@include breakpoint("phone") {
color: #ccc;
a {
color: #000;
}
}
SCSS
it { should_not report_lint }
end
end
end
context 'when the nesting is crazy deep' do
context 'and nothing is wrong' do
let(:scss) { <<-SCSS }
div {
ul {
@extend .thing;
li {
@include box-shadow(yes);
background: green;
a {
span {
@include border-radius(5px);
color: #000;
}
}
}
}
}
SCSS
it { should_not report_lint }
end
context 'and something is wrong' do
let(:scss) { <<-SCSS }
div {
ul {
li {
a {
span {
color: #000;
@include border-radius(5px);
}
}
}
}
}
SCSS
it { should report_lint line: 7 }
end
end
context 'when inside a @media query and rule set' do
context 'contains @extend before a property' do
let(:scss) { <<-SCSS }
@media only screen and (max-width: 1px) {
a {
@extend foo;
color: #f00;
}
}
SCSS
it { should_not report_lint }
end
context 'contains @extend after a property' do
let(:scss) { <<-SCSS }
@media only screen and (max-width: 1px) {
a {
color: #f00;
@extend foo;
}
}
SCSS
it { should report_lint line: 4 }
end
context 'contains @extend after nested rule set' do
let(:scss) { <<-SCSS }
@media only screen and (max-width: 1px) {
a {
span {
color: #000;
}
@extend foo;
}
}
SCSS
it { should report_lint line: 6 }
end
end
context 'when a pseudo-element appears before a property' do
let(:scss) { <<-SCSS }
a {
&:hover {
color: #000;
}
color: #fff;
}
SCSS
it { should report_lint line: 5 }
end
context 'when a pseudo-element appears after a property' do
let(:scss) { <<-SCSS }
a {
color: #fff;
&:focus {
color: #000;
}
}
SCSS
it { should_not report_lint }
end
context 'when a chained selector appears after a property' do
let(:scss) { <<-SCSS }
a {
color: #fff;
&.is-active {
color: #000;
}
}
SCSS
it { should_not report_lint }
end
context 'when a chained selector appears before a property' do
let(:scss) { <<-SCSS }
a {
&.is-active {
color: #000;
}
color: #fff;
}
SCSS
it { should report_lint line: 5 }
end
context 'when a selector with parent reference appears after a property' do
let(:scss) { <<-SCSS }
a {
color: #fff;
.is-active & {
color: #000;
}
}
SCSS
it { should_not report_lint }
end
context 'when a selector with parent reference appears before a property' do
let(:scss) { <<-SCSS }
a {
.is-active & {
color: #000;
}
color: #fff;
}
SCSS
it { should report_lint line: 5 }
end
context 'when a pseudo-element appears after a property' do
let(:scss) { <<-SCSS }
a {
color: #fff;
&:before {
color: #000;
}
}
SCSS
it { should_not report_lint }
end
context 'when a pseudo-element appears before a property' do
let(:scss) { <<-SCSS }
a {
&:before {
color: #000;
}
color: #fff;
}
SCSS
it { should report_lint line: 5 }
end
context 'when a direct descendent appears after a property' do
let(:scss) { <<-SCSS }
a {
color: #fff;
> .foo {
color: #000;
}
}
SCSS
it { should_not report_lint }
end
context 'when a direct descendent appears before a property' do
let(:scss) { <<-SCSS }
a {
> .foo {
color: #000;
}
color: #fff;
}
SCSS
it { should report_lint line: 5 }
end
context 'when an adjacent sibling appears after a property' do
let(:scss) { <<-SCSS }
a {
color: #fff;
& + .foo {
color: #000;
}
}
SCSS
it { should_not report_lint }
end
context 'when an adjacent sibling appears before a property' do
let(:scss) { <<-SCSS }
a {
& + .foo {
color: #000;
}
color: #fff;
}
SCSS
it { should report_lint line: 5 }
end
context 'when a general sibling appears after a property' do
let(:scss) { <<-SCSS }
a {
color: #fff;
& ~ .foo {
color: #000;
}
}
SCSS
it { should_not report_lint }
end
context 'when a general sibling appears before a property' do
let(:scss) { <<-SCSS }
a {
& ~ .foo {
color: #000;
}
color: #fff;
}
SCSS
it { should report_lint line: 5 }
end
context 'when a descendent appears after a property' do
let(:scss) { <<-SCSS }
a {
color: #fff;
.foo {
color: #000;
}
}
SCSS
it { should_not report_lint }
end
context 'when a descendent appears before a property' do
let(:scss) { <<-SCSS }
a {
.foo {
color: #000;
}
color: #fff;
}
SCSS
it { should report_lint line: 5 }
end
context 'when order within a media query is incorrect' do
let(:scss) { <<-SCSS }
@media screen and (max-width: 600px) {
@include mix1();
width: 100%;
height: 100%;
@include mix2();
}
SCSS
it { should report_lint }
end
end
| ingdir/scss-lint | spec/scss_lint/linter/declaration_order_spec.rb | Ruby | mit | 10,847 |
/**
* Module dependencies
*/
var fs = require('fs-extra')
, _ = require('lodash')
, path = require('path')
, reportback = require('reportback')();
/**
* Generate a JSON file
*
* @option {String} rootPath
* @option {Object} data
* [@option {Boolean} force=false]
*
* @handlers success
* @handlers error
* @handlers alreadyExists
*/
module.exports = function ( options, handlers ) {
// Provide default values for handlers
handlers = reportback.extend(handlers, {
alreadyExists: 'error'
});
// Provide defaults and validate required options
_.defaults(options, {
force: false
});
var missingOpts = _.difference([
'rootPath',
'data'
], Object.keys(options));
if ( missingOpts.length ) return handlers.invalid(missingOpts);
var rootPath = path.resolve( process.cwd() , options.rootPath );
// Only override an existing file if `options.force` is true
fs.exists(rootPath, function (exists) {
if (exists && !options.force) {
return handlers.alreadyExists('Something else already exists at ::'+rootPath);
}
if ( exists ) {
fs.remove(rootPath, function deletedOldINode (err) {
if (err) return handlers.error(err);
_afterwards_();
});
}
else _afterwards_();
function _afterwards_ () {
fs.outputJSON(rootPath, options.data, function (err){
if (err) return handlers.error(err);
else handlers.success();
});
}
});
};
| harindaka/node-mvc-starter | node_modules/sails/node_modules/sails-generate/lib/helpers/jsonfile/index.js | JavaScript | mit | 1,395 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WebStack.QA.Share.Controllers.TypeLibrary;
namespace WebStack.QA.Share.Controllers
{
public class CollectionController : ApiController
{
#region IEnumerable, IEnumerable<T>
[AcceptVerbs("PUT", "POST", "DELETE")]
public IEnumerable EchoIEnumerable(IEnumerable input)
{
return input;
}
[AcceptVerbs("PUT", "POST", "DELETE")]
public IEnumerable<string> EchoIEnumerableOfString(IEnumerable<string> input)
{
return input;
}
[AcceptVerbs("PUT", "POST", "DELETE")]
public IEnumerable<Address> EchoIEnumerableOfAddress(IEnumerable<Address> input)
{
return input;
}
#endregion
#region IList, IList<T>, List<T>
[AcceptVerbs("PUT", "POST", "DELETE")]
public IList EchoIList(IList input)
{
return input;
}
[AcceptVerbs("PUT", "POST", "DELETE")]
public IList<int?> EchoIListNullableInt(IList<int?> input)
{
return input;
}
[AcceptVerbs("PUT", "POST", "DELETE")]
public List<object> EchoListOfObject(List<object> input)
{
return input;
}
#endregion
#region Array
[AcceptVerbs("PUT", "POST", "DELETE")]
public Guid[] ReverseGuidArray(Guid[] input)
{
return (input == null) ? null : input.Reverse().ToArray();
}
[AcceptVerbs("PUT", "POST", "DELETE")]
public double?[] ReverseNullableDoubleArray(double?[] input)
{
return (input == null) ? null : input.Reverse().ToArray();
}
[AcceptVerbs("PUT", "POST", "DELETE")]
public Nullable<DateTime>[] ReverseNullableDateTimeArray(Nullable<DateTime>[] input)
{
return (input == null) ? null : input.Reverse().ToArray();
}
[AcceptVerbs("PUT", "POST", "DELETE")]
public Person[] ReversePersonArray(Person[] input)
{
return (input == null) ? null : input.Reverse().ToArray();
}
#endregion
#region IDictionary, Dictionary<K,V>
[AcceptVerbs("PUT", "POST", "DELETE")]
public IDictionary EchoIDictionary(IDictionary input)
{
return input;
}
[AcceptVerbs("PUT", "POST", "DELETE")]
public IDictionary<string, Person> EchoIDictionaryOfStringAndPerson(IDictionary<string, Person> input)
{
return input;
}
[AcceptVerbs("PUT", "POST", "DELETE")]
public Dictionary<int, string> EchoListOfObject(Dictionary<int, string> input)
{
return input;
}
#endregion
}
} | lungisam/WebApi | OData/test/E2ETestV3/WebStack.QA.Share/Controllers/CollectionController.cs | C# | mit | 2,854 |
require 'active_support/execution_wrapper'
module ActiveSupport
#--
# This class defines several callbacks:
#
# to_prepare -- Run once at application startup, and also from
# +to_run+.
#
# to_run -- Run before a work run that is reloading. If
# +reload_classes_only_on_change+ is true (the default), the class
# unload will have already occurred.
#
# to_complete -- Run after a work run that has reloaded. If
# +reload_classes_only_on_change+ is false, the class unload will
# have occurred after the work run, but before this callback.
#
# before_class_unload -- Run immediately before the classes are
# unloaded.
#
# after_class_unload -- Run immediately after the classes are
# unloaded.
#
class Reloader < ExecutionWrapper
define_callbacks :prepare
define_callbacks :class_unload
def self.to_prepare(*args, &block)
set_callback(:prepare, *args, &block)
end
def self.before_class_unload(*args, &block)
set_callback(:class_unload, *args, &block)
end
def self.after_class_unload(*args, &block)
set_callback(:class_unload, :after, *args, &block)
end
to_run(:after) { self.class.prepare! }
# Initiate a manual reload
def self.reload!
executor.wrap do
new.tap do |instance|
begin
instance.run!
ensure
instance.complete!
end
end
end
prepare!
end
def self.run! # :nodoc:
if check!
super
else
Null
end
end
# Run the supplied block as a work unit, reloading code as needed
def self.wrap
executor.wrap do
super
end
end
class_attribute :executor
class_attribute :check
self.executor = Executor
self.check = lambda { false }
def self.check! # :nodoc:
@should_reload ||= check.call
end
def self.reloaded! # :nodoc:
@should_reload = false
end
def self.prepare! # :nodoc:
new.run_callbacks(:prepare)
end
def initialize
super
@locked = false
end
# Acquire the ActiveSupport::Dependencies::Interlock unload lock,
# ensuring it will be released automatically
def require_unload_lock!
unless @locked
ActiveSupport::Dependencies.interlock.start_unloading
@locked = true
end
end
# Release the unload lock if it has been previously obtained
def release_unload_lock!
if @locked
@locked = false
ActiveSupport::Dependencies.interlock.done_unloading
end
end
def run! # :nodoc:
super
release_unload_lock!
end
def class_unload!(&block) # :nodoc:
require_unload_lock!
run_callbacks(:class_unload, &block)
end
def complete! # :nodoc:
super
self.class.reloaded!
ensure
release_unload_lock!
end
end
end
| afuerstenau/daily-notes | vendor/cache/ruby/2.5.0/gems/activesupport-5.0.6/lib/active_support/reloader.rb | Ruby | mit | 2,922 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal static class FailFast
{
[DebuggerHidden]
[DoesNotReturn]
internal static void OnFatalException(Exception exception)
{
// EDMAURER Now using the managed API to fail fast so as to default
// to the managed VS debug engine and hopefully get great
// Watson bucketing. Before vanishing trigger anyone listening.
if (Debugger.IsAttached)
{
Debugger.Break();
}
#if !NET20
// don't fail fast with an aggregate exception that is masking true exception
if (exception is AggregateException aggregate && aggregate.InnerExceptions.Count == 1)
{
exception = aggregate.InnerExceptions[0];
}
#endif
DumpStackTrace(exception: exception);
Environment.FailFast(exception.ToString(), exception);
throw ExceptionUtilities.Unreachable; // to satisfy [DoesNotReturn]
}
[DebuggerHidden]
[DoesNotReturn]
internal static void Fail(string message)
{
DumpStackTrace(message: message);
Environment.FailFast(message);
throw ExceptionUtilities.Unreachable; // to satisfy [DoesNotReturn]
}
/// <summary>
/// Dumps the stack trace of the exception and the handler to the console. This is useful
/// for debugging unit tests that hit a fatal exception
/// </summary>
[Conditional("DEBUG")]
internal static void DumpStackTrace(Exception? exception = null, string? message = null)
{
Console.WriteLine("Dumping info before call to failfast");
if (message is object)
{
Console.WriteLine(message);
}
if (exception is object)
{
Console.WriteLine("Exception info");
for (Exception? current = exception; current is object; current = current.InnerException)
{
Console.WriteLine(current.Message);
Console.WriteLine(current.StackTrace);
}
}
#if !NET20 && !NETSTANDARD1_3
Console.WriteLine("Stack trace of handler");
var stackTrace = new StackTrace();
Console.WriteLine(stackTrace.ToString());
#endif
Console.Out.Flush();
}
/// <summary>
/// Checks for the given <paramref name="condition"/>; if the <paramref name="condition"/> is <c>true</c>,
/// immediately terminates the process without running any pending <c>finally</c> blocks or finalizers
/// and causes a crash dump to be collected (if the system is configured to do so).
/// Otherwise, the process continues normally.
/// </summary>
/// <param name="condition">The conditional expression to evaluate.</param>
/// <param name="message">An optional message to be recorded in the dump in case of failure. Can be <c>null</c>.</param>
[Conditional("DEBUG")]
[DebuggerHidden]
internal static void Assert([DoesNotReturnIf(false)] bool condition, string? message = null)
{
if (condition)
{
return;
}
if (Debugger.IsAttached)
{
Debugger.Break();
}
DumpStackTrace(message: message);
Environment.FailFast("ASSERT FAILED" + Environment.NewLine + message);
}
}
}
| AlekseyTs/roslyn | src/Compilers/Core/Portable/InternalUtilities/FailFast.cs | C# | mit | 3,898 |
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010, IBM Corporation
*/
package com.phonegap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import android.util.Log;
public class ContactManager extends Plugin {
private ContactAccessor contactAccessor;
private static final String LOG_TAG = "Contact Query";
public static final int UNKNOWN_ERROR = 0;
public static final int INVALID_ARGUMENT_ERROR = 1;
public static final int TIMEOUT_ERROR = 2;
public static final int PENDING_OPERATION_ERROR = 3;
public static final int IO_ERROR = 4;
public static final int NOT_SUPPORTED_ERROR = 5;
public static final int PERMISSION_DENIED_ERROR = 20;
/**
* Constructor.
*/
public ContactManager() {
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
/**
* Check to see if we are on an Android 1.X device. If we are return an error as we
* do not support this as of PhoneGap 1.0.
*/
if (android.os.Build.VERSION.RELEASE.startsWith("1.")) {
JSONObject res = null;
try {
res = new JSONObject();
res.put("code", NOT_SUPPORTED_ERROR);
res.put("message", "Contacts are not supported in Android 1.X devices");
} catch (JSONException e) {
// This should never happen
Log.e(LOG_TAG, e.getMessage(), e);
}
return new PluginResult(PluginResult.Status.ERROR, res);
}
/**
* Only create the contactAccessor after we check the Android version or the program will crash
* older phones.
*/
if (this.contactAccessor == null) {
this.contactAccessor = new ContactAccessorSdk5(this.webView, this.ctx);
}
try {
if (action.equals("search")) {
JSONArray res = contactAccessor.search(args.getJSONArray(0), args.optJSONObject(1));
return new PluginResult(status, res, "navigator.contacts.cast");
}
else if (action.equals("save")) {
String id = contactAccessor.save(args.getJSONObject(0));
if (id != null) {
JSONObject res = contactAccessor.getContactById(id);
if (res != null) {
return new PluginResult(status, res);
}
}
}
else if (action.equals("remove")) {
if (contactAccessor.remove(args.getString(0))) {
return new PluginResult(status, result);
}
}
// If we get to this point an error has occurred
JSONObject r = new JSONObject();
r.put("code", UNKNOWN_ERROR);
return new PluginResult(PluginResult.Status.ERROR, r);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
}
| roadlabs/android | appMobiLib/src/com/phonegap/ContactManager.java | Java | mit | 3,535 |
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2016 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#include "Trace.hpp"
#include "Vector.hpp"
#include "Util/GlobalSliceAllocator.hpp"
#include <algorithm>
Trace::Trace(const unsigned _no_thin_time, const unsigned max_time,
const unsigned max_size)
:cached_size(0),
max_time(max_time),
no_thin_time(_no_thin_time),
max_size(max_size),
opt_size((3 * max_size) / 4)
{
assert(max_size >= 4);
}
void
Trace::clear()
{
assert(cached_size == delta_list.size());
assert(cached_size == chronological_list.size());
average_delta_distance = 0;
average_delta_time = 0;
delta_list.clear();
chronological_list.clear_and_dispose(MakeDisposer());
cached_size = 0;
assert(cached_size == delta_list.size());
assert(cached_size == chronological_list.size());
++modify_serial;
++append_serial;
}
unsigned
Trace::GetRecentTime(const unsigned t) const
{
if (empty())
return 0;
const TracePoint &last = back();
if (last.GetTime() > t)
return last.GetTime() - t;
return 0;
}
void
Trace::UpdateDelta(TraceDelta &td)
{
assert(cached_size == delta_list.size());
assert(cached_size == chronological_list.size());
if (&td == &chronological_list.front() ||
&td == &chronological_list.back())
return;
const auto ci = chronological_list.iterator_to(td);
const TraceDelta &previous = *std::prev(ci);
const TraceDelta &next = *std::next(ci);
delta_list.erase(delta_list.iterator_to(td));
td.Update(previous.point, next.point);
delta_list.insert(td);
}
void
Trace::EraseInside(DeltaList::iterator it)
{
assert(cached_size > 0);
assert(cached_size == delta_list.size());
assert(cached_size == chronological_list.size());
assert(it != delta_list.end());
const TraceDelta &td = *it;
assert(!td.IsEdge());
const auto ci = chronological_list.iterator_to(td);
TraceDelta &previous = const_cast<TraceDelta &>(*std::prev(ci));
TraceDelta &next = const_cast<TraceDelta &>(*std::next(ci));
// now delete the item
chronological_list.erase(chronological_list.iterator_to(td));
delta_list.erase_and_dispose(it, MakeDisposer());
--cached_size;
// and update the deltas
UpdateDelta(previous);
UpdateDelta(next);
}
bool
Trace::EraseDelta(const unsigned target_size, const unsigned recent)
{
assert(cached_size == delta_list.size());
assert(cached_size == chronological_list.size());
if (size() <= 2)
return false;
bool modified = false;
const unsigned recent_time = GetRecentTime(recent);
auto candidate = delta_list.begin();
while (size() > target_size) {
const TraceDelta &td = *candidate;
if (!td.IsEdge() && td.point.GetTime() < recent_time) {
EraseInside(candidate);
candidate = delta_list.begin(); // find new top
modified = true;
} else {
++candidate;
// suppressed removal, skip it.
}
}
return modified;
}
bool
Trace::EraseEarlierThan(const unsigned p_time)
{
if (p_time == 0 || empty() || GetFront().point.GetTime() >= p_time)
// there will be nothing to remove
return false;
do {
auto ci = chronological_list.begin();
TraceDelta &td = *ci;
chronological_list.erase(ci);
auto i = delta_list.find(td);
assert(i != delta_list.end());
delta_list.erase_and_dispose(i, MakeDisposer());
--cached_size;
} while (!empty() && GetFront().point.GetTime() < p_time);
// need to set deltas for first point, only one of these
// will occur (have to search for this point)
if (!empty())
EraseStart(GetFront());
++modify_serial;
++append_serial;
return true;
}
void
Trace::EraseLaterThan(const unsigned min_time)
{
assert(min_time > 0);
assert(!empty());
while (!empty() && GetBack().point.GetTime() > min_time) {
TraceDelta &td = GetBack();
chronological_list.erase(chronological_list.iterator_to(td));
auto i = delta_list.find(td);
assert(i != delta_list.end());
delta_list.erase_and_dispose(i, MakeDisposer());
--cached_size;
}
/* need to set deltas for first point, only one of these will occur
(have to search for this point) */
if (!empty())
EraseStart(GetBack());
}
/**
* Update start node (and neighbour) after min time pruning
*/
void
Trace::EraseStart(TraceDelta &td)
{
delta_list.erase(delta_list.iterator_to(td));
td.elim_distance = null_delta;
td.elim_time = null_time;
delta_list.insert(td);
}
void
Trace::push_back(const TracePoint &point)
{
assert(cached_size == delta_list.size());
assert(cached_size == chronological_list.size());
if (empty()) {
// first point determines origin for flat projection
task_projection.Reset(point.GetLocation());
task_projection.Update();
} else if (point.GetTime() < back().GetTime()) {
// gone back in time
if (point.GetTime() + 180 < back().GetTime()) {
/* not fixable, clear the trace and restart from scratch */
clear();
return;
}
/* not much, try to fix it */
EraseLaterThan(point.GetTime() - 10);
++modify_serial;
} else if (point.GetTime() - back().GetTime() < 2)
// only add one item per two seconds
return;
EnforceTimeWindow(point.GetTime());
if (size() >= max_size)
Thin();
assert(size() < max_size);
TraceDelta *td = allocator.allocate(1);
allocator.construct(td, point);
td->point.Project(task_projection);
delta_list.insert(*td);
chronological_list.push_back(*td);
++cached_size;
if (td != &chronological_list.front())
UpdateDelta(*std::prev(chronological_list.iterator_to(*td)));
++append_serial;
}
unsigned
Trace::CalcAverageDeltaDistance(const unsigned no_thin) const
{
unsigned r = GetRecentTime(no_thin);
unsigned acc = 0;
unsigned counter = 0;
const auto end = chronological_list.end();
for (auto it = chronological_list.begin();
it != end && it->point.GetTime() < r; ++it, ++counter)
acc += it->delta_distance;
if (counter)
return acc / counter;
return 0;
}
unsigned
Trace::CalcAverageDeltaTime(const unsigned no_thin) const
{
unsigned r = GetRecentTime(no_thin);
unsigned counter = 0;
/* find the last item before the "r" timestamp */
const auto end = chronological_list.end();
ChronologicalList::const_iterator it;
for (it = chronological_list.begin(); it != end && it->point.GetTime() < r; ++it)
++counter;
if (counter < 2)
return 0;
--it;
--counter;
unsigned start_time = front().GetTime();
unsigned end_time = it->point.GetTime();
return (end_time - start_time) / counter;
}
void
Trace::EnforceTimeWindow(unsigned latest_time)
{
if (max_time == null_time)
/* no time window configured */
return;
if (latest_time <= max_time)
/* this can only happen if the flight launched shortly after
midnight; this check is just here to avoid unsigned integer
underflow */
return;
EraseEarlierThan(latest_time - max_time);
}
void
Trace::Thin2()
{
const unsigned target_size = opt_size;
assert(size() > target_size);
// if still too big, remove points based on line simplification
EraseDelta(target_size, no_thin_time);
if (size() <= target_size)
return;
// if still too big, thin again, ignoring recency
if (no_thin_time > 0)
EraseDelta(target_size, 0);
assert(size() <= target_size);
}
void
Trace::Thin()
{
assert(cached_size == delta_list.size());
assert(cached_size == chronological_list.size());
assert(size() == max_size);
Thin2();
assert(size() < max_size);
average_delta_distance = CalcAverageDeltaDistance(no_thin_time);
average_delta_time = CalcAverageDeltaTime(no_thin_time);
++modify_serial;
++append_serial;
}
void
Trace::GetPoints(TracePointVector& iov) const
{
iov.clear();
iov.reserve(size());
std::copy(begin(), end(), std::back_inserter(iov));
}
template<typename I>
class PointerIterator {
I i;
public:
typedef typename I::iterator_category iterator_category;
typedef typename I::pointer value_type;
typedef typename I::pointer *pointer;
typedef value_type &reference;
typedef typename I::difference_type difference_type;
PointerIterator() = default;
explicit PointerIterator(I _i):i(_i) {}
PointerIterator<I> &operator=(const PointerIterator<I> &other) = default;
PointerIterator<I> &operator--() {
--i;
return *this;
}
PointerIterator<I> &operator++() {
++i;
return *this;
}
typename I::pointer operator*() {
return &*i;
}
bool operator==(const PointerIterator<I> &other) const {
return i == other.i;
}
bool operator!=(const PointerIterator<I> &other) const {
return i != other.i;
}
};
void
Trace::GetPoints(TracePointerVector &v) const
{
v.clear();
v.reserve(size());
std::copy(PointerIterator<decltype(begin())>(begin()),
PointerIterator<decltype(end())>(end()),
std::back_inserter(v));
}
bool
Trace::SyncPoints(TracePointerVector &v) const
{
assert(v.size() <= size());
if (v.size() == size())
/* no news */
return false;
v.reserve(size());
PointerIterator<decltype(end())> e(end());
std::copy(std::prev(e, size() - v.size()), e,
std::back_inserter(v));
assert(v.size() == size());
return true;
}
void
Trace::GetPoints(TracePointVector &v, unsigned min_time,
const GeoPoint &location, double min_distance) const
{
/* skip the trace points that are before min_time */
Trace::const_iterator i = begin(), end = this->end();
unsigned skipped = 0;
while (true) {
if (i == end)
/* nothing left */
return;
if (i->GetTime() >= min_time)
/* found the first point that is within range */
break;
++i;
++skipped;
}
assert(skipped < size());
v.reserve(size() - skipped);
const unsigned range = ProjectRange(location, min_distance);
const unsigned sq_range = range * range;
do {
v.push_back(*i);
i.NextSquareRange(sq_range, end);
} while (i != end);
}
| matthewturnbull/xcsoar | src/Engine/Trace/Trace.cpp | C++ | gpl-2.0 | 10,776 |
/*
* 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 io.mycat.util;
/*
* BE ADVISED: New imports added here might introduce new dependencies for
* the clientutil jar. If in doubt, run the `ant test-clientutil-jar' target
* afterward, and ensure the tests still pass.
*/
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* Utility methods to make ByteBuffers less painful
* The following should illustrate the different ways byte buffers can be used
*
* public void testArrayOffet()
* {
*
* byte[] b = "test_slice_array".getBytes();
* ByteBuffer bb = ByteBuffer.allocate(1024);
*
* assert bb.position() == 0;
* assert bb.limit() == 1024;
* assert bb.capacity() == 1024;
*
* bb.put(b);
*
* assert bb.position() == b.length;
* assert bb.remaining() == bb.limit() - bb.position();
*
* ByteBuffer bb2 = bb.slice();
*
* assert bb2.position() == 0;
*
* //slice should begin at other buffers current position
* assert bb2.arrayOffset() == bb.position();
*
* //to match the position in the underlying array one needs to
* //track arrayOffset
* assert bb2.limit()+bb2.arrayOffset() == bb.limit();
*
*
* assert bb2.remaining() == bb.remaining();
*
* }
*
* }
*
*/
public class ByteBufferUtil
{
public static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.wrap(new byte[0]);
public static int compareUnsigned(ByteBuffer o1, ByteBuffer o2)
{
return FastByteOperations.compareUnsigned(o1, o2);
}
public static int compare(byte[] o1, ByteBuffer o2)
{
return FastByteOperations.compareUnsigned(o1, 0, o1.length, o2);
}
public static int compare(ByteBuffer o1, byte[] o2)
{
return FastByteOperations.compareUnsigned(o1, o2, 0, o2.length);
}
/**
* Decode a String representation.
* This method assumes that the encoding charset is UTF_8.
*
* @param buffer a byte buffer holding the string representation
* @return the decoded string
*/
public static String string(ByteBuffer buffer) throws CharacterCodingException
{
return string(buffer, StandardCharsets.UTF_8);
}
/**
* Decode a String representation.
* This method assumes that the encoding charset is UTF_8.
*
* @param buffer a byte buffer holding the string representation
* @param position the starting position in {@code buffer} to start decoding from
* @param length the number of bytes from {@code buffer} to use
* @return the decoded string
*/
public static String string(ByteBuffer buffer, int position, int length) throws CharacterCodingException
{
return string(buffer, position, length, StandardCharsets.UTF_8);
}
/**
* Decode a String representation.
*
* @param buffer a byte buffer holding the string representation
* @param position the starting position in {@code buffer} to start decoding from
* @param length the number of bytes from {@code buffer} to use
* @param charset the String encoding charset
* @return the decoded string
*/
public static String string(ByteBuffer buffer, int position, int length, Charset charset) throws CharacterCodingException
{
ByteBuffer copy = buffer.duplicate();
copy.position(position);
copy.limit(copy.position() + length);
return string(copy, charset);
}
/**
* Decode a String representation.
*
* @param buffer a byte buffer holding the string representation
* @param charset the String encoding charset
* @return the decoded string
*/
public static String string(ByteBuffer buffer, Charset charset) throws CharacterCodingException
{
return charset.newDecoder().decode(buffer.duplicate()).toString();
}
/**
* You should almost never use this. Instead, use the write* methods to avoid copies.
*/
public static byte[] getArray(ByteBuffer buffer)
{
int length = buffer.remaining();
if (buffer.hasArray())
{
int boff = buffer.arrayOffset() + buffer.position();
return Arrays.copyOfRange(buffer.array(), boff, boff + length);
}
// else, DirectByteBuffer.get() is the fastest route
byte[] bytes = new byte[length];
buffer.duplicate().get(bytes);
return bytes;
}
/**
* ByteBuffer adaptation of org.apache.commons.lang3.ArrayUtils.lastIndexOf method
*
* @param buffer the array to traverse for looking for the object, may be <code>null</code>
* @param valueToFind the value to find
* @param startIndex the start index (i.e. BB position) to travers backwards from
* @return the last index (i.e. BB position) of the value within the array
* [between buffer.position() and buffer.limit()]; <code>-1</code> if not found.
*/
public static int lastIndexOf(ByteBuffer buffer, byte valueToFind, int startIndex)
{
assert buffer != null;
if (startIndex < buffer.position())
{
return -1;
}
else if (startIndex >= buffer.limit())
{
startIndex = buffer.limit() - 1;
}
for (int i = startIndex; i >= buffer.position(); i--)
{
if (valueToFind == buffer.get(i)) {
return i;
}
}
return -1;
}
/**
* Encode a String in a ByteBuffer using UTF_8.
*
* @param s the string to encode
* @return the encoded string
*/
public static ByteBuffer bytes(String s)
{
return ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8));
}
/**
* Encode a String in a ByteBuffer using the provided charset.
*
* @param s the string to encode
* @param charset the String encoding charset to use
* @return the encoded string
*/
public static ByteBuffer bytes(String s, Charset charset)
{
return ByteBuffer.wrap(s.getBytes(charset));
}
/**
* @return a new copy of the data in @param buffer
* USUALLY YOU SHOULD USE ByteBuffer.duplicate() INSTEAD, which creates a new Buffer
* (so you can mutate its position without affecting the original) without copying the underlying array.
*/
public static ByteBuffer clone(ByteBuffer buffer)
{
assert buffer != null;
if (buffer.remaining() == 0) {
return EMPTY_BYTE_BUFFER;
}
ByteBuffer clone = ByteBuffer.allocate(buffer.remaining());
if (buffer.hasArray())
{
System.arraycopy(buffer.array(), buffer.arrayOffset() + buffer.position(), clone.array(), 0, buffer.remaining());
}
else
{
clone.put(buffer.duplicate());
clone.flip();
}
return clone;
}
public static void arrayCopy(ByteBuffer src, int srcPos, byte[] dst, int dstPos, int length)
{
FastByteOperations.copy(src, srcPos, dst, dstPos, length);
}
/**
* Transfer bytes from one ByteBuffer to another.
* This function acts as System.arrayCopy() but for ByteBuffers.
*
* @param src the source ByteBuffer
* @param srcPos starting position in the source ByteBuffer
* @param dst the destination ByteBuffer
* @param dstPos starting position in the destination ByteBuffer
* @param length the number of bytes to copy
*/
public static void arrayCopy(ByteBuffer src, int srcPos, ByteBuffer dst, int dstPos, int length)
{
FastByteOperations.copy(src, srcPos, dst, dstPos, length);
}
public static void writeWithLength(byte[] bytes, DataOutput out) throws IOException
{
out.writeInt(bytes.length);
out.write(bytes);
}
/* @return An unsigned short in an integer. */
public static int readShortLength(DataInput in) throws IOException
{
return in.readUnsignedShort();
}
public static byte[] readBytes(DataInput in, int length) throws IOException
{
assert length > 0 : "length is not > 0: " + length;
byte[] bytes = new byte[length];
in.readFully(bytes);
return bytes;
}
/**
* Convert a byte buffer to an integer.
* Does not change the byte buffer position.
*
* @param bytes byte buffer to convert to integer
* @return int representation of the byte buffer
*/
public static int toInt(ByteBuffer bytes)
{
return bytes.getInt(bytes.position());
}
public static long toLong(ByteBuffer bytes)
{
return bytes.getLong(bytes.position());
}
public static float toFloat(ByteBuffer bytes)
{
return bytes.getFloat(bytes.position());
}
public static double toDouble(ByteBuffer bytes)
{
return bytes.getDouble(bytes.position());
}
public static ByteBuffer bytes(int i)
{
return ByteBuffer.allocate(4).putInt(0, i);
}
public static ByteBuffer bytes(long n)
{
return ByteBuffer.allocate(8).putLong(0, n);
}
public static ByteBuffer bytes(float f)
{
return ByteBuffer.allocate(4).putFloat(0, f);
}
public static ByteBuffer bytes(double d)
{
return ByteBuffer.allocate(8).putDouble(0, d);
}
public static InputStream inputStream(ByteBuffer bytes)
{
final ByteBuffer copy = bytes.duplicate();
return new InputStream()
{
public int read()
{
if (!copy.hasRemaining()) {
return -1;
}
return copy.get() & 0xFF;
}
@Override
public int read(byte[] bytes, int off, int len)
{
if (!copy.hasRemaining()) {
return -1;
}
len = Math.min(len, copy.remaining());
copy.get(bytes, off, len);
return len;
}
@Override
public int available()
{
return copy.remaining();
}
};
}
/**
* Compare two ByteBuffer at specified offsets for length.
* Compares the non equal bytes as unsigned.
* @param bytes1 First byte buffer to compare.
* @param offset1 Position to start the comparison at in the first array.
* @param bytes2 Second byte buffer to compare.
* @param offset2 Position to start the comparison at in the second array.
* @param length How many bytes to compare?
* @return -1 if byte1 is less than byte2, 1 if byte2 is less than byte1 or 0 if equal.
*/
public static int compareSubArrays(ByteBuffer bytes1, int offset1, ByteBuffer bytes2, int offset2, int length)
{
if (bytes1 == null) {
return bytes2 == null ? 0 : -1;
}
if (bytes2 == null) {
return 1;
}
assert bytes1.limit() >= offset1 + length : "The first byte array isn't long enough for the specified offset and length.";
assert bytes2.limit() >= offset2 + length : "The second byte array isn't long enough for the specified offset and length.";
for (int i = 0; i < length; i++)
{
byte byte1 = bytes1.get(offset1 + i);
byte byte2 = bytes2.get(offset2 + i);
// if (byte1 == byte2)
// continue;
// compare non-equal bytes as unsigned
if( byte1 != byte2 ) {
return (byte1 & 0xFF) < (byte2 & 0xFF) ? -1 : 1;
}
}
return 0;
}
public static ByteBuffer bytes(InetAddress address)
{
return ByteBuffer.wrap(address.getAddress());
}
// Returns whether {@code prefix} is a prefix of {@code value}.
public static boolean isPrefix(ByteBuffer prefix, ByteBuffer value)
{
if (prefix.remaining() > value.remaining()) {
return false;
}
int diff = value.remaining() - prefix.remaining();
return prefix.equals(value.duplicate().limit(value.remaining() - diff));
}
/** trims size of bytebuffer to exactly number of bytes in it, to do not hold too much memory */
public static ByteBuffer minimalBufferFor(ByteBuffer buf)
{
return buf.capacity() > buf.remaining() || !buf.hasArray() ? ByteBuffer.wrap(getArray(buf)) : buf;
}
// Doesn't change bb position
public static int getShortLength(ByteBuffer bb, int position)
{
int length = (bb.get(position) & 0xFF) << 8;
return length | (bb.get(position + 1) & 0xFF);
}
// changes bb position
public static int readShortLength(ByteBuffer bb)
{
int length = (bb.get() & 0xFF) << 8;
return length | (bb.get() & 0xFF);
}
// changes bb position
public static void writeShortLength(ByteBuffer bb, int length)
{
bb.put((byte) ((length >> 8) & 0xFF));
bb.put((byte) (length & 0xFF));
}
// changes bb position
public static ByteBuffer readBytes(ByteBuffer bb, int length)
{
ByteBuffer copy = bb.duplicate();
copy.limit(copy.position() + length);
bb.position(bb.position() + length);
return copy;
}
// changes bb position
public static ByteBuffer readBytesWithShortLength(ByteBuffer bb)
{
int length = readShortLength(bb);
return readBytes(bb, length);
}
}
| zagnix/Mycat-Server | src/main/java/io/mycat/util/ByteBufferUtil.java | Java | gpl-2.0 | 14,659 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "mohawk/cstime_game.h"
#include "mohawk/cstime_ui.h"
#include "mohawk/cstime_view.h"
#include "mohawk/resource.h"
#include "common/algorithm.h" // find
#include "common/events.h"
#include "common/system.h"
#include "common/textconsole.h"
#include "graphics/fontman.h"
namespace Mohawk {
// read a null-terminated string from a stream
static Common::String readString(Common::SeekableReadStream *stream) {
Common::String ret;
while (!stream->eos()) {
byte in = stream->readByte();
if (!in)
break;
ret += in;
}
return ret;
}
CSTimeInterface::CSTimeInterface(MohawkEngine_CSTime *vm) : _vm(vm) {
_sceneRect = Common::Rect(0, 0, 640, 340);
_uiRect = Common::Rect(0, 340, 640, 480);
_bookRect = Common::Rect(_uiRect.right - 95, _uiRect.top + 32, _uiRect.right - 25, _uiRect.top + 122);
_noteRect = Common::Rect(_uiRect.left + 27, _uiRect.top + 31, _uiRect.left + 103, _uiRect.top + 131);
_dialogTextRect = Common::Rect(0 + 125, 340 + 40, 640 - 125, 480 - 20);
_cursorActive = false;
_cursorShapes[0] = 0xFFFF;
_cursorShapes[1] = 0xFFFF;
_cursorShapes[2] = 0xFFFF;
_cursorNextTime = 0;
_help = new CSTimeHelp(_vm);
_inventoryDisplay = new CSTimeInventoryDisplay(_vm, _dialogTextRect);
_book = new CSTimeBook(_vm);
_note = new CSTimeCarmenNote(_vm);
_options = new CSTimeOptions(_vm);
// The demo uses hardcoded system fonts
if (!(_vm->getFeatures() & GF_DEMO)) {
if (!_normalFont.loadFromFON("EvP14.fon"))
error("failed to load normal font");
if (!_dialogFont.loadFromFON("Int1212.fon"))
error("failed to load dialog font");
if (!_rolloverFont.loadFromFON("Int1818.fon"))
error("failed to load rollover font");
}
_uiFeature = NULL;
_dialogTextFeature = NULL;
_rolloverTextFeature = NULL;
_bubbleTextFeature = NULL;
_mouseWasInScene = false;
_state = kCSTimeInterfaceStateNormal;
_dialogLines.resize(5);
_dialogLineColors.resize(5);
}
CSTimeInterface::~CSTimeInterface() {
delete _help;
delete _inventoryDisplay;
delete _book;
delete _note;
delete _options;
}
const Graphics::Font &CSTimeInterface::getNormalFont() const {
// HACK: Use a ScummVM GUI font in place of a system one for the demo
if (_vm->getFeatures() & GF_DEMO)
return *FontMan.getFontByUsage(Graphics::FontManager::kGUIFont);
return _normalFont;
}
const Graphics::Font &CSTimeInterface::getDialogFont() const {
// HACK: Use a ScummVM GUI font in place of a system one for the demo
if (_vm->getFeatures() & GF_DEMO)
return *FontMan.getFontByUsage(Graphics::FontManager::kGUIFont);
return _dialogFont;
}
const Graphics::Font &CSTimeInterface::getRolloverFont() const {
// HACK: Use a ScummVM GUI font in place of a system one for the demo
if (_vm->getFeatures() & GF_DEMO)
return *FontMan.getFontByUsage(Graphics::FontManager::kBigGUIFont);
return _rolloverFont;
}
void CSTimeInterface::cursorInstall() {
_vm->getView()->loadBitmapCursors(200);
}
void CSTimeInterface::cursorIdle() {
if (!_cursorActive || _cursorShapes[1] == 0xFFFF)
return;
if (_vm->_system->getMillis() <= _cursorNextTime + 250)
return;
cursorSetShape(_cursorShapes[1], false);
_cursorShapes[1] = _cursorShapes[2];
_cursorShapes[2] = 0xFFFF;
}
void CSTimeInterface::cursorActivate(bool state) {
_cursorActive = state;
}
void CSTimeInterface::cursorChangeShape(uint16 id) {
if (_cursorShapes[1] == 0xFFFF)
_cursorShapes[1] = id;
else
_cursorShapes[2] = id;
}
uint16 CSTimeInterface::cursorGetShape() {
if (_cursorShapes[2] != 0xFFFF)
return _cursorShapes[2];
else if (_cursorShapes[1] != 0xFFFF)
return _cursorShapes[1];
else
return _cursorShapes[0];
}
void CSTimeInterface::cursorSetShape(uint16 id, bool reset) {
if (_cursorShapes[0] != id) {
_cursorShapes[0] = id;
_vm->getView()->setBitmapCursor(id);
_cursorNextTime = _vm->_system->getMillis();
}
}
void CSTimeInterface::cursorSetWaitCursor() {
uint16 shape = cursorGetShape();
switch (shape) {
case 8:
cursorChangeShape(9);
break;
case 9:
break;
case 11:
cursorChangeShape(12);
break;
case 13:
cursorChangeShape(15);
break;
default:
cursorChangeShape(3);
break;
}
}
void CSTimeInterface::openResFile() {
_vm->loadResourceFile("data/iface");
}
void CSTimeInterface::install() {
uint16 resourceId = 100; // TODO
_vm->getView()->installGroup(resourceId, 16, 0, true, 100);
// TODO: store/reset these
_dialogTextFeature = _vm->getView()->installViewFeature(0, 0, NULL);
_dialogTextFeature->_data.bounds = _dialogTextRect;
_dialogTextFeature->_data.bitmapIds[0] = 0;
// We don't set a port.
_dialogTextFeature->_moveProc = (Module::FeatureProc)&CSTimeModule::dialogTextMoveProc;
_dialogTextFeature->_drawProc = (Module::FeatureProc)&CSTimeModule::dialogTextDrawProc;
_dialogTextFeature->_timeProc = NULL;
_dialogTextFeature->_flags = kFeatureOldSortForeground; // FIXME: not in original
_rolloverTextFeature = _vm->getView()->installViewFeature(0, 0, NULL);
_rolloverTextFeature->_data.bounds = Common::Rect(0 + 100, 340 + 5, 640 - 100, 480 - 25);
_rolloverTextFeature->_data.bitmapIds[0] = 0;
_rolloverTextFeature->_moveProc = (Module::FeatureProc)&CSTimeModule::rolloverTextMoveProc;
_rolloverTextFeature->_drawProc = (Module::FeatureProc)&CSTimeModule::rolloverTextDrawProc;
_rolloverTextFeature->_timeProc = NULL;
_rolloverTextFeature->_flags = kFeatureOldSortForeground; // FIXME: not in original
}
void CSTimeInterface::draw() {
// TODO
if (!_uiFeature) {
uint32 flags = kFeatureSortStatic | kFeatureNewNoLoop;
assert(flags == 0x4800000);
uint16 resourceId = 100; // TODO
_uiFeature = _vm->getView()->installViewFeature(resourceId, flags, NULL);
// TODO: special-case for case 20
} else {
_uiFeature->resetFeatureScript(1, 0);
// TODO: special-case for case 20
}
// TODO: special-case for cases 19 and 20
_note->drawSmallNote();
_book->drawSmallBook();
_inventoryDisplay->draw();
}
void CSTimeInterface::idle() {
// TODO: inv sound handling
_vm->getCase()->getCurrScene()->idle();
_inventoryDisplay->idle();
cursorIdle();
_vm->getView()->idleView();
}
void CSTimeInterface::mouseDown(Common::Point pos) {
_vm->resetTimeout();
if (_options->getState()) {
// TODO: _options->mouseDown(pos);
return;
}
if (!cursorGetState())
return;
if (_vm->getCase()->getCurrScene()->eventIsActive())
return;
switch (cursorGetShape()) {
case 1:
cursorChangeShape(4);
break;
case 2:
cursorChangeShape(5);
break;
case 13:
cursorChangeShape(14);
break;
}
if (_book->getState() == 2) {
// TODO: _book->mouseDown(pos);
return;
}
// TODO: if in sailing puzzle, sailing puzzle mouse down, return
if (_note->getState() > 0) {
return;
}
if (_sceneRect.contains(pos)) {
_vm->getCase()->getCurrScene()->mouseDown(pos);
return;
}
// TODO: case 20 ui craziness is handled seperately..
CSTimeConversation *conv = _vm->getCase()->getCurrConversation();
if (_bookRect.contains(pos) || (_noteRect.contains(pos) && _note->havePiece(0xffff))) {
if (conv->getState() != (uint)~0)
conv->end(false);
if (_help->getState() != (uint)~0)
_help->end();
return;
}
if (_help->getState() != (uint)~0) {
_help->mouseDown(pos);
return;
}
if (conv->getState() != (uint)~0) {
conv->mouseDown(pos);
return;
}
// TODO: handle symbols
if (_inventoryDisplay->_invRect.contains(pos)) {
// TODO: special handling for case 6
_inventoryDisplay->mouseDown(pos);
}
}
void CSTimeInterface::mouseMove(Common::Point pos) {
if (_options->getState()) {
// TODO: _options->mouseMove(pos);
return;
}
if (!cursorGetState())
return;
if (_mouseWasInScene && _uiRect.contains(pos)) {
clearTextLine();
_mouseWasInScene = false;
}
if (_book->getState() == 2) {
// TODO: _book->mouseMove(pos);
return;
}
if (_note->getState() == 2)
return;
// TODO: case 20 ui craziness is handled seperately..
if (_sceneRect.contains(pos) && !_vm->getCase()->getCurrScene()->eventIsActive()) {
_vm->getCase()->getCurrScene()->mouseMove(pos);
_mouseWasInScene = true;
return;
}
if (cursorGetShape() == 13) {
cursorSetShape(1);
return;
} else if (cursorGetShape() == 14) {
cursorSetShape(4);
return;
}
bool mouseIsDown = _vm->getEventManager()->getButtonState() & 1;
if (_book->getState() == 1 && !_bookRect.contains(pos)) {
if (_state != kCSTimeInterfaceStateDragging) {
clearTextLine();
cursorSetShape(mouseIsDown ? 4 : 1);
_book->setState(0);
}
return;
}
// TODO: case 20 ui craziness again
if (_note->getState() == 1 && !_noteRect.contains(pos)) {
if (_state != kCSTimeInterfaceStateDragging) {
clearTextLine();
cursorSetShape(mouseIsDown ? 4 : 1);
_note->setState(0);
}
return;
}
// TODO: handle symbols
if (_bookRect.contains(pos)) {
if (_state != kCSTimeInterfaceStateDragging) {
displayTextLine("Open Chronopedia");
cursorSetShape(mouseIsDown ? 5 : 2);
_book->setState(1);
}
return;
}
if (_noteRect.contains(pos)) {
if (_state != kCSTimeInterfaceStateDragging && _note->havePiece(0xffff) && !_note->getState()) {
displayTextLine("Look at Note");
cursorSetShape(mouseIsDown ? 5 : 2);
_note->setState(1);
}
return;
}
if (_vm->getCase()->getCurrConversation()->getState() != (uint)~0) {
_vm->getCase()->getCurrConversation()->mouseMove(pos);
return;
}
if (_help->getState() != (uint)~0) {
_help->mouseMove(pos);
return;
}
if (_state == kCSTimeInterfaceStateDragging) {
// FIXME: dragging
return;
}
// FIXME: if case is 20, we're done, return
if (_inventoryDisplay->_invRect.contains(pos)) {
_inventoryDisplay->mouseMove(pos);
}
}
void CSTimeInterface::mouseUp(Common::Point pos) {
if (_options->getState()) {
// TODO: options->mouseUp(pos);
return;
}
if (!cursorGetState())
return;
if (_state == kCSTimeInterfaceStateDragging) {
stopDragging();
return;
}
if (_state == kCSTimeInterfaceStateDragStart)
_state = kCSTimeInterfaceStateNormal;
switch (cursorGetShape()) {
case 4:
cursorChangeShape(1);
break;
case 5:
cursorChangeShape(2);
break;
case 14:
cursorChangeShape(13);
break;
}
if (_vm->getCase()->getCurrScene()->eventIsActive()) {
if (_vm->getCurrentEventType() == kCSTimeEventWaitForClick)
_vm->mouseClicked();
return;
}
if (_book->getState() == 2) {
// TODO: _book->mouseUp(pos);
return;
}
if (_note->getState() == 2) {
_note->closeNote();
mouseMove(pos);
return;
}
// TODO: if in sailing puzzle, sailing puzzle mouse up, return
// TODO: case 20 ui craziness is handled seperately..
if (_sceneRect.contains(pos)) {
_vm->getCase()->getCurrScene()->mouseUp(pos);
return;
}
if (_vm->getCase()->getCurrConversation()->getState() != (uint)~0) {
_vm->getCase()->getCurrConversation()->mouseUp(pos);
return;
}
if (_help->getState() != (uint)~0) {
_help->mouseUp(pos);
return;
}
// TODO: handle symbols
if (_bookRect.contains(pos)) {
// TODO: handle flashing cuffs
// TODO: _book->open();
return;
}
if (_noteRect.contains(pos)) {
// TODO: special-casing for case 19
if (_note->havePiece(0xffff))
_note->drawBigNote();
}
if (_inventoryDisplay->_invRect.contains(pos)) {
// TODO: special-casing for case 6
_inventoryDisplay->mouseUp(pos);
}
}
void CSTimeInterface::cursorOverHotspot() {
if (!cursorGetState())
return;
if (_state == kCSTimeInterfaceStateDragStart || _state == kCSTimeInterfaceStateDragging)
return;
if (cursorGetShape() == 3 || cursorGetShape() == 9)
return;
bool mouseIsDown = _vm->getEventManager()->getButtonState() & 1;
if (mouseIsDown)
cursorSetShape(5);
else if (cursorGetShape() == 1)
cursorChangeShape(2);
}
void CSTimeInterface::setCursorForCurrentPoint() {
uint16 shape = 1;
Common::Point mousePos = _vm->getEventManager()->getMousePos();
if (_bookRect.contains(mousePos)) {
shape = 2;
} else {
uint convState = _vm->getCase()->getCurrConversation()->getState();
uint helpState = _help->getState();
// TODO: symbols too
if (convState == (uint)~0 || convState == 0 || helpState == (uint)~0 || helpState == 0) {
// FIXME: set cursor to 2 if inventory display occupied
} else if (convState == 1 || helpState == 1) {
// FIXME: set cursor to 2 if over conversation rect
}
}
cursorSetShape(shape);
}
void CSTimeInterface::clearTextLine() {
_rolloverText.clear();
}
void CSTimeInterface::displayTextLine(Common::String text) {
_rolloverText = text;
}
void CSTimeInterface::clearDialogArea() {
_dialogLines.clear();
_dialogLines.resize(5);
// TODO: dirty feature
}
void CSTimeInterface::clearDialogLine(uint line) {
_dialogLines[line].clear();
// TODO: dirty feature
}
void CSTimeInterface::displayDialogLine(uint16 id, uint line, byte color) {
Common::SeekableReadStream *stream = _vm->getResource(ID_STRI, id);
Common::String text = readString(stream);
delete stream;
_dialogLines[line] = text;
_dialogLineColors[line] = color;
// TODO: dirty feature
}
void CSTimeInterface::drawTextIdToBubble(uint16 id) {
Common::SeekableReadStream *stream = _vm->getResource(ID_STRI, id);
Common::String text = readString(stream);
delete stream;
drawTextToBubble(&text);
}
void CSTimeInterface::drawTextToBubble(Common::String *text) {
if (_bubbleTextFeature)
error("Attempt to display two text objects");
if (!text)
text = &_bubbleText;
if (text->empty())
return;
_currentBubbleText = *text;
uint bubbleId = _vm->getCase()->getCurrScene()->getBubbleType();
Common::Rect bounds;
switch (bubbleId) {
case 0:
bounds = Common::Rect(15, 7, 625, 80);
break;
case 1:
bounds = Common::Rect(160, 260, 625, 333);
break;
case 2:
bounds = Common::Rect(356, 3, 639, 90);
break;
case 3:
bounds = Common::Rect(10, 7, 380, 80);
break;
case 4:
bounds = Common::Rect(15, 270, 625, 328);
break;
case 5:
bounds = Common::Rect(15, 7, 550, 70);
break;
case 6:
bounds = Common::Rect(0, 0, 313, 76);
break;
case 7:
bounds = Common::Rect(200, 25, 502, 470);
break;
default:
error("unknown bubble type %d in drawTextToBubble", bubbleId);
}
_bubbleTextFeature = _vm->getView()->installViewFeature(0, 0, NULL);
_bubbleTextFeature->_data.bounds = bounds;
_bubbleTextFeature->_data.bitmapIds[0] = 0;
_bubbleTextFeature->_moveProc = (Module::FeatureProc)&CSTimeModule::bubbleTextMoveProc;
_bubbleTextFeature->_drawProc = (Module::FeatureProc)&CSTimeModule::bubbleTextDrawProc;
_bubbleTextFeature->_timeProc = NULL;
_bubbleTextFeature->_flags = kFeatureOldSortForeground; // FIXME: not in original
}
void CSTimeInterface::closeBubble() {
if (_bubbleTextFeature)
_vm->getView()->removeFeature(_bubbleTextFeature, true);
_bubbleTextFeature = NULL;
}
void CSTimeInterface::startDragging(uint16 id) {
CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[id];
cursorSetShape(11);
_draggedItem = id;
if (_draggedItem == TIME_CUFFS_ID) {
if (_inventoryDisplay->getCuffsShape() == 11) {
_inventoryDisplay->setCuffsFlashing();
_vm->getView()->idleView();
}
}
uint32 dragFlags = (grabbedFromInventory() ? 0x800 : 0x600);
_vm->getView()->dragFeature((NewFeature *)invObj->feature, _grabPoint, 4, dragFlags, NULL);
if (_vm->getCase()->getId() == 1 && id == 2) {
// Hardcoded behavior for the torch in the first case.
if (_vm->getCase()->getCurrScene()->getId() == 4) {
// This is the dark tomb.
// FIXME: apply torch hack
_vm->_caseVariable[2]++;
} else {
// FIXME: unapply torch hack
}
}
_state = kCSTimeInterfaceStateDragging;
if (grabbedFromInventory())
return;
// Hide the associated scene feature, if there is one.
if (invObj->featureId != 0xffff) {
CSTimeEvent event;
event.type = kCSTimeEventDisableFeature;
event.param2 = invObj->featureId;
_vm->addEvent(event);
}
_vm->addEventList(invObj->events);
}
void CSTimeInterface::stopDragging() {
CSTimeScene *scene = _vm->getCase()->getCurrScene();
CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[_draggedItem];
Common::Point mousePos = _vm->_system->getEventManager()->getMousePos();
_state = kCSTimeInterfaceStateNormal;
if (_sceneRect.contains(mousePos))
scene->setCursorForCurrentPoint();
else
setCursorForCurrentPoint();
// Find the inventory object hotspot which is topmost for this drop, if any.
uint16 foundInvObjHotspot = 0xffff;
const Common::Array<CSTimeHotspot> &hotspots = scene->getHotspots();
for (uint i = 0; i < hotspots.size(); i++) {
if (hotspots[i].state != 1)
continue;
if (!hotspots[i].region.containsPoint(mousePos))
continue;
for (uint j = 0; j < invObj->hotspots.size(); j++) {
if (invObj->hotspots[j].sceneId != scene->getId())
continue;
if (invObj->hotspots[j].hotspotId != i)
continue;
if (foundInvObjHotspot != 0xffff && invObj->hotspots[foundInvObjHotspot].hotspotId < invObj->hotspots[j].hotspotId)
continue;
foundInvObjHotspot = j;
}
}
// Work out if we're going to consume (nom-nom) the object after the drop.
bool consumeObj = false;
bool runConsumeEvents = false;
if (foundInvObjHotspot != 0xffff) {
CSTimeInventoryHotspot &hotspot = invObj->hotspots[foundInvObjHotspot];
clearTextLine();
for (uint i = 0; i < invObj->locations.size(); i++) {
if (invObj->locations[i].sceneId != hotspot.sceneId)
continue;
if (invObj->locations[i].hotspotId != hotspot.hotspotId)
continue;
consumeObj = true;
break;
}
if (_draggedItem == TIME_CUFFS_ID && !_inventoryDisplay->getCuffsState()) {
consumeObj = false;
// Nuh-uh, they're not activated yet.
_vm->addEvent(CSTimeEvent(kCSTimeEventCharStartFlapping, _vm->getCase()->getCurrScene()->getHelperId(), 9902));
} else {
// FIXME: ding();
runConsumeEvents = true;
}
}
// Deal with the actual drop.
if (grabbedFromInventory()) {
if (!consumeObj) {
_vm->getView()->dragFeature((NewFeature *)invObj->feature, mousePos, 2, 0x800, NULL);
// TODO: playSound(151);
} else if (_draggedItem != TIME_CUFFS_ID) {
_vm->getView()->dragFeature((NewFeature *)invObj->feature, mousePos, 2, 0x600, NULL);
_vm->_haveInvItem[_draggedItem] = 0;
invObj->feature = NULL;
invObj->featureDisabled = true;
_inventoryDisplay->removeItem(_draggedItem);
} else if (!_inventoryDisplay->getCuffsState()) {
// Inactive cuffs.
// TODO: We never actually get here? Which would explain why it makes no sense.
_vm->getView()->dragFeature((NewFeature *)invObj->feature, mousePos, 2, 0x800, NULL);
invObj->feature = NULL;
} else {
// Active cuffs.
_vm->getView()->dragFeature((NewFeature *)invObj->feature, mousePos, 2, 0x600, NULL);
_vm->_haveInvItem[_draggedItem] = 0;
invObj->feature = NULL;
invObj->featureDisabled = true;
}
if (runConsumeEvents) {
_vm->addEventList(invObj->hotspots[foundInvObjHotspot].events);
}
_inventoryDisplay->draw();
} else {
uint32 dragFlags = 0x600;
_vm->getView()->dragFeature((NewFeature *)invObj->feature, mousePos, 2, dragFlags, NULL);
if (_inventoryDisplay->_invRect.contains(mousePos)) {
// Dropped into the inventory.
invObj->feature = NULL;
if (invObj->canTake) {
dropItemInInventory(_draggedItem);
if (invObj->hotspotId)
_vm->addEvent(CSTimeEvent(kCSTimeEventDisableHotspot, 0xffff, invObj->hotspotId));
} else {
if (invObj->featureId)
_vm->addEvent(CSTimeEvent(kCSTimeEventAddFeature, 0xffff, invObj->featureId));
}
for (uint i = 0; i < invObj->hotspots.size(); i++) {
if (invObj->hotspots[i].sceneId != scene->getId())
continue;
if (invObj->hotspots[i].hotspotId != 0xffff)
continue;
_vm->addEventList(invObj->hotspots[i].events);
}
} else {
// Dropped into the scene.
CSTimeEvent event;
event.param1 = 0xffff;
if (consumeObj) {
invObj->feature = NULL;
invObj->featureDisabled = true;
event.type = kCSTimeEventDisableHotspot;
event.param2 = invObj->hotspotId;
} else {
invObj->feature = NULL;
event.type = kCSTimeEventAddFeature;
event.param2 = invObj->featureId;
}
_vm->addEvent(event);
if (runConsumeEvents) {
_vm->addEventList(invObj->hotspots[foundInvObjHotspot].events);
} else {
for (uint i = 0; i < invObj->hotspots.size(); i++) {
if (invObj->hotspots[i].sceneId != scene->getId())
continue;
if (invObj->hotspots[i].hotspotId != 0xfffe)
continue;
_vm->addEventList(invObj->hotspots[i].events);
}
}
}
}
if (_vm->getCase()->getId() == 1 && _vm->getCase()->getCurrScene()->getId() == 4) {
// Hardcoded behavior for torches in the dark tomb, in the first case.
if (_draggedItem == 1 && foundInvObjHotspot == 0xffff) {
// Trying to drag an unlit torch around?
_vm->addEvent(CSTimeEvent(kCSTimeEventCharStartFlapping, 0, 16352));
} else if (_draggedItem == 2 && _vm->_caseVariable[2] == 1) {
// This the first time we tried dragging the lit torch around.
_vm->addEvent(CSTimeEvent(kCSTimeEventCharStartFlapping, 0, 16354));
}
}
// TODO: Is this necessary?
_draggedItem = 0xffff;
}
void CSTimeInterface::setGrabPoint() {
_grabPoint = _vm->_system->getEventManager()->getMousePos();
}
bool CSTimeInterface::grabbedFromInventory() {
return (_inventoryDisplay->_invRect.contains(_grabPoint));
}
void CSTimeInterface::dropItemInInventory(uint16 id) {
if (_vm->_haveInvItem[id])
return;
_vm->_haveInvItem[id] = 1;
_vm->getCase()->_inventoryObjs[id]->feature = NULL;
_inventoryDisplay->insertItemInDisplay(id);
// TODO: deal with symbols
if (_vm->getCase()->getCurrConversation()->getState() == (uint)~0 || _vm->getCase()->getCurrConversation()->getState() == 0) {
// FIXME: additional check here
// FIXME: play sound 151?
_inventoryDisplay->draw();
return;
}
// FIXME: ding();
clearDialogArea();
_inventoryDisplay->show();
_inventoryDisplay->draw();
_inventoryDisplay->setState(kCSTimeInterfaceDroppedInventory);
}
CSTimeHelp::CSTimeHelp(MohawkEngine_CSTime *vm) : _vm(vm) {
_state = (uint)~0;
_currEntry = 0xffff;
_currHover = 0xffff;
_nextToProcess = 0xffff;
}
CSTimeHelp::~CSTimeHelp() {
}
void CSTimeHelp::addQaR(uint16 text, uint16 speech) {
CSTimeHelpQaR qar;
qar.text = text;
qar.speech = speech;
_qars.push_back(qar);
}
void CSTimeHelp::start() {
if (_vm->getInterface()->getInventoryDisplay()->getState() == 4)
return;
_state = 2;
uint16 speech = 5900 + _vm->_rnd->getRandomNumberRng(0, 2);
_vm->addEvent(CSTimeEvent(kCSTimeEventCharStartFlapping, _vm->getCase()->getCurrScene()->getHelperId(), speech));
if (noHelperChanges())
return;
// Play a NIS, making sure the Good Guide is disabled.
_vm->addEvent(CSTimeEvent(kCSTimeEventCharSetState, _vm->getCase()->getCurrScene()->getHelperId(), 0));
_vm->addEvent(CSTimeEvent(kCSTimeEventCharPlayNIS, _vm->getCase()->getCurrScene()->getHelperId(), 0));
_vm->addEvent(CSTimeEvent(kCSTimeEventCharSetState, _vm->getCase()->getCurrScene()->getHelperId(), 0));
}
void CSTimeHelp::end(bool runEvents) {
_state = (uint)~0;
_currHover = 0xffff;
_vm->getInterface()->clearDialogArea();
_vm->getInterface()->getInventoryDisplay()->show();
if (noHelperChanges())
return;
_vm->addEvent(CSTimeEvent(kCSTimeEventCharSetState, _vm->getCase()->getCurrScene()->getHelperId(), 1));
_vm->addEvent(CSTimeEvent(kCSTimeEventCharSomeNIS55, _vm->getCase()->getCurrScene()->getHelperId(), 1));
}
void CSTimeHelp::cleanupAfterFlapping() {
if (_state == 2) {
// Startup.
_vm->getInterface()->getInventoryDisplay()->hide();
selectStrings();
display();
_state = 1;
return;
}
if (_nextToProcess == 0xffff)
return;
unhighlightLine(_nextToProcess);
_nextToProcess = 0xffff;
// TODO: case 18 hard-coding
}
void CSTimeHelp::mouseDown(Common::Point &pos) {
for (uint i = 0; i < _qars.size(); i++) {
Common::Rect thisRect = _vm->getInterface()->_dialogTextRect;
thisRect.top += 1 + i*15;
thisRect.bottom = thisRect.top + 15;
if (!thisRect.contains(pos))
continue;
_currEntry = i;
highlightLine(i);
_vm->getInterface()->cursorSetShape(5);
}
}
void CSTimeHelp::mouseMove(Common::Point &pos) {
bool mouseIsDown = _vm->getEventManager()->getButtonState() & 1;
for (uint i = 0; i < _qars.size(); i++) {
Common::Rect thisRect = _vm->getInterface()->_dialogTextRect;
thisRect.top += 1 + i*15;
thisRect.bottom = thisRect.top + 15;
if (!thisRect.contains(pos))
continue;
if (mouseIsDown) {
if (i != _currEntry)
break;
highlightLine(i);
}
_vm->getInterface()->cursorOverHotspot();
_currHover = i;
return;
}
if (_currHover != 0xffff) {
if (_vm->getInterface()->cursorGetShape() != 3) {
unhighlightLine(_currHover);
_vm->getInterface()->cursorSetShape(1);
}
_currHover = 0xffff;
}
}
void CSTimeHelp::mouseUp(Common::Point &pos) {
if (_currEntry == 0xffff || _qars[_currEntry].speech == 0) {
_vm->getInterface()->cursorSetShape(1);
end();
return;
}
Common::Rect thisRect = _vm->getInterface()->_dialogTextRect;
thisRect.top += 1 + _currEntry*15;
thisRect.bottom = thisRect.top + 15;
if (!thisRect.contains(pos))
return;
_vm->addEvent(CSTimeEvent(kCSTimeEventCharStartFlapping, _vm->getCase()->getCurrScene()->getHelperId(), 5900 + _qars[_currEntry].speech));
_nextToProcess = _currEntry;
_askedAlready.push_back(_qars[_currEntry].text);
}
void CSTimeHelp::display() {
_vm->getInterface()->clearDialogArea();
for (uint i = 0; i < _qars.size(); i++) {
uint16 text = _qars[i].text;
bool askedAlready = Common::find(_askedAlready.begin(), _askedAlready.end(), text) != _askedAlready.end();
_vm->getInterface()->displayDialogLine(5900 + text, i, askedAlready ? 13 : 32);
}
}
void CSTimeHelp::highlightLine(uint line) {
uint16 text = _qars[line].text;
_vm->getInterface()->displayDialogLine(5900 + text, line, 244);
}
void CSTimeHelp::unhighlightLine(uint line) {
uint16 text = _qars[line].text;
bool askedAlready = Common::find(_askedAlready.begin(), _askedAlready.end(), text) != _askedAlready.end();
_vm->getInterface()->displayDialogLine(5900 + text, line, askedAlready ? 13 : 32);
}
void CSTimeHelp::selectStrings() {
_qars.clear();
_vm->getCase()->selectHelpStrings();
}
bool CSTimeHelp::noHelperChanges() {
// These are hardcoded.
if (_vm->getCase()->getId() == 4 && _vm->getCase()->getCurrScene()->getId() == 5)
return true;
if (_vm->getCase()->getId() == 5)
return true;
if (_vm->getCase()->getId() == 14 && _vm->getCase()->getCurrScene()->getId() == 4)
return true;
if (_vm->getCase()->getId() == 17 && _vm->getCase()->getCurrScene()->getId() == 2)
return true;
return false;
}
CSTimeInventoryDisplay::CSTimeInventoryDisplay(MohawkEngine_CSTime *vm, Common::Rect baseRect) : _vm(vm) {
_state = 0;
_cuffsState = false;
_cuffsShape = 10;
_invRect = baseRect;
for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) {
_itemRect[i].left = baseRect.left + 15 + i * 92;
_itemRect[i].top = baseRect.top + 5;
_itemRect[i].right = _itemRect[i].left + 90;
_itemRect[i].bottom = _itemRect[i].top + 70;
}
}
CSTimeInventoryDisplay::~CSTimeInventoryDisplay() {
}
void CSTimeInventoryDisplay::install() {
uint count = _vm->getCase()->_inventoryObjs.size() - 1;
// FIXME: some cases have hard-coded counts
_vm->getView()->installGroup(9000, count, 0, true, 9000);
}
void CSTimeInventoryDisplay::draw() {
for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) {
if (_displayedItems[i] == 0xffff)
continue;
CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[_displayedItems[i]];
if (invObj->featureDisabled)
continue;
if (invObj->feature) {
invObj->feature->resetFeatureScript(1, 0);
continue;
}
// TODO: 0x2000 is set! help?
uint32 flags = kFeatureSortStatic | kFeatureNewNoLoop | 0x2000;
if (i == TIME_CUFFS_ID) {
// Time Cuffs are handled differently.
// TODO: Can we not use _cuffsShape here?
uint16 id = 100 + 10;
if (_cuffsState) {
id = 100 + 12;
flags &= ~kFeatureNewNoLoop;
}
invObj->feature = _vm->getView()->installViewFeature(id, flags, NULL);
} else {
Common::Point pos((_itemRect[i].left + _itemRect[i].right) / 2, (_itemRect[i].top + _itemRect[i].bottom) / 2);
uint16 id = 9000 + (invObj->id - 1);
invObj->feature = _vm->getView()->installViewFeature(id, flags, &pos);
}
}
}
void CSTimeInventoryDisplay::show() {
for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) {
if (_displayedItems[i] == 0xffff)
continue;
CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[_displayedItems[i]];
if (!invObj->feature)
continue;
invObj->feature->show();
}
}
void CSTimeInventoryDisplay::hide() {
for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) {
if (_displayedItems[i] == 0xffff)
continue;
CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[_displayedItems[i]];
if (!invObj->feature)
continue;
invObj->feature->hide(true);
}
}
void CSTimeInventoryDisplay::idle() {
if (_vm->getInterface()->getCarmenNote()->getState() ||
_vm->getCase()->getCurrConversation()->getState() != 0xffff ||
_vm->getInterface()->getHelp()->getState() != 0xffff) {
if (_state == 4) {
// FIXME: check timeout!
hide();
_vm->getCase()->getCurrConversation()->display();
_state = 0;
}
return;
}
if (!_state)
return;
// FIXME: deal with actual inventory stuff
}
void CSTimeInventoryDisplay::clearDisplay() {
for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++)
_displayedItems[i] = 0xffff;
// We always start out with the Time Cuffs.
_vm->_haveInvItem[TIME_CUFFS_ID] = 1;
insertItemInDisplay(TIME_CUFFS_ID);
_cuffsState = false;
}
void CSTimeInventoryDisplay::insertItemInDisplay(uint16 id) {
for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++)
if (_displayedItems[i] == id)
return;
for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++)
if (_displayedItems[i] == 0xffff) {
_displayedItems[i] = id;
return;
}
error("couldn't insert item into display");
}
void CSTimeInventoryDisplay::removeItem(uint16 id) {
CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[id];
if (invObj->feature) {
_vm->getView()->removeFeature(invObj->feature, true);
invObj->feature = NULL;
}
for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++)
if (_displayedItems[i] == id)
_displayedItems[i] = 0xffff;
}
void CSTimeInventoryDisplay::mouseDown(Common::Point &pos) {
for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) {
if (_displayedItems[i] == 0xffff)
continue;
if (!_itemRect[i].contains(pos))
continue;
_draggedItem = i;
_vm->getInterface()->cursorSetShape(8);
_vm->getInterface()->setGrabPoint();
_vm->getInterface()->setState(kCSTimeInterfaceStateDragStart);
}
}
void CSTimeInventoryDisplay::mouseMove(Common::Point &pos) {
bool mouseIsDown = _vm->getEventManager()->getButtonState() & 1;
if (mouseIsDown && _vm->getInterface()->cursorGetShape() == 8) {
Common::Point grabPoint = _vm->getInterface()->getGrabPoint();
if (mouseIsDown && (abs(grabPoint.x - pos.x) > 2 || abs(grabPoint.y - pos.y) > 2)) {
if (_vm->getInterface()->grabbedFromInventory()) {
_vm->getInterface()->startDragging(getLastDisplayedClicked());
} else {
// TODO: CSTimeScene::mouseMove does quite a lot more, why not here too?
_vm->getInterface()->startDragging(_vm->getCase()->getCurrScene()->getInvObjForCurrentHotspot());
}
}
}
for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) {
if (_displayedItems[i] == 0xffff)
continue;
if (!_itemRect[i].contains(pos))
continue;
CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[_displayedItems[i]];
Common::String text = "Pick up ";
// TODO: special-case for case 11, scene 3, inv obj 1 (just use "Read " instead)
text += _vm->getCase()->getRolloverText(invObj->stringId);
_vm->getInterface()->displayTextLine(text);
_vm->getInterface()->cursorOverHotspot();
// FIXME: there's some trickery here to store the id for the below
return;
}
if (false /* FIXME: if we get here and the stored id mentioned above is set.. */) {
_vm->getInterface()->clearTextLine();
if (_vm->getInterface()->getState() != kCSTimeInterfaceStateDragging) {
if (_vm->getInterface()->cursorGetShape() != 3 && _vm->getInterface()->cursorGetShape() != 9)
_vm->getInterface()->cursorSetShape(1);
}
// FIXME: reset that stored id
}
}
void CSTimeInventoryDisplay::mouseUp(Common::Point &pos) {
for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) {
if (_displayedItems[i] == 0xffff)
continue;
if (!_itemRect[i].contains(pos))
continue;
// TODO: instead, stupid hack for case 11, scene 3, inv obj 1 (kCSTimeEventUnknown39, 0xffff, 0xffff)
// TODO: instead, stupid hack for case 18, scene not 3, inv obj 4 (kCSTimeEventCondition, 1, 29)
CSTimeEvent event;
event.param1 = _vm->getCase()->getCurrScene()->getHelperId();
if (event.param1 == 0xffff)
event.type = kCSTimeEventSpeech;
else
event.type = kCSTimeEventCharStartFlapping;
if (i == TIME_CUFFS_ID) {
if (_cuffsState)
event.param2 = 9903;
else
event.param2 = 9902;
} else {
event.param2 = 9905 + _displayedItems[i];
}
_vm->addEvent(event);
}
}
void CSTimeInventoryDisplay::activateCuffs(bool active) {
_cuffsState = active;
if (!_cuffsState)
return;
CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[TIME_CUFFS_ID];
_cuffsShape = 11;
if (invObj->feature)
_vm->getView()->removeFeature(invObj->feature, true);
uint32 flags = kFeatureSortStatic | kFeatureNewNoLoop;
invObj->feature = _vm->getView()->installViewFeature(100 + _cuffsShape, flags, NULL);
invObj->featureDisabled = false;
}
void CSTimeInventoryDisplay::setCuffsFlashing() {
CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[TIME_CUFFS_ID];
_cuffsShape = 12;
if (invObj->feature)
_vm->getView()->removeFeature(invObj->feature, true);
uint32 flags = kFeatureSortStatic | 0x2000;
invObj->feature = _vm->getView()->installViewFeature(100 + _cuffsShape, flags, NULL);
invObj->featureDisabled = false;
}
bool CSTimeInventoryDisplay::isItemDisplayed(uint16 id) {
for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) {
if (_displayedItems[i] == id)
return true;
}
return false;
}
CSTimeBook::CSTimeBook(MohawkEngine_CSTime *vm) : _vm(vm) {
_state = 0;
_smallBookFeature = NULL;
}
CSTimeBook::~CSTimeBook() {
}
void CSTimeBook::drawSmallBook() {
if (!_smallBookFeature) {
_smallBookFeature = _vm->getView()->installViewFeature(101, kFeatureSortStatic | kFeatureNewNoLoop, NULL);
} else {
_smallBookFeature->resetFeature(false, NULL, 0);
}
}
CSTimeCarmenNote::CSTimeCarmenNote(MohawkEngine_CSTime *vm) : _vm(vm) {
_state = 0;
_feature = NULL;
clearPieces();
}
CSTimeCarmenNote::~CSTimeCarmenNote() {
}
void CSTimeCarmenNote::clearPieces() {
for (uint i = 0; i < NUM_NOTE_PIECES; i++)
_pieces[i] = 0xffff;
}
bool CSTimeCarmenNote::havePiece(uint16 piece) {
for (uint i = 0; i < NUM_NOTE_PIECES; i++) {
if (piece == 0xffff) {
if (_pieces[i] != 0xffff)
return true;
} else if (_pieces[i] == piece)
return true;
}
return false;
}
void CSTimeCarmenNote::addPiece(uint16 piece, uint16 speech) {
uint i;
for (i = 0; i < NUM_NOTE_PIECES; i++) {
if (_pieces[i] == 0xffff) {
_pieces[i] = piece;
break;
}
}
if (i == NUM_NOTE_PIECES)
error("addPiece couldn't add piece to carmen note");
// Get the Good Guide to say something.
if (i == 2)
speech = 9900; // Found the third piece.
if (speech != 0xffff)
_vm->addEvent(CSTimeEvent(kCSTimeEventCharStartFlapping, _vm->getCase()->getCurrScene()->getHelperId(), speech));
// Remove the note feature, if any.
uint16 noteFeatureId = _vm->getCase()->getNoteFeatureId(piece);
if (noteFeatureId != 0xffff)
_vm->addEvent(CSTimeEvent(kCSTimeEventDisableFeature, 0xffff, noteFeatureId));
_vm->addEvent(CSTimeEvent(kCSTimeEventShowBigNote, 0xffff, 0xffff));
if (i != 2)
return;
// TODO: special-casing for case 5
_vm->addEvent(CSTimeEvent(kCSTimeEventCharPlayNIS, _vm->getCase()->getCurrScene()->getHelperId(), 3));
// TODO: special-casing for case 5
_vm->addEvent(CSTimeEvent(kCSTimeEventCharStartFlapping, _vm->getCase()->getCurrScene()->getHelperId(), 9901));
_vm->addEvent(CSTimeEvent(kCSTimeEventActivateCuffs, 0xffff, 0xffff));
}
void CSTimeCarmenNote::drawSmallNote() {
if (!havePiece(0xffff))
return;
uint16 id = 100;
if (_pieces[2] != 0xffff)
id += 5;
else if (_pieces[1] != 0xffff)
id += 4;
else
id += 2;
if (_feature)
_vm->getView()->removeFeature(_feature, true);
_feature = _vm->getView()->installViewFeature(id, kFeatureSortStatic | kFeatureNewNoLoop, NULL);
}
void CSTimeCarmenNote::drawBigNote() {
if (_vm->getCase()->getCurrConversation()->getState() != (uint)~0) {
_vm->getCase()->getCurrConversation()->end(false);
} else if (_vm->getInterface()->getHelp()->getState() != (uint)~0) {
_vm->getInterface()->getHelp()->end();
}
// TODO: kill symbols too
uint16 id = 100;
if (_pieces[2] != 0xffff)
id += 9;
else if (_pieces[1] != 0xffff)
id += 8;
else
id += 6;
if (_feature)
_vm->getView()->removeFeature(_feature, true);
_feature = _vm->getView()->installViewFeature(id, kFeatureSortStatic | kFeatureNewNoLoop, NULL);
// FIXME: attach note drawing proc
_state = 2;
}
void CSTimeCarmenNote::closeNote() {
_state = 0;
drawSmallNote();
}
CSTimeOptions::CSTimeOptions(MohawkEngine_CSTime *vm) : _vm(vm) {
_state = 0;
}
CSTimeOptions::~CSTimeOptions() {
}
} // End of namespace Mohawk
| lordhoto/scummvm | engines/mohawk/cstime_ui.cpp | C++ | gpl-2.0 | 38,280 |
class PermalinkSerializer < ApplicationSerializer
attributes :id, :url, :topic_id, :topic_title, :topic_url,
:post_id, :post_url, :post_number, :post_topic_title,
:category_id, :category_name, :category_url, :external_url
def topic_title
object&.topic&.title
end
def topic_url
object&.topic&.url
end
def post_url
# use `full_url` to support subfolder setups
object&.post&.full_url
end
def post_number
object&.post&.post_number
end
def post_topic_title
object&.post&.topic&.title
end
def category_name
object&.category&.name
end
def category_url
object&.category&.url
end
end
| andriy-kravchuck/discourse9323 | app/serializers/permalink_serializer.rb | Ruby | gpl-2.0 | 670 |
package info.novatec.inspectit.indexing.aggregation.impl;
import info.novatec.inspectit.communication.IAggregatedData;
import info.novatec.inspectit.communication.data.ThreadInformationData;
import info.novatec.inspectit.indexing.aggregation.IAggregator;
import java.io.Serializable;
/**
* {@link IAggregator} for the {@link ThreadInformationData}.
*
* @author Ivan Senic
*
*/
public class ThreadInformationDataAggregator implements IAggregator<ThreadInformationData>, Serializable {
/**
* Generated UID.
*/
private static final long serialVersionUID = 749269646913958594L;
/**
* {@inheritDoc}
*/
public void aggregate(IAggregatedData<ThreadInformationData> aggregatedObject, ThreadInformationData objectToAdd) {
aggregatedObject.aggregate(objectToAdd);
}
/**
* {@inheritDoc}
*/
public ThreadInformationData getClone(ThreadInformationData threadInformationData) {
ThreadInformationData clone = new ThreadInformationData();
clone.setPlatformIdent(threadInformationData.getPlatformIdent());
clone.setSensorTypeIdent(threadInformationData.getSensorTypeIdent());
return clone;
}
/**
* {@inheritDoc}
*/
public boolean isCloning() {
return true;
}
/**
* {@inheritDoc}
*/
public Object getAggregationKey(ThreadInformationData object) {
return object.getPlatformIdent();
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
// we must make constant hashCode because of the caching
result = prime * result + this.getClass().getName().hashCode();
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return true;
}
}
| kugelr/inspectIT | CommonsCS/src/info/novatec/inspectit/indexing/aggregation/impl/ThreadInformationDataAggregator.java | Java | agpl-3.0 | 1,820 |
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"bytes"
"encoding/json"
"fmt"
"io"
"github.com/ghodss/yaml"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
apijson "k8s.io/apimachinery/pkg/util/json"
api "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/kubectl"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/cmd/util/editor"
"k8s.io/kubernetes/pkg/kubectl/resource"
"k8s.io/kubernetes/pkg/kubectl/scheme"
"k8s.io/kubernetes/pkg/kubectl/util/i18n"
)
type SetLastAppliedOptions struct {
FilenameOptions resource.FilenameOptions
Selector string
InfoList []*resource.Info
Mapper meta.RESTMapper
Typer runtime.ObjectTyper
Namespace string
EnforceNamespace bool
DryRun bool
ShortOutput bool
CreateAnnotation bool
Output string
PatchBufferList []PatchBuffer
Factory cmdutil.Factory
Out io.Writer
ErrOut io.Writer
}
type PatchBuffer struct {
Patch []byte
PatchType types.PatchType
}
var (
applySetLastAppliedLong = templates.LongDesc(i18n.T(`
Set the latest last-applied-configuration annotations by setting it to match the contents of a file.
This results in the last-applied-configuration being updated as though 'kubectl apply -f <file>' was run,
without updating any other parts of the object.`))
applySetLastAppliedExample = templates.Examples(i18n.T(`
# Set the last-applied-configuration of a resource to match the contents of a file.
kubectl apply set-last-applied -f deploy.yaml
# Execute set-last-applied against each configuration file in a directory.
kubectl apply set-last-applied -f path/
# Set the last-applied-configuration of a resource to match the contents of a file, will create the annotation if it does not already exist.
kubectl apply set-last-applied -f deploy.yaml --create-annotation=true
`))
)
func NewCmdApplySetLastApplied(f cmdutil.Factory, out, err io.Writer) *cobra.Command {
options := &SetLastAppliedOptions{Out: out, ErrOut: err}
cmd := &cobra.Command{
Use: "set-last-applied -f FILENAME",
DisableFlagsInUseLine: true,
Short: i18n.T("Set the last-applied-configuration annotation on a live object to match the contents of a file."),
Long: applySetLastAppliedLong,
Example: applySetLastAppliedExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(options.Complete(f, cmd))
cmdutil.CheckErr(options.Validate(f, cmd))
cmdutil.CheckErr(options.RunSetLastApplied(f, cmd))
},
}
cmdutil.AddDryRunFlag(cmd)
cmdutil.AddRecordFlag(cmd)
cmdutil.AddPrinterFlags(cmd)
cmd.Flags().BoolVar(&options.CreateAnnotation, "create-annotation", false, "Will create 'last-applied-configuration' annotations if current objects doesn't have one")
usage := "that contains the last-applied-configuration annotations"
kubectl.AddJsonFilenameFlag(cmd, &options.FilenameOptions.Filenames, "Filename, directory, or URL to files "+usage)
return cmd
}
func (o *SetLastAppliedOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {
o.DryRun = cmdutil.GetDryRunFlag(cmd)
o.Output = cmdutil.GetFlagString(cmd, "output")
o.ShortOutput = o.Output == "name"
var err error
o.Mapper, o.Typer = f.Object()
if err != nil {
return err
}
o.Namespace, o.EnforceNamespace, err = f.DefaultNamespace()
return err
}
func (o *SetLastAppliedOptions) Validate(f cmdutil.Factory, cmd *cobra.Command) error {
r := f.NewBuilder().
Unstructured().
NamespaceParam(o.Namespace).DefaultNamespace().
FilenameParam(o.EnforceNamespace, &o.FilenameOptions).
Flatten().
Do()
err := r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
patchBuf, diffBuf, patchType, err := editor.GetApplyPatch(info.Object, scheme.DefaultJSONEncoder())
if err != nil {
return err
}
// Verify the object exists in the cluster before trying to patch it.
if err := info.Get(); err != nil {
if errors.IsNotFound(err) {
return err
} else {
return cmdutil.AddSourceToErr(fmt.Sprintf("retrieving current configuration of:\n%v\nfrom server for:", info), info.Source, err)
}
}
originalBuf, err := kubectl.GetOriginalConfiguration(info.Mapping, info.Object)
if err != nil {
return cmdutil.AddSourceToErr(fmt.Sprintf("retrieving current configuration of:\n%v\nfrom server for:", info), info.Source, err)
}
if originalBuf == nil && !o.CreateAnnotation {
return cmdutil.UsageErrorf(cmd, "no last-applied-configuration annotation found on resource: %s, to create the annotation, run the command with --create-annotation", info.Name)
}
//only add to PatchBufferList when changed
if !bytes.Equal(cmdutil.StripComments(originalBuf), cmdutil.StripComments(diffBuf)) {
p := PatchBuffer{Patch: patchBuf, PatchType: patchType}
o.PatchBufferList = append(o.PatchBufferList, p)
o.InfoList = append(o.InfoList, info)
} else {
fmt.Fprintf(o.Out, "set-last-applied %s: no changes required.\n", info.Name)
}
return nil
})
return err
}
func (o *SetLastAppliedOptions) RunSetLastApplied(f cmdutil.Factory, cmd *cobra.Command) error {
for i, patch := range o.PatchBufferList {
info := o.InfoList[i]
if !o.DryRun {
mapping := info.ResourceMapping()
client, err := f.UnstructuredClientForMapping(mapping)
if err != nil {
return err
}
helper := resource.NewHelper(client, mapping)
patchedObj, err := helper.Patch(o.Namespace, info.Name, patch.PatchType, patch.Patch)
if err != nil {
return err
}
if len(o.Output) > 0 && !o.ShortOutput {
info.Refresh(patchedObj, false)
return cmdutil.PrintObject(cmd, info.Object, o.Out)
}
cmdutil.PrintSuccess(o.ShortOutput, o.Out, info.Object, o.DryRun, "configured")
} else {
err := o.formatPrinter(o.Output, patch.Patch, o.Out)
if err != nil {
return err
}
cmdutil.PrintSuccess(o.ShortOutput, o.Out, info.Object, o.DryRun, "configured")
}
}
return nil
}
func (o *SetLastAppliedOptions) formatPrinter(output string, buf []byte, w io.Writer) error {
yamlOutput, err := yaml.JSONToYAML(buf)
if err != nil {
return err
}
switch output {
case "json":
jsonBuffer := &bytes.Buffer{}
err = json.Indent(jsonBuffer, buf, "", " ")
if err != nil {
return err
}
fmt.Fprintf(w, "%s\n", jsonBuffer.String())
case "yaml":
fmt.Fprintf(w, "%s\n", string(yamlOutput))
}
return nil
}
func (o *SetLastAppliedOptions) getPatch(info *resource.Info) ([]byte, []byte, error) {
objMap := map[string]map[string]map[string]string{}
metadataMap := map[string]map[string]string{}
annotationsMap := map[string]string{}
localFile, err := runtime.Encode(scheme.DefaultJSONEncoder(), info.Object)
if err != nil {
return nil, localFile, err
}
annotationsMap[api.LastAppliedConfigAnnotation] = string(localFile)
metadataMap["annotations"] = annotationsMap
objMap["metadata"] = metadataMap
jsonString, err := apijson.Marshal(objMap)
return jsonString, localFile, err
}
| dobbymoodge/origin | vendor/k8s.io/kubernetes/pkg/kubectl/cmd/apply_set_last_applied.go | GO | apache-2.0 | 7,729 |
/*
Copyright 2012 Harri Smatt
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 fi.harism.curl;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.RectF;
/**
* Storage class for page textures, blend colors and possibly some other values
* in the future.
*
* @author harism
*/
public class CurlPage {
public static final int SIDE_BACK = 2;
public static final int SIDE_BOTH = 3;
public static final int SIDE_FRONT = 1;
private int mColorBack;
private int mColorFront;
private Bitmap mTextureBack;
private Bitmap mTextureFront;
private boolean mTexturesChanged;
/**
* Default constructor.
*/
public CurlPage() {
reset();
}
/**
* Getter for color.
*/
public int getColor(int side) {
switch (side) {
case SIDE_FRONT:
return mColorFront;
default:
return mColorBack;
}
}
/**
* Calculates the next highest power of two for a given integer.
*/
private int getNextHighestPO2(int n) {
n -= 1;
n = n | (n >> 1);
n = n | (n >> 2);
n = n | (n >> 4);
n = n | (n >> 8);
n = n | (n >> 16);
n = n | (n >> 32);
return n + 1;
}
/**
* Generates nearest power of two sized Bitmap for give Bitmap. Returns this
* new Bitmap using default return statement + original texture coordinates
* are stored into RectF.
*/
private Bitmap getTexture(Bitmap bitmap, RectF textureRect) {
// Bitmap original size.
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// Bitmap size expanded to next power of two. This is done due to
// the requirement on many devices, texture width and height should
// be power of two.
int newW = getNextHighestPO2(w);
int newH = getNextHighestPO2(h);
// TODO: Is there another way to create a bigger Bitmap and copy
// original Bitmap to it more efficiently? Immutable bitmap anyone?
Bitmap bitmapTex = Bitmap.createBitmap(newW, newH, bitmap.getConfig());
Canvas c = new Canvas(bitmapTex);
c.drawBitmap(bitmap, 0, 0, null);
// Calculate final texture coordinates.
float texX = (float) w / newW;
float texY = (float) h / newH;
textureRect.set(0f, 0f, texX, texY);
return bitmapTex;
}
/**
* Getter for textures. Creates Bitmap sized to nearest power of two, copies
* original Bitmap into it and returns it. RectF given as parameter is
* filled with actual texture coordinates in this new upscaled texture
* Bitmap.
*/
public Bitmap getTexture(RectF textureRect, int side) {
switch (side) {
case SIDE_FRONT:
return getTexture(mTextureFront, textureRect);
default:
return getTexture(mTextureBack, textureRect);
}
}
/**
* Returns true if textures have changed.
*/
public boolean getTexturesChanged() {
return mTexturesChanged;
}
/**
* Returns true if back siding texture exists and it differs from front
* facing one.
*/
public boolean hasBackTexture() {
return !mTextureFront.equals(mTextureBack);
}
/**
* Recycles and frees underlying Bitmaps.
*/
public void recycle() {
if (mTextureFront != null) {
mTextureFront.recycle();
}
mTextureFront = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565);
mTextureFront.eraseColor(mColorFront);
if (mTextureBack != null) {
mTextureBack.recycle();
}
mTextureBack = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565);
mTextureBack.eraseColor(mColorBack);
mTexturesChanged = false;
}
/**
* Resets this CurlPage into its initial state.
*/
public void reset() {
mColorBack = Color.WHITE;
mColorFront = Color.WHITE;
recycle();
}
/**
* Setter blend color.
*/
public void setColor(int color, int side) {
switch (side) {
case SIDE_FRONT:
mColorFront = color;
break;
case SIDE_BACK:
mColorBack = color;
break;
default:
mColorFront = mColorBack = color;
break;
}
}
/**
* Setter for textures.
*/
public void setTexture(Bitmap texture, int side) {
if (texture == null) {
texture = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565);
if (side == SIDE_BACK) {
texture.eraseColor(mColorBack);
} else {
texture.eraseColor(mColorFront);
}
}
switch (side) {
case SIDE_FRONT:
if (mTextureFront != null)
mTextureFront.recycle();
mTextureFront = texture;
break;
case SIDE_BACK:
if (mTextureBack != null)
mTextureBack.recycle();
mTextureBack = texture;
break;
case SIDE_BOTH:
if (mTextureFront != null)
mTextureFront.recycle();
if (mTextureBack != null)
mTextureBack.recycle();
mTextureFront = mTextureBack = texture;
break;
}
mTexturesChanged = true;
}
}
| yytang2012/android_page_curl | src/fi/harism/curl/CurlPage.java | Java | apache-2.0 | 5,100 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.api.common.serialization;
import org.apache.flink.annotation.PublicEvolving;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
/**
* A simple {@link Encoder} that uses {@code toString()} on the input elements and writes them to
* the output bucket file separated by newline.
*
* @param <IN> The type of the elements that are being written by the sink.
*/
@PublicEvolving
public class SimpleStringEncoder<IN> implements Encoder<IN> {
private static final long serialVersionUID = -6865107843734614452L;
private String charsetName;
private transient Charset charset;
/**
* Creates a new {@code StringWriter} that uses {@code "UTF-8"} charset to convert strings to
* bytes.
*/
public SimpleStringEncoder() {
this("UTF-8");
}
/**
* Creates a new {@code StringWriter} that uses the given charset to convert strings to bytes.
*
* @param charsetName Name of the charset to be used, must be valid input for {@code
* Charset.forName(charsetName)}
*/
public SimpleStringEncoder(String charsetName) {
this.charsetName = charsetName;
}
@Override
public void encode(IN element, OutputStream stream) throws IOException {
if (charset == null) {
charset = Charset.forName(charsetName);
}
stream.write(element.toString().getBytes(charset));
stream.write('\n');
}
}
| lincoln-lil/flink | flink-core/src/main/java/org/apache/flink/api/common/serialization/SimpleStringEncoder.java | Java | apache-2.0 | 2,282 |
<?php
final class PhabricatorApplicationEditEngine
extends PhabricatorEditEngine {
const ENGINECONST = 'application.application';
public function getEngineApplicationClass() {
return 'PhabricatorApplicationsApplication';
}
public function getEngineName() {
return pht('Applications');
}
public function getSummaryHeader() {
return pht('Configure Application Forms');
}
public function getSummaryText() {
return pht('Configure creation and editing forms in Applications.');
}
public function isEngineConfigurable() {
return false;
}
protected function newEditableObject() {
throw new PhutilMethodNotImplementedException();
}
protected function newObjectQuery() {
return new PhabricatorApplicationQuery();
}
protected function getObjectCreateTitleText($object) {
return pht('Create New Application');
}
protected function getObjectEditTitleText($object) {
return pht('Edit Application: %s', $object->getName());
}
protected function getObjectEditShortText($object) {
return $object->getName();
}
protected function getObjectCreateShortText() {
return pht('Create Application');
}
protected function getObjectName() {
return pht('Application');
}
protected function getObjectViewURI($object) {
return $object->getViewURI();
}
protected function buildCustomEditFields($object) {
return array();
}
}
| folsom-labs/phabricator | src/applications/meta/editor/PhabricatorApplicationEditEngine.php | PHP | apache-2.0 | 1,428 |
/*
* Copyright (C) 2013 salesforce.com, 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.
*/
({
doInit: function(component, event, helper) {
// Add some data to the "data" attribute to show in the iteration
var mapdata = {
items: [
{ "label": "0"},
{ "label": "1"},
{ "label": "2"},
{ "label": "3"},
{ "label": "4"}
]
};
component.set("v.mapdata", mapdata);
},
}) | forcedotcom/aura | aura-components/src/test/components/iterationTest/iterationArrayValueChange_ObjectFromAttribute_PassThroughValue/iterationArrayValueChange_ObjectFromAttribute_PassThroughValueController.js | JavaScript | apache-2.0 | 919 |