repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
ainsofsoo/generatedata | resources/classes/Constants.class.php | 299 | <?php
/**
* A storage class for all script-wide constants.
* @package Core
*/
class Constants {
const PLUGIN_DATA_TYPE = "dataType";
const PLUGIN_EXPORT_TYPE = "exportType";
const PLUGIN_COUNTRY = "country";
const GEN_ENVIRONMENT_POST = "POST";
const GEN_ENVIRONMENT_API = "API";
}
| gpl-3.0 |
Oygron/rainloop-webmail | rainloop/v/0.0.0/app/libraries/SabreForRainLoop/DAVACL/PrincipalCollection.php | 942 | <?php
namespace SabreForRainLoop\DAVACL;
/**
* Principals Collection
*
* This collection represents a list of users.
* The users are instances of SabreForRainLoop\DAVACL\Principal
*
* @copyright Copyright (C) 2007-2013 fruux GmbH (https://fruux.com/).
* @author Evert Pot (http://evertpot.com/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class PrincipalCollection extends AbstractPrincipalCollection {
/**
* This method returns a node for a principal.
*
* The passed array contains principal information, and is guaranteed to
* at least contain a uri item. Other properties may or may not be
* supplied by the authentication backend.
*
* @param array $principal
* @return \SabreForRainLoop\DAV\INode
*/
public function getChildForPrincipal(array $principal) {
return new Principal($this->principalBackend, $principal);
}
}
| agpl-3.0 |
mbroadst/debian-qpid-proton-old | proton-j/src/main/java/org/apache/qpid/proton/amqp/transaction/TransactionErrors.java | 1200 |
/*
*
* 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.qpid.proton.amqp.transaction;
import org.apache.qpid.proton.amqp.Symbol;
public interface TransactionErrors
{
final static Symbol UNKNOWN_ID = Symbol.valueOf("amqp:transaction:unknown-id");
final static Symbol TRANSACTION_ROLLBACK = Symbol.valueOf("amqp:transaction:rollback");
final static Symbol TRANSACTION_TIMEOUT = Symbol.valueOf("amqp:transaction:timeout");
}
| apache-2.0 |
minestarks/TypeScript | tests/cases/conformance/es6/functionPropertyAssignments/FunctionPropertyAssignments2_es6.ts | 36 | // @target: es6
var v = { *() { } } | apache-2.0 |
tmckayus/oshinko-cli | vendor/github.com/gogo/protobuf/test/stdtypes/stdtypes.pb.go | 40463 | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: stdtypes.proto
/*
Package stdtypes is a generated protocol buffer package.
It is generated from these files:
stdtypes.proto
It has these top-level messages:
StdTypes
RepStdTypes
MapStdTypes
OneofStdTypes
*/
package stdtypes
import proto "github.com/gogo/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "github.com/gogo/protobuf/gogoproto"
import _ "github.com/gogo/protobuf/types"
import _ "github.com/gogo/protobuf/types"
import time "time"
import github_com_gogo_protobuf_types "github.com/gogo/protobuf/types"
import strings "strings"
import reflect "reflect"
import sortkeys "github.com/gogo/protobuf/sortkeys"
import types "github.com/gogo/protobuf/types"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
var _ = time.Kitchen
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
type StdTypes struct {
NullableTimestamp *time.Time `protobuf:"bytes,1,opt,name=nullableTimestamp,stdtime" json:"nullableTimestamp,omitempty"`
NullableDuration *time.Duration `protobuf:"bytes,2,opt,name=nullableDuration,stdduration" json:"nullableDuration,omitempty"`
Timestamp time.Time `protobuf:"bytes,3,opt,name=timestamp,stdtime" json:"timestamp"`
Duration time.Duration `protobuf:"bytes,4,opt,name=duration,stdduration" json:"duration"`
}
func (m *StdTypes) Reset() { *m = StdTypes{} }
func (m *StdTypes) String() string { return proto.CompactTextString(m) }
func (*StdTypes) ProtoMessage() {}
func (*StdTypes) Descriptor() ([]byte, []int) { return fileDescriptorStdtypes, []int{0} }
func (m *StdTypes) GetNullableTimestamp() *time.Time {
if m != nil {
return m.NullableTimestamp
}
return nil
}
func (m *StdTypes) GetNullableDuration() *time.Duration {
if m != nil {
return m.NullableDuration
}
return nil
}
func (m *StdTypes) GetTimestamp() time.Time {
if m != nil {
return m.Timestamp
}
return time.Time{}
}
func (m *StdTypes) GetDuration() time.Duration {
if m != nil {
return m.Duration
}
return 0
}
type RepStdTypes struct {
NullableTimestamps []*time.Time `protobuf:"bytes,1,rep,name=nullableTimestamps,stdtime" json:"nullableTimestamps,omitempty"`
NullableDurations []*time.Duration `protobuf:"bytes,2,rep,name=nullableDurations,stdduration" json:"nullableDurations,omitempty"`
Timestamps []time.Time `protobuf:"bytes,3,rep,name=timestamps,stdtime" json:"timestamps"`
Durations []time.Duration `protobuf:"bytes,4,rep,name=durations,stdduration" json:"durations"`
}
func (m *RepStdTypes) Reset() { *m = RepStdTypes{} }
func (m *RepStdTypes) String() string { return proto.CompactTextString(m) }
func (*RepStdTypes) ProtoMessage() {}
func (*RepStdTypes) Descriptor() ([]byte, []int) { return fileDescriptorStdtypes, []int{1} }
func (m *RepStdTypes) GetNullableTimestamps() []*time.Time {
if m != nil {
return m.NullableTimestamps
}
return nil
}
func (m *RepStdTypes) GetNullableDurations() []*time.Duration {
if m != nil {
return m.NullableDurations
}
return nil
}
func (m *RepStdTypes) GetTimestamps() []time.Time {
if m != nil {
return m.Timestamps
}
return nil
}
func (m *RepStdTypes) GetDurations() []time.Duration {
if m != nil {
return m.Durations
}
return nil
}
type MapStdTypes struct {
NullableTimestamp map[int32]*time.Time `protobuf:"bytes,1,rep,name=nullableTimestamp,stdtime" json:"nullableTimestamp,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"`
Timestamp map[int32]time.Time `protobuf:"bytes,2,rep,name=timestamp,stdtime" json:"timestamp" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"`
NullableDuration map[int32]*time.Duration `protobuf:"bytes,3,rep,name=nullableDuration,stdduration" json:"nullableDuration,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"`
Duration map[int32]time.Duration `protobuf:"bytes,4,rep,name=duration,stdduration" json:"duration" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"`
}
func (m *MapStdTypes) Reset() { *m = MapStdTypes{} }
func (m *MapStdTypes) String() string { return proto.CompactTextString(m) }
func (*MapStdTypes) ProtoMessage() {}
func (*MapStdTypes) Descriptor() ([]byte, []int) { return fileDescriptorStdtypes, []int{2} }
func (m *MapStdTypes) GetNullableTimestamp() map[int32]*time.Time {
if m != nil {
return m.NullableTimestamp
}
return nil
}
func (m *MapStdTypes) GetTimestamp() map[int32]time.Time {
if m != nil {
return m.Timestamp
}
return nil
}
func (m *MapStdTypes) GetNullableDuration() map[int32]*time.Duration {
if m != nil {
return m.NullableDuration
}
return nil
}
func (m *MapStdTypes) GetDuration() map[int32]time.Duration {
if m != nil {
return m.Duration
}
return nil
}
type OneofStdTypes struct {
// Types that are valid to be assigned to OneOfStdTimes:
// *OneofStdTypes_Timestamp
// *OneofStdTypes_Duration
OneOfStdTimes isOneofStdTypes_OneOfStdTimes `protobuf_oneof:"OneOfStdTimes"`
}
func (m *OneofStdTypes) Reset() { *m = OneofStdTypes{} }
func (m *OneofStdTypes) String() string { return proto.CompactTextString(m) }
func (*OneofStdTypes) ProtoMessage() {}
func (*OneofStdTypes) Descriptor() ([]byte, []int) { return fileDescriptorStdtypes, []int{3} }
type isOneofStdTypes_OneOfStdTimes interface {
isOneofStdTypes_OneOfStdTimes()
Equal(interface{}) bool
VerboseEqual(interface{}) error
Size() int
}
type OneofStdTypes_Timestamp struct {
Timestamp *time.Time `protobuf:"bytes,1,opt,name=timestamp,oneof,stdtime"`
}
type OneofStdTypes_Duration struct {
Duration *time.Duration `protobuf:"bytes,2,opt,name=duration,oneof,stdduration"`
}
func (*OneofStdTypes_Timestamp) isOneofStdTypes_OneOfStdTimes() {}
func (*OneofStdTypes_Duration) isOneofStdTypes_OneOfStdTimes() {}
func (m *OneofStdTypes) GetOneOfStdTimes() isOneofStdTypes_OneOfStdTimes {
if m != nil {
return m.OneOfStdTimes
}
return nil
}
func (m *OneofStdTypes) GetTimestamp() *time.Time {
if x, ok := m.GetOneOfStdTimes().(*OneofStdTypes_Timestamp); ok {
return x.Timestamp
}
return nil
}
func (m *OneofStdTypes) GetDuration() *time.Duration {
if x, ok := m.GetOneOfStdTimes().(*OneofStdTypes_Duration); ok {
return x.Duration
}
return nil
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*OneofStdTypes) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _OneofStdTypes_OneofMarshaler, _OneofStdTypes_OneofUnmarshaler, _OneofStdTypes_OneofSizer, []interface{}{
(*OneofStdTypes_Timestamp)(nil),
(*OneofStdTypes_Duration)(nil),
}
}
func _OneofStdTypes_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*OneofStdTypes)
// OneOfStdTimes
switch x := m.OneOfStdTimes.(type) {
case *OneofStdTypes_Timestamp:
_ = b.EncodeVarint(1<<3 | proto.WireBytes)
dAtA, err := github_com_gogo_protobuf_types.StdTimeMarshal(*x.Timestamp)
if err != nil {
return err
}
if err := b.EncodeRawBytes(dAtA); err != nil {
return err
}
case *OneofStdTypes_Duration:
_ = b.EncodeVarint(2<<3 | proto.WireBytes)
dAtA, err := github_com_gogo_protobuf_types.StdDurationMarshal(*x.Duration)
if err != nil {
return err
}
if err := b.EncodeRawBytes(dAtA); err != nil {
return err
}
case nil:
default:
return fmt.Errorf("OneofStdTypes.OneOfStdTimes has unexpected type %T", x)
}
return nil
}
func _OneofStdTypes_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*OneofStdTypes)
switch tag {
case 1: // OneOfStdTimes.timestamp
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeRawBytes(true)
if err != nil {
return true, err
}
c := new(time.Time)
if err2 := github_com_gogo_protobuf_types.StdTimeUnmarshal(c, x); err2 != nil {
return true, err
}
m.OneOfStdTimes = &OneofStdTypes_Timestamp{c}
return true, err
case 2: // OneOfStdTimes.duration
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeRawBytes(true)
if err != nil {
return true, err
}
c := new(time.Duration)
if err2 := github_com_gogo_protobuf_types.StdDurationUnmarshal(c, x); err2 != nil {
return true, err
}
m.OneOfStdTimes = &OneofStdTypes_Duration{c}
return true, err
default:
return false, nil
}
}
func _OneofStdTypes_OneofSizer(msg proto.Message) (n int) {
m := msg.(*OneofStdTypes)
// OneOfStdTimes
switch x := m.OneOfStdTimes.(type) {
case *OneofStdTypes_Timestamp:
s := github_com_gogo_protobuf_types.SizeOfStdTime(*x.Timestamp)
n += proto.SizeVarint(1<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case *OneofStdTypes_Duration:
s := github_com_gogo_protobuf_types.SizeOfStdDuration(*x.Duration)
n += proto.SizeVarint(2<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
func init() {
proto.RegisterType((*StdTypes)(nil), "stdtypes.StdTypes")
proto.RegisterType((*RepStdTypes)(nil), "stdtypes.RepStdTypes")
proto.RegisterType((*MapStdTypes)(nil), "stdtypes.MapStdTypes")
proto.RegisterType((*OneofStdTypes)(nil), "stdtypes.OneofStdTypes")
}
func (this *StdTypes) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*StdTypes)
if !ok {
that2, ok := that.(StdTypes)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *StdTypes")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *StdTypes but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *StdTypes but is not nil && this == nil")
}
if that1.NullableTimestamp == nil {
if this.NullableTimestamp != nil {
return fmt.Errorf("this.NullableTimestamp != nil && that1.NullableTimestamp == nil")
}
} else if !this.NullableTimestamp.Equal(*that1.NullableTimestamp) {
return fmt.Errorf("NullableTimestamp this(%v) Not Equal that(%v)", this.NullableTimestamp, that1.NullableTimestamp)
}
if this.NullableDuration != nil && that1.NullableDuration != nil {
if *this.NullableDuration != *that1.NullableDuration {
return fmt.Errorf("NullableDuration this(%v) Not Equal that(%v)", *this.NullableDuration, *that1.NullableDuration)
}
} else if this.NullableDuration != nil {
return fmt.Errorf("this.NullableDuration == nil && that.NullableDuration != nil")
} else if that1.NullableDuration != nil {
return fmt.Errorf("NullableDuration this(%v) Not Equal that(%v)", this.NullableDuration, that1.NullableDuration)
}
if !this.Timestamp.Equal(that1.Timestamp) {
return fmt.Errorf("Timestamp this(%v) Not Equal that(%v)", this.Timestamp, that1.Timestamp)
}
if this.Duration != that1.Duration {
return fmt.Errorf("Duration this(%v) Not Equal that(%v)", this.Duration, that1.Duration)
}
return nil
}
func (this *StdTypes) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*StdTypes)
if !ok {
that2, ok := that.(StdTypes)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if that1.NullableTimestamp == nil {
if this.NullableTimestamp != nil {
return false
}
} else if !this.NullableTimestamp.Equal(*that1.NullableTimestamp) {
return false
}
if this.NullableDuration != nil && that1.NullableDuration != nil {
if *this.NullableDuration != *that1.NullableDuration {
return false
}
} else if this.NullableDuration != nil {
return false
} else if that1.NullableDuration != nil {
return false
}
if !this.Timestamp.Equal(that1.Timestamp) {
return false
}
if this.Duration != that1.Duration {
return false
}
return true
}
func (this *RepStdTypes) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*RepStdTypes)
if !ok {
that2, ok := that.(RepStdTypes)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *RepStdTypes")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *RepStdTypes but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *RepStdTypes but is not nil && this == nil")
}
if len(this.NullableTimestamps) != len(that1.NullableTimestamps) {
return fmt.Errorf("NullableTimestamps this(%v) Not Equal that(%v)", len(this.NullableTimestamps), len(that1.NullableTimestamps))
}
for i := range this.NullableTimestamps {
if !this.NullableTimestamps[i].Equal(*that1.NullableTimestamps[i]) {
return fmt.Errorf("NullableTimestamps this[%v](%v) Not Equal that[%v](%v)", i, this.NullableTimestamps[i], i, that1.NullableTimestamps[i])
}
}
if len(this.NullableDurations) != len(that1.NullableDurations) {
return fmt.Errorf("NullableDurations this(%v) Not Equal that(%v)", len(this.NullableDurations), len(that1.NullableDurations))
}
for i := range this.NullableDurations {
if dthis, dthat := this.NullableDurations[i], that1.NullableDurations[i]; (dthis != nil && dthat != nil && *dthis != *dthat) || (dthis != nil && dthat == nil) || (dthis == nil && dthat != nil) {
return fmt.Errorf("NullableDurations this[%v](%v) Not Equal that[%v](%v)", i, this.NullableDurations[i], i, that1.NullableDurations[i])
}
}
if len(this.Timestamps) != len(that1.Timestamps) {
return fmt.Errorf("Timestamps this(%v) Not Equal that(%v)", len(this.Timestamps), len(that1.Timestamps))
}
for i := range this.Timestamps {
if !this.Timestamps[i].Equal(that1.Timestamps[i]) {
return fmt.Errorf("Timestamps this[%v](%v) Not Equal that[%v](%v)", i, this.Timestamps[i], i, that1.Timestamps[i])
}
}
if len(this.Durations) != len(that1.Durations) {
return fmt.Errorf("Durations this(%v) Not Equal that(%v)", len(this.Durations), len(that1.Durations))
}
for i := range this.Durations {
if this.Durations[i] != that1.Durations[i] {
return fmt.Errorf("Durations this[%v](%v) Not Equal that[%v](%v)", i, this.Durations[i], i, that1.Durations[i])
}
}
return nil
}
func (this *RepStdTypes) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*RepStdTypes)
if !ok {
that2, ok := that.(RepStdTypes)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if len(this.NullableTimestamps) != len(that1.NullableTimestamps) {
return false
}
for i := range this.NullableTimestamps {
if !this.NullableTimestamps[i].Equal(*that1.NullableTimestamps[i]) {
return false
}
}
if len(this.NullableDurations) != len(that1.NullableDurations) {
return false
}
for i := range this.NullableDurations {
if dthis, dthat := this.NullableDurations[i], that1.NullableDurations[i]; (dthis != nil && dthat != nil && *dthis != *dthat) || (dthis != nil && dthat == nil) || (dthis == nil && dthat != nil) {
return false
}
}
if len(this.Timestamps) != len(that1.Timestamps) {
return false
}
for i := range this.Timestamps {
if !this.Timestamps[i].Equal(that1.Timestamps[i]) {
return false
}
}
if len(this.Durations) != len(that1.Durations) {
return false
}
for i := range this.Durations {
if this.Durations[i] != that1.Durations[i] {
return false
}
}
return true
}
func (this *MapStdTypes) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*MapStdTypes)
if !ok {
that2, ok := that.(MapStdTypes)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *MapStdTypes")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *MapStdTypes but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *MapStdTypes but is not nil && this == nil")
}
if len(this.NullableTimestamp) != len(that1.NullableTimestamp) {
return fmt.Errorf("NullableTimestamp this(%v) Not Equal that(%v)", len(this.NullableTimestamp), len(that1.NullableTimestamp))
}
for i := range this.NullableTimestamp {
if !this.NullableTimestamp[i].Equal(*that1.NullableTimestamp[i]) {
return fmt.Errorf("NullableTimestamp this[%v](%v) Not Equal that[%v](%v)", i, this.NullableTimestamp[i], i, that1.NullableTimestamp[i])
}
}
if len(this.Timestamp) != len(that1.Timestamp) {
return fmt.Errorf("Timestamp this(%v) Not Equal that(%v)", len(this.Timestamp), len(that1.Timestamp))
}
for i := range this.Timestamp {
if !this.Timestamp[i].Equal(that1.Timestamp[i]) {
return fmt.Errorf("Timestamp this[%v](%v) Not Equal that[%v](%v)", i, this.Timestamp[i], i, that1.Timestamp[i])
}
}
if len(this.NullableDuration) != len(that1.NullableDuration) {
return fmt.Errorf("NullableDuration this(%v) Not Equal that(%v)", len(this.NullableDuration), len(that1.NullableDuration))
}
for i := range this.NullableDuration {
if dthis, dthat := this.NullableDuration[i], that1.NullableDuration[i]; (dthis != nil && dthat != nil && *dthis != *dthat) || (dthis != nil && dthat == nil) || (dthis == nil && dthat != nil) {
return fmt.Errorf("NullableDuration this[%v](%v) Not Equal that[%v](%v)", i, this.NullableDuration[i], i, that1.NullableDuration[i])
}
}
if len(this.Duration) != len(that1.Duration) {
return fmt.Errorf("Duration this(%v) Not Equal that(%v)", len(this.Duration), len(that1.Duration))
}
for i := range this.Duration {
if this.Duration[i] != that1.Duration[i] {
return fmt.Errorf("Duration this[%v](%v) Not Equal that[%v](%v)", i, this.Duration[i], i, that1.Duration[i])
}
}
return nil
}
func (this *MapStdTypes) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*MapStdTypes)
if !ok {
that2, ok := that.(MapStdTypes)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if len(this.NullableTimestamp) != len(that1.NullableTimestamp) {
return false
}
for i := range this.NullableTimestamp {
if !this.NullableTimestamp[i].Equal(*that1.NullableTimestamp[i]) {
return false
}
}
if len(this.Timestamp) != len(that1.Timestamp) {
return false
}
for i := range this.Timestamp {
if !this.Timestamp[i].Equal(that1.Timestamp[i]) {
return false
}
}
if len(this.NullableDuration) != len(that1.NullableDuration) {
return false
}
for i := range this.NullableDuration {
if dthis, dthat := this.NullableDuration[i], that1.NullableDuration[i]; (dthis != nil && dthat != nil && *dthis != *dthat) || (dthis != nil && dthat == nil) || (dthis == nil && dthat != nil) {
return false
}
}
if len(this.Duration) != len(that1.Duration) {
return false
}
for i := range this.Duration {
if this.Duration[i] != that1.Duration[i] {
return false
}
}
return true
}
func (this *OneofStdTypes) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*OneofStdTypes)
if !ok {
that2, ok := that.(OneofStdTypes)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *OneofStdTypes")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *OneofStdTypes but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *OneofStdTypes but is not nil && this == nil")
}
if that1.OneOfStdTimes == nil {
if this.OneOfStdTimes != nil {
return fmt.Errorf("this.OneOfStdTimes != nil && that1.OneOfStdTimes == nil")
}
} else if this.OneOfStdTimes == nil {
return fmt.Errorf("this.OneOfStdTimes == nil && that1.OneOfStdTimes != nil")
} else if err := this.OneOfStdTimes.VerboseEqual(that1.OneOfStdTimes); err != nil {
return err
}
return nil
}
func (this *OneofStdTypes_Timestamp) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*OneofStdTypes_Timestamp)
if !ok {
that2, ok := that.(OneofStdTypes_Timestamp)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *OneofStdTypes_Timestamp")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *OneofStdTypes_Timestamp but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *OneofStdTypes_Timestamp but is not nil && this == nil")
}
if that1.Timestamp == nil {
if this.Timestamp != nil {
return fmt.Errorf("this.Timestamp != nil && that1.Timestamp == nil")
}
} else if !this.Timestamp.Equal(*that1.Timestamp) {
return fmt.Errorf("Timestamp this(%v) Not Equal that(%v)", this.Timestamp, that1.Timestamp)
}
return nil
}
func (this *OneofStdTypes_Duration) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*OneofStdTypes_Duration)
if !ok {
that2, ok := that.(OneofStdTypes_Duration)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *OneofStdTypes_Duration")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *OneofStdTypes_Duration but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *OneofStdTypes_Duration but is not nil && this == nil")
}
if this.Duration != nil && that1.Duration != nil {
if *this.Duration != *that1.Duration {
return fmt.Errorf("Duration this(%v) Not Equal that(%v)", *this.Duration, *that1.Duration)
}
} else if this.Duration != nil {
return fmt.Errorf("this.Duration == nil && that.Duration != nil")
} else if that1.Duration != nil {
return fmt.Errorf("Duration this(%v) Not Equal that(%v)", this.Duration, that1.Duration)
}
return nil
}
func (this *OneofStdTypes) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*OneofStdTypes)
if !ok {
that2, ok := that.(OneofStdTypes)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if that1.OneOfStdTimes == nil {
if this.OneOfStdTimes != nil {
return false
}
} else if this.OneOfStdTimes == nil {
return false
} else if !this.OneOfStdTimes.Equal(that1.OneOfStdTimes) {
return false
}
return true
}
func (this *OneofStdTypes_Timestamp) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*OneofStdTypes_Timestamp)
if !ok {
that2, ok := that.(OneofStdTypes_Timestamp)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if that1.Timestamp == nil {
if this.Timestamp != nil {
return false
}
} else if !this.Timestamp.Equal(*that1.Timestamp) {
return false
}
return true
}
func (this *OneofStdTypes_Duration) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*OneofStdTypes_Duration)
if !ok {
that2, ok := that.(OneofStdTypes_Duration)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if this.Duration != nil && that1.Duration != nil {
if *this.Duration != *that1.Duration {
return false
}
} else if this.Duration != nil {
return false
} else if that1.Duration != nil {
return false
}
return true
}
func (this *StdTypes) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 8)
s = append(s, "&stdtypes.StdTypes{")
s = append(s, "NullableTimestamp: "+fmt.Sprintf("%#v", this.NullableTimestamp)+",\n")
s = append(s, "NullableDuration: "+fmt.Sprintf("%#v", this.NullableDuration)+",\n")
s = append(s, "Timestamp: "+fmt.Sprintf("%#v", this.Timestamp)+",\n")
s = append(s, "Duration: "+fmt.Sprintf("%#v", this.Duration)+",\n")
s = append(s, "}")
return strings.Join(s, "")
}
func (this *RepStdTypes) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 8)
s = append(s, "&stdtypes.RepStdTypes{")
s = append(s, "NullableTimestamps: "+fmt.Sprintf("%#v", this.NullableTimestamps)+",\n")
s = append(s, "NullableDurations: "+fmt.Sprintf("%#v", this.NullableDurations)+",\n")
s = append(s, "Timestamps: "+fmt.Sprintf("%#v", this.Timestamps)+",\n")
s = append(s, "Durations: "+fmt.Sprintf("%#v", this.Durations)+",\n")
s = append(s, "}")
return strings.Join(s, "")
}
func (this *MapStdTypes) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 8)
s = append(s, "&stdtypes.MapStdTypes{")
keysForNullableTimestamp := make([]int32, 0, len(this.NullableTimestamp))
for k := range this.NullableTimestamp {
keysForNullableTimestamp = append(keysForNullableTimestamp, k)
}
sortkeys.Int32s(keysForNullableTimestamp)
mapStringForNullableTimestamp := "map[int32]*time.Time{"
for _, k := range keysForNullableTimestamp {
mapStringForNullableTimestamp += fmt.Sprintf("%#v: %#v,", k, this.NullableTimestamp[k])
}
mapStringForNullableTimestamp += "}"
if this.NullableTimestamp != nil {
s = append(s, "NullableTimestamp: "+mapStringForNullableTimestamp+",\n")
}
keysForTimestamp := make([]int32, 0, len(this.Timestamp))
for k := range this.Timestamp {
keysForTimestamp = append(keysForTimestamp, k)
}
sortkeys.Int32s(keysForTimestamp)
mapStringForTimestamp := "map[int32]time.Time{"
for _, k := range keysForTimestamp {
mapStringForTimestamp += fmt.Sprintf("%#v: %#v,", k, this.Timestamp[k])
}
mapStringForTimestamp += "}"
if this.Timestamp != nil {
s = append(s, "Timestamp: "+mapStringForTimestamp+",\n")
}
keysForNullableDuration := make([]int32, 0, len(this.NullableDuration))
for k := range this.NullableDuration {
keysForNullableDuration = append(keysForNullableDuration, k)
}
sortkeys.Int32s(keysForNullableDuration)
mapStringForNullableDuration := "map[int32]*time.Duration{"
for _, k := range keysForNullableDuration {
mapStringForNullableDuration += fmt.Sprintf("%#v: %#v,", k, this.NullableDuration[k])
}
mapStringForNullableDuration += "}"
if this.NullableDuration != nil {
s = append(s, "NullableDuration: "+mapStringForNullableDuration+",\n")
}
keysForDuration := make([]int32, 0, len(this.Duration))
for k := range this.Duration {
keysForDuration = append(keysForDuration, k)
}
sortkeys.Int32s(keysForDuration)
mapStringForDuration := "map[int32]time.Duration{"
for _, k := range keysForDuration {
mapStringForDuration += fmt.Sprintf("%#v: %#v,", k, this.Duration[k])
}
mapStringForDuration += "}"
if this.Duration != nil {
s = append(s, "Duration: "+mapStringForDuration+",\n")
}
s = append(s, "}")
return strings.Join(s, "")
}
func (this *OneofStdTypes) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 6)
s = append(s, "&stdtypes.OneofStdTypes{")
if this.OneOfStdTimes != nil {
s = append(s, "OneOfStdTimes: "+fmt.Sprintf("%#v", this.OneOfStdTimes)+",\n")
}
s = append(s, "}")
return strings.Join(s, "")
}
func (this *OneofStdTypes_Timestamp) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&stdtypes.OneofStdTypes_Timestamp{` +
`Timestamp:` + fmt.Sprintf("%#v", this.Timestamp) + `}`}, ", ")
return s
}
func (this *OneofStdTypes_Duration) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&stdtypes.OneofStdTypes_Duration{` +
`Duration:` + fmt.Sprintf("%#v", this.Duration) + `}`}, ", ")
return s
}
func valueToGoStringStdtypes(v interface{}, typ string) string {
rv := reflect.ValueOf(v)
if rv.IsNil() {
return "nil"
}
pv := reflect.Indirect(rv).Interface()
return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
}
func NewPopulatedStdTypes(r randyStdtypes, easy bool) *StdTypes {
this := &StdTypes{}
if r.Intn(10) != 0 {
this.NullableTimestamp = types.NewPopulatedStdTime(r, easy)
}
if r.Intn(10) != 0 {
this.NullableDuration = types.NewPopulatedStdDuration(r, easy)
}
v1 := types.NewPopulatedStdTime(r, easy)
this.Timestamp = *v1
v2 := types.NewPopulatedStdDuration(r, easy)
this.Duration = *v2
if !easy && r.Intn(10) != 0 {
}
return this
}
func NewPopulatedRepStdTypes(r randyStdtypes, easy bool) *RepStdTypes {
this := &RepStdTypes{}
if r.Intn(10) != 0 {
v3 := r.Intn(5)
this.NullableTimestamps = make([]*time.Time, v3)
for i := 0; i < v3; i++ {
this.NullableTimestamps[i] = types.NewPopulatedStdTime(r, easy)
}
}
if r.Intn(10) != 0 {
v4 := r.Intn(5)
this.NullableDurations = make([]*time.Duration, v4)
for i := 0; i < v4; i++ {
this.NullableDurations[i] = types.NewPopulatedStdDuration(r, easy)
}
}
if r.Intn(10) != 0 {
v5 := r.Intn(5)
this.Timestamps = make([]time.Time, v5)
for i := 0; i < v5; i++ {
v6 := types.NewPopulatedStdTime(r, easy)
this.Timestamps[i] = *v6
}
}
if r.Intn(10) != 0 {
v7 := r.Intn(5)
this.Durations = make([]time.Duration, v7)
for i := 0; i < v7; i++ {
v8 := types.NewPopulatedStdDuration(r, easy)
this.Durations[i] = *v8
}
}
if !easy && r.Intn(10) != 0 {
}
return this
}
func NewPopulatedMapStdTypes(r randyStdtypes, easy bool) *MapStdTypes {
this := &MapStdTypes{}
if r.Intn(10) != 0 {
v9 := r.Intn(10)
this.NullableTimestamp = make(map[int32]*time.Time)
for i := 0; i < v9; i++ {
this.NullableTimestamp[int32(r.Int31())] = types.NewPopulatedStdTime(r, easy)
}
}
if r.Intn(10) != 0 {
v10 := r.Intn(10)
this.Timestamp = make(map[int32]time.Time)
for i := 0; i < v10; i++ {
this.Timestamp[int32(r.Int31())] = *types.NewPopulatedStdTime(r, easy)
}
}
if r.Intn(10) != 0 {
v11 := r.Intn(10)
this.NullableDuration = make(map[int32]*time.Duration)
for i := 0; i < v11; i++ {
this.NullableDuration[int32(r.Int31())] = types.NewPopulatedStdDuration(r, easy)
}
}
if r.Intn(10) != 0 {
v12 := r.Intn(10)
this.Duration = make(map[int32]time.Duration)
for i := 0; i < v12; i++ {
this.Duration[int32(r.Int31())] = *types.NewPopulatedStdDuration(r, easy)
}
}
if !easy && r.Intn(10) != 0 {
}
return this
}
func NewPopulatedOneofStdTypes(r randyStdtypes, easy bool) *OneofStdTypes {
this := &OneofStdTypes{}
oneofNumber_OneOfStdTimes := []int32{1, 2}[r.Intn(2)]
switch oneofNumber_OneOfStdTimes {
case 1:
this.OneOfStdTimes = NewPopulatedOneofStdTypes_Timestamp(r, easy)
case 2:
this.OneOfStdTimes = NewPopulatedOneofStdTypes_Duration(r, easy)
}
if !easy && r.Intn(10) != 0 {
}
return this
}
func NewPopulatedOneofStdTypes_Timestamp(r randyStdtypes, easy bool) *OneofStdTypes_Timestamp {
this := &OneofStdTypes_Timestamp{}
this.Timestamp = types.NewPopulatedStdTime(r, easy)
return this
}
func NewPopulatedOneofStdTypes_Duration(r randyStdtypes, easy bool) *OneofStdTypes_Duration {
this := &OneofStdTypes_Duration{}
this.Duration = types.NewPopulatedStdDuration(r, easy)
return this
}
type randyStdtypes interface {
Float32() float32
Float64() float64
Int63() int64
Int31() int32
Uint32() uint32
Intn(n int) int
}
func randUTF8RuneStdtypes(r randyStdtypes) rune {
ru := r.Intn(62)
if ru < 10 {
return rune(ru + 48)
} else if ru < 36 {
return rune(ru + 55)
}
return rune(ru + 61)
}
func randStringStdtypes(r randyStdtypes) string {
v13 := r.Intn(100)
tmps := make([]rune, v13)
for i := 0; i < v13; i++ {
tmps[i] = randUTF8RuneStdtypes(r)
}
return string(tmps)
}
func randUnrecognizedStdtypes(r randyStdtypes, maxFieldNumber int) (dAtA []byte) {
l := r.Intn(5)
for i := 0; i < l; i++ {
wire := r.Intn(4)
if wire == 3 {
wire = 5
}
fieldNumber := maxFieldNumber + r.Intn(100)
dAtA = randFieldStdtypes(dAtA, r, fieldNumber, wire)
}
return dAtA
}
func randFieldStdtypes(dAtA []byte, r randyStdtypes, fieldNumber int, wire int) []byte {
key := uint32(fieldNumber)<<3 | uint32(wire)
switch wire {
case 0:
dAtA = encodeVarintPopulateStdtypes(dAtA, uint64(key))
v14 := r.Int63()
if r.Intn(2) == 0 {
v14 *= -1
}
dAtA = encodeVarintPopulateStdtypes(dAtA, uint64(v14))
case 1:
dAtA = encodeVarintPopulateStdtypes(dAtA, uint64(key))
dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
case 2:
dAtA = encodeVarintPopulateStdtypes(dAtA, uint64(key))
ll := r.Intn(100)
dAtA = encodeVarintPopulateStdtypes(dAtA, uint64(ll))
for j := 0; j < ll; j++ {
dAtA = append(dAtA, byte(r.Intn(256)))
}
default:
dAtA = encodeVarintPopulateStdtypes(dAtA, uint64(key))
dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
}
return dAtA
}
func encodeVarintPopulateStdtypes(dAtA []byte, v uint64) []byte {
for v >= 1<<7 {
dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80))
v >>= 7
}
dAtA = append(dAtA, uint8(v))
return dAtA
}
func (m *StdTypes) Size() (n int) {
var l int
_ = l
if m.NullableTimestamp != nil {
l = types.SizeOfStdTime(*m.NullableTimestamp)
n += 1 + l + sovStdtypes(uint64(l))
}
if m.NullableDuration != nil {
l = types.SizeOfStdDuration(*m.NullableDuration)
n += 1 + l + sovStdtypes(uint64(l))
}
l = types.SizeOfStdTime(m.Timestamp)
n += 1 + l + sovStdtypes(uint64(l))
l = types.SizeOfStdDuration(m.Duration)
n += 1 + l + sovStdtypes(uint64(l))
return n
}
func (m *RepStdTypes) Size() (n int) {
var l int
_ = l
if len(m.NullableTimestamps) > 0 {
for _, e := range m.NullableTimestamps {
l = types.SizeOfStdTime(*e)
n += 1 + l + sovStdtypes(uint64(l))
}
}
if len(m.NullableDurations) > 0 {
for _, e := range m.NullableDurations {
l = types.SizeOfStdDuration(*e)
n += 1 + l + sovStdtypes(uint64(l))
}
}
if len(m.Timestamps) > 0 {
for _, e := range m.Timestamps {
l = types.SizeOfStdTime(e)
n += 1 + l + sovStdtypes(uint64(l))
}
}
if len(m.Durations) > 0 {
for _, e := range m.Durations {
l = types.SizeOfStdDuration(e)
n += 1 + l + sovStdtypes(uint64(l))
}
}
return n
}
func (m *MapStdTypes) Size() (n int) {
var l int
_ = l
if len(m.NullableTimestamp) > 0 {
for k, v := range m.NullableTimestamp {
_ = k
_ = v
l = 0
if v != nil {
l = types.SizeOfStdTime(*v)
l += 1 + sovStdtypes(uint64(l))
}
mapEntrySize := 1 + sovStdtypes(uint64(k)) + l
n += mapEntrySize + 1 + sovStdtypes(uint64(mapEntrySize))
}
}
if len(m.Timestamp) > 0 {
for k, v := range m.Timestamp {
_ = k
_ = v
l = types.SizeOfStdTime(v)
mapEntrySize := 1 + sovStdtypes(uint64(k)) + 1 + l + sovStdtypes(uint64(l))
n += mapEntrySize + 1 + sovStdtypes(uint64(mapEntrySize))
}
}
if len(m.NullableDuration) > 0 {
for k, v := range m.NullableDuration {
_ = k
_ = v
l = 0
if v != nil {
l = types.SizeOfStdDuration(*v)
l += 1 + sovStdtypes(uint64(l))
}
mapEntrySize := 1 + sovStdtypes(uint64(k)) + l
n += mapEntrySize + 1 + sovStdtypes(uint64(mapEntrySize))
}
}
if len(m.Duration) > 0 {
for k, v := range m.Duration {
_ = k
_ = v
l = types.SizeOfStdDuration(v)
mapEntrySize := 1 + sovStdtypes(uint64(k)) + 1 + l + sovStdtypes(uint64(l))
n += mapEntrySize + 1 + sovStdtypes(uint64(mapEntrySize))
}
}
return n
}
func (m *OneofStdTypes) Size() (n int) {
var l int
_ = l
if m.OneOfStdTimes != nil {
n += m.OneOfStdTimes.Size()
}
return n
}
func (m *OneofStdTypes_Timestamp) Size() (n int) {
var l int
_ = l
if m.Timestamp != nil {
l = types.SizeOfStdTime(*m.Timestamp)
n += 1 + l + sovStdtypes(uint64(l))
}
return n
}
func (m *OneofStdTypes_Duration) Size() (n int) {
var l int
_ = l
if m.Duration != nil {
l = types.SizeOfStdDuration(*m.Duration)
n += 1 + l + sovStdtypes(uint64(l))
}
return n
}
func sovStdtypes(x uint64) (n int) {
for {
n++
x >>= 7
if x == 0 {
break
}
}
return n
}
func sozStdtypes(x uint64) (n int) {
return sovStdtypes(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func init() { proto.RegisterFile("stdtypes.proto", fileDescriptorStdtypes) }
var fileDescriptorStdtypes = []byte{
// 540 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x94, 0x31, 0x6f, 0xd3, 0x40,
0x1c, 0xc5, 0x7d, 0x4e, 0x82, 0xd2, 0x7f, 0xd4, 0x52, 0x4e, 0x02, 0x19, 0x0f, 0x97, 0x2a, 0x30,
0x20, 0x51, 0x1c, 0x04, 0x0b, 0x42, 0x42, 0x80, 0x55, 0xa4, 0x22, 0x68, 0x8b, 0x42, 0x85, 0x58,
0x40, 0x75, 0x88, 0x6b, 0x22, 0x9c, 0x5c, 0x14, 0x9f, 0x91, 0xb2, 0xf1, 0x11, 0x18, 0x59, 0xd9,
0x18, 0xd8, 0x61, 0x64, 0xec, 0xc8, 0x8e, 0x04, 0x8d, 0xf9, 0x02, 0x8c, 0x1d, 0x91, 0xcf, 0x3e,
0x9f, 0x13, 0x5f, 0xea, 0x2c, 0xdd, 0x7c, 0xf1, 0xff, 0xfd, 0xee, 0xe5, 0xf9, 0xdd, 0xc1, 0x5a,
0xc0, 0x7a, 0x6c, 0x32, 0x72, 0x03, 0x6b, 0x34, 0xa6, 0x8c, 0xe2, 0xba, 0x58, 0x9b, 0x37, 0xbc,
0x3e, 0x7b, 0x1b, 0x76, 0xad, 0x37, 0x74, 0xd0, 0xf6, 0xa8, 0x47, 0xdb, 0x7c, 0xa0, 0x1b, 0x1e,
0xf2, 0x15, 0x5f, 0xf0, 0xa7, 0x44, 0x68, 0x12, 0x8f, 0x52, 0xcf, 0x77, 0xe5, 0x54, 0x2f, 0x1c,
0x3b, 0xac, 0x4f, 0x87, 0xe9, 0xfb, 0xe6, 0xfc, 0x7b, 0xd6, 0x1f, 0xb8, 0x01, 0x73, 0x06, 0xa3,
0x64, 0xa0, 0xf5, 0x55, 0x87, 0xfa, 0x73, 0xd6, 0xdb, 0x8f, 0x37, 0xc7, 0xbb, 0x70, 0x61, 0x18,
0xfa, 0xbe, 0xd3, 0xf5, 0xdd, 0x7d, 0x31, 0x67, 0xa0, 0x0d, 0x74, 0xad, 0x71, 0xcb, 0xb4, 0x12,
0x92, 0x25, 0x48, 0x56, 0x36, 0x61, 0x57, 0x3f, 0xfe, 0x69, 0xa2, 0x4e, 0x51, 0x8a, 0x9f, 0xc0,
0xba, 0xf8, 0x71, 0x2b, 0xf5, 0x65, 0xe8, 0x1c, 0x77, 0xb9, 0x80, 0x13, 0x03, 0x76, 0xf5, 0x53,
0x4c, 0x2b, 0x08, 0xb1, 0x0d, 0x2b, 0x99, 0x79, 0xa3, 0x52, 0x6a, 0xaa, 0x7e, 0xf4, 0xbb, 0xa9,
0x71, 0x63, 0x52, 0x86, 0xef, 0x43, 0x5d, 0x04, 0x64, 0x54, 0xcb, 0x8c, 0x70, 0x02, 0x37, 0x93,
0x89, 0x5a, 0xdf, 0x74, 0x68, 0x74, 0xdc, 0x51, 0x96, 0xd8, 0x33, 0xc0, 0x85, 0xbf, 0x1d, 0x18,
0x68, 0xa3, 0xb2, 0x54, 0x64, 0x0a, 0x2d, 0xde, 0x91, 0xdf, 0x40, 0x38, 0x09, 0x0c, 0x9d, 0x03,
0x4b, 0x43, 0x2b, 0x2a, 0xf1, 0x16, 0x00, 0x93, 0xc6, 0x2a, 0xa5, 0xc6, 0x64, 0x6c, 0x39, 0x1d,
0x7e, 0x08, 0x2b, 0xbd, 0xcc, 0x4c, 0xb5, 0xcc, 0x8c, 0x0c, 0x4e, 0xaa, 0x5a, 0xbf, 0x6a, 0xd0,
0xd8, 0x71, 0x64, 0x72, 0x07, 0xea, 0xae, 0xc5, 0xe8, 0x4d, 0x2b, 0x3b, 0x1e, 0x39, 0x85, 0xb5,
0x3b, 0x3f, 0xfe, 0x68, 0xc8, 0xc6, 0x93, 0xc5, 0xed, 0x7b, 0x9a, 0x2f, 0x4c, 0x92, 0xe0, 0x55,
0x35, 0x79, 0x8e, 0xa8, 0xac, 0xce, 0x2b, 0x45, 0x97, 0x93, 0x38, 0xaf, 0x9f, 0x6e, 0x57, 0x4c,
0xa7, 0x6e, 0x17, 0xb4, 0xfb, 0xf1, 0x4c, 0x33, 0x63, 0xec, 0x15, 0x35, 0x76, 0x16, 0xa7, 0xe8,
0xa8, 0x79, 0x00, 0x97, 0xd4, 0x51, 0xe1, 0x75, 0xa8, 0xbc, 0x73, 0x27, 0xfc, 0x44, 0xd7, 0x3a,
0xf1, 0x23, 0xbe, 0x09, 0xb5, 0xf7, 0x8e, 0x1f, 0xba, 0xe9, 0xb1, 0x3c, 0xa5, 0x19, 0x9d, 0x64,
0xf0, 0xae, 0x7e, 0x07, 0x99, 0x2f, 0x61, 0xed, 0x8c, 0xc8, 0xaf, 0xe1, 0xa2, 0x32, 0x37, 0xc5,
0x06, 0xed, 0xd9, 0x0d, 0x16, 0xf7, 0x31, 0xcf, 0x7f, 0x01, 0xab, 0x67, 0xc1, 0x6d, 0x7d, 0x46,
0xb0, 0xba, 0x37, 0x74, 0xe9, 0x61, 0xd6, 0xef, 0x07, 0xf9, 0xf6, 0x2d, 0x79, 0x87, 0x6e, 0x6b,
0xf9, 0xc6, 0xdd, 0xcb, 0x55, 0x62, 0xb9, 0x5b, 0x73, 0x5b, 0x93, 0x35, 0xb0, 0xcf, 0x73, 0x47,
0x7b, 0xdc, 0x51, 0xcc, 0xb4, 0x37, 0x8f, 0xa7, 0x04, 0xfd, 0x9b, 0x12, 0x74, 0x32, 0x25, 0xe8,
0x4b, 0x44, 0xd0, 0xf7, 0x88, 0xa0, 0x1f, 0x11, 0x41, 0x47, 0x11, 0xd1, 0x7e, 0x46, 0x44, 0x3b,
0x8e, 0x08, 0x3a, 0x89, 0x88, 0xf6, 0xe1, 0x2f, 0xd1, 0xba, 0xe7, 0xf8, 0x1e, 0xb7, 0xff, 0x07,
0x00, 0x00, 0xff, 0xff, 0x00, 0x68, 0x05, 0x4b, 0xab, 0x06, 0x00, 0x00,
}
| apache-2.0 |
rbaindourov/v8-inspector | Source/chrome/v8/src/zone.cc | 8505 | // Copyright 2012 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.
#include "src/zone.h"
#include <cstring>
#include "src/v8.h"
#ifdef V8_USE_ADDRESS_SANITIZER
#include <sanitizer/asan_interface.h>
#endif // V8_USE_ADDRESS_SANITIZER
namespace v8 {
namespace internal {
namespace {
#if V8_USE_ADDRESS_SANITIZER
const size_t kASanRedzoneBytes = 24; // Must be a multiple of 8.
#else
#define ASAN_POISON_MEMORY_REGION(start, size) \
do { \
USE(start); \
USE(size); \
} while (false)
#define ASAN_UNPOISON_MEMORY_REGION(start, size) \
do { \
USE(start); \
USE(size); \
} while (false)
const size_t kASanRedzoneBytes = 0;
#endif // V8_USE_ADDRESS_SANITIZER
} // namespace
// Segments represent chunks of memory: They have starting address
// (encoded in the this pointer) and a size in bytes. Segments are
// chained together forming a LIFO structure with the newest segment
// available as segment_head_. Segments are allocated using malloc()
// and de-allocated using free().
class Segment {
public:
void Initialize(Segment* next, size_t size) {
next_ = next;
size_ = size;
}
Segment* next() const { return next_; }
void clear_next() { next_ = nullptr; }
size_t size() const { return size_; }
size_t capacity() const { return size_ - sizeof(Segment); }
Address start() const { return address(sizeof(Segment)); }
Address end() const { return address(size_); }
private:
// Computes the address of the nth byte in this segment.
Address address(size_t n) const { return Address(this) + n; }
Segment* next_;
size_t size_;
};
Zone::Zone()
: allocation_size_(0),
segment_bytes_allocated_(0),
position_(0),
limit_(0),
segment_head_(nullptr) {}
Zone::~Zone() {
DeleteAll();
DeleteKeptSegment();
DCHECK(segment_bytes_allocated_ == 0);
}
void* Zone::New(size_t size) {
// Round up the requested size to fit the alignment.
size = RoundUp(size, kAlignment);
// If the allocation size is divisible by 8 then we return an 8-byte aligned
// address.
if (kPointerSize == 4 && kAlignment == 4) {
position_ += ((~size) & 4) & (reinterpret_cast<intptr_t>(position_) & 4);
} else {
DCHECK(kAlignment >= kPointerSize);
}
// Check if the requested size is available without expanding.
Address result = position_;
const size_t size_with_redzone = size + kASanRedzoneBytes;
if (limit_ < position_ + size_with_redzone) {
result = NewExpand(size_with_redzone);
} else {
position_ += size_with_redzone;
}
Address redzone_position = result + size;
DCHECK(redzone_position + kASanRedzoneBytes == position_);
ASAN_POISON_MEMORY_REGION(redzone_position, kASanRedzoneBytes);
// Check that the result has the proper alignment and return it.
DCHECK(IsAddressAligned(result, kAlignment, 0));
allocation_size_ += size;
return reinterpret_cast<void*>(result);
}
void Zone::DeleteAll() {
#ifdef DEBUG
// Constant byte value used for zapping dead memory in debug mode.
static const unsigned char kZapDeadByte = 0xcd;
#endif
// Find a segment with a suitable size to keep around.
Segment* keep = nullptr;
// Traverse the chained list of segments, zapping (in debug mode)
// and freeing every segment except the one we wish to keep.
for (Segment* current = segment_head_; current;) {
Segment* next = current->next();
if (!keep && current->size() <= kMaximumKeptSegmentSize) {
// Unlink the segment we wish to keep from the list.
keep = current;
keep->clear_next();
} else {
size_t size = current->size();
#ifdef DEBUG
// Un-poison first so the zapping doesn't trigger ASan complaints.
ASAN_UNPOISON_MEMORY_REGION(current, size);
// Zap the entire current segment (including the header).
memset(current, kZapDeadByte, size);
#endif
DeleteSegment(current, size);
}
current = next;
}
// If we have found a segment we want to keep, we must recompute the
// variables 'position' and 'limit' to prepare for future allocate
// attempts. Otherwise, we must clear the position and limit to
// force a new segment to be allocated on demand.
if (keep) {
Address start = keep->start();
position_ = RoundUp(start, kAlignment);
limit_ = keep->end();
// Un-poison so we can re-use the segment later.
ASAN_UNPOISON_MEMORY_REGION(start, keep->capacity());
#ifdef DEBUG
// Zap the contents of the kept segment (but not the header).
memset(start, kZapDeadByte, keep->capacity());
#endif
} else {
position_ = limit_ = 0;
}
allocation_size_ = 0;
// Update the head segment to be the kept segment (if any).
segment_head_ = keep;
}
void Zone::DeleteKeptSegment() {
#ifdef DEBUG
// Constant byte value used for zapping dead memory in debug mode.
static const unsigned char kZapDeadByte = 0xcd;
#endif
DCHECK(segment_head_ == nullptr || segment_head_->next() == nullptr);
if (segment_head_ != nullptr) {
size_t size = segment_head_->size();
#ifdef DEBUG
// Un-poison first so the zapping doesn't trigger ASan complaints.
ASAN_UNPOISON_MEMORY_REGION(segment_head_, size);
// Zap the entire kept segment (including the header).
memset(segment_head_, kZapDeadByte, size);
#endif
DeleteSegment(segment_head_, size);
segment_head_ = nullptr;
}
DCHECK(segment_bytes_allocated_ == 0);
}
// Creates a new segment, sets it size, and pushes it to the front
// of the segment chain. Returns the new segment.
Segment* Zone::NewSegment(size_t size) {
Segment* result = reinterpret_cast<Segment*>(Malloced::New(size));
segment_bytes_allocated_ += size;
if (result != nullptr) {
result->Initialize(segment_head_, size);
segment_head_ = result;
}
return result;
}
// Deletes the given segment. Does not touch the segment chain.
void Zone::DeleteSegment(Segment* segment, size_t size) {
segment_bytes_allocated_ -= size;
Malloced::Delete(segment);
}
Address Zone::NewExpand(size_t size) {
// Make sure the requested size is already properly aligned and that
// there isn't enough room in the Zone to satisfy the request.
DCHECK_EQ(size, RoundDown(size, kAlignment));
DCHECK_LT(limit_, position_ + size);
// Compute the new segment size. We use a 'high water mark'
// strategy, where we increase the segment size every time we expand
// except that we employ a maximum segment size when we delete. This
// is to avoid excessive malloc() and free() overhead.
Segment* head = segment_head_;
const size_t old_size = (head == nullptr) ? 0 : head->size();
static const size_t kSegmentOverhead = sizeof(Segment) + kAlignment;
const size_t new_size_no_overhead = size + (old_size << 1);
size_t new_size = kSegmentOverhead + new_size_no_overhead;
const size_t min_new_size = kSegmentOverhead + size;
// Guard against integer overflow.
if (new_size_no_overhead < size || new_size < kSegmentOverhead) {
V8::FatalProcessOutOfMemory("Zone");
return nullptr;
}
if (new_size < kMinimumSegmentSize) {
new_size = kMinimumSegmentSize;
} else if (new_size > kMaximumSegmentSize) {
// Limit the size of new segments to avoid growing the segment size
// exponentially, thus putting pressure on contiguous virtual address space.
// All the while making sure to allocate a segment large enough to hold the
// requested size.
new_size = Max(min_new_size, kMaximumSegmentSize);
}
if (new_size > INT_MAX) {
V8::FatalProcessOutOfMemory("Zone");
return nullptr;
}
Segment* segment = NewSegment(new_size);
if (segment == nullptr) {
V8::FatalProcessOutOfMemory("Zone");
return nullptr;
}
// Recompute 'top' and 'limit' based on the new segment.
Address result = RoundUp(segment->start(), kAlignment);
position_ = result + size;
// Check for address overflow.
// (Should not happen since the segment is guaranteed to accomodate
// size bytes + header and alignment padding)
DCHECK(reinterpret_cast<uintptr_t>(position_) >=
reinterpret_cast<uintptr_t>(result));
limit_ = segment->end();
DCHECK(position_ <= limit_);
return result;
}
} // namespace internal
} // namespace v8
| bsd-3-clause |
pombredanne/algos-urv | media/documentjs/distance.js | 1065 | steal.then(function() {
// the distance between 2 strings
DocumentJS.distance = function( s1, s2 ) {
if ( s1 == s2 ) {
return 0;
}
var s1_len = s1.length,
s2_len = s2.length;
if ( s1_len === 0 ) {
return s2_len;
}
if ( s2_len === 0 ) {
return s1_len;
}
s1 = s1.split('');
s2 = s2.split('');
var v0 = new Array(s1_len + 1),
v1 = new Array(s1_len + 1),
s1_idx = 0,
s2_idx = 0,
cost = 0;
for ( s1_idx = 0; s1_idx < s1_len + 1; s1_idx++ ) {
v0[s1_idx] = s1_idx;
}
var char_s1 = '',
char_s2 = '';
for ( s2_idx = 1; s2_idx <= s2_len; s2_idx++ ) {
v1[0] = s2_idx;
char_s2 = s2[s2_idx - 1];
for ( s1_idx = 0; s1_idx < s1_len; s1_idx++ ) {
char_s1 = s1[s1_idx];
cost = (char_s1 == char_s2) ? 0 : 1;
var m_min = v0[s1_idx + 1] + 1;
var b = v1[s1_idx] + 1;
var c = v0[s1_idx] + cost;
if ( b < m_min ) {
m_min = b;
}
if ( c < m_min ) {
m_min = c;
}
v1[s1_idx + 1] = m_min;
}
var v_tmp = v0;
v0 = v1;
v1 = v_tmp;
}
return v0[s1_len];
}
}) | bsd-3-clause |
LeaYeh/cdnjs | ajax/libs/dojo/1.7.5/dnd/Target.js.uncompressed.js | 449 | define("dojo/dnd/Target", [ "./Source" ], function(Source){
/*===== Source = dojo.dnd.Source =====*/
return dojo.declare("dojo.dnd.Target", Source, {
// summary: a Target object, which can be used as a DnD target
constructor: function(node, params){
// summary:
// a constructor of the Target --- see the `dojo.dnd.Source.constructor` for details
this.isSource = false;
dojo.removeClass(this.node, "dojoDndSource");
}
});
});
| mit |
MTASZTAKI/ApertusVR | core/sceneManager/network/3rdParty/raknet/Source/VariableListDeltaTracker.cpp | 1488 | /*
* Copyright (c) 2014, Oculus VR, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "VariableListDeltaTracker.h"
using namespace RakNet;
VariableListDeltaTracker::VariableListDeltaTracker() {nextWriteIndex=0;}
VariableListDeltaTracker::~VariableListDeltaTracker()
{
unsigned int i;
for (i=0; i < variableList.Size(); i++)
rakFree_Ex(variableList[i].lastData,_FILE_AND_LINE_);
}
// Call before using a series of WriteVar
void VariableListDeltaTracker::StartWrite(void) {nextWriteIndex=0;}
void VariableListDeltaTracker::FlagDirtyFromBitArray(unsigned char *bArray)
{
unsigned short readOffset=0;
for (readOffset=0; readOffset < variableList.Size(); readOffset++)
{
bool result = ( bArray[ readOffset >> 3 ] & ( 0x80 >> ( readOffset & 7 ) ) ) !=0;
if (result==true)
variableList[readOffset].isDirty=true;
}
}
VariableListDeltaTracker::VariableLastValueNode::VariableLastValueNode()
{
lastData=0;
}
VariableListDeltaTracker::VariableLastValueNode::VariableLastValueNode(const unsigned char *data, int _byteLength)
{
lastData=(char*) rakMalloc_Ex(_byteLength,_FILE_AND_LINE_);
memcpy(lastData,data,_byteLength);
byteLength=_byteLength;
isDirty=false;
}
VariableListDeltaTracker::VariableLastValueNode::~VariableLastValueNode()
{
}
| mit |
Hack4Eugene/Hack4Cause2016 | src/cosmodojo/files/sites/all/modules/contrib/civicrm/api/v3/examples/Setting/GetDefaults.php | 2047 | <?php
/**
* Test Generated example demonstrating the Setting.getdefaults API.
*
* Gets defaults setting a variable for a given domain - if no domain is set current is assumed.
*
* @return array
* API result array
*/
function setting_getdefaults_example() {
$params = array(
'name' => 'address_format',
);
try{
$result = civicrm_api3('Setting', 'getdefaults', $params);
}
catch (CiviCRM_API3_Exception $e) {
// Handle error here.
$errorMessage = $e->getMessage();
$errorCode = $e->getErrorCode();
$errorData = $e->getExtraParams();
return array(
'error' => $errorMessage,
'error_code' => $errorCode,
'error_data' => $errorData,
);
}
return $result;
}
/**
* Function returns array of result expected from previous function.
*
* @return array
* API result array
*/
function setting_getdefaults_expectedresult() {
$expectedResult = array(
'is_error' => 0,
'version' => 3,
'count' => 1,
'id' => 1,
'values' => array(
'1' => array(
'address_format' => '{contact.address_name}
{contact.street_address}
{contact.supplemental_address_1}
{contact.supplemental_address_2}
{contact.city}{, }{contact.state_province}{ }{contact.postal_code}
{contact.country}',
),
),
);
return $expectedResult;
}
/*
* This example has been generated from the API test suite.
* The test that created it is called "testGetDefaults"
* and can be found at:
* https://github.com/civicrm/civicrm-core/blob/master/tests/phpunit/api/v3/SettingTest.php
*
* You can see the outcome of the API tests at
* https://test.civicrm.org/job/CiviCRM-master-git/
*
* To Learn about the API read
* http://wiki.civicrm.org/confluence/display/CRMDOC/Using+the+API
*
* Browse the api on your own site with the api explorer
* http://MYSITE.ORG/path/to/civicrm/api
*
* Read more about testing here
* http://wiki.civicrm.org/confluence/display/CRM/Testing
*
* API Standards documentation:
* http://wiki.civicrm.org/confluence/display/CRM/API+Architecture+Standards
*/
| mit |
PX4/uavcan | libuavcan/test/util/lazy_constructor.cpp | 1197 | /*
* Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
*/
#include <gtest/gtest.h>
#include <uavcan/util/lazy_constructor.hpp>
TEST(LazyConstructor, Basic)
{
using ::uavcan::LazyConstructor;
LazyConstructor<std::string> a;
LazyConstructor<std::string> b;
ASSERT_FALSE(a);
ASSERT_FALSE(b.isConstructed());
/*
* Construction
*/
a.destroy(); // no-op
a.construct();
b.construct<const char*>("Hello world");
ASSERT_TRUE(a);
ASSERT_TRUE(b.isConstructed());
ASSERT_NE(*a, *b);
ASSERT_STRNE(a->c_str(), b->c_str());
ASSERT_EQ(*a, "");
ASSERT_EQ(*b, "Hello world");
/*
* Copying
*/
a = b; // Assignment operator performs destruction and immediate copy construction
ASSERT_EQ(*a, *b);
ASSERT_EQ(*a, "Hello world");
LazyConstructor<std::string> c(a); // Copy constructor call is forwarded to std::string
ASSERT_EQ(*c, *a);
*a = "123";
ASSERT_NE(*c, *a);
ASSERT_EQ(*c, *b);
*c = "456";
ASSERT_NE(*a, *c);
ASSERT_NE(*b, *a);
ASSERT_NE(*c, *b);
/*
* Destruction
*/
ASSERT_TRUE(c);
c.destroy();
ASSERT_FALSE(c);
}
| mit |
joeyparrish/cdnjs | ajax/libs/highcharts/7.0.0/es-modules/masters/modules/sankey.src.js | 229 | /**
* @license @product.name@ JS v@product.version@ (@product.date@)
* Sankey diagram module
*
* (c) 2010-2018 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../modules/sankey.src.js';
| mit |
markogresak/DefinitelyTyped | types/carbon__icons-react/lib/watson-health/cut-in-half/24.d.ts | 88 | import { WatsonHealthCutInHalf24 } from "../../../";
export = WatsonHealthCutInHalf24;
| mit |
markogresak/DefinitelyTyped | types/carbon__icons-react/lib/checkmark--filled--warning/16.d.ts | 87 | import { CheckmarkFilledWarning16 } from "../../";
export = CheckmarkFilledWarning16;
| mit |
bluekylin/cocos2d-js | samples/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.js | 12506 | /****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
var ControlButtonTest_HelloVariableSize = ControlScene.extend({
init:function () {
if (this._super()) {
var screenSize = cc.director.getWinSize();
// Defines an array of title to create buttons dynamically
var stringArray = ["Hello", "Variable", "Size", "!"];
var layer = new cc.Node();
this.addChild(layer, 1);
var total_width = 0, height = 0;
// For each title in the array
for (var i = 0; i < stringArray.length; i++) {
var button = this.standardButtonWithTitle(stringArray[i]);
if (i == 0) {
button.opacity = 50;
//todo setColor not work in canvas
//button.color = cc.color(0, 255, 0);
}
else if (i == 1) {
button.opacity = 200;
//todo setColor not work in canvas
//button.color = cc.color(0, 255, 0);
}
else if (i == 2) {
button.opacity = 100;
//todo setColor not work in canvas
//button.color = cc.color(0, 0, 255);
}
button.x = total_width + button.width / 2;
button.y = button.height / 2;
layer.addChild(button);
// Compute the size of the layer
height = button.height;
total_width += button.width;
}
layer.anchorX = 0.5;
layer.anchorY = 0.5;
layer.width = total_width;
layer.height = height;
layer.x = screenSize.width / 2.0;
layer.y = screenSize.height / 2.0;
// Add the black background
var background = new cc.Scale9Sprite(s_extensions_buttonBackground);
background.width = total_width + 14;
background.height = height + 14;
background.x = screenSize.width / 2.0;
background.y = screenSize.height / 2.0;
this.addChild(background);
return true;
}
return false;
},
// Creates and return a button with a default background and title color.
standardButtonWithTitle:function (title) {
// Creates and return a button with a default background and title color.
var backgroundButton = new cc.Scale9Sprite(s_extensions_button);
var backgroundHighlightedButton = new cc.Scale9Sprite(s_extensions_buttonHighlighted);
var titleButton = new cc.LabelTTF(title, "Marker Felt", 30);
titleButton.color = cc.color(159, 168, 176);
var button = new cc.ControlButton(titleButton, backgroundButton);
button.setBackgroundSpriteForState(backgroundHighlightedButton, cc.CONTROL_STATE_HIGHLIGHTED);
button.setTitleColorForState(cc.color.WHITE, cc.CONTROL_STATE_HIGHLIGHTED);
return button;
}
});
ControlButtonTest_HelloVariableSize.create = function (sceneTitle) {
var scene = new cc.Scene();
var controlLayer = new ControlButtonTest_HelloVariableSize();
if (controlLayer && controlLayer.init()) {
controlLayer.getSceneTitleLabel().setString(sceneTitle);
scene.addChild(controlLayer);
}
return scene;
};
var ControlButtonTest_Event = ControlScene.extend({
_displayValueLabel:null,
init:function () {
if (this._super()) {
var screenSize = cc.director.getWinSize();
// Add the button
var backgroundButton = new cc.Scale9Sprite(s_extensions_button);
var backgroundHighlightedButton = new cc.Scale9Sprite(s_extensions_buttonHighlighted);
// Add a label in which the button events will be displayed
this.setDisplayValueLabel(new cc.LabelTTF("No Event", "Marker Felt", 32));
this._displayValueLabel.anchorX = 0.5;
this._displayValueLabel.anchorY = -1;
this._displayValueLabel.x = screenSize.width / 2.0;
this._displayValueLabel.y = screenSize.height / 2.0;
this.addChild(this._displayValueLabel, 10);
var titleButton = new cc.LabelTTF("Touch Me!", "Marker Felt", 30);
titleButton.color = cc.color(159, 168, 176);
var controlButton = new cc.ControlButton(titleButton, backgroundButton);
controlButton.setBackgroundSpriteForState(backgroundHighlightedButton, cc.CONTROL_STATE_HIGHLIGHTED);
controlButton.setTitleColorForState(cc.color.WHITE, cc.CONTROL_STATE_HIGHLIGHTED);
controlButton.anchorX = 0.5;
controlButton.anchorY = 1;
controlButton.x = screenSize.width / 2.0;
controlButton.y = screenSize.height / 2.0;
this.addChild(controlButton, 1);
// Add the black background
var background = new cc.Scale9Sprite(s_extensions_buttonBackground);
background.width = 300;
background.height = 170;
background.x = screenSize.width / 2.0;
background.y = screenSize.height / 2.0;
this.addChild(background);
// Sets up event handlers
controlButton.addTargetWithActionForControlEvents(this, this.touchDownAction, cc.CONTROL_EVENT_TOUCH_DOWN);
controlButton.addTargetWithActionForControlEvents(this, this.touchDragInsideAction, cc.CONTROL_EVENT_TOUCH_DRAG_INSIDE);
controlButton.addTargetWithActionForControlEvents(this, this.touchDragOutsideAction, cc.CONTROL_EVENT_TOUCH_DRAG_OUTSIDE);
controlButton.addTargetWithActionForControlEvents(this, this.touchDragEnterAction, cc.CONTROL_EVENT_TOUCH_DRAG_ENTER);
controlButton.addTargetWithActionForControlEvents(this, this.touchDragExitAction, cc.CONTROL_EVENT_TOUCH_DRAG_EXIT);
controlButton.addTargetWithActionForControlEvents(this, this.touchUpInsideAction, cc.CONTROL_EVENT_TOUCH_UP_INSIDE);
controlButton.addTargetWithActionForControlEvents(this, this.touchUpOutsideAction, cc.CONTROL_EVENT_TOUCH_UP_OUTSIDE);
controlButton.addTargetWithActionForControlEvents(this, this.touchCancelAction, cc.CONTROL_EVENT_TOUCH_CANCEL);
return true;
}
return false;
},
getDisplayValueLabel:function () {
return this._displayValueLabel;
},
setDisplayValueLabel:function (displayValueLabel) {
this._displayValueLabel = displayValueLabel;
},
touchDownAction:function (sender, controlEvent) {
this._displayValueLabel.setString("Touch Down");
},
touchDragInsideAction:function (sender, controlEvent) {
this._displayValueLabel.setString("Drag Inside");
},
touchDragOutsideAction:function (sender, controlEvent) {
this._displayValueLabel.setString("Drag Outside");
},
touchDragEnterAction:function (sender, controlEvent) {
this._displayValueLabel.setString("Drag Enter");
},
touchDragExitAction:function (sender, controlEvent) {
this._displayValueLabel.setString("Drag Exit");
},
touchUpInsideAction:function (sender, controlEvent) {
this._displayValueLabel.setString("Touch Up Inside.");
},
touchUpOutsideAction:function (sender, controlEvent) {
this._displayValueLabel.setString("Touch Up Outside.");
},
touchCancelAction:function (sender, controlEvent) {
this._displayValueLabel.setString("Touch Cancel");
}
});
ControlButtonTest_Event.create = function (sceneTitle) {
var scene = new cc.Scene();
var controlLayer = new ControlButtonTest_Event();
if (controlLayer && controlLayer.init()) {
controlLayer.getSceneTitleLabel().setString(sceneTitle);
scene.addChild(controlLayer);
}
return scene;
};
var ControlButtonTest_Styling = ControlScene.extend({
init:function () {
if (this._super()) {
var screenSize = cc.director.getWinSize();
var layer = new cc.Node();
this.addChild(layer, 1);
var space = 10; // px
var max_w = 0, max_h = 0;
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
// Add the buttons
var button = this.standardButtonWithTitle((0 | (Math.random() * 30)) + "");
button.setAdjustBackgroundImage(false); // Tells the button that the background image must not be adjust
// It'll use the prefered size of the background image
button.x = button.width / 2 + (button.width + space) * i;
button.y = button.height / 2 + (button.height + space) * j;
layer.addChild(button);
max_w = Math.max(button.width * (i + 1) + space * i, max_w);
max_h = Math.max(button.height * (j + 1) + space * j, max_h);
}
}
layer.anchorX = 0.5;
layer.anchorY = 0.5;
layer.width = max_w;
layer.height = max_h;
layer.x = screenSize.width / 2.0;
layer.y = screenSize.height / 2.0;
// Add the black background
var backgroundButton = new cc.Scale9Sprite(s_extensions_buttonBackground);
backgroundButton.width = max_w + 14;
backgroundButton.height = max_h + 14;
backgroundButton.x = screenSize.width / 2.0;
backgroundButton.y = screenSize.height / 2.0;
this.addChild(backgroundButton);
return true;
}
return false;
},
standardButtonWithTitle:function (title) {
/** Creates and return a button with a default background and title color. */
var backgroundButton = new cc.Scale9Sprite(s_extensions_button);
backgroundButton.setPreferredSize(cc.size(45, 45)); // Set the prefered size
var backgroundHighlightedButton = new cc.Scale9Sprite(s_extensions_buttonHighlighted);
backgroundHighlightedButton.setPreferredSize(cc.size(45, 45)); // Set the prefered size
var titleButton = new cc.LabelTTF(title, "Marker Felt", 30);
titleButton.color = cc.color(159, 168, 176);
var button = new cc.ControlButton(titleButton, backgroundButton);
button.setBackgroundSpriteForState(backgroundHighlightedButton, cc.CONTROL_STATE_HIGHLIGHTED);
button.setTitleColorForState(cc.color.WHITE, cc.CONTROL_STATE_HIGHLIGHTED);
return button;
}
});
ControlButtonTest_Styling.create = function (sceneTitle) {
var scene = new cc.Scene();
var controlLayer = new ControlButtonTest_Styling();
if (controlLayer && controlLayer.init()) {
controlLayer.getSceneTitleLabel().setString(sceneTitle);
scene.addChild(controlLayer);
}
return scene;
};
| mit |
markogresak/DefinitelyTyped | types/carbon__icons-react/lib/function-math/32.d.ts | 67 | import { FunctionMath32 } from "../../";
export = FunctionMath32;
| mit |
paphko/openhab | bundles/persistence/org.openhab.persistence.exec.test/src/test/java/org/openhab/persistence/exec/internal/ExecServiceTest.java | 1454 | /**
* Copyright (c) 2010-2016, openHAB.org 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
*/
package org.openhab.persistence.exec.internal;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import junit.framework.Assert;
/**
* @author Thomas.Eichstaedt-Engelen
* @since 1.1.0
*/
public class ExecServiceTest {
ExecService service;
@Before
public void init() {
service = new ExecService();
}
@Test
public void testFormatAlias() throws IOException {
Date date = Calendar.getInstance().getTime();
String dateFormatString = "%2$tY-%2$tm-%2$td %2$tT %2$ts : %1$s";
String value = "testValue";
String formattedDate = String.format(dateFormatString, value, date);
String alias = "/Users/me/writeToFile.sh /Users/me/TempOut.txt " + dateFormatString;
String expected = "/Users/me/writeToFile.sh /Users/me/TempOut.txt " + formattedDate;
System.out.println("expected String: " + expected);
// Method under Test
String result = service.formatAlias(alias, value, date);
// Expected results ...
Assert.assertEquals(expected, result);
}
}
| epl-1.0 |
mrguessed/openhab | bundles/binding/org.openhab.binding.freeswitch/src/main/java/org/openhab/binding/freeswitch/internal/FreeswitchActivator.java | 1471 | /**
* Copyright (c) 2010-2016, openHAB.org 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
*/
package org.openhab.binding.freeswitch.internal;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Extension of the default OSGi bundle activator
*
* @author Dan Cunningham
* @since 1.4.0
*/
public final class FreeswitchActivator implements BundleActivator {
private static Logger logger = LoggerFactory.getLogger(FreeswitchActivator.class);
private static BundleContext context;
/**
* Called whenever the OSGi framework starts our bundle
*/
@Override
public void start(BundleContext bc) throws Exception {
context = bc;
logger.debug("Freeswitch binding has been started.");
}
/**
* Called whenever the OSGi framework stops our bundle
*/
@Override
public void stop(BundleContext bc) throws Exception {
context = null;
logger.debug("Freeswitch binding has been stopped.");
}
/**
* Returns the bundle context of this bundle
*
* @return the bundle context
*/
public static BundleContext getContext() {
return context;
}
}
| epl-1.0 |
besutra/freeraum | core/modules/aggregator/src/Tests/FeedLanguageTest.php | 2127 | <?php
/**
* @file
* Contains \Drupal\aggregator\Tests\FeedLanguageTest.
*/
namespace Drupal\aggregator\Tests;
use Drupal\Core\Language\Language;
/**
* Tests aggregator feeds in multiple languages.
*/
class FeedLanguageTest extends AggregatorTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('language');
/**
* List of langcodes.
*
* @var array
*/
protected $langcodes = array();
public static function getInfo() {
return array(
'name' => 'Multilingual feeds',
'description' => 'Checks creating of feeds in multiple languages',
'group' => 'Aggregator',
);
}
public function setUp() {
parent::setUp();
// Create test languages.
$this->langcodes = array(language_load('en'));
for ($i = 1; $i < 3; ++$i) {
$language = new Language(array(
'id' => 'l' . $i,
'name' => $this->randomString(),
));
language_save($language);
$this->langcodes[$i] = $language;
}
}
/**
* Tests creation of feeds with a language.
*/
public function testFeedLanguage() {
$feeds = array();
// Create feeds.
$feeds[1] = $this->createFeed(NULL, array('langcode' => $this->langcodes[1]->id));
$feeds[2] = $this->createFeed(NULL, array('langcode' => $this->langcodes[2]->id));
// Make sure that the language has been assigned.
$this->assertEqual($feeds[1]->language()->id, $this->langcodes[1]->id);
$this->assertEqual($feeds[2]->language()->id, $this->langcodes[2]->id);
// Create example nodes to create feed items from and then update the feeds.
$this->createSampleNodes();
$this->cronRun();
// Loop over the created feed items and verify that their language matches
// the one from the feed.
foreach ($feeds as $feed) {
$items = entity_load_multiple_by_properties('aggregator_item', array('fid' => $feed->id()));
$this->assertTrue(count($items) > 0, 'Feed items were created.');
foreach ($items as $item) {
$this->assertEqual($item->language()->id, $feed->language()->id);
}
}
}
}
| gpl-2.0 |
antonyevans/plantwiki | includes/api/ApiExpandTemplates.php | 3712 | <?php
/**
*
*
* Created on Oct 05, 2007
*
* Copyright © 2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
*/
/**
* API module that functions as a shortcut to the wikitext preprocessor. Expands
* any templates in a provided string, and returns the result of this expansion
* to the caller.
*
* @ingroup API
*/
class ApiExpandTemplates extends ApiBase {
public function __construct( $main, $action ) {
parent::__construct( $main, $action );
}
public function execute() {
// Cache may vary on $wgUser because ParserOptions gets data from it
$this->getMain()->setCacheMode( 'anon-public-user-private' );
// Get parameters
$params = $this->extractRequestParams();
// Create title for parser
$title_obj = Title::newFromText( $params['title'] );
if ( !$title_obj ) {
$this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
}
$result = $this->getResult();
// Parse text
global $wgParser;
$options = ParserOptions::newFromContext( $this->getContext() );
if ( $params['includecomments'] ) {
$options->setRemoveComments( false );
}
if ( $params['generatexml'] ) {
$wgParser->startExternalParse( $title_obj, $options, OT_PREPROCESS );
$dom = $wgParser->preprocessToDom( $params['text'] );
if ( is_callable( array( $dom, 'saveXML' ) ) ) {
$xml = $dom->saveXML();
} else {
$xml = $dom->__toString();
}
$xml_result = array();
$result->setContent( $xml_result, $xml );
$result->addValue( null, 'parsetree', $xml_result );
}
$retval = $wgParser->preprocess( $params['text'], $title_obj, $options );
// Return result
$retval_array = array();
$result->setContent( $retval_array, $retval );
$result->addValue( null, $this->getModuleName(), $retval_array );
}
public function getAllowedParams() {
return array(
'title' => array(
ApiBase::PARAM_DFLT => 'API',
),
'text' => array(
ApiBase::PARAM_TYPE => 'string',
ApiBase::PARAM_REQUIRED => true,
),
'generatexml' => false,
'includecomments' => false,
);
}
public function getParamDescription() {
return array(
'text' => 'Wikitext to convert',
'title' => 'Title of page',
'generatexml' => 'Generate XML parse tree',
'includecomments' => 'Whether to include HTML comments in the output',
);
}
public function getResultProperties() {
return array(
'' => array(
'*' => 'string'
)
);
}
public function getDescription() {
return 'Expands all templates in wikitext';
}
public function getPossibleErrors() {
return array_merge( parent::getPossibleErrors(), array(
array( 'invalidtitle', 'title' ),
) );
}
public function getExamples() {
return array(
'api.php?action=expandtemplates&text={{Project:Sandbox}}'
);
}
public function getHelpUrls() {
return 'https://www.mediawiki.org/wiki/API:Parsing_wikitext#expandtemplates';
}
public function getVersion() {
return __CLASS__ . ': $Id$';
}
}
| gpl-2.0 |
DocSkellington/pcsx2-1.4.0-rr | 3rdparty/wxwidgets3.0/src/common/strconv.cpp | 102376 | /////////////////////////////////////////////////////////////////////////////
// Name: src/common/strconv.cpp
// Purpose: Unicode conversion classes
// Author: Ove Kaaven, Robert Roebling, Vadim Zeitlin, Vaclav Slavik,
// Ryan Norton, Fredrik Roubert (UTF7)
// Modified by:
// Created: 29/01/98
// Copyright: (c) 1999 Ove Kaaven, Robert Roebling, Vaclav Slavik
// (c) 2000-2003 Vadim Zeitlin
// (c) 2004 Ryan Norton, Fredrik Roubert
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif //__BORLANDC__
#ifndef WX_PRECOMP
#include "wx/intl.h"
#include "wx/log.h"
#include "wx/utils.h"
#include "wx/hashmap.h"
#endif
#include "wx/strconv.h"
#ifndef __WXWINCE__
#include <errno.h>
#endif
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#if defined(__WIN32__) && !defined(__WXMICROWIN__)
#include "wx/msw/private.h"
#include "wx/msw/missing.h"
#define wxHAVE_WIN32_MB2WC
#endif
#ifdef HAVE_ICONV
#include <iconv.h>
#include "wx/thread.h"
#endif
#include "wx/encconv.h"
#include "wx/fontmap.h"
#ifdef __DARWIN__
#include "wx/osx/core/private/strconv_cf.h"
#endif //def __DARWIN__
#define TRACE_STRCONV wxT("strconv")
// WC_UTF16 is defined only if sizeof(wchar_t) == 2, otherwise it's supposed to
// be 4 bytes
#if SIZEOF_WCHAR_T == 2
#define WC_UTF16
#endif
// ============================================================================
// implementation
// ============================================================================
// helper function of cMB2WC(): check if n bytes at this location are all NUL
static bool NotAllNULs(const char *p, size_t n)
{
while ( n && *p++ == '\0' )
n--;
return n != 0;
}
// ----------------------------------------------------------------------------
// UTF-16 en/decoding to/from UCS-4 with surrogates handling
// ----------------------------------------------------------------------------
static size_t encode_utf16(wxUint32 input, wxUint16 *output)
{
if (input <= 0xffff)
{
if (output)
*output = (wxUint16) input;
return 1;
}
else if (input >= 0x110000)
{
return wxCONV_FAILED;
}
else
{
if (output)
{
*output++ = (wxUint16) ((input >> 10) + 0xd7c0);
*output = (wxUint16) ((input & 0x3ff) + 0xdc00);
}
return 2;
}
}
static size_t decode_utf16(const wxUint16* input, wxUint32& output)
{
if ((*input < 0xd800) || (*input > 0xdfff))
{
output = *input;
return 1;
}
else if ((input[1] < 0xdc00) || (input[1] > 0xdfff))
{
output = *input;
return wxCONV_FAILED;
}
else
{
output = ((input[0] - 0xd7c0) << 10) + (input[1] - 0xdc00);
return 2;
}
}
#ifdef WC_UTF16
typedef wchar_t wxDecodeSurrogate_t;
#else // !WC_UTF16
typedef wxUint16 wxDecodeSurrogate_t;
#endif // WC_UTF16/!WC_UTF16
// returns the next UTF-32 character from the wchar_t buffer and advances the
// pointer to the character after this one
//
// if an invalid character is found, *pSrc is set to NULL, the caller must
// check for this
static wxUint32 wxDecodeSurrogate(const wxDecodeSurrogate_t **pSrc)
{
wxUint32 out;
const size_t
n = decode_utf16(reinterpret_cast<const wxUint16 *>(*pSrc), out);
if ( n == wxCONV_FAILED )
*pSrc = NULL;
else
*pSrc += n;
return out;
}
// ----------------------------------------------------------------------------
// wxMBConv
// ----------------------------------------------------------------------------
size_t
wxMBConv::ToWChar(wchar_t *dst, size_t dstLen,
const char *src, size_t srcLen) const
{
// although new conversion classes are supposed to implement this function
// directly, the existing ones only implement the old MB2WC() and so, to
// avoid to have to rewrite all conversion classes at once, we provide a
// default (but not efficient) implementation of this one in terms of the
// old function by copying the input to ensure that it's NUL-terminated and
// then using MB2WC() to convert it
//
// moreover, some conversion classes simply can't implement ToWChar()
// directly, the primary example is wxConvLibc: mbstowcs() only handles
// NUL-terminated strings
// the number of chars [which would be] written to dst [if it were not NULL]
size_t dstWritten = 0;
// the number of NULs terminating this string
size_t nulLen = 0; // not really needed, but just to avoid warnings
// if we were not given the input size we just have to assume that the
// string is properly terminated as we have no way of knowing how long it
// is anyhow, but if we do have the size check whether there are enough
// NULs at the end
wxCharBuffer bufTmp;
const char *srcEnd;
if ( srcLen != wxNO_LEN )
{
// we need to know how to find the end of this string
nulLen = GetMBNulLen();
if ( nulLen == wxCONV_FAILED )
return wxCONV_FAILED;
// if there are enough NULs we can avoid the copy
if ( srcLen < nulLen || NotAllNULs(src + srcLen - nulLen, nulLen) )
{
// make a copy in order to properly NUL-terminate the string
bufTmp = wxCharBuffer(srcLen + nulLen - 1 /* 1 will be added */);
char * const p = bufTmp.data();
memcpy(p, src, srcLen);
for ( char *s = p + srcLen; s < p + srcLen + nulLen; s++ )
*s = '\0';
src = bufTmp;
}
srcEnd = src + srcLen;
}
else // quit after the first loop iteration
{
srcEnd = NULL;
}
// the idea of this code is straightforward: it converts a NUL-terminated
// chunk of the string during each iteration and updates the output buffer
// with the result
//
// all the complication come from the fact that this function, for
// historical reasons, must behave in 2 subtly different ways when it's
// called with a fixed number of characters and when it's called for the
// entire NUL-terminated string: in the former case (srcEnd != NULL) we
// must count all characters we convert, NUL or not; but in the latter we
// do not count the trailing NUL -- but still count all the NULs inside the
// string
//
// so for the (simple) former case we just always count the trailing NUL,
// but for the latter we need to wait until we see if there is going to be
// another loop iteration and only count it then
for ( ;; )
{
// try to convert the current chunk
size_t lenChunk = MB2WC(NULL, src, 0);
if ( lenChunk == wxCONV_FAILED )
return wxCONV_FAILED;
dstWritten += lenChunk;
if ( !srcEnd )
dstWritten++;
if ( !lenChunk )
{
// nothing left in the input string, conversion succeeded
break;
}
if ( dst )
{
if ( dstWritten > dstLen )
return wxCONV_FAILED;
// +1 is for trailing NUL
if ( MB2WC(dst, src, lenChunk + 1) == wxCONV_FAILED )
return wxCONV_FAILED;
dst += lenChunk;
if ( !srcEnd )
dst++;
}
if ( !srcEnd )
{
// we convert just one chunk in this case as this is the entire
// string anyhow (and we don't count the trailing NUL in this case)
break;
}
// advance the input pointer past the end of this chunk: notice that we
// will always stop before srcEnd because we know that the chunk is
// always properly NUL-terminated
while ( NotAllNULs(src, nulLen) )
{
// notice that we must skip over multiple bytes here as we suppose
// that if NUL takes 2 or 4 bytes, then all the other characters do
// too and so if advanced by a single byte we might erroneously
// detect sequences of NUL bytes in the middle of the input
src += nulLen;
}
// if the buffer ends before this NUL, we shouldn't count it in our
// output so skip the code below
if ( src == srcEnd )
break;
// do count this terminator as it's inside the buffer we convert
dstWritten++;
if ( dst )
dst++;
src += nulLen; // skip the terminator itself
if ( src >= srcEnd )
break;
}
return dstWritten;
}
size_t
wxMBConv::FromWChar(char *dst, size_t dstLen,
const wchar_t *src, size_t srcLen) const
{
// the number of chars [which would be] written to dst [if it were not NULL]
size_t dstWritten = 0;
// if we don't know its length we have no choice but to assume that it is
// NUL-terminated (notice that it can still be NUL-terminated even if
// explicit length is given but it doesn't change our return value)
const bool isNulTerminated = srcLen == wxNO_LEN;
// make a copy of the input string unless it is already properly
// NUL-terminated
wxWCharBuffer bufTmp;
if ( isNulTerminated )
{
srcLen = wxWcslen(src) + 1;
}
else if ( srcLen != 0 && src[srcLen - 1] != L'\0' )
{
// make a copy in order to properly NUL-terminate the string
bufTmp = wxWCharBuffer(srcLen);
memcpy(bufTmp.data(), src, srcLen * sizeof(wchar_t));
src = bufTmp;
}
const size_t lenNul = GetMBNulLen();
for ( const wchar_t * const srcEnd = src + srcLen;
src < srcEnd;
src++ /* skip L'\0' too */ )
{
// try to convert the current chunk
size_t lenChunk = WC2MB(NULL, src, 0);
if ( lenChunk == wxCONV_FAILED )
return wxCONV_FAILED;
dstWritten += lenChunk;
const wchar_t * const
chunkEnd = isNulTerminated ? srcEnd - 1 : src + wxWcslen(src);
// our return value accounts for the trailing NUL(s), unlike that of
// WC2MB(), however don't do it for the last NUL we artificially added
// ourselves above
if ( chunkEnd < srcEnd )
dstWritten += lenNul;
if ( dst )
{
if ( dstWritten > dstLen )
return wxCONV_FAILED;
// if we know that there is enough space in the destination buffer
// (because we accounted for lenNul in dstWritten above), we can
// convert directly in place -- but otherwise we need another
// temporary buffer to ensure that we don't overwrite the output
wxCharBuffer dstBuf;
char *dstTmp;
if ( chunkEnd == srcEnd )
{
dstBuf = wxCharBuffer(lenChunk + lenNul - 1);
dstTmp = dstBuf.data();
}
else
{
dstTmp = dst;
}
if ( WC2MB(dstTmp, src, lenChunk + lenNul) == wxCONV_FAILED )
return wxCONV_FAILED;
if ( dstTmp != dst )
{
// copy everything up to but excluding the terminating NUL(s)
// into the real output buffer
memcpy(dst, dstTmp, lenChunk);
// micro-optimization: if dstTmp != dst it means that chunkEnd
// == srcEnd and so we're done, no need to update anything below
break;
}
dst += lenChunk;
if ( chunkEnd < srcEnd )
dst += lenNul;
}
src = chunkEnd;
}
return dstWritten;
}
size_t wxMBConv::MB2WC(wchar_t *outBuff, const char *inBuff, size_t outLen) const
{
size_t rc = ToWChar(outBuff, outLen, inBuff);
if ( rc != wxCONV_FAILED )
{
// ToWChar() returns the buffer length, i.e. including the trailing
// NUL, while this method doesn't take it into account
rc--;
}
return rc;
}
size_t wxMBConv::WC2MB(char *outBuff, const wchar_t *inBuff, size_t outLen) const
{
size_t rc = FromWChar(outBuff, outLen, inBuff);
if ( rc != wxCONV_FAILED )
{
rc -= GetMBNulLen();
}
return rc;
}
wxMBConv::~wxMBConv()
{
// nothing to do here (necessary for Darwin linking probably)
}
const wxWCharBuffer wxMBConv::cMB2WC(const char *psz) const
{
if ( psz )
{
// calculate the length of the buffer needed first
const size_t nLen = ToWChar(NULL, 0, psz);
if ( nLen != wxCONV_FAILED )
{
// now do the actual conversion
wxWCharBuffer buf(nLen - 1 /* +1 added implicitly */);
// +1 for the trailing NULL
if ( ToWChar(buf.data(), nLen, psz) != wxCONV_FAILED )
return buf;
}
}
return wxWCharBuffer();
}
const wxCharBuffer wxMBConv::cWC2MB(const wchar_t *pwz) const
{
if ( pwz )
{
const size_t nLen = FromWChar(NULL, 0, pwz);
if ( nLen != wxCONV_FAILED )
{
wxCharBuffer buf(nLen - 1);
if ( FromWChar(buf.data(), nLen, pwz) != wxCONV_FAILED )
return buf;
}
}
return wxCharBuffer();
}
const wxWCharBuffer
wxMBConv::cMB2WC(const char *inBuff, size_t inLen, size_t *outLen) const
{
const size_t dstLen = ToWChar(NULL, 0, inBuff, inLen);
if ( dstLen != wxCONV_FAILED )
{
// notice that we allocate space for dstLen+1 wide characters here
// because we want the buffer to always be NUL-terminated, even if the
// input isn't (as otherwise the caller has no way to know its length)
wxWCharBuffer wbuf(dstLen);
if ( ToWChar(wbuf.data(), dstLen, inBuff, inLen) != wxCONV_FAILED )
{
if ( outLen )
{
*outLen = dstLen;
// we also need to handle NUL-terminated input strings
// specially: for them the output is the length of the string
// excluding the trailing NUL, however if we're asked to
// convert a specific number of characters we return the length
// of the resulting output even if it's NUL-terminated
if ( inLen == wxNO_LEN )
(*outLen)--;
}
return wbuf;
}
}
if ( outLen )
*outLen = 0;
return wxWCharBuffer();
}
const wxCharBuffer
wxMBConv::cWC2MB(const wchar_t *inBuff, size_t inLen, size_t *outLen) const
{
size_t dstLen = FromWChar(NULL, 0, inBuff, inLen);
if ( dstLen != wxCONV_FAILED )
{
const size_t nulLen = GetMBNulLen();
// as above, ensure that the buffer is always NUL-terminated, even if
// the input is not
wxCharBuffer buf(dstLen + nulLen - 1);
memset(buf.data() + dstLen, 0, nulLen);
if ( FromWChar(buf.data(), dstLen, inBuff, inLen) != wxCONV_FAILED )
{
if ( outLen )
{
*outLen = dstLen;
if ( inLen == wxNO_LEN )
{
// in this case both input and output are NUL-terminated
// and we're not supposed to count NUL
*outLen -= nulLen;
}
}
return buf;
}
}
if ( outLen )
*outLen = 0;
return wxCharBuffer();
}
const wxWCharBuffer wxMBConv::cMB2WC(const wxScopedCharBuffer& buf) const
{
const size_t srcLen = buf.length();
if ( srcLen )
{
const size_t dstLen = ToWChar(NULL, 0, buf, srcLen);
if ( dstLen != wxCONV_FAILED )
{
wxWCharBuffer wbuf(dstLen);
wbuf.data()[dstLen] = L'\0';
if ( ToWChar(wbuf.data(), dstLen, buf, srcLen) != wxCONV_FAILED )
return wbuf;
}
}
return wxScopedWCharBuffer::CreateNonOwned(L"", 0);
}
const wxCharBuffer wxMBConv::cWC2MB(const wxScopedWCharBuffer& wbuf) const
{
const size_t srcLen = wbuf.length();
if ( srcLen )
{
const size_t dstLen = FromWChar(NULL, 0, wbuf, srcLen);
if ( dstLen != wxCONV_FAILED )
{
wxCharBuffer buf(dstLen);
buf.data()[dstLen] = '\0';
if ( FromWChar(buf.data(), dstLen, wbuf, srcLen) != wxCONV_FAILED )
return buf;
}
}
return wxScopedCharBuffer::CreateNonOwned("", 0);
}
// ----------------------------------------------------------------------------
// wxMBConvLibc
// ----------------------------------------------------------------------------
size_t wxMBConvLibc::MB2WC(wchar_t *buf, const char *psz, size_t n) const
{
return wxMB2WC(buf, psz, n);
}
size_t wxMBConvLibc::WC2MB(char *buf, const wchar_t *psz, size_t n) const
{
return wxWC2MB(buf, psz, n);
}
// ----------------------------------------------------------------------------
// wxConvBrokenFileNames
// ----------------------------------------------------------------------------
#ifdef __UNIX__
wxConvBrokenFileNames::wxConvBrokenFileNames(const wxString& charset)
{
if ( wxStricmp(charset, wxT("UTF-8")) == 0 ||
wxStricmp(charset, wxT("UTF8")) == 0 )
m_conv = new wxMBConvUTF8(wxMBConvUTF8::MAP_INVALID_UTF8_TO_PUA);
else
m_conv = new wxCSConv(charset);
}
#endif // __UNIX__
// ----------------------------------------------------------------------------
// UTF-7
// ----------------------------------------------------------------------------
// Implementation (C) 2004 Fredrik Roubert
//
// Changes to work in streaming mode (C) 2008 Vadim Zeitlin
//
// BASE64 decoding table
//
static const unsigned char utf7unb64[] =
{
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x3e, 0xff, 0xff, 0xff, 0x3f,
0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b,
0x3c, 0x3d, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
0x17, 0x18, 0x19, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
0x31, 0x32, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
size_t wxMBConvUTF7::ToWChar(wchar_t *dst, size_t dstLen,
const char *src, size_t srcLen) const
{
DecoderState stateOrig,
*statePtr;
if ( srcLen == wxNO_LEN )
{
// convert the entire string, up to and including the trailing NUL
srcLen = strlen(src) + 1;
// when working on the entire strings we don't update nor use the shift
// state from the previous call
statePtr = &stateOrig;
}
else // when working with partial strings we do use the shift state
{
statePtr = const_cast<DecoderState *>(&m_stateDecoder);
// also save the old state to be able to rollback to it on error
stateOrig = m_stateDecoder;
}
// but to simplify the code below we use this variable in both cases
DecoderState& state = *statePtr;
// number of characters [which would have been] written to dst [if it were
// not NULL]
size_t len = 0;
const char * const srcEnd = src + srcLen;
while ( (src < srcEnd) && (!dst || (len < dstLen)) )
{
const unsigned char cc = *src++;
if ( state.IsShifted() )
{
const unsigned char dc = utf7unb64[cc];
if ( dc == 0xff )
{
// end of encoded part, check that nothing was left: there can
// be up to 4 bits of 0 padding but nothing else (we also need
// to check isLSB as we count bits modulo 8 while a valid UTF-7
// encoded sequence must contain an integral number of UTF-16
// characters)
if ( state.isLSB || state.bit > 4 ||
(state.accum & ((1 << state.bit) - 1)) )
{
if ( !len )
state = stateOrig;
return wxCONV_FAILED;
}
state.ToDirect();
// re-parse this character normally below unless it's '-' which
// is consumed by the decoder
if ( cc == '-' )
continue;
}
else // valid encoded character
{
// mini base64 decoder: each character is 6 bits
state.bit += 6;
state.accum <<= 6;
state.accum += dc;
if ( state.bit >= 8 )
{
// got the full byte, consume it
state.bit -= 8;
unsigned char b = (state.accum >> state.bit) & 0x00ff;
if ( state.isLSB )
{
// we've got the full word, output it
if ( dst )
*dst++ = (state.msb << 8) | b;
len++;
state.isLSB = false;
}
else // MSB
{
// just store it while we wait for LSB
state.msb = b;
state.isLSB = true;
}
}
}
}
if ( state.IsDirect() )
{
// start of an encoded segment?
if ( cc == '+' )
{
if ( *src == '-' )
{
// just the encoded plus sign, don't switch to shifted mode
if ( dst )
*dst++ = '+';
len++;
src++;
}
else if ( utf7unb64[(unsigned)*src] == 0xff )
{
// empty encoded chunks are not allowed
if ( !len )
state = stateOrig;
return wxCONV_FAILED;
}
else // base-64 encoded chunk follows
{
state.ToShifted();
}
}
else // not '+'
{
// only printable 7 bit ASCII characters (with the exception of
// NUL, TAB, CR and LF) can be used directly
if ( cc >= 0x7f || (cc < ' ' &&
!(cc == '\0' || cc == '\t' || cc == '\r' || cc == '\n')) )
return wxCONV_FAILED;
if ( dst )
*dst++ = cc;
len++;
}
}
}
if ( !len )
{
// as we didn't read any characters we should be called with the same
// data (followed by some more new data) again later so don't save our
// state
state = stateOrig;
return wxCONV_FAILED;
}
return len;
}
//
// BASE64 encoding table
//
static const unsigned char utf7enb64[] =
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'
};
//
// UTF-7 encoding table
//
// 0 - Set D (directly encoded characters)
// 1 - Set O (optional direct characters)
// 2 - whitespace characters (optional)
// 3 - special characters
//
static const unsigned char utf7encode[128] =
{
0, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 3,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3
};
static inline bool wxIsUTF7Direct(wchar_t wc)
{
return wc < 0x80 && utf7encode[wc] < 1;
}
size_t wxMBConvUTF7::FromWChar(char *dst, size_t dstLen,
const wchar_t *src, size_t srcLen) const
{
EncoderState stateOrig,
*statePtr;
if ( srcLen == wxNO_LEN )
{
// we don't apply the stored state when operating on entire strings at
// once
statePtr = &stateOrig;
srcLen = wxWcslen(src) + 1;
}
else // do use the mode we left the output in previously
{
stateOrig = m_stateEncoder;
statePtr = const_cast<EncoderState *>(&m_stateEncoder);
}
EncoderState& state = *statePtr;
size_t len = 0;
const wchar_t * const srcEnd = src + srcLen;
while ( src < srcEnd && (!dst || len < dstLen) )
{
wchar_t cc = *src++;
if ( wxIsUTF7Direct(cc) )
{
if ( state.IsShifted() )
{
// pad with zeros the last encoded block if necessary
if ( state.bit )
{
if ( dst )
*dst++ = utf7enb64[((state.accum % 16) << (6 - state.bit)) % 64];
len++;
}
state.ToDirect();
if ( dst )
*dst++ = '-';
len++;
}
if ( dst )
*dst++ = (char)cc;
len++;
}
else if ( cc == '+' && state.IsDirect() )
{
if ( dst )
{
*dst++ = '+';
*dst++ = '-';
}
len += 2;
}
#ifndef WC_UTF16
else if (((wxUint32)cc) > 0xffff)
{
// no surrogate pair generation (yet?)
return wxCONV_FAILED;
}
#endif
else
{
if ( state.IsDirect() )
{
state.ToShifted();
if ( dst )
*dst++ = '+';
len++;
}
// BASE64 encode string
for ( ;; )
{
for ( unsigned lsb = 0; lsb < 2; lsb++ )
{
state.accum <<= 8;
state.accum += lsb ? cc & 0xff : (cc & 0xff00) >> 8;
for (state.bit += 8; state.bit >= 6; )
{
state.bit -= 6;
if ( dst )
*dst++ = utf7enb64[(state.accum >> state.bit) % 64];
len++;
}
}
if ( src == srcEnd || wxIsUTF7Direct(cc = *src) )
break;
src++;
}
}
}
// we need to restore the original encoder state if we were called just to
// calculate the amount of space needed as we will presumably be called
// again to really convert the data now
if ( !dst )
state = stateOrig;
return len;
}
// ----------------------------------------------------------------------------
// UTF-8
// ----------------------------------------------------------------------------
static const wxUint32 utf8_max[]=
{ 0x7f, 0x7ff, 0xffff, 0x1fffff, 0x3ffffff, 0x7fffffff, 0xffffffff };
// boundaries of the private use area we use to (temporarily) remap invalid
// characters invalid in a UTF-8 encoded string
const wxUint32 wxUnicodePUA = 0x100000;
const wxUint32 wxUnicodePUAEnd = wxUnicodePUA + 256;
// this table gives the length of the UTF-8 encoding from its first character:
const unsigned char tableUtf8Lengths[256] = {
// single-byte sequences (ASCII):
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 00..0F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 10..1F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 20..2F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 30..3F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 40..4F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 50..5F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 60..6F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 70..7F
// these are invalid:
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 80..8F
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 90..9F
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A0..AF
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B0..BF
0, 0, // C0,C1
// two-byte sequences:
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C2..CF
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // D0..DF
// three-byte sequences:
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // E0..EF
// four-byte sequences:
4, 4, 4, 4, 4, // F0..F4
// these are invalid again (5- or 6-byte
// sequences and sequences for code points
// above U+10FFFF, as restricted by RFC 3629):
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // F5..FF
};
size_t
wxMBConvStrictUTF8::ToWChar(wchar_t *dst, size_t dstLen,
const char *src, size_t srcLen) const
{
wchar_t *out = dstLen ? dst : NULL;
size_t written = 0;
if ( srcLen == wxNO_LEN )
srcLen = strlen(src) + 1;
for ( const char *p = src; ; p++ )
{
if ( (srcLen == wxNO_LEN ? !*p : !srcLen) )
{
// all done successfully, just add the trailing NULL if we are not
// using explicit length
if ( srcLen == wxNO_LEN )
{
if ( out )
{
if ( !dstLen )
break;
*out = L'\0';
}
written++;
}
return written;
}
if ( out && !dstLen-- )
break;
wxUint32 code;
unsigned char c = *p;
if ( c < 0x80 )
{
if ( srcLen == 0 ) // the test works for wxNO_LEN too
break;
if ( srcLen != wxNO_LEN )
srcLen--;
code = c;
}
else
{
unsigned len = tableUtf8Lengths[c];
if ( !len )
break;
if ( srcLen < len ) // the test works for wxNO_LEN too
break;
if ( srcLen != wxNO_LEN )
srcLen -= len;
// Char. number range | UTF-8 octet sequence
// (hexadecimal) | (binary)
// ----------------------+----------------------------------------
// 0000 0000 - 0000 007F | 0xxxxxxx
// 0000 0080 - 0000 07FF | 110xxxxx 10xxxxxx
// 0000 0800 - 0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
// 0001 0000 - 0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
//
// Code point value is stored in bits marked with 'x',
// lowest-order bit of the value on the right side in the diagram
// above. (from RFC 3629)
// mask to extract lead byte's value ('x' bits above), by sequence
// length:
static const unsigned char leadValueMask[] = { 0x7F, 0x1F, 0x0F, 0x07 };
// mask and value of lead byte's most significant bits, by length:
static const unsigned char leadMarkerMask[] = { 0x80, 0xE0, 0xF0, 0xF8 };
static const unsigned char leadMarkerVal[] = { 0x00, 0xC0, 0xE0, 0xF0 };
len--; // it's more convenient to work with 0-based length here
// extract the lead byte's value bits:
if ( (c & leadMarkerMask[len]) != leadMarkerVal[len] )
break;
code = c & leadValueMask[len];
// all remaining bytes, if any, are handled in the same way
// regardless of sequence's length:
for ( ; len; --len )
{
c = *++p;
if ( (c & 0xC0) != 0x80 )
return wxCONV_FAILED;
code <<= 6;
code |= c & 0x3F;
}
}
#ifdef WC_UTF16
// cast is ok because wchar_t == wxUint16 if WC_UTF16
if ( encode_utf16(code, (wxUint16 *)out) == 2 )
{
if ( out )
out++;
written++;
}
#else // !WC_UTF16
if ( out )
*out = code;
#endif // WC_UTF16/!WC_UTF16
if ( out )
out++;
written++;
}
return wxCONV_FAILED;
}
size_t
wxMBConvStrictUTF8::FromWChar(char *dst, size_t dstLen,
const wchar_t *src, size_t srcLen) const
{
char *out = dstLen ? dst : NULL;
size_t written = 0;
for ( const wchar_t *wp = src; ; wp++ )
{
if ( (srcLen == wxNO_LEN ? !*wp : !srcLen) )
{
// all done successfully, just add the trailing NULL if we are not
// using explicit length
if ( srcLen == wxNO_LEN )
{
if ( out )
{
if ( !dstLen )
break;
*out = '\0';
}
written++;
}
return written;
}
if ( srcLen != wxNO_LEN )
srcLen--;
wxUint32 code;
#ifdef WC_UTF16
// cast is ok for WC_UTF16
if ( decode_utf16((const wxUint16 *)wp, code) == 2 )
{
// skip the next char too as we decoded a surrogate
wp++;
if ( srcLen != wxNO_LEN )
srcLen--;
}
#else // wchar_t is UTF-32
code = *wp & 0x7fffffff;
#endif
unsigned len;
if ( code <= 0x7F )
{
len = 1;
if ( out )
{
if ( dstLen < len )
break;
out[0] = (char)code;
}
}
else if ( code <= 0x07FF )
{
len = 2;
if ( out )
{
if ( dstLen < len )
break;
// NB: this line takes 6 least significant bits, encodes them as
// 10xxxxxx and discards them so that the next byte can be encoded:
out[1] = 0x80 | (code & 0x3F); code >>= 6;
out[0] = 0xC0 | code;
}
}
else if ( code < 0xFFFF )
{
len = 3;
if ( out )
{
if ( dstLen < len )
break;
out[2] = 0x80 | (code & 0x3F); code >>= 6;
out[1] = 0x80 | (code & 0x3F); code >>= 6;
out[0] = 0xE0 | code;
}
}
else if ( code <= 0x10FFFF )
{
len = 4;
if ( out )
{
if ( dstLen < len )
break;
out[3] = 0x80 | (code & 0x3F); code >>= 6;
out[2] = 0x80 | (code & 0x3F); code >>= 6;
out[1] = 0x80 | (code & 0x3F); code >>= 6;
out[0] = 0xF0 | code;
}
}
else
{
wxFAIL_MSG( wxT("trying to encode undefined Unicode character") );
break;
}
if ( out )
{
out += len;
dstLen -= len;
}
written += len;
}
// we only get here if an error occurs during decoding
return wxCONV_FAILED;
}
size_t wxMBConvUTF8::ToWChar(wchar_t *buf, size_t n,
const char *psz, size_t srcLen) const
{
if ( m_options == MAP_INVALID_UTF8_NOT )
return wxMBConvStrictUTF8::ToWChar(buf, n, psz, srcLen);
size_t len = 0;
// The length can be either given explicitly or computed implicitly for the
// NUL-terminated strings.
const bool isNulTerminated = srcLen == wxNO_LEN;
while ((isNulTerminated ? *psz : srcLen--) && ((!buf) || (len < n)))
{
const char *opsz = psz;
bool invalid = false;
unsigned char cc = *psz++, fc = cc;
unsigned cnt;
for (cnt = 0; fc & 0x80; cnt++)
fc <<= 1;
if (!cnt)
{
// plain ASCII char
if (buf)
*buf++ = cc;
len++;
// escape the escape character for octal escapes
if ((m_options & MAP_INVALID_UTF8_TO_OCTAL)
&& cc == '\\' && (!buf || len < n))
{
if (buf)
*buf++ = cc;
len++;
}
}
else
{
cnt--;
if (!cnt)
{
// invalid UTF-8 sequence
invalid = true;
}
else
{
unsigned ocnt = cnt - 1;
wxUint32 res = cc & (0x3f >> cnt);
while (cnt--)
{
if (!isNulTerminated && !srcLen)
{
// invalid UTF-8 sequence ending before the end of code
// point.
invalid = true;
break;
}
cc = *psz;
if ((cc & 0xC0) != 0x80)
{
// invalid UTF-8 sequence
invalid = true;
break;
}
psz++;
if (!isNulTerminated)
srcLen--;
res = (res << 6) | (cc & 0x3f);
}
if (invalid || res <= utf8_max[ocnt])
{
// illegal UTF-8 encoding
invalid = true;
}
else if ((m_options & MAP_INVALID_UTF8_TO_PUA) &&
res >= wxUnicodePUA && res < wxUnicodePUAEnd)
{
// if one of our PUA characters turns up externally
// it must also be treated as an illegal sequence
// (a bit like you have to escape an escape character)
invalid = true;
}
else
{
#ifdef WC_UTF16
// cast is ok because wchar_t == wxUint16 if WC_UTF16
size_t pa = encode_utf16(res, (wxUint16 *)buf);
if (pa == wxCONV_FAILED)
{
invalid = true;
}
else
{
if (buf)
buf += pa;
len += pa;
}
#else // !WC_UTF16
if (buf)
*buf++ = (wchar_t)res;
len++;
#endif // WC_UTF16/!WC_UTF16
}
}
if (invalid)
{
if (m_options & MAP_INVALID_UTF8_TO_PUA)
{
while (opsz < psz && (!buf || len < n))
{
#ifdef WC_UTF16
// cast is ok because wchar_t == wxUuint16 if WC_UTF16
size_t pa = encode_utf16((unsigned char)*opsz + wxUnicodePUA, (wxUint16 *)buf);
wxASSERT(pa != wxCONV_FAILED);
if (buf)
buf += pa;
opsz++;
len += pa;
#else
if (buf)
*buf++ = (wchar_t)(wxUnicodePUA + (unsigned char)*opsz);
opsz++;
len++;
#endif
}
}
else if (m_options & MAP_INVALID_UTF8_TO_OCTAL)
{
while (opsz < psz && (!buf || len < n))
{
if ( buf && len + 3 < n )
{
unsigned char on = *opsz;
*buf++ = L'\\';
*buf++ = (wchar_t)( L'0' + on / 0100 );
*buf++ = (wchar_t)( L'0' + (on % 0100) / 010 );
*buf++ = (wchar_t)( L'0' + on % 010 );
}
opsz++;
len += 4;
}
}
else // MAP_INVALID_UTF8_NOT
{
return wxCONV_FAILED;
}
}
}
}
if ( isNulTerminated )
{
// Add the trailing NUL in this case if we have a large enough buffer.
if ( buf && (len < n) )
*buf = 0;
// And count it in any case.
len++;
}
return len;
}
static inline bool isoctal(wchar_t wch)
{
return L'0' <= wch && wch <= L'7';
}
size_t wxMBConvUTF8::FromWChar(char *buf, size_t n,
const wchar_t *psz, size_t srcLen) const
{
if ( m_options == MAP_INVALID_UTF8_NOT )
return wxMBConvStrictUTF8::FromWChar(buf, n, psz, srcLen);
size_t len = 0;
// The length can be either given explicitly or computed implicitly for the
// NUL-terminated strings.
const bool isNulTerminated = srcLen == wxNO_LEN;
while ((isNulTerminated ? *psz : srcLen--) && ((!buf) || (len < n)))
{
wxUint32 cc;
#ifdef WC_UTF16
// cast is ok for WC_UTF16
size_t pa = decode_utf16((const wxUint16 *)psz, cc);
psz += (pa == wxCONV_FAILED) ? 1 : pa;
#else
cc = (*psz++) & 0x7fffffff;
#endif
if ( (m_options & MAP_INVALID_UTF8_TO_PUA)
&& cc >= wxUnicodePUA && cc < wxUnicodePUAEnd )
{
if (buf)
*buf++ = (char)(cc - wxUnicodePUA);
len++;
}
else if ( (m_options & MAP_INVALID_UTF8_TO_OCTAL)
&& cc == L'\\' && psz[0] == L'\\' )
{
if (buf)
*buf++ = (char)cc;
psz++;
len++;
}
else if ( (m_options & MAP_INVALID_UTF8_TO_OCTAL) &&
cc == L'\\' &&
isoctal(psz[0]) && isoctal(psz[1]) && isoctal(psz[2]) )
{
if (buf)
{
*buf++ = (char) ((psz[0] - L'0') * 0100 +
(psz[1] - L'0') * 010 +
(psz[2] - L'0'));
}
psz += 3;
len++;
}
else
{
unsigned cnt;
for (cnt = 0; cc > utf8_max[cnt]; cnt++)
{
}
if (!cnt)
{
// plain ASCII char
if (buf)
*buf++ = (char) cc;
len++;
}
else
{
len += cnt + 1;
if (buf)
{
*buf++ = (char) ((-128 >> cnt) | ((cc >> (cnt * 6)) & (0x3f >> cnt)));
while (cnt--)
*buf++ = (char) (0x80 | ((cc >> (cnt * 6)) & 0x3f));
}
}
}
}
if ( isNulTerminated )
{
// Add the trailing NUL in this case if we have a large enough buffer.
if ( buf && (len < n) )
*buf = 0;
// And count it in any case.
len++;
}
return len;
}
// ============================================================================
// UTF-16
// ============================================================================
#ifdef WORDS_BIGENDIAN
#define wxMBConvUTF16straight wxMBConvUTF16BE
#define wxMBConvUTF16swap wxMBConvUTF16LE
#else
#define wxMBConvUTF16swap wxMBConvUTF16BE
#define wxMBConvUTF16straight wxMBConvUTF16LE
#endif
/* static */
size_t wxMBConvUTF16Base::GetLength(const char *src, size_t srcLen)
{
if ( srcLen == wxNO_LEN )
{
// count the number of bytes in input, including the trailing NULs
const wxUint16 *inBuff = reinterpret_cast<const wxUint16 *>(src);
for ( srcLen = 1; *inBuff++; srcLen++ )
;
srcLen *= BYTES_PER_CHAR;
}
else // we already have the length
{
// we can only convert an entire number of UTF-16 characters
if ( srcLen % BYTES_PER_CHAR )
return wxCONV_FAILED;
}
return srcLen;
}
// case when in-memory representation is UTF-16 too
#ifdef WC_UTF16
// ----------------------------------------------------------------------------
// conversions without endianness change
// ----------------------------------------------------------------------------
size_t
wxMBConvUTF16straight::ToWChar(wchar_t *dst, size_t dstLen,
const char *src, size_t srcLen) const
{
// set up the scene for using memcpy() (which is presumably more efficient
// than copying the bytes one by one)
srcLen = GetLength(src, srcLen);
if ( srcLen == wxNO_LEN )
return wxCONV_FAILED;
const size_t inLen = srcLen / BYTES_PER_CHAR;
if ( dst )
{
if ( dstLen < inLen )
return wxCONV_FAILED;
memcpy(dst, src, srcLen);
}
return inLen;
}
size_t
wxMBConvUTF16straight::FromWChar(char *dst, size_t dstLen,
const wchar_t *src, size_t srcLen) const
{
if ( srcLen == wxNO_LEN )
srcLen = wxWcslen(src) + 1;
srcLen *= BYTES_PER_CHAR;
if ( dst )
{
if ( dstLen < srcLen )
return wxCONV_FAILED;
memcpy(dst, src, srcLen);
}
return srcLen;
}
// ----------------------------------------------------------------------------
// endian-reversing conversions
// ----------------------------------------------------------------------------
size_t
wxMBConvUTF16swap::ToWChar(wchar_t *dst, size_t dstLen,
const char *src, size_t srcLen) const
{
srcLen = GetLength(src, srcLen);
if ( srcLen == wxNO_LEN )
return wxCONV_FAILED;
srcLen /= BYTES_PER_CHAR;
if ( dst )
{
if ( dstLen < srcLen )
return wxCONV_FAILED;
const wxUint16 *inBuff = reinterpret_cast<const wxUint16 *>(src);
for ( size_t n = 0; n < srcLen; n++, inBuff++ )
{
*dst++ = wxUINT16_SWAP_ALWAYS(*inBuff);
}
}
return srcLen;
}
size_t
wxMBConvUTF16swap::FromWChar(char *dst, size_t dstLen,
const wchar_t *src, size_t srcLen) const
{
if ( srcLen == wxNO_LEN )
srcLen = wxWcslen(src) + 1;
srcLen *= BYTES_PER_CHAR;
if ( dst )
{
if ( dstLen < srcLen )
return wxCONV_FAILED;
wxUint16 *outBuff = reinterpret_cast<wxUint16 *>(dst);
for ( size_t n = 0; n < srcLen; n += BYTES_PER_CHAR, src++ )
{
*outBuff++ = wxUINT16_SWAP_ALWAYS(*src);
}
}
return srcLen;
}
#else // !WC_UTF16: wchar_t is UTF-32
// ----------------------------------------------------------------------------
// conversions without endianness change
// ----------------------------------------------------------------------------
size_t
wxMBConvUTF16straight::ToWChar(wchar_t *dst, size_t dstLen,
const char *src, size_t srcLen) const
{
srcLen = GetLength(src, srcLen);
if ( srcLen == wxNO_LEN )
return wxCONV_FAILED;
const size_t inLen = srcLen / BYTES_PER_CHAR;
size_t outLen = 0;
const wxUint16 *inBuff = reinterpret_cast<const wxUint16 *>(src);
for ( const wxUint16 * const inEnd = inBuff + inLen; inBuff < inEnd; )
{
const wxUint32 ch = wxDecodeSurrogate(&inBuff);
if ( !inBuff )
return wxCONV_FAILED;
outLen++;
if ( dst )
{
if ( outLen > dstLen )
return wxCONV_FAILED;
*dst++ = ch;
}
}
return outLen;
}
size_t
wxMBConvUTF16straight::FromWChar(char *dst, size_t dstLen,
const wchar_t *src, size_t srcLen) const
{
if ( srcLen == wxNO_LEN )
srcLen = wxWcslen(src) + 1;
size_t outLen = 0;
wxUint16 *outBuff = reinterpret_cast<wxUint16 *>(dst);
for ( size_t n = 0; n < srcLen; n++ )
{
wxUint16 cc[2] = { 0 };
const size_t numChars = encode_utf16(*src++, cc);
if ( numChars == wxCONV_FAILED )
return wxCONV_FAILED;
outLen += numChars * BYTES_PER_CHAR;
if ( outBuff )
{
if ( outLen > dstLen )
return wxCONV_FAILED;
*outBuff++ = cc[0];
if ( numChars == 2 )
{
// second character of a surrogate
*outBuff++ = cc[1];
}
}
}
return outLen;
}
// ----------------------------------------------------------------------------
// endian-reversing conversions
// ----------------------------------------------------------------------------
size_t
wxMBConvUTF16swap::ToWChar(wchar_t *dst, size_t dstLen,
const char *src, size_t srcLen) const
{
srcLen = GetLength(src, srcLen);
if ( srcLen == wxNO_LEN )
return wxCONV_FAILED;
const size_t inLen = srcLen / BYTES_PER_CHAR;
size_t outLen = 0;
const wxUint16 *inBuff = reinterpret_cast<const wxUint16 *>(src);
for ( const wxUint16 * const inEnd = inBuff + inLen; inBuff < inEnd; )
{
wxUint32 ch;
wxUint16 tmp[2];
tmp[0] = wxUINT16_SWAP_ALWAYS(*inBuff);
inBuff++;
tmp[1] = wxUINT16_SWAP_ALWAYS(*inBuff);
const size_t numChars = decode_utf16(tmp, ch);
if ( numChars == wxCONV_FAILED )
return wxCONV_FAILED;
if ( numChars == 2 )
inBuff++;
outLen++;
if ( dst )
{
if ( outLen > dstLen )
return wxCONV_FAILED;
*dst++ = ch;
}
}
return outLen;
}
size_t
wxMBConvUTF16swap::FromWChar(char *dst, size_t dstLen,
const wchar_t *src, size_t srcLen) const
{
if ( srcLen == wxNO_LEN )
srcLen = wxWcslen(src) + 1;
size_t outLen = 0;
wxUint16 *outBuff = reinterpret_cast<wxUint16 *>(dst);
for ( const wchar_t *srcEnd = src + srcLen; src < srcEnd; src++ )
{
wxUint16 cc[2] = { 0 };
const size_t numChars = encode_utf16(*src, cc);
if ( numChars == wxCONV_FAILED )
return wxCONV_FAILED;
outLen += numChars * BYTES_PER_CHAR;
if ( outBuff )
{
if ( outLen > dstLen )
return wxCONV_FAILED;
*outBuff++ = wxUINT16_SWAP_ALWAYS(cc[0]);
if ( numChars == 2 )
{
// second character of a surrogate
*outBuff++ = wxUINT16_SWAP_ALWAYS(cc[1]);
}
}
}
return outLen;
}
#endif // WC_UTF16/!WC_UTF16
// ============================================================================
// UTF-32
// ============================================================================
#ifdef WORDS_BIGENDIAN
#define wxMBConvUTF32straight wxMBConvUTF32BE
#define wxMBConvUTF32swap wxMBConvUTF32LE
#else
#define wxMBConvUTF32swap wxMBConvUTF32BE
#define wxMBConvUTF32straight wxMBConvUTF32LE
#endif
WXDLLIMPEXP_DATA_BASE(wxMBConvUTF32LE) wxConvUTF32LE;
WXDLLIMPEXP_DATA_BASE(wxMBConvUTF32BE) wxConvUTF32BE;
/* static */
size_t wxMBConvUTF32Base::GetLength(const char *src, size_t srcLen)
{
if ( srcLen == wxNO_LEN )
{
// count the number of bytes in input, including the trailing NULs
const wxUint32 *inBuff = reinterpret_cast<const wxUint32 *>(src);
for ( srcLen = 1; *inBuff++; srcLen++ )
;
srcLen *= BYTES_PER_CHAR;
}
else // we already have the length
{
// we can only convert an entire number of UTF-32 characters
if ( srcLen % BYTES_PER_CHAR )
return wxCONV_FAILED;
}
return srcLen;
}
// case when in-memory representation is UTF-16
#ifdef WC_UTF16
// ----------------------------------------------------------------------------
// conversions without endianness change
// ----------------------------------------------------------------------------
size_t
wxMBConvUTF32straight::ToWChar(wchar_t *dst, size_t dstLen,
const char *src, size_t srcLen) const
{
srcLen = GetLength(src, srcLen);
if ( srcLen == wxNO_LEN )
return wxCONV_FAILED;
const wxUint32 *inBuff = reinterpret_cast<const wxUint32 *>(src);
const size_t inLen = srcLen / BYTES_PER_CHAR;
size_t outLen = 0;
for ( size_t n = 0; n < inLen; n++ )
{
wxUint16 cc[2] = { 0 };
const size_t numChars = encode_utf16(*inBuff++, cc);
if ( numChars == wxCONV_FAILED )
return wxCONV_FAILED;
outLen += numChars;
if ( dst )
{
if ( outLen > dstLen )
return wxCONV_FAILED;
*dst++ = cc[0];
if ( numChars == 2 )
{
// second character of a surrogate
*dst++ = cc[1];
}
}
}
return outLen;
}
size_t
wxMBConvUTF32straight::FromWChar(char *dst, size_t dstLen,
const wchar_t *src, size_t srcLen) const
{
if ( srcLen == wxNO_LEN )
srcLen = wxWcslen(src) + 1;
if ( !dst )
{
// optimization: return maximal space which could be needed for this
// string instead of the exact amount which could be less if there are
// any surrogates in the input
//
// we consider that surrogates are rare enough to make it worthwhile to
// avoid running the loop below at the cost of slightly extra memory
// consumption
return srcLen * BYTES_PER_CHAR;
}
wxUint32 *outBuff = reinterpret_cast<wxUint32 *>(dst);
size_t outLen = 0;
for ( const wchar_t * const srcEnd = src + srcLen; src < srcEnd; )
{
const wxUint32 ch = wxDecodeSurrogate(&src);
if ( !src )
return wxCONV_FAILED;
outLen += BYTES_PER_CHAR;
if ( outLen > dstLen )
return wxCONV_FAILED;
*outBuff++ = ch;
}
return outLen;
}
// ----------------------------------------------------------------------------
// endian-reversing conversions
// ----------------------------------------------------------------------------
size_t
wxMBConvUTF32swap::ToWChar(wchar_t *dst, size_t dstLen,
const char *src, size_t srcLen) const
{
srcLen = GetLength(src, srcLen);
if ( srcLen == wxNO_LEN )
return wxCONV_FAILED;
const wxUint32 *inBuff = reinterpret_cast<const wxUint32 *>(src);
const size_t inLen = srcLen / BYTES_PER_CHAR;
size_t outLen = 0;
for ( size_t n = 0; n < inLen; n++, inBuff++ )
{
wxUint16 cc[2] = { 0 };
const size_t numChars = encode_utf16(wxUINT32_SWAP_ALWAYS(*inBuff), cc);
if ( numChars == wxCONV_FAILED )
return wxCONV_FAILED;
outLen += numChars;
if ( dst )
{
if ( outLen > dstLen )
return wxCONV_FAILED;
*dst++ = cc[0];
if ( numChars == 2 )
{
// second character of a surrogate
*dst++ = cc[1];
}
}
}
return outLen;
}
size_t
wxMBConvUTF32swap::FromWChar(char *dst, size_t dstLen,
const wchar_t *src, size_t srcLen) const
{
if ( srcLen == wxNO_LEN )
srcLen = wxWcslen(src) + 1;
if ( !dst )
{
// optimization: return maximal space which could be needed for this
// string instead of the exact amount which could be less if there are
// any surrogates in the input
//
// we consider that surrogates are rare enough to make it worthwhile to
// avoid running the loop below at the cost of slightly extra memory
// consumption
return srcLen*BYTES_PER_CHAR;
}
wxUint32 *outBuff = reinterpret_cast<wxUint32 *>(dst);
size_t outLen = 0;
for ( const wchar_t * const srcEnd = src + srcLen; src < srcEnd; )
{
const wxUint32 ch = wxDecodeSurrogate(&src);
if ( !src )
return wxCONV_FAILED;
outLen += BYTES_PER_CHAR;
if ( outLen > dstLen )
return wxCONV_FAILED;
*outBuff++ = wxUINT32_SWAP_ALWAYS(ch);
}
return outLen;
}
#else // !WC_UTF16: wchar_t is UTF-32
// ----------------------------------------------------------------------------
// conversions without endianness change
// ----------------------------------------------------------------------------
size_t
wxMBConvUTF32straight::ToWChar(wchar_t *dst, size_t dstLen,
const char *src, size_t srcLen) const
{
// use memcpy() as it should be much faster than hand-written loop
srcLen = GetLength(src, srcLen);
if ( srcLen == wxNO_LEN )
return wxCONV_FAILED;
const size_t inLen = srcLen/BYTES_PER_CHAR;
if ( dst )
{
if ( dstLen < inLen )
return wxCONV_FAILED;
memcpy(dst, src, srcLen);
}
return inLen;
}
size_t
wxMBConvUTF32straight::FromWChar(char *dst, size_t dstLen,
const wchar_t *src, size_t srcLen) const
{
if ( srcLen == wxNO_LEN )
srcLen = wxWcslen(src) + 1;
srcLen *= BYTES_PER_CHAR;
if ( dst )
{
if ( dstLen < srcLen )
return wxCONV_FAILED;
memcpy(dst, src, srcLen);
}
return srcLen;
}
// ----------------------------------------------------------------------------
// endian-reversing conversions
// ----------------------------------------------------------------------------
size_t
wxMBConvUTF32swap::ToWChar(wchar_t *dst, size_t dstLen,
const char *src, size_t srcLen) const
{
srcLen = GetLength(src, srcLen);
if ( srcLen == wxNO_LEN )
return wxCONV_FAILED;
srcLen /= BYTES_PER_CHAR;
if ( dst )
{
if ( dstLen < srcLen )
return wxCONV_FAILED;
const wxUint32 *inBuff = reinterpret_cast<const wxUint32 *>(src);
for ( size_t n = 0; n < srcLen; n++, inBuff++ )
{
*dst++ = wxUINT32_SWAP_ALWAYS(*inBuff);
}
}
return srcLen;
}
size_t
wxMBConvUTF32swap::FromWChar(char *dst, size_t dstLen,
const wchar_t *src, size_t srcLen) const
{
if ( srcLen == wxNO_LEN )
srcLen = wxWcslen(src) + 1;
srcLen *= BYTES_PER_CHAR;
if ( dst )
{
if ( dstLen < srcLen )
return wxCONV_FAILED;
wxUint32 *outBuff = reinterpret_cast<wxUint32 *>(dst);
for ( size_t n = 0; n < srcLen; n += BYTES_PER_CHAR, src++ )
{
*outBuff++ = wxUINT32_SWAP_ALWAYS(*src);
}
}
return srcLen;
}
#endif // WC_UTF16/!WC_UTF16
// ============================================================================
// The classes doing conversion using the iconv_xxx() functions
// ============================================================================
#ifdef HAVE_ICONV
// VS: glibc 2.1.3 is broken in that iconv() conversion to/from UCS4 fails with
// E2BIG if output buffer is _exactly_ as big as needed. Such case is
// (unless there's yet another bug in glibc) the only case when iconv()
// returns with (size_t)-1 (which means error) and says there are 0 bytes
// left in the input buffer -- when _real_ error occurs,
// bytes-left-in-input buffer is non-zero. Hence, this alternative test for
// iconv() failure.
// [This bug does not appear in glibc 2.2.]
#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ <= 1
#define ICONV_FAILED(cres, bufLeft) ((cres == (size_t)-1) && \
(errno != E2BIG || bufLeft != 0))
#else
#define ICONV_FAILED(cres, bufLeft) (cres == (size_t)-1)
#endif
#define ICONV_CHAR_CAST(x) ((ICONV_CONST char **)(x))
#define ICONV_T_INVALID ((iconv_t)-1)
#if SIZEOF_WCHAR_T == 4
#define WC_BSWAP wxUINT32_SWAP_ALWAYS
#define WC_ENC wxFONTENCODING_UTF32
#elif SIZEOF_WCHAR_T == 2
#define WC_BSWAP wxUINT16_SWAP_ALWAYS
#define WC_ENC wxFONTENCODING_UTF16
#else // sizeof(wchar_t) != 2 nor 4
// does this ever happen?
#error "Unknown sizeof(wchar_t): please report this to wx-dev@lists.wxwindows.org"
#endif
// ----------------------------------------------------------------------------
// wxMBConv_iconv: encapsulates an iconv character set
// ----------------------------------------------------------------------------
class wxMBConv_iconv : public wxMBConv
{
public:
wxMBConv_iconv(const char *name);
virtual ~wxMBConv_iconv();
// implement base class virtual methods
virtual size_t ToWChar(wchar_t *dst, size_t dstLen,
const char *src, size_t srcLen = wxNO_LEN) const;
virtual size_t FromWChar(char *dst, size_t dstLen,
const wchar_t *src, size_t srcLen = wxNO_LEN) const;
virtual size_t GetMBNulLen() const;
#if wxUSE_UNICODE_UTF8
virtual bool IsUTF8() const;
#endif
virtual wxMBConv *Clone() const
{
wxMBConv_iconv *p = new wxMBConv_iconv(m_name);
p->m_minMBCharWidth = m_minMBCharWidth;
return p;
}
bool IsOk() const
{ return (m2w != ICONV_T_INVALID) && (w2m != ICONV_T_INVALID); }
protected:
// the iconv handlers used to translate from multibyte
// to wide char and in the other direction
iconv_t m2w,
w2m;
#if wxUSE_THREADS
// guards access to m2w and w2m objects
wxMutex m_iconvMutex;
#endif
private:
// the name (for iconv_open()) of a wide char charset -- if none is
// available on this machine, it will remain NULL
static wxString ms_wcCharsetName;
// true if the wide char encoding we use (i.e. ms_wcCharsetName) has
// different endian-ness than the native one
static bool ms_wcNeedsSwap;
// name of the encoding handled by this conversion
const char *m_name;
// cached result of GetMBNulLen(); set to 0 meaning "unknown"
// initially
size_t m_minMBCharWidth;
};
// make the constructor available for unit testing
WXDLLIMPEXP_BASE wxMBConv* new_wxMBConv_iconv( const char* name )
{
wxMBConv_iconv* result = new wxMBConv_iconv( name );
if ( !result->IsOk() )
{
delete result;
return 0;
}
return result;
}
wxString wxMBConv_iconv::ms_wcCharsetName;
bool wxMBConv_iconv::ms_wcNeedsSwap = false;
wxMBConv_iconv::wxMBConv_iconv(const char *name)
: m_name(wxStrdup(name))
{
m_minMBCharWidth = 0;
// check for charset that represents wchar_t:
if ( ms_wcCharsetName.empty() )
{
wxLogTrace(TRACE_STRCONV, wxT("Looking for wide char codeset:"));
#if wxUSE_FONTMAP
const wxChar *const *names = wxFontMapperBase::GetAllEncodingNames(WC_ENC);
#else // !wxUSE_FONTMAP
static const wxChar *const names_static[] =
{
#if SIZEOF_WCHAR_T == 4
wxT("UCS-4"),
#elif SIZEOF_WCHAR_T == 2
wxT("UCS-2"),
#endif
NULL
};
const wxChar *const *names = names_static;
#endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
for ( ; *names && ms_wcCharsetName.empty(); ++names )
{
const wxString nameCS(*names);
// first try charset with explicit bytesex info (e.g. "UCS-4LE"):
wxString nameXE(nameCS);
#ifdef WORDS_BIGENDIAN
nameXE += wxT("BE");
#else // little endian
nameXE += wxT("LE");
#endif
wxLogTrace(TRACE_STRCONV, wxT(" trying charset \"%s\""),
nameXE.c_str());
m2w = iconv_open(nameXE.ToAscii(), name);
if ( m2w == ICONV_T_INVALID )
{
// try charset w/o bytesex info (e.g. "UCS4")
wxLogTrace(TRACE_STRCONV, wxT(" trying charset \"%s\""),
nameCS.c_str());
m2w = iconv_open(nameCS.ToAscii(), name);
// and check for bytesex ourselves:
if ( m2w != ICONV_T_INVALID )
{
char buf[2], *bufPtr;
wchar_t wbuf[2];
size_t insz, outsz;
size_t res;
buf[0] = 'A';
buf[1] = 0;
wbuf[0] = 0;
insz = 2;
outsz = SIZEOF_WCHAR_T * 2;
char* wbufPtr = (char*)wbuf;
bufPtr = buf;
res = iconv(
m2w, ICONV_CHAR_CAST(&bufPtr), &insz,
&wbufPtr, &outsz);
if (ICONV_FAILED(res, insz))
{
wxLogLastError(wxT("iconv"));
wxLogError(_("Conversion to charset '%s' doesn't work."),
nameCS.c_str());
}
else // ok, can convert to this encoding, remember it
{
ms_wcCharsetName = nameCS;
ms_wcNeedsSwap = wbuf[0] != (wchar_t)buf[0];
}
}
}
else // use charset not requiring byte swapping
{
ms_wcCharsetName = nameXE;
}
}
wxLogTrace(TRACE_STRCONV,
wxT("iconv wchar_t charset is \"%s\"%s"),
ms_wcCharsetName.empty() ? wxString("<none>")
: ms_wcCharsetName,
ms_wcNeedsSwap ? wxT(" (needs swap)")
: wxT(""));
}
else // we already have ms_wcCharsetName
{
m2w = iconv_open(ms_wcCharsetName.ToAscii(), name);
}
if ( ms_wcCharsetName.empty() )
{
w2m = ICONV_T_INVALID;
}
else
{
w2m = iconv_open(name, ms_wcCharsetName.ToAscii());
if ( w2m == ICONV_T_INVALID )
{
wxLogTrace(TRACE_STRCONV,
wxT("\"%s\" -> \"%s\" works but not the converse!?"),
ms_wcCharsetName.c_str(), name);
}
}
}
wxMBConv_iconv::~wxMBConv_iconv()
{
free(const_cast<char *>(m_name));
if ( m2w != ICONV_T_INVALID )
iconv_close(m2w);
if ( w2m != ICONV_T_INVALID )
iconv_close(w2m);
}
size_t
wxMBConv_iconv::ToWChar(wchar_t *dst, size_t dstLen,
const char *src, size_t srcLen) const
{
if ( srcLen == wxNO_LEN )
{
// find the string length: notice that must be done differently for
// NUL-terminated strings and UTF-16/32 which are terminated with 2/4
// consecutive NULs
const size_t nulLen = GetMBNulLen();
switch ( nulLen )
{
default:
return wxCONV_FAILED;
case 1:
srcLen = strlen(src); // arguably more optimized than our version
break;
case 2:
case 4:
// for UTF-16/32 not only we need to have 2/4 consecutive NULs
// but they also have to start at character boundary and not
// span two adjacent characters
const char *p;
for ( p = src; NotAllNULs(p, nulLen); p += nulLen )
;
srcLen = p - src;
break;
}
// when we're determining the length of the string ourselves we count
// the terminating NUL(s) as part of it and always NUL-terminate the
// output
srcLen += nulLen;
}
// we express length in the number of (wide) characters but iconv always
// counts buffer sizes it in bytes
dstLen *= SIZEOF_WCHAR_T;
#if wxUSE_THREADS
// NB: iconv() is MT-safe, but each thread must use its own iconv_t handle.
// Unfortunately there are a couple of global wxCSConv objects such as
// wxConvLocal that are used all over wx code, so we have to make sure
// the handle is used by at most one thread at the time. Otherwise
// only a few wx classes would be safe to use from non-main threads
// as MB<->WC conversion would fail "randomly".
wxMutexLocker lock(wxConstCast(this, wxMBConv_iconv)->m_iconvMutex);
#endif // wxUSE_THREADS
size_t res, cres;
const char *pszPtr = src;
if ( dst )
{
char* bufPtr = (char*)dst;
// have destination buffer, convert there
size_t dstLenOrig = dstLen;
cres = iconv(m2w,
ICONV_CHAR_CAST(&pszPtr), &srcLen,
&bufPtr, &dstLen);
// convert the number of bytes converted as returned by iconv to the
// number of (wide) characters converted that we need
res = (dstLenOrig - dstLen) / SIZEOF_WCHAR_T;
if (ms_wcNeedsSwap)
{
// convert to native endianness
for ( unsigned i = 0; i < res; i++ )
dst[i] = WC_BSWAP(dst[i]);
}
}
else // no destination buffer
{
// convert using temp buffer to calculate the size of the buffer needed
wchar_t tbuf[256];
res = 0;
do
{
char* bufPtr = (char*)tbuf;
dstLen = 8 * SIZEOF_WCHAR_T;
cres = iconv(m2w,
ICONV_CHAR_CAST(&pszPtr), &srcLen,
&bufPtr, &dstLen );
res += 8 - (dstLen / SIZEOF_WCHAR_T);
}
while ((cres == (size_t)-1) && (errno == E2BIG));
}
if (ICONV_FAILED(cres, srcLen))
{
//VS: it is ok if iconv fails, hence trace only
wxLogTrace(TRACE_STRCONV, wxT("iconv failed: %s"), wxSysErrorMsg(wxSysErrorCode()));
return wxCONV_FAILED;
}
return res;
}
size_t wxMBConv_iconv::FromWChar(char *dst, size_t dstLen,
const wchar_t *src, size_t srcLen) const
{
#if wxUSE_THREADS
// NB: explained in MB2WC
wxMutexLocker lock(wxConstCast(this, wxMBConv_iconv)->m_iconvMutex);
#endif
if ( srcLen == wxNO_LEN )
srcLen = wxWcslen(src) + 1;
size_t inbuflen = srcLen * SIZEOF_WCHAR_T;
size_t outbuflen = dstLen;
size_t res, cres;
wchar_t *tmpbuf = 0;
if (ms_wcNeedsSwap)
{
// need to copy to temp buffer to switch endianness
// (doing WC_BSWAP twice on the original buffer won't work, as it
// could be in read-only memory, or be accessed in some other thread)
tmpbuf = (wchar_t *)malloc(inbuflen);
for ( size_t i = 0; i < srcLen; i++ )
tmpbuf[i] = WC_BSWAP(src[i]);
src = tmpbuf;
}
char* inbuf = (char*)src;
if ( dst )
{
// have destination buffer, convert there
cres = iconv(w2m, ICONV_CHAR_CAST(&inbuf), &inbuflen, &dst, &outbuflen);
res = dstLen - outbuflen;
}
else // no destination buffer
{
// convert using temp buffer to calculate the size of the buffer needed
char tbuf[256];
res = 0;
do
{
dst = tbuf;
outbuflen = WXSIZEOF(tbuf);
cres = iconv(w2m, ICONV_CHAR_CAST(&inbuf), &inbuflen, &dst, &outbuflen);
res += WXSIZEOF(tbuf) - outbuflen;
}
while ((cres == (size_t)-1) && (errno == E2BIG));
}
if (ms_wcNeedsSwap)
{
free(tmpbuf);
}
if (ICONV_FAILED(cres, inbuflen))
{
wxLogTrace(TRACE_STRCONV, wxT("iconv failed: %s"), wxSysErrorMsg(wxSysErrorCode()));
return wxCONV_FAILED;
}
return res;
}
size_t wxMBConv_iconv::GetMBNulLen() const
{
if ( m_minMBCharWidth == 0 )
{
wxMBConv_iconv * const self = wxConstCast(this, wxMBConv_iconv);
#if wxUSE_THREADS
// NB: explained in MB2WC
wxMutexLocker lock(self->m_iconvMutex);
#endif
const wchar_t *wnul = L"";
char buf[8]; // should be enough for NUL in any encoding
size_t inLen = sizeof(wchar_t),
outLen = WXSIZEOF(buf);
char *inBuff = (char *)wnul;
char *outBuff = buf;
if ( iconv(w2m, ICONV_CHAR_CAST(&inBuff), &inLen, &outBuff, &outLen) == (size_t)-1 )
{
self->m_minMBCharWidth = (size_t)-1;
}
else // ok
{
self->m_minMBCharWidth = outBuff - buf;
}
}
return m_minMBCharWidth;
}
#if wxUSE_UNICODE_UTF8
bool wxMBConv_iconv::IsUTF8() const
{
return wxStricmp(m_name, "UTF-8") == 0 ||
wxStricmp(m_name, "UTF8") == 0;
}
#endif
#endif // HAVE_ICONV
// ============================================================================
// Win32 conversion classes
// ============================================================================
#ifdef wxHAVE_WIN32_MB2WC
// from utils.cpp
#if wxUSE_FONTMAP
extern WXDLLIMPEXP_BASE long wxCharsetToCodepage(const char *charset);
extern WXDLLIMPEXP_BASE long wxEncodingToCodepage(wxFontEncoding encoding);
#endif
class wxMBConv_win32 : public wxMBConv
{
public:
wxMBConv_win32()
{
m_CodePage = CP_ACP;
m_minMBCharWidth = 0;
}
wxMBConv_win32(const wxMBConv_win32& conv)
: wxMBConv()
{
m_CodePage = conv.m_CodePage;
m_minMBCharWidth = conv.m_minMBCharWidth;
}
#if wxUSE_FONTMAP
wxMBConv_win32(const char* name)
{
m_CodePage = wxCharsetToCodepage(name);
m_minMBCharWidth = 0;
}
wxMBConv_win32(wxFontEncoding encoding)
{
m_CodePage = wxEncodingToCodepage(encoding);
m_minMBCharWidth = 0;
}
#endif // wxUSE_FONTMAP
virtual size_t MB2WC(wchar_t *buf, const char *psz, size_t n) const
{
// note that we have to use MB_ERR_INVALID_CHARS flag as it without it
// the behaviour is not compatible with the Unix version (using iconv)
// and break the library itself, e.g. wxTextInputStream::NextChar()
// wouldn't work if reading an incomplete MB char didn't result in an
// error
//
// Moreover, MB_ERR_INVALID_CHARS is only supported on Win 2K SP4 or
// Win XP or newer and it is not supported for UTF-[78] so we always
// use our own conversions in this case. See
// http://blogs.msdn.com/michkap/archive/2005/04/19/409566.aspx
// http://msdn.microsoft.com/library/en-us/intl/unicode_17si.asp
if ( m_CodePage == CP_UTF8 )
{
return wxMBConvUTF8().MB2WC(buf, psz, n);
}
if ( m_CodePage == CP_UTF7 )
{
return wxMBConvUTF7().MB2WC(buf, psz, n);
}
int flags = 0;
if ( (m_CodePage < 50000 && m_CodePage != CP_SYMBOL) &&
IsAtLeastWin2kSP4() )
{
flags = MB_ERR_INVALID_CHARS;
}
const size_t len = ::MultiByteToWideChar
(
m_CodePage, // code page
flags, // flags: fall on error
psz, // input string
-1, // its length (NUL-terminated)
buf, // output string
buf ? n : 0 // size of output buffer
);
if ( !len )
{
// function totally failed
return wxCONV_FAILED;
}
// if we were really converting and didn't use MB_ERR_INVALID_CHARS,
// check if we succeeded, by doing a double trip:
if ( !flags && buf )
{
const size_t mbLen = strlen(psz);
wxCharBuffer mbBuf(mbLen);
if ( ::WideCharToMultiByte
(
m_CodePage,
0,
buf,
-1,
mbBuf.data(),
mbLen + 1, // size in bytes, not length
NULL,
NULL
) == 0 ||
strcmp(mbBuf, psz) != 0 )
{
// we didn't obtain the same thing we started from, hence
// the conversion was lossy and we consider that it failed
return wxCONV_FAILED;
}
}
// note that it returns count of written chars for buf != NULL and size
// of the needed buffer for buf == NULL so in either case the length of
// the string (which never includes the terminating NUL) is one less
return len - 1;
}
virtual size_t WC2MB(char *buf, const wchar_t *pwz, size_t n) const
{
/*
we have a problem here: by default, WideCharToMultiByte() may
replace characters unrepresentable in the target code page with bad
quality approximations such as turning "1/2" symbol (U+00BD) into
"1" for the code pages which don't have it and we, obviously, want
to avoid this at any price
the trouble is that this function does it _silently_, i.e. it won't
even tell us whether it did or not... Win98/2000 and higher provide
WC_NO_BEST_FIT_CHARS but it doesn't work for the older systems and
we have to resort to a round trip, i.e. check that converting back
results in the same string -- this is, of course, expensive but
otherwise we simply can't be sure to not garble the data.
*/
// determine if we can rely on WC_NO_BEST_FIT_CHARS: according to MSDN
// it doesn't work with CJK encodings (which we test for rather roughly
// here...) nor with UTF-7/8 nor, of course, with Windows versions not
// supporting it
BOOL usedDef wxDUMMY_INITIALIZE(false);
BOOL *pUsedDef;
int flags;
if ( CanUseNoBestFit() && m_CodePage < 50000 )
{
// it's our lucky day
flags = WC_NO_BEST_FIT_CHARS;
pUsedDef = &usedDef;
}
else // old system or unsupported encoding
{
flags = 0;
pUsedDef = NULL;
}
const size_t len = ::WideCharToMultiByte
(
m_CodePage, // code page
flags, // either none or no best fit
pwz, // input string
-1, // it is (wide) NUL-terminated
buf, // output buffer
buf ? n : 0, // and its size
NULL, // default "replacement" char
pUsedDef // [out] was it used?
);
if ( !len )
{
// function totally failed
return wxCONV_FAILED;
}
// we did something, check if we really succeeded
if ( flags )
{
// check if the conversion failed, i.e. if any replacements
// were done
if ( usedDef )
return wxCONV_FAILED;
}
else // we must resort to double tripping...
{
// first we need to ensure that we really have the MB data: this is
// not the case if we're called with NULL buffer, in which case we
// need to do the conversion yet again
wxCharBuffer bufDef;
if ( !buf )
{
bufDef = wxCharBuffer(len);
buf = bufDef.data();
if ( !::WideCharToMultiByte(m_CodePage, flags, pwz, -1,
buf, len, NULL, NULL) )
return wxCONV_FAILED;
}
if ( !n )
n = wcslen(pwz);
wxWCharBuffer wcBuf(n);
if ( MB2WC(wcBuf.data(), buf, n + 1) == wxCONV_FAILED ||
wcscmp(wcBuf, pwz) != 0 )
{
// we didn't obtain the same thing we started from, hence
// the conversion was lossy and we consider that it failed
return wxCONV_FAILED;
}
}
// see the comment above for the reason of "len - 1"
return len - 1;
}
virtual size_t GetMBNulLen() const
{
if ( m_minMBCharWidth == 0 )
{
int len = ::WideCharToMultiByte
(
m_CodePage, // code page
0, // no flags
L"", // input string
1, // translate just the NUL
NULL, // output buffer
0, // and its size
NULL, // no replacement char
NULL // [out] don't care if it was used
);
wxMBConv_win32 * const self = wxConstCast(this, wxMBConv_win32);
switch ( len )
{
default:
wxLogDebug(wxT("Unexpected NUL length %d"), len);
self->m_minMBCharWidth = (size_t)-1;
break;
case 0:
self->m_minMBCharWidth = (size_t)-1;
break;
case 1:
case 2:
case 4:
self->m_minMBCharWidth = len;
break;
}
}
return m_minMBCharWidth;
}
virtual wxMBConv *Clone() const { return new wxMBConv_win32(*this); }
bool IsOk() const { return m_CodePage != -1; }
private:
static bool CanUseNoBestFit()
{
static int s_isWin98Or2k = -1;
if ( s_isWin98Or2k == -1 )
{
int verMaj, verMin;
switch ( wxGetOsVersion(&verMaj, &verMin) )
{
case wxOS_WINDOWS_9X:
s_isWin98Or2k = verMaj >= 4 && verMin >= 10;
break;
case wxOS_WINDOWS_NT:
s_isWin98Or2k = verMaj >= 5;
break;
default:
// unknown: be conservative by default
s_isWin98Or2k = 0;
break;
}
wxASSERT_MSG( s_isWin98Or2k != -1, wxT("should be set above") );
}
return s_isWin98Or2k == 1;
}
static bool IsAtLeastWin2kSP4()
{
#ifdef __WXWINCE__
return false;
#else
static int s_isAtLeastWin2kSP4 = -1;
if ( s_isAtLeastWin2kSP4 == -1 )
{
OSVERSIONINFOEX ver;
memset(&ver, 0, sizeof(ver));
ver.dwOSVersionInfoSize = sizeof(ver);
GetVersionEx((OSVERSIONINFO*)&ver);
s_isAtLeastWin2kSP4 =
((ver.dwMajorVersion > 5) || // Vista+
(ver.dwMajorVersion == 5 && ver.dwMinorVersion > 0) || // XP/2003
(ver.dwMajorVersion == 5 && ver.dwMinorVersion == 0 &&
ver.wServicePackMajor >= 4)) // 2000 SP4+
? 1 : 0;
}
return s_isAtLeastWin2kSP4 == 1;
#endif
}
// the code page we're working with
long m_CodePage;
// cached result of GetMBNulLen(), set to 0 initially meaning
// "unknown"
size_t m_minMBCharWidth;
};
#endif // wxHAVE_WIN32_MB2WC
// ============================================================================
// wxEncodingConverter based conversion classes
// ============================================================================
#if wxUSE_FONTMAP
class wxMBConv_wxwin : public wxMBConv
{
private:
void Init()
{
// Refuse to use broken wxEncodingConverter code for Mac-specific encodings.
// The wxMBConv_cf class does a better job.
m_ok = (m_enc < wxFONTENCODING_MACMIN || m_enc > wxFONTENCODING_MACMAX) &&
m2w.Init(m_enc, wxFONTENCODING_UNICODE) &&
w2m.Init(wxFONTENCODING_UNICODE, m_enc);
}
public:
// temporarily just use wxEncodingConverter stuff,
// so that it works while a better implementation is built
wxMBConv_wxwin(const char* name)
{
if (name)
m_enc = wxFontMapperBase::Get()->CharsetToEncoding(name, false);
else
m_enc = wxFONTENCODING_SYSTEM;
Init();
}
wxMBConv_wxwin(wxFontEncoding enc)
{
m_enc = enc;
Init();
}
size_t MB2WC(wchar_t *buf, const char *psz, size_t WXUNUSED(n)) const
{
size_t inbuf = strlen(psz);
if (buf)
{
if (!m2w.Convert(psz, buf))
return wxCONV_FAILED;
}
return inbuf;
}
size_t WC2MB(char *buf, const wchar_t *psz, size_t WXUNUSED(n)) const
{
const size_t inbuf = wxWcslen(psz);
if (buf)
{
if (!w2m.Convert(psz, buf))
return wxCONV_FAILED;
}
return inbuf;
}
virtual size_t GetMBNulLen() const
{
switch ( m_enc )
{
case wxFONTENCODING_UTF16BE:
case wxFONTENCODING_UTF16LE:
return 2;
case wxFONTENCODING_UTF32BE:
case wxFONTENCODING_UTF32LE:
return 4;
default:
return 1;
}
}
virtual wxMBConv *Clone() const { return new wxMBConv_wxwin(m_enc); }
bool IsOk() const { return m_ok; }
public:
wxFontEncoding m_enc;
wxEncodingConverter m2w, w2m;
private:
// were we initialized successfully?
bool m_ok;
wxDECLARE_NO_COPY_CLASS(wxMBConv_wxwin);
};
// make the constructors available for unit testing
WXDLLIMPEXP_BASE wxMBConv* new_wxMBConv_wxwin( const char* name )
{
wxMBConv_wxwin* result = new wxMBConv_wxwin( name );
if ( !result->IsOk() )
{
delete result;
return 0;
}
return result;
}
#endif // wxUSE_FONTMAP
// ============================================================================
// wxCSConv implementation
// ============================================================================
void wxCSConv::Init()
{
m_name = NULL;
m_convReal = NULL;
}
void wxCSConv::SetEncoding(wxFontEncoding encoding)
{
switch ( encoding )
{
case wxFONTENCODING_MAX:
case wxFONTENCODING_SYSTEM:
if ( m_name )
{
// It's ok to not have encoding value if we have a name for it.
m_encoding = wxFONTENCODING_SYSTEM;
}
else // No name neither.
{
// Fall back to the system default encoding in this case (not
// sure how much sense does this make but this is how the old
// code used to behave).
#if wxUSE_INTL
m_encoding = wxLocale::GetSystemEncoding();
if ( m_encoding == wxFONTENCODING_SYSTEM )
#endif // wxUSE_INTL
m_encoding = wxFONTENCODING_ISO8859_1;
}
break;
case wxFONTENCODING_DEFAULT:
// wxFONTENCODING_DEFAULT is same as US-ASCII in this context
m_encoding = wxFONTENCODING_ISO8859_1;
break;
default:
// Just use the provided encoding.
m_encoding = encoding;
}
}
wxCSConv::wxCSConv(const wxString& charset)
{
Init();
if ( !charset.empty() )
{
SetName(charset.ToAscii());
}
#if wxUSE_FONTMAP
SetEncoding(wxFontMapperBase::GetEncodingFromName(charset));
#else
SetEncoding(wxFONTENCODING_SYSTEM);
#endif
m_convReal = DoCreate();
}
wxCSConv::wxCSConv(wxFontEncoding encoding)
{
if ( encoding == wxFONTENCODING_MAX || encoding == wxFONTENCODING_DEFAULT )
{
wxFAIL_MSG( wxT("invalid encoding value in wxCSConv ctor") );
encoding = wxFONTENCODING_SYSTEM;
}
Init();
SetEncoding(encoding);
m_convReal = DoCreate();
}
wxCSConv::~wxCSConv()
{
Clear();
}
wxCSConv::wxCSConv(const wxCSConv& conv)
: wxMBConv()
{
Init();
SetName(conv.m_name);
SetEncoding(conv.m_encoding);
m_convReal = DoCreate();
}
wxCSConv& wxCSConv::operator=(const wxCSConv& conv)
{
Clear();
SetName(conv.m_name);
SetEncoding(conv.m_encoding);
m_convReal = DoCreate();
return *this;
}
void wxCSConv::Clear()
{
free(m_name);
m_name = NULL;
wxDELETE(m_convReal);
}
void wxCSConv::SetName(const char *charset)
{
if ( charset )
m_name = wxStrdup(charset);
}
#if wxUSE_FONTMAP
WX_DECLARE_HASH_MAP( wxFontEncoding, wxString, wxIntegerHash, wxIntegerEqual,
wxEncodingNameCache );
static wxEncodingNameCache gs_nameCache;
#endif
wxMBConv *wxCSConv::DoCreate() const
{
#if wxUSE_FONTMAP
wxLogTrace(TRACE_STRCONV,
wxT("creating conversion for %s"),
(m_name ? m_name
: (const char*)wxFontMapperBase::GetEncodingName(m_encoding).mb_str()));
#endif // wxUSE_FONTMAP
// check for the special case of ASCII or ISO8859-1 charset: as we have
// special knowledge of it anyhow, we don't need to create a special
// conversion object
if ( m_encoding == wxFONTENCODING_ISO8859_1 )
{
// don't convert at all
return NULL;
}
// we trust OS to do conversion better than we can so try external
// conversion methods first
//
// the full order is:
// 1. OS conversion (iconv() under Unix or Win32 API)
// 2. hard coded conversions for UTF
// 3. wxEncodingConverter as fall back
// step (1)
#ifdef HAVE_ICONV
#if !wxUSE_FONTMAP
if ( m_name )
#endif // !wxUSE_FONTMAP
{
#if wxUSE_FONTMAP
wxFontEncoding encoding(m_encoding);
#endif
if ( m_name )
{
wxMBConv_iconv *conv = new wxMBConv_iconv(m_name);
if ( conv->IsOk() )
return conv;
delete conv;
#if wxUSE_FONTMAP
encoding =
wxFontMapperBase::Get()->CharsetToEncoding(m_name, false);
#endif // wxUSE_FONTMAP
}
#if wxUSE_FONTMAP
{
const wxEncodingNameCache::iterator it = gs_nameCache.find(encoding);
if ( it != gs_nameCache.end() )
{
if ( it->second.empty() )
return NULL;
wxMBConv_iconv *conv = new wxMBConv_iconv(it->second.ToAscii());
if ( conv->IsOk() )
return conv;
delete conv;
}
const wxChar* const* names = wxFontMapperBase::GetAllEncodingNames(encoding);
// CS : in case this does not return valid names (eg for MacRoman)
// encoding got a 'failure' entry in the cache all the same,
// although it just has to be created using a different method, so
// only store failed iconv creation attempts (or perhaps we
// shoulnd't do this at all ?)
if ( names[0] != NULL )
{
for ( ; *names; ++names )
{
// FIXME-UTF8: wxFontMapperBase::GetAllEncodingNames()
// will need changes that will obsolete this
wxString name(*names);
wxMBConv_iconv *conv = new wxMBConv_iconv(name.ToAscii());
if ( conv->IsOk() )
{
gs_nameCache[encoding] = *names;
return conv;
}
delete conv;
}
gs_nameCache[encoding] = wxT(""); // cache the failure
}
}
#endif // wxUSE_FONTMAP
}
#endif // HAVE_ICONV
#ifdef wxHAVE_WIN32_MB2WC
{
#if wxUSE_FONTMAP
wxMBConv_win32 *conv = m_name ? new wxMBConv_win32(m_name)
: new wxMBConv_win32(m_encoding);
if ( conv->IsOk() )
return conv;
delete conv;
#else
return NULL;
#endif
}
#endif // wxHAVE_WIN32_MB2WC
#ifdef __DARWIN__
{
// leave UTF16 and UTF32 to the built-ins of wx
if ( m_name || ( m_encoding < wxFONTENCODING_UTF16BE ||
( m_encoding >= wxFONTENCODING_MACMIN && m_encoding <= wxFONTENCODING_MACMAX ) ) )
{
#if wxUSE_FONTMAP
wxMBConv_cf *conv = m_name ? new wxMBConv_cf(m_name)
: new wxMBConv_cf(m_encoding);
#else
wxMBConv_cf *conv = new wxMBConv_cf(m_encoding);
#endif
if ( conv->IsOk() )
return conv;
delete conv;
}
}
#endif // __DARWIN__
// step (2)
wxFontEncoding enc = m_encoding;
#if wxUSE_FONTMAP
if ( enc == wxFONTENCODING_SYSTEM && m_name )
{
// use "false" to suppress interactive dialogs -- we can be called from
// anywhere and popping up a dialog from here is the last thing we want to
// do
enc = wxFontMapperBase::Get()->CharsetToEncoding(m_name, false);
}
#endif // wxUSE_FONTMAP
switch ( enc )
{
case wxFONTENCODING_UTF7:
return new wxMBConvUTF7;
case wxFONTENCODING_UTF8:
return new wxMBConvUTF8;
case wxFONTENCODING_UTF16BE:
return new wxMBConvUTF16BE;
case wxFONTENCODING_UTF16LE:
return new wxMBConvUTF16LE;
case wxFONTENCODING_UTF32BE:
return new wxMBConvUTF32BE;
case wxFONTENCODING_UTF32LE:
return new wxMBConvUTF32LE;
default:
// nothing to do but put here to suppress gcc warnings
break;
}
// step (3)
#if wxUSE_FONTMAP
{
wxMBConv_wxwin *conv = m_name ? new wxMBConv_wxwin(m_name)
: new wxMBConv_wxwin(m_encoding);
if ( conv->IsOk() )
return conv;
delete conv;
}
wxLogTrace(TRACE_STRCONV,
wxT("encoding \"%s\" is not supported by this system"),
(m_name ? wxString(m_name)
: wxFontMapperBase::GetEncodingName(m_encoding)));
#endif // wxUSE_FONTMAP
return NULL;
}
bool wxCSConv::IsOk() const
{
// special case: no convReal created for wxFONTENCODING_ISO8859_1
if ( m_encoding == wxFONTENCODING_ISO8859_1 )
return true; // always ok as we do it ourselves
// m_convReal->IsOk() is called at its own creation, so we know it must
// be ok if m_convReal is non-NULL
return m_convReal != NULL;
}
size_t wxCSConv::ToWChar(wchar_t *dst, size_t dstLen,
const char *src, size_t srcLen) const
{
if (m_convReal)
return m_convReal->ToWChar(dst, dstLen, src, srcLen);
// latin-1 (direct)
if ( srcLen == wxNO_LEN )
srcLen = strlen(src) + 1; // take trailing NUL too
if ( dst )
{
if ( dstLen < srcLen )
return wxCONV_FAILED;
for ( size_t n = 0; n < srcLen; n++ )
dst[n] = (unsigned char)(src[n]);
}
return srcLen;
}
size_t wxCSConv::FromWChar(char *dst, size_t dstLen,
const wchar_t *src, size_t srcLen) const
{
if (m_convReal)
return m_convReal->FromWChar(dst, dstLen, src, srcLen);
// latin-1 (direct)
if ( srcLen == wxNO_LEN )
srcLen = wxWcslen(src) + 1;
if ( dst )
{
if ( dstLen < srcLen )
return wxCONV_FAILED;
for ( size_t n = 0; n < srcLen; n++ )
{
if ( src[n] > 0xFF )
return wxCONV_FAILED;
dst[n] = (char)src[n];
}
}
else // still need to check the input validity
{
for ( size_t n = 0; n < srcLen; n++ )
{
if ( src[n] > 0xFF )
return wxCONV_FAILED;
}
}
return srcLen;
}
size_t wxCSConv::GetMBNulLen() const
{
if ( m_convReal )
return m_convReal->GetMBNulLen();
// otherwise, we are ISO-8859-1
return 1;
}
#if wxUSE_UNICODE_UTF8
bool wxCSConv::IsUTF8() const
{
if ( m_convReal )
return m_convReal->IsUTF8();
// otherwise, we are ISO-8859-1
return false;
}
#endif
#if wxUSE_UNICODE
wxWCharBuffer wxSafeConvertMB2WX(const char *s)
{
if ( !s )
return wxWCharBuffer();
wxWCharBuffer wbuf(wxConvLibc.cMB2WX(s));
if ( !wbuf )
wbuf = wxMBConvUTF8().cMB2WX(s);
if ( !wbuf )
wbuf = wxConvISO8859_1.cMB2WX(s);
return wbuf;
}
wxCharBuffer wxSafeConvertWX2MB(const wchar_t *ws)
{
if ( !ws )
return wxCharBuffer();
wxCharBuffer buf(wxConvLibc.cWX2MB(ws));
if ( !buf )
buf = wxMBConvUTF8(wxMBConvUTF8::MAP_INVALID_UTF8_TO_OCTAL).cWX2MB(ws);
return buf;
}
#endif // wxUSE_UNICODE
// ----------------------------------------------------------------------------
// globals
// ----------------------------------------------------------------------------
// NB: The reason why we create converted objects in this convoluted way,
// using a factory function instead of global variable, is that they
// may be used at static initialization time (some of them are used by
// wxString ctors and there may be a global wxString object). In other
// words, possibly _before_ the converter global object would be
// initialized.
#undef wxConvLibc
#undef wxConvUTF8
#undef wxConvUTF7
#undef wxConvLocal
#undef wxConvISO8859_1
#define WX_DEFINE_GLOBAL_CONV2(klass, impl_klass, name, ctor_args) \
WXDLLIMPEXP_DATA_BASE(klass*) name##Ptr = NULL; \
WXDLLIMPEXP_BASE klass* wxGet_##name##Ptr() \
{ \
static impl_klass name##Obj ctor_args; \
return &name##Obj; \
} \
/* this ensures that all global converter objects are created */ \
/* by the time static initialization is done, i.e. before any */ \
/* thread is launched: */ \
static klass* gs_##name##instance = wxGet_##name##Ptr()
#define WX_DEFINE_GLOBAL_CONV(klass, name, ctor_args) \
WX_DEFINE_GLOBAL_CONV2(klass, klass, name, ctor_args)
#ifdef __INTELC__
// disable warning "variable 'xxx' was declared but never referenced"
#pragma warning(disable: 177)
#endif // Intel C++
#ifdef __WINDOWS__
WX_DEFINE_GLOBAL_CONV2(wxMBConv, wxMBConv_win32, wxConvLibc, wxEMPTY_PARAMETER_VALUE);
#elif 0 // defined(__WXOSX__)
WX_DEFINE_GLOBAL_CONV2(wxMBConv, wxMBConv_cf, wxConvLibc, (wxFONTENCODING_UTF8));
#else
WX_DEFINE_GLOBAL_CONV2(wxMBConv, wxMBConvLibc, wxConvLibc, wxEMPTY_PARAMETER_VALUE);
#endif
// NB: we can't use wxEMPTY_PARAMETER_VALUE as final argument here because it's
// passed to WX_DEFINE_GLOBAL_CONV2 after a macro expansion and so still
// provokes an error message about "not enough macro parameters"; and we
// can't use "()" here as the name##Obj declaration would be parsed as a
// function declaration then, so use a semicolon and live with an extra
// empty statement (and hope that no compilers warns about this)
WX_DEFINE_GLOBAL_CONV(wxMBConvStrictUTF8, wxConvUTF8, ;);
WX_DEFINE_GLOBAL_CONV(wxMBConvUTF7, wxConvUTF7, ;);
WX_DEFINE_GLOBAL_CONV(wxCSConv, wxConvLocal, (wxFONTENCODING_SYSTEM));
WX_DEFINE_GLOBAL_CONV(wxCSConv, wxConvISO8859_1, (wxFONTENCODING_ISO8859_1));
WXDLLIMPEXP_DATA_BASE(wxMBConv *) wxConvCurrent = wxGet_wxConvLibcPtr();
WXDLLIMPEXP_DATA_BASE(wxMBConv *) wxConvUI = wxGet_wxConvLocalPtr();
#ifdef __DARWIN__
// It is important to use this conversion object under Darwin as it ensures
// that Unicode strings are (re)composed correctly even though xnu kernel uses
// decomposed form internally (at least for the file names).
static wxMBConv_cf wxConvMacUTF8DObj(wxFONTENCODING_UTF8);
#endif
WXDLLIMPEXP_DATA_BASE(wxMBConv *) wxConvFileName =
#ifdef __DARWIN__
&wxConvMacUTF8DObj;
#else // !__DARWIN__
wxGet_wxConvLibcPtr();
#endif // __DARWIN__/!__DARWIN__
| gpl-2.0 |
npe9/slurm | contribs/phpext/slurm_php/tests/slurm_get_control_configuration_values_basic.phpt | 1286 | --TEST--
Test function slurm_get_control_configuration_values() by calling it with its expected arguments
--CREDIT--
Peter Vermeulen <nmb_pv@hotmail.com>
--SKIPIF--
<?php
extension_loaded("slurm") or die("skip slurm extension not loaded\n");
function_exists("slurm_get_control_configuration_values") or die("skip function slurm_get_control_configuration_values unavailable");
?>
--FILE--
<?php
echo "*** Test by calling method or function with its expected arguments ***\n";
$config_values_arr = slurm_get_control_configuration_values();
if(is_array($config_values_arr)){
if(count($config_values_arr)==0) {
$config_values_arr = -1;
}
}
if((gettype($config_values_arr)=="array") && ($config_values_arr != NULL)) {
echo "! slurm_get_control_configuration_values : SUCCESS";
} else if($config_values_arr == -3) {
echo "[SLURM:ERROR] -3 : Faulty variables ( or no variables ) where passed on";
} else if($config_values_arr == -2) {
echo "[SLURM:ERROR] -2 : Daemons not online";
} else if($config_values_arr == -1) {
echo "[SLURM:ERROR] -1 : No configuration data was found on your system";
} else {
echo "[SLURM:ERROR] -4 : ?Unknown?";
}
?>
--EXPECT--
*** Test by calling method or function with its expected arguments ***
! slurm_get_control_configuration_values : SUCCESS
| gpl-2.0 |
FIF/gemini_one | wp-content/plugins/theme-my-login/modules/user-moderation/admin/user-moderation-admin.php | 13764 | <?php
/**
* Holds Theme My Login User Moderation Admin class
*
* @package Theme_My_Login
* @subpackage Theme_My_Login_User_Moderation
* @since 6.0
*/
if ( ! class_exists( 'Theme_My_Login_User_Moderation_Admin' ) ) :
/**
* Theme My Login User Moderation Admin class
*
* @since 6.0
*/
class Theme_My_Login_User_Moderation_Admin extends Theme_My_Login_Abstract {
/**
* Holds options key
*
* @since 6.3
* @access protected
* @var string
*/
protected $options_key = 'theme_my_login_moderation';
/**
* Returns singleton instance
*
* @since 6.3
* @access public
* @return object
*/
public static function get_object( $class = null ) {
return parent::get_object( __CLASS__ );
}
/**
* Loads the module
*
* @since 6.0
* @access protected
*/
protected function load() {
add_action( 'tml_activate_user-moderation/user-moderation.php', array( &$this, 'activate' ) );
add_action( 'tml_uninstall_user-moderation/user-moderation.php', array( &$this, 'uninstall' ) );
add_action( 'tml_modules_loaded', array( &$this, 'modules_loaded' ) );
if ( is_multisite() )
return;
add_action( 'admin_menu', array( &$this, 'admin_menu' ) );
add_action( 'admin_init', array( &$this, 'admin_init' ) );
add_action( 'load-users.php', array( &$this, 'load_users_page' ) );
add_filter( 'user_row_actions', array( &$this, 'user_row_actions' ), 10, 2 );
add_action( 'delete_user', array( &$this, 'deny_user' ) );
}
/**
* Returns default options
*
* @since 6.3
* @access public
*
* @return array Default options
*/
public static function default_options() {
return Theme_My_Login_User_Moderation::default_options();
}
/**
* Activates the module
*
* Callback for "tml_activate_user-moderation/user-moderation.php" hook in method Theme_My_Login_Admin::activate_module()
*
* @see Theme_My_Login_Admin::activate_module()
* @since 6.0
* @access public
*
* @param object $theme_my_login Reference to global $theme_my_login object
*/
public function activate() {
if ( is_multisite() ) {
add_settings_error( $this->options_key, 'invalid_module', __( 'User Moderation is not currently compatible with multisite.', 'theme-my-login' ) );
return;
}
add_role( 'pending', 'Pending', array() );
}
/**
* Uninstalls the module
*
* Callback for "tml_uninstall_user-moderation/user-moderation.php" hook in method Theme_My_Login_Admin::uninstall()
*
* @see Theme_My_Login_Admin::uninstall()
* @since 6.3
* @access public
*/
public function uninstall() {
delete_option( $this->options_key );
remove_role( 'pending' );
}
/**
* Disables the module if multisite
*
* @since 6.3
* @access public
*/
public function modules_loaded() {
if ( is_multisite() ) {
$theme_my_login_admin = Theme_My_Login_Admin::get_object();
$active_modules = $theme_my_login_admin->get_option( 'active_modules' );
$active_modules = array_values( array_diff( $active_modules, array( 'user-moderation/user-moderation.php' ) ) );
$theme_my_login_admin->set_option( 'active_modules', $active_modules );
$theme_my_login_admin->save_options();
return;
}
}
/**
* Adds "Moderation" to Theme My Login menu
*
* Callback for "admin_menu" hook
*
* @since 6.0
* @access public
*/
public function admin_menu() {
add_submenu_page(
'theme_my_login',
__( 'Theme My Login User Moderation Settings', 'theme-my-login' ),
__( 'Moderation', 'theme-my-login' ),
'manage_options',
$this->options_key,
array( &$this, 'settings_page' )
);
add_settings_section( 'general', null, '__return_false', $this->options_key );
add_settings_field( 'type', __( 'Moderation Type', 'theme-my-login' ), array( &$this, 'settings_field_moderation_type' ), $this->options_key, 'general' );
}
/**
* Registers options group
*
* Callback for "admin_init" hook
*
* @since 6.0
* @access public
*/
public function admin_init() {
register_setting( $this->options_key, $this->options_key, array( &$this, 'save_settings' ) );
}
/**
* Renders settings page
*
* @since 6.3
* @access public
*/
public function settings_page() {
Theme_My_Login_Admin::settings_page( array(
'title' => __( 'Theme My Login User Moderation Settings', 'theme-my-login' ),
'options_key' => $this->options_key
) );
}
/**
* Renders Moderation Type settings field
*
* @since 6.3
* @access public
*/
public function settings_field_moderation_type() {
?>
<input name="<?php echo $this->options_key; ?>[type]" type="radio" id="<?php echo $this->options_key; ?>_type_none" value="none"<?php checked( $this->get_option( 'type' ), 'none' ); ?> />
<label for="<?php echo $this->options_key; ?>_type_none"><?php _e( 'None', 'theme-my-login' ); ?></label>
<p class="description"><?php _e( 'Check this option to require no moderation.', 'theme-my-login' ); ?></p>
<input name="<?php echo $this->options_key; ?>[type]" type="radio" id="<?php echo $this->options_key; ?>_type_email" value="email" <?php checked( $this->get_option( 'type' ), 'email' ); ?> />
<label for="<?php echo $this->options_key; ?>_type_email"><?php _e( 'E-mail Confirmation', 'theme-my-login' ); ?></label>
<p class="description"><?php _e( 'Check this option to require new users to confirm their e-mail address before they may log in.', 'theme-my-login' ); ?></p>
<input name="<?php echo $this->options_key; ?>[type]" type="radio" id="<?php echo $this->options_key; ?>_type_admin" value="admin" <?php checked( $this->get_option( 'type' ), 'admin' ); ?> />
<label for="<?php echo $this->options_key; ?>_type_admin"><?php _e( 'Admin Approval', 'theme-my-login' ); ?></label>
<p class="description"><?php _e( 'Check this option to require new users to be approved by an administrator before they may log in.', 'theme-my-login' ); ?></p>
<?php
}
/**
* Sanitizes settings
*
* @since 6.3
* @access public
*
* @param array $settings Posted settings
* @return array Sanitized settings
*/
public function save_settings( $settings ) {
return array(
'type' => in_array( $settings['type'], array( 'none', 'email', 'admin' ) ) ? $settings['type'] : 'none'
);
}
/**
* Attaches actions/filters explicitly to users.php
*
* Callback for "load-users.php" hook
*
* @since 6.0
* @access public
*/
public function load_users_page() {
add_action( 'admin_notices', array( &$this, 'admin_notices' ) );
// Is there an action?
if ( isset( $_GET['action'] ) ) {
// Is it a sanctioned action?
if ( in_array( $_GET['action'], array( 'approve', 'resendactivation' ) ) ) {
// Is there a user ID?
$user = isset( $_GET['user'] ) ? $_GET['user'] : '';
// No user ID?
if ( ! $user || ! current_user_can( 'edit_user', $user ) )
wp_die( __( 'You can’t edit that user.', 'theme-my-login' ) );
// Where did we come from?
$redirect_to = isset( $_REQUEST['wp_http_referer'] ) ? remove_query_arg( array( 'wp_http_referer', 'updated', 'delete_count' ), stripslashes( $_REQUEST['wp_http_referer'] ) ) : 'users.php';
switch ( $_GET['action'] ) {
case 'approve' :
check_admin_referer( 'approve-user' );
if ( ! self::approve_user( $user ) )
wp_die( __( 'You can’t edit that user.' ) );
$redirect_to = add_query_arg( 'update', 'approve', $redirect_to );
break;
case 'resendactivation' :
check_admin_referer( 'resend-activation' );
do_action( 'tml_user_activation_resend', $user );
if ( ! Theme_My_Login_User_Moderation::new_user_activation_notification( $user ) )
wp_die( __( 'The e-mail could not be sent.' ) . "<br />\n" . __( 'Possible reason: your host may have disabled the mail() function...' ) );
$redirect_to = add_query_arg( 'update', 'sendactivation', $redirect_to );
break;
}
wp_redirect( $redirect_to );
exit;
}
}
}
/**
* Adds update messages to the admin screen
*
* Callback for "admin_notices" hook in file admin-header.php
*
* @since 6.0
* @access public
*/
public function admin_notices() {
if ( isset( $_GET['update'] ) && in_array( $_GET['update'], array( 'approve', 'sendactivation' ) ) ) {
echo '<div id="message" class="updated fade"><p>';
if ( 'approve' == $_GET['update'] )
_e( 'User approved.', 'theme-my-login' );
elseif ( 'sendactivation' == $_GET['update'] )
_e( 'Activation sent.', 'theme-my-login' );
echo '</p></div>';
}
}
/**
* Adds "Approve" link for each pending user on users.php
*
* Callback for "user_row_actions" hook in {@internal unknown}
*
* @since 6.0
* @access public
*
* @param array $actions The user actions
* @param WP_User $user_object The current user object
* @return array The filtered user actions
*/
public function user_row_actions( $actions, $user_object ) {
$current_user = wp_get_current_user();
if ( $current_user->ID != $user_object->ID ) {
if ( in_array( 'pending', (array) $user_object->roles ) ) {
switch ( $this->get_option( 'type' ) ) {
case 'email' :
// Add "Resend Activation" link
$actions['resend-activation'] = sprintf( '<a href="%1$s">%2$s</a>',
add_query_arg( 'wp_http_referer',
urlencode( esc_url( stripslashes( $_SERVER['REQUEST_URI'] ) ) ),
wp_nonce_url( "users.php?action=resendactivation&user=$user_object->ID", 'resend-activation' )
),
__( 'Resend Activation', 'theme-my-login' )
);
break;
case 'admin' :
// Add "Approve" link
$actions['approve-user'] = sprintf( '<a href="%1$s">%2$s</a>',
add_query_arg( 'wp_http_referer',
urlencode( esc_url( stripslashes( $_SERVER['REQUEST_URI'] ) ) ),
wp_nonce_url( "users.php?action=approve&user=$user_object->ID", 'approve-user' )
),
__( 'Approve', 'theme-my-login' )
);
break;
}
}
}
return $actions;
}
/**
* Handles activating a new user by admin approval
*
* @since 6.0
* @access public
*
* @param int $user_id User's ID
* @return bool Returns false if not a valid user
*/
public static function approve_user( $user_id ) {
global $wpdb, $current_site;
$user_id = (int) $user_id;
// Get user by ID
$user = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->users WHERE ID = %d", $user_id ) );
if ( empty( $user ) )
return false;
do_action( 'approve_user', $user->ID );
// Clear the activation key if there is one
$wpdb->update( $wpdb->users, array( 'user_activation_key' => '' ), array( 'ID' => $user->ID ) );
$approval_role = apply_filters( 'tml_approval_role', get_option( 'default_role' ), $user->ID );
// Set user role
$user_object = new WP_User( $user->ID );
$user_object->set_role( $approval_role );
unset( $user_object );
// Check for plaintext pass
if ( ! $user_pass = get_user_meta( $user->ID, 'user_pass', true ) ) {
$user_pass = wp_generate_password();
wp_set_password( $user_pass, $user->ID );
}
// Delete plaintext pass
delete_user_meta( $user->ID, 'user_pass' );
if ( is_multisite() ) {
$blogname = $current_site->site_name;
} else {
// The blogname option is escaped with esc_html on the way into the database in sanitize_option
// we want to reverse this for the plain text arena of emails.
$blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
}
$message = sprintf( __( 'You have been approved access to %s', 'theme-my-login' ), $blogname ) . "\r\n\r\n";
$message .= sprintf( __( 'Username: %s', 'theme-my-login' ), $user->user_login ) . "\r\n";
$message .= sprintf( __( 'Password: %s', 'theme-my-login' ), $user_pass ) . "\r\n\r\n";
$message .= site_url( 'wp-login.php', 'login' ) . "\r\n";
$title = sprintf( __( '[%s] Registration Approved', 'theme-my-login' ), $blogname );
$title = apply_filters( 'user_approval_notification_title', $title, $user->ID );
$message = apply_filters( 'user_approval_notification_message', $message, $user_pass, $user->ID );
if ( $message && ! wp_mail( $user->user_email, $title, $message ) )
die( '<p>' . __( 'The e-mail could not be sent.' ) . "<br />\n" . __( 'Possible reason: your host may have disabled the mail() function...' ) . '</p>' );
return true;
}
/**
* Called upon deletion of a user in the "Pending" role
*
* @since 6.0
* @access public
*
* @param int $user_id User's ID
*/
public function deny_user( $user_id ) {
global $current_site;
$user_id = (int) $user_id;
$user = new WP_User( $user_id );
if ( ! in_array( 'pending', (array) $user->roles ) )
return;
do_action( 'deny_user', $user->ID );
if ( is_multisite() ) {
$blogname = $current_site->site_name;
} else {
// The blogname option is escaped with esc_html on the way into the database in sanitize_option
// we want to reverse this for the plain text arena of emails.
$blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
}
$message = sprintf( __( 'You have been denied access to %s', 'theme-my-login' ), $blogname );
$title = sprintf( __( '[%s] Registration Denied', 'theme-my-login' ), $blogname );
$title = apply_filters( 'user_denial_notification_title', $title, $user_id );
$message = apply_filters( 'user_denial_notification_message', $message, $user_id );
if ( $message && ! wp_mail( $user->user_email, $title, $message ) )
die( '<p>' . __( 'The e-mail could not be sent.' ) . "<br />\n" . __( 'Possible reason: your host may have disabled the mail() function...' ) . '</p>' );
}
}
Theme_My_Login_User_Moderation_Admin::get_object();
endif;
| gpl-2.0 |
sathish-ifline/iflinedevelopment | sites/all/modules/contrib/search_api_autocomplete/search_api_autocomplete.entity.php | 8533 | <?php
/**
* @file
* Contains SearchApiAutocompleteSearch.
*/
/**
* Describes the autocomplete settings for a certain search.
*/
class SearchApiAutocompleteSearch extends Entity {
// Entity properties, loaded from the database:
/**
* @var integer
*/
public $id;
/**
* @var string
*/
public $machine_name;
/**
* @var string
*/
public $name;
/**
* @var integer
*/
public $index_id;
/**
* @var string
*/
public $suggester_id;
/**
* @var string
*/
public $type;
/**
* @var boolean
*/
public $enabled;
/**
* An array of options for this search, containing any of the following:
* - results: Boolean indicating whether to also list the estimated number of
* results for each suggestion (if possible).
* - fields: Array containing the fulltext fields to use for autocompletion.
* - custom: An array of type-specific settings.
*
* @var array
*/
public $options = array();
// Inferred properties, for caching:
/**
* @var SearchApiIndex
*/
protected $index;
/**
* @var SearchApiServer
*/
protected $server;
/**
* The suggester plugin this search uses.
*
* @var SearchApiAutocompleteSuggesterInterface
*/
protected $suggester;
/**
* Constructs a SearchApiAutocompleteSearch.
*
* @param array $values
* The entity properties.
*/
public function __construct(array $values = array()) {
parent::__construct($values, 'search_api_autocomplete_search');
}
/**
* @return SearchApiIndex
* The index this search belongs to.
*/
public function index() {
if (!isset($this->index)) {
$this->index = search_api_index_load($this->index_id);
if (!$this->index) {
$this->index = FALSE;
}
}
return $this->index;
}
/**
* Retrieves the server this search would at the moment be executed on.
*
* @return SearchApiServer
* The server this search would at the moment be executed on.
*
* @throws SearchApiException
* If a server is set for the index but it doesn't exist.
*/
public function server() {
if (!isset($this->server)) {
if (!$this->index() || !$this->index()->server) {
$this->server = FALSE;
}
else {
$this->server = $this->index()->server();
if (!$this->server) {
$this->server = FALSE;
}
}
}
return $this->server;
}
/**
* Retrieves the ID of the suggester plugin for this search.
*
* @return string
* This search's suggester plugin's ID.
*/
public function getSuggesterId() {
return $this->suggester_id;
}
/**
* Retrieves the suggester plugin for this search.
*
* @param bool $reset
* (optional) If TRUE, clear the internal static cache and reload the
* suggester.
*
* @return SearchApiAutocompleteSuggesterInterface|null
* This search's suggester plugin, or NULL if it could not be loaded.
*/
public function getSuggester($reset = FALSE) {
if (!isset($this->suggester) || $reset) {
$configuration = !empty($this->options['suggester_configuration']) ? $this->options['suggester_configuration'] : array();
$this->suggester = search_api_autocomplete_suggester_load($this->suggester_id, $this, $configuration);
if (!$this->suggester) {
$variables['@search'] = $this->machine_name;
$variables['@index'] = $this->index() ? $this->index()->label() : $this->index_id;
$variables['@suggester_id'] = $this->suggester_id;
watchdog('search_api_autocomplete', 'Autocomplete search @search on index @index specifies an invalid suggester plugin @suggester_id.', $variables, WATCHDOG_ERROR);
$this->suggester = FALSE;
}
}
return $this->suggester ? $this->suggester : NULL;
}
/**
* Determines whether autocompletion is currently supported for this search.
*
* @return bool
* TRUE if autocompletion is possible for this search with the current
* settings; FALSE otherwise.
*/
public function supportsAutocompletion() {
return $this->index() && $this->getSuggester() && $this->getSuggester()->supportsIndex($this->index());
}
/**
* Helper method for altering a textfield form element to use autocompletion.
*/
public function alterElement(array &$element, array $fields = array()) {
if (search_api_autocomplete_access($this)) {
// Add option defaults (in case of updates from earlier versions).
$options = $this->options + array(
'submit_button_selector' => ':submit',
'autosubmit' => TRUE,
'min_length' => 1,
);
$fields_string = $fields ? implode(' ', $fields) : '-';
$module_path = drupal_get_path('module', 'search_api_autocomplete');
$autocomplete_path = 'search_api_autocomplete/' . $this->machine_name . '/' . $fields_string;
$element['#attached']['css'][] = $module_path . '/search_api_autocomplete.css';
$element['#attached']['js'][] = $module_path . '/search_api_autocomplete.js';
$js_settings = array();
if ($options['submit_button_selector'] != ':submit') {
$js_settings['selector'] = $options['submit_button_selector'];
}
if (($delay = variable_get('search_api_autocomplete_delay')) !== NULL) {
$js_settings['delay'] = $delay;
}
// Allow overriding of the default handler with a custom script.
$path_overrides = variable_get('search_api_autocomplete_scripts', array());
if (!empty($path_overrides[$this->machine_name])) {
$autocomplete_path = NULL;
$override = $path_overrides[$this->machine_name];
if (is_scalar($override)) {
$autocomplete_path = url($override, array('absolute' => TRUE, 'query' => array('machine_name' => $this->machine_name)));
}
elseif (!empty($override['#callback']) && is_callable($override['#callback'])) {
$autocomplete_path = call_user_func($override['#callback'], $this, $element, $override);
}
if (!$autocomplete_path) {
return;
}
$js_settings['custom_path'] = TRUE;
}
if ($js_settings) {
$element['#attached']['js'][] = array(
'type' => 'setting',
'data' => array(
'search_api_autocomplete' => array(
$this->machine_name => $js_settings,
),
),
);
}
$element['#autocomplete_path'] = $autocomplete_path;
$element += array('#attributes' => array());
$element['#attributes'] += array('class'=> array());
if ($options['autosubmit']) {
$element['#attributes']['class'][] = 'auto_submit';
}
$element['#attributes']['data-search-api-autocomplete-search'] = $this->machine_name;
if ($options['min_length'] > 1) {
$element['#attributes']['data-min-autocomplete-length'] = $options['min_length'];
}
}
}
/**
* Split a string with search keywords into two parts.
*
* The first part consists of all words the user has typed completely, the
* second one contains the beginning of the last, possibly incomplete word.
*
* @return array
* An array with $keys split into exactly two parts, both of which may be
* empty.
*/
public function splitKeys($keys) {
$keys = ltrim($keys);
// If there is whitespace or a quote on the right, all words have been
// completed.
if (rtrim($keys, " \"") != $keys) {
return array(rtrim($keys, ' '), '');
}
if (preg_match('/^(.*?)\s*"?([\S]*)$/', $keys, $m)) {
return array($m[1], $m[2]);
}
return array('', $keys);
}
/**
* Create the query that would be issued for this search for the complete keys.
*
* @param $complete
* A string containing the complete search keys.
* @param $incomplete
* A string containing the incomplete last search key.
*
* @return SearchApiQueryInterface
* The query that would normally be executed when only $complete was entered
* as the search keys for this search.
*
* @throws SearchApiException
* If the query couldn't be created.
*/
public function getQuery($complete, $incomplete) {
$info = search_api_autocomplete_get_types($this->type);
if (empty($info['create query'])) {
return NULL;
}
$query = $info['create query']($this, $complete, $incomplete);
if ($complete && !$query->getKeys()) {
$query->keys($complete);
}
return $query;
}
}
| gpl-2.0 |
kmcurry/3Scape | public/bower_components/font-awesome/js-packages/@fortawesome/free-solid-svg-icons/faDirections.d.ts | 398 | import { IconDefinition, IconPrefix, IconName } from "@fortawesome/fontawesome-common-types";
export const definition: IconDefinition;
export const faDirections: IconDefinition;
export const prefix: IconPrefix;
export const iconName: IconName;
export const width: number;
export const height: number;
export const ligatures: string[];
export const unicode: string;
export const svgPathData: string; | gpl-3.0 |
gamchantoi/AgroSHop-UTUAWARDS | engine/Shopware/Plugins/Default/Backend/SwagUpdate/Components/Checks/RegexCheck.php | 4745 | <?php
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*/
namespace ShopwarePlugins\SwagUpdate\Components\Checks;
use ShopwarePlugins\SwagUpdate\Components\CheckInterface;
use Enlight_Components_Snippet_Namespace as SnippetNamespace;
/**
* @category Shopware
* @copyright Copyright (c) shopware AG (http://www.shopware.com)
*/
class RegexCheck implements CheckInterface
{
const CHECK_TYPE = 'regex';
/**
* @param SnippetNamespace $namespace
* @param string $userLang
*/
public function __construct(SnippetNamespace $namespace, $userLang)
{
$this->namespace = $namespace;
$this->userLang = $userLang;
}
/**
* {@inheritdoc}
*/
public function canHandle($requirement)
{
return $requirement['type'] == self::CHECK_TYPE;
}
/**
* {@inheritdoc}
*/
public function check($requirement)
{
$results = array();
foreach ($requirement['value']['directories'] as $dir) {
$result = $this->scanDirectoryForRegex(
Shopware()->DocPath($dir),
$requirement['value']['expression'],
$requirement['value']['fileRegex']
);
$results = array_merge($results, $result);
}
$message = $this->extractLocalizedMessage($requirement['value']['message']);
if (empty($results)) {
return null;
} else {
$files = array_keys($results);
return array(
'type' => self::CHECK_TYPE,
'errorLevel' => $requirement['level'],
'description' => $requirement['description'],
'message' => sprintf($message, implode('<br>', $files))
);
}
}
/**
* Search for a given string
*
* @param string $path
* @param string $regex
* @param string $regexFile
* @return array
*/
private function scanDirectoryForRegex($path, $regex, $regexFile = null)
{
// Iterate the given path recursively
$directoryIterator = new \RecursiveDirectoryIterator($path);
// get a flat iterator
$iterator = new \RecursiveIteratorIterator($directoryIterator);
$results = array();
// Allow files to be filtered out by name
if (isset($regexFile) && !empty($regexFile)) {
$iterator = new \RegexIterator($iterator, $regexFile);
}
// Iterate the result, get file content, check for $regex matches
foreach ($iterator as $splFileInfo) {
if ($splFileInfo->isDir()) {
continue;
}
$realPath = $splFileInfo->getRealPath();
if (strpos($realPath, 'SwagUpdateCheck') !== false) {
continue;
}
$result = $this->searchFileForRegex($realPath, $regex);
if ($result) {
$results[$realPath] = $result;
}
}
return $results;
}
/**
* Searches inside a file for a given regex. Will return Match-Objects or false if no match was found
*
* @param $file
* @param $regex
* @return bool
*/
private function searchFileForRegex($file, $regex)
{
$content = file_get_contents($file);
if (preg_match_all($regex, $content, $matches)) {
return $matches;
}
return false;
}
/**
* @param $messages
* @return string
*/
private function extractLocalizedMessage($messages)
{
$languages = array(
$this->userLang,
'en',
'de',
);
while ($language = array_shift($languages)) {
if (isset($messages[$language])) {
return $messages[$language];
}
}
return '';
}
}
| agpl-3.0 |
fmacias64/Dato-Core | src/unity/python_deps/psutil/test/_osx.py | 5059 | #!/usr/bin/env python
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""OSX specific tests. These are implicitly run by test_psutil.py."""
import os
import re
import subprocess
import sys
import time
import psutil
from psutil._compat import PY3
from test_psutil import (TOLERANCE, sh, get_test_subprocess, reap_children,
retry_before_failing, unittest)
PAGESIZE = os.sysconf("SC_PAGE_SIZE")
def sysctl(cmdline):
"""Expects a sysctl command with an argument and parse the result
returning only the value of interest.
"""
p = subprocess.Popen(cmdline, shell=1, stdout=subprocess.PIPE)
result = p.communicate()[0].strip().split()[1]
if PY3:
result = str(result, sys.stdout.encoding)
try:
return int(result)
except ValueError:
return result
def vm_stat(field):
"""Wrapper around 'vm_stat' cmdline utility."""
out = sh('vm_stat')
for line in out.split('\n'):
if field in line:
break
else:
raise ValueError("line not found")
return int(re.search('\d+', line).group(0)) * PAGESIZE
class OSXSpecificTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.pid = get_test_subprocess().pid
@classmethod
def tearDownClass(cls):
reap_children()
def test_process_create_time(self):
cmdline = "ps -o lstart -p %s" % self.pid
p = subprocess.Popen(cmdline, shell=1, stdout=subprocess.PIPE)
output = p.communicate()[0]
if PY3:
output = str(output, sys.stdout.encoding)
start_ps = output.replace('STARTED', '').strip()
start_psutil = psutil.Process(self.pid).create_time()
start_psutil = time.strftime("%a %b %e %H:%M:%S %Y",
time.localtime(start_psutil))
self.assertEqual(start_ps, start_psutil)
def test_disks(self):
# test psutil.disk_usage() and psutil.disk_partitions()
# against "df -a"
def df(path):
out = sh('df -k "%s"' % path).strip()
lines = out.split('\n')
lines.pop(0)
line = lines.pop(0)
dev, total, used, free = line.split()[:4]
if dev == 'none':
dev = ''
total = int(total) * 1024
used = int(used) * 1024
free = int(free) * 1024
return dev, total, used, free
for part in psutil.disk_partitions(all=False):
usage = psutil.disk_usage(part.mountpoint)
dev, total, used, free = df(part.mountpoint)
self.assertEqual(part.device, dev)
self.assertEqual(usage.total, total)
# 10 MB tollerance
if abs(usage.free - free) > 10 * 1024 * 1024:
self.fail("psutil=%s, df=%s" % usage.free, free)
if abs(usage.used - used) > 10 * 1024 * 1024:
self.fail("psutil=%s, df=%s" % usage.used, used)
# --- virtual mem
def test_vmem_total(self):
sysctl_hwphymem = sysctl('sysctl hw.memsize')
self.assertEqual(sysctl_hwphymem, psutil.virtual_memory().total)
@retry_before_failing()
def test_vmem_free(self):
num = vm_stat("free")
self.assertAlmostEqual(psutil.virtual_memory().free, num,
delta=TOLERANCE)
@retry_before_failing()
def test_vmem_active(self):
num = vm_stat("active")
self.assertAlmostEqual(psutil.virtual_memory().active, num,
delta=TOLERANCE)
@retry_before_failing()
def test_vmem_inactive(self):
num = vm_stat("inactive")
self.assertAlmostEqual(psutil.virtual_memory().inactive, num,
delta=TOLERANCE)
@retry_before_failing()
def test_vmem_wired(self):
num = vm_stat("wired")
self.assertAlmostEqual(psutil.virtual_memory().wired, num,
delta=TOLERANCE)
# --- swap mem
def test_swapmem_sin(self):
num = vm_stat("Pageins")
self.assertEqual(psutil.swap_memory().sin, num)
def test_swapmem_sout(self):
num = vm_stat("Pageouts")
self.assertEqual(psutil.swap_memory().sout, num)
def test_swapmem_total(self):
tot1 = psutil.swap_memory().total
tot2 = 0
# OSX uses multiple cache files:
# http://en.wikipedia.org/wiki/Paging#OS_X
for name in os.listdir("/var/vm/"):
file = os.path.join("/var/vm", name)
if os.path.isfile(file):
tot2 += os.path.getsize(file)
self.assertEqual(tot1, tot2)
def test_main():
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.makeSuite(OSXSpecificTestCase))
result = unittest.TextTestRunner(verbosity=2).run(test_suite)
return result.wasSuccessful()
if __name__ == '__main__':
if not test_main():
sys.exit(1)
| agpl-3.0 |
gkneighb/insoshi | config/initializers/0_load_first.rb | 349 |
# Methods in this file need to be loaded first.
# This is because other initializers may depend on them.
# The funky filename? Rails loads the initializers in alphabetical order.
def development?
env_is('development')
end
def production?
env_is('production')
end
def test?
env_is('test')
end
def env_is(env)
ENV['RAILS_ENV'] == env
end | agpl-3.0 |
edwinspire/open-ams | openmonitoringsystem/opt/openmonitoringsystem/frontend/node_modules/jsdom/lib/jsdom/living/generated/LinkStyle.js | 2929 | "use strict";
const conversions = require("webidl-conversions");
const utils = require("./utils.js");
const impl = utils.implSymbol;
function LinkStyle() {
throw new TypeError("Illegal constructor");
}
Object.defineProperty(LinkStyle, "prototype", {
value: LinkStyle.prototype,
writable: false,
enumerable: false,
configurable: false
});
Object.defineProperty(LinkStyle.prototype, "sheet", {
get() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return utils.tryWrapperForImpl(this[impl]["sheet"]);
},
enumerable: true,
configurable: true
});
Object.defineProperty(LinkStyle.prototype, Symbol.toStringTag, {
value: "LinkStyle",
writable: false,
enumerable: false,
configurable: true
});
const iface = {
// When an interface-module that implements this interface as a mixin is loaded, it will append its own `.is()`
// method into this array. It allows objects that directly implements *those* interfaces to be recognized as
// implementing this mixin interface.
_mixedIntoPredicates: [],
is(obj) {
if (obj) {
if (utils.hasOwn(obj, impl) && obj[impl] instanceof Impl.implementation) {
return true;
}
for (const isMixedInto of module.exports._mixedIntoPredicates) {
if (isMixedInto(obj)) {
return true;
}
}
}
return false;
},
isImpl(obj) {
if (obj) {
if (obj instanceof Impl.implementation) {
return true;
}
const wrapper = utils.wrapperForImpl(obj);
for (const isMixedInto of module.exports._mixedIntoPredicates) {
if (isMixedInto(wrapper)) {
return true;
}
}
}
return false;
},
convert(obj, { context = "The provided value" } = {}) {
if (module.exports.is(obj)) {
return utils.implForWrapper(obj);
}
throw new TypeError(`${context} is not of type 'LinkStyle'.`);
},
create(constructorArgs, privateData) {
let obj = Object.create(LinkStyle.prototype);
obj = this.setup(obj, constructorArgs, privateData);
return obj;
},
createImpl(constructorArgs, privateData) {
let obj = Object.create(LinkStyle.prototype);
obj = this.setup(obj, constructorArgs, privateData);
return utils.implForWrapper(obj);
},
_internalSetup(obj) {},
setup(obj, constructorArgs, privateData) {
if (!privateData) privateData = {};
privateData.wrapper = obj;
this._internalSetup(obj);
Object.defineProperty(obj, impl, {
value: new Impl.implementation(constructorArgs, privateData),
writable: false,
enumerable: false,
configurable: true
});
obj[impl][utils.wrapperSymbol] = obj;
if (Impl.init) {
Impl.init(obj[impl], privateData);
}
return obj;
},
interface: LinkStyle,
expose: {}
}; // iface
module.exports = iface;
const Impl = require("../nodes/LinkStyle-impl.js");
| lgpl-3.0 |
caseydavenport/kubernetes | staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/types_jsonschema.go | 3279 | /*
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 apiextensions
// JSONSchemaProps is a JSON-Schema following Specification Draft 4 (http://json-schema.org/).
type JSONSchemaProps struct {
ID string
Schema JSONSchemaURL
Ref *string
Description string
Type string
Nullable bool
Format string
Title string
Default *JSON
Maximum *float64
ExclusiveMaximum bool
Minimum *float64
ExclusiveMinimum bool
MaxLength *int64
MinLength *int64
Pattern string
MaxItems *int64
MinItems *int64
UniqueItems bool
MultipleOf *float64
Enum []JSON
MaxProperties *int64
MinProperties *int64
Required []string
Items *JSONSchemaPropsOrArray
AllOf []JSONSchemaProps
OneOf []JSONSchemaProps
AnyOf []JSONSchemaProps
Not *JSONSchemaProps
Properties map[string]JSONSchemaProps
AdditionalProperties *JSONSchemaPropsOrBool
PatternProperties map[string]JSONSchemaProps
Dependencies JSONSchemaDependencies
AdditionalItems *JSONSchemaPropsOrBool
Definitions JSONSchemaDefinitions
ExternalDocs *ExternalDocumentation
Example *JSON
}
// JSON represents any valid JSON value.
// These types are supported: bool, int64, float64, string, []interface{}, map[string]interface{} and nil.
type JSON interface{}
// JSONSchemaURL represents a schema url.
type JSONSchemaURL string
// JSONSchemaPropsOrArray represents a value that can either be a JSONSchemaProps
// or an array of JSONSchemaProps. Mainly here for serialization purposes.
type JSONSchemaPropsOrArray struct {
Schema *JSONSchemaProps
JSONSchemas []JSONSchemaProps
}
// JSONSchemaPropsOrBool represents JSONSchemaProps or a boolean value.
// Defaults to true for the boolean property.
type JSONSchemaPropsOrBool struct {
Allows bool
Schema *JSONSchemaProps
}
// JSONSchemaDependencies represent a dependencies property.
type JSONSchemaDependencies map[string]JSONSchemaPropsOrStringArray
// JSONSchemaPropsOrStringArray represents a JSONSchemaProps or a string array.
type JSONSchemaPropsOrStringArray struct {
Schema *JSONSchemaProps
Property []string
}
// JSONSchemaDefinitions contains the models explicitly defined in this spec.
type JSONSchemaDefinitions map[string]JSONSchemaProps
// ExternalDocumentation allows referencing an external resource for extended documentation.
type ExternalDocumentation struct {
Description string
URL string
}
| apache-2.0 |
wangwangheng/jadx | jadx-core/src/test/java/jadx/tests/integration/loops/TestArrayForEach.java | 713 | package jadx.tests.integration.loops;
import jadx.core.dex.nodes.ClassNode;
import jadx.tests.api.IntegrationTest;
import org.junit.Test;
import static jadx.tests.api.utils.JadxMatchers.containsLines;
import static org.junit.Assert.assertThat;
public class TestArrayForEach extends IntegrationTest {
public static class TestCls {
private int test(int[] a) {
int sum = 0;
for (int n : a) {
sum += n;
}
return sum;
}
}
@Test
public void test() {
ClassNode cls = getClassNode(TestCls.class);
String code = cls.getCode().toString();
assertThat(code, containsLines(2,
"int sum = 0;",
"for (int n : a) {",
indent(1) + "sum += n;",
"}",
"return sum;"
));
}
}
| apache-2.0 |
algorich/active_merchant | test/remote/gateways/remote_authorize_net_cim_test.rb | 34091 | require 'test_helper'
require 'pp'
class AuthorizeNetCimTest < Test::Unit::TestCase
def setup
Base.mode = :test
@gateway = AuthorizeNetCimGateway.new(fixtures(:authorize_net))
@amount = 100
@credit_card = credit_card('4242424242424242')
@payment = {
:credit_card => @credit_card
}
@profile = {
:merchant_customer_id => 'Up to 20 chars', # Optional
:description => 'Up to 255 Characters', # Optional
:email => 'Up to 255 Characters', # Optional
:payment_profiles => { # Optional
:customer_type => 'individual', # Optional
:bill_to => address,
:payment => @payment
},
:ship_to_list => {
:first_name => 'John',
:last_name => 'Doe',
:company => 'Widgets, Inc',
:address1 => '1234 Fake Street',
:city => 'Anytown',
:state => 'MD',
:zip => '12345',
:country => 'USA',
:phone_number => '(123)123-1234', # Optional - Up to 25 digits (no letters)
:fax_number => '(123)123-1234' # Optional - Up to 25 digits (no letters)
}
}
@options = {
:ref_id => '1234', # Optional
:profile => @profile
}
end
def teardown
if @customer_profile_id
assert response = @gateway.delete_customer_profile(:customer_profile_id => @customer_profile_id)
assert_success response
@customer_profile_id = nil
end
end
def test_successful_profile_create_get_update_and_delete
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert_success response
assert response.test?
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert response.test?
assert_success response
assert_equal @customer_profile_id, response.authorization
assert_equal 'Successful.', response.message
assert response.params['profile']['payment_profiles']['customer_payment_profile_id'] =~ /\d+/, 'The customer_payment_profile_id should be a number'
assert_equal "XXXX#{@credit_card.last_digits}", response.params['profile']['payment_profiles']['payment']['credit_card']['card_number'], "The card number should contain the last 4 digits of the card we passed in #{@credit_card.last_digits}"
assert_equal @profile[:merchant_customer_id], response.params['profile']['merchant_customer_id']
assert_equal @profile[:description], response.params['profile']['description']
assert_equal @profile[:email], response.params['profile']['email']
assert_equal @profile[:payment_profiles][:customer_type], response.params['profile']['payment_profiles']['customer_type']
assert_equal @profile[:ship_to_list][:phone_number], response.params['profile']['ship_to_list']['phone_number']
assert_equal @profile[:ship_to_list][:company], response.params['profile']['ship_to_list']['company']
assert response = @gateway.update_customer_profile(:profile => {:customer_profile_id => @customer_profile_id, :email => 'new email address'})
assert response.test?
assert_success response
assert_nil response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert_nil response.params['profile']['merchant_customer_id']
assert_nil response.params['profile']['description']
assert_equal 'new email address', response.params['profile']['email']
end
# NOTE - prior_auth_capture should be used to complete an auth_only request
# (not capture_only as that will leak the authorization), so don't use this
# test as a template.
def test_successful_create_customer_profile_transaction_auth_only_and_then_capture_only_requests
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
@customer_payment_profile_id = response.params['profile']['payment_profiles']['customer_payment_profile_id']
assert response = @gateway.create_customer_profile_transaction(
:transaction => {
:customer_profile_id => @customer_profile_id,
:customer_payment_profile_id => @customer_payment_profile_id,
:type => :auth_only,
:amount => @amount
}
)
assert response.test?
assert_success response
assert_equal response.authorization, response.params['direct_response']['transaction_id']
assert_match %r{(?:(TESTMODE) )?This transaction has been approved.}, response.params['direct_response']['message']
assert response.params['direct_response']['approval_code'] =~ /\w{6}/
assert_equal "auth_only", response.params['direct_response']['transaction_type']
assert_equal "100.00", response.params['direct_response']['amount']
assert_match /\d+/, response.params['direct_response']['transaction_id']
approval_code = response.params['direct_response']['approval_code']
# Capture the previously authorized funds
assert response = @gateway.create_customer_profile_transaction(
:transaction => {
:customer_profile_id => @customer_profile_id,
:customer_payment_profile_id => @customer_payment_profile_id,
:type => :capture_only,
:amount => @amount,
:approval_code => approval_code
}
)
assert response.test?
assert_success response
assert_equal response.authorization, response.params['direct_response']['transaction_id']
assert_match %r{(?:(TESTMODE) )?This transaction has been approved.}, response.params['direct_response']['message']
assert_equal approval_code, response.params['direct_response']['approval_code']
assert_equal "capture_only", response.params['direct_response']['transaction_type']
assert_equal "100.00", response.params['direct_response']['amount']
end
def test_successful_create_customer_profile_transaction_auth_capture_request
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
@customer_payment_profile_id = response.params['profile']['payment_profiles']['customer_payment_profile_id']
assert response = @gateway.create_customer_profile_transaction(
:transaction => {
:customer_profile_id => @customer_profile_id,
:customer_payment_profile_id => @customer_payment_profile_id,
:type => :auth_capture,
:order => {
:invoice_number => '1234',
:description => 'Test Order Description',
:purchase_order_number => '4321'
},
:recurring_billing => true,
:card_code => '900', # authorize.net says this is a matching CVV
:amount => @amount
}
)
assert response.test?
assert_success response
assert_equal response.authorization, response.params['direct_response']['transaction_id']
assert_match %r{(?:(TESTMODE) )?This transaction has been approved.}, response.params['direct_response']['message']
assert response.params['direct_response']['approval_code'] =~ /\w{6}/
assert_equal "auth_capture", response.params['direct_response']['transaction_type']
assert_equal "100.00", response.params['direct_response']['amount']
assert_equal response.params['direct_response']['invoice_number'], '1234'
assert_equal response.params['direct_response']['order_description'], 'Test Order Description'
assert_equal response.params['direct_response']['purchase_order_number'], '4321'
end
def test_successful_create_customer_payment_profile_request
payment_profile = @options[:profile].delete(:payment_profiles)
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert_nil response.params['profile']['payment_profiles']
assert response = @gateway.create_customer_payment_profile(
:customer_profile_id => @customer_profile_id,
:payment_profile => payment_profile
)
assert response.test?
assert_success response
assert_nil response.authorization
assert customer_payment_profile_id = response.params['customer_payment_profile_id']
assert customer_payment_profile_id =~ /\d+/, "The customerPaymentProfileId should be numeric. It was #{customer_payment_profile_id}"
end
def test_successful_create_customer_payment_profile_request_with_bank_account
payment_profile = @options[:profile].delete(:payment_profiles)
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert_nil response.params['profile']['payment_profiles']
assert response = @gateway.create_customer_payment_profile(
:customer_profile_id => @customer_profile_id,
:payment_profile => {
:customer_type => 'individual', # Optional
:bill_to => @address,
:payment => {
:bank_account => {
:account_type => :checking,
:name_on_account => 'John Doe',
:echeck_type => :ccd,
:bank_name => 'Bank of America',
:routing_number => '123456789',
:account_number => '12345'
}
},
:drivers_license => {
:state => 'MD',
:number => '12345',
:date_of_birth => '1981-3-31'
},
:tax_id => '123456789'
}
)
assert response.test?
assert_success response
assert_nil response.authorization
assert customer_payment_profile_id = response.params['customer_payment_profile_id']
assert customer_payment_profile_id =~ /\d+/, "The customerPaymentProfileId should be numeric. It was #{customer_payment_profile_id}"
end
def test_successful_create_customer_shipping_address_request
shipping_address = @options[:profile].delete(:ship_to_list)
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert_nil response.params['profile']['ship_to_list']
assert response = @gateway.create_customer_shipping_address(
:customer_profile_id => @customer_profile_id,
:address => shipping_address
)
assert response.test?
assert_success response
assert_nil response.authorization
assert customer_address_id = response.params['customer_address_id']
assert customer_address_id =~ /\d+/, "The customerAddressId should be numeric. It was #{customer_address_id}"
end
def test_successful_get_customer_profile_with_multiple_payment_profiles
second_payment_profile = {
:customer_type => 'individual',
:bill_to => @address,
:payment => {
:credit_card => credit_card('1234123412341234')
}
}
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert response = @gateway.create_customer_payment_profile(
:customer_profile_id => @customer_profile_id,
:payment_profile => second_payment_profile
)
assert response.test?
assert_success response
assert_nil response.authorization
assert customer_payment_profile_id = response.params['customer_payment_profile_id']
assert customer_payment_profile_id =~ /\d+/, "The customerPaymentProfileId should be numeric. It was #{customer_payment_profile_id}"
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert_equal 2, response.params['profile']['payment_profiles'].size
assert_equal 'XXXX4242', response.params['profile']['payment_profiles'][0]['payment']['credit_card']['card_number']
assert_equal 'XXXX1234', response.params['profile']['payment_profiles'][1]['payment']['credit_card']['card_number']
end
def test_successful_delete_customer_payment_profile_request
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert customer_payment_profile_id = response.params['profile']['payment_profiles']['customer_payment_profile_id']
assert response = @gateway.delete_customer_payment_profile(
:customer_profile_id => @customer_profile_id,
:customer_payment_profile_id => customer_payment_profile_id
)
assert response.test?
assert_success response
assert_nil response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert_nil response.params['profile']['payment_profiles']
end
def test_successful_delete_customer_shipping_address_request
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert customer_address_id = response.params['profile']['ship_to_list']['customer_address_id']
assert response = @gateway.delete_customer_shipping_address(
:customer_profile_id => @customer_profile_id,
:customer_address_id => customer_address_id
)
assert response.test?
assert_success response
assert_nil response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert_nil response.params['profile']['ship_to_list']
end
def test_successful_get_customer_payment_profile_request
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert customer_payment_profile_id = response.params['profile']['payment_profiles']['customer_payment_profile_id']
assert response = @gateway.get_customer_payment_profile(
:customer_profile_id => @customer_profile_id,
:customer_payment_profile_id => customer_payment_profile_id
)
assert response.test?
assert_success response
assert_nil response.authorization
assert response.params['payment_profile']['customer_payment_profile_id'] =~ /\d+/, 'The customer_payment_profile_id should be a number'
assert_equal "XXXX#{@credit_card.last_digits}", response.params['payment_profile']['payment']['credit_card']['card_number'], "The card number should contain the last 4 digits of the card we passed in #{@credit_card.last_digits}"
assert_equal @profile[:payment_profiles][:customer_type], response.params['payment_profile']['customer_type']
end
def test_successful_get_customer_shipping_address_request
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert customer_address_id = response.params['profile']['ship_to_list']['customer_address_id']
assert response = @gateway.get_customer_shipping_address(
:customer_profile_id => @customer_profile_id,
:customer_address_id => customer_address_id
)
assert response.test?
assert_success response
assert_nil response.authorization
assert response.params['address']['customer_address_id'] =~ /\d+/, 'The customer_address_id should be a number'
assert_equal @profile[:ship_to_list][:city], response.params['address']['city']
end
def test_successful_update_customer_payment_profile_request
# Create a new Customer Profile with Payment Profile
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
# Get the customerPaymentProfileId
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert customer_payment_profile_id = response.params['profile']['payment_profiles']['customer_payment_profile_id']
# Get the customerPaymentProfile
assert response = @gateway.get_customer_payment_profile(
:customer_profile_id => @customer_profile_id,
:customer_payment_profile_id => customer_payment_profile_id
)
# The value before updating
assert_equal "XXXX4242", response.params['payment_profile']['payment']['credit_card']['card_number'], "The card number should contain the last 4 digits of the card we passed in 4242"
# Update the payment profile
assert response = @gateway.update_customer_payment_profile(
:customer_profile_id => @customer_profile_id,
:payment_profile => {
:customer_payment_profile_id => customer_payment_profile_id,
:payment => {
:credit_card => credit_card('1234123412341234')
}
}
)
assert response.test?
assert_success response
assert_nil response.authorization
# Get the updated payment profile
assert response = @gateway.get_customer_payment_profile(
:customer_profile_id => @customer_profile_id,
:customer_payment_profile_id => customer_payment_profile_id
)
# Show that the payment profile was updated
assert_equal "XXXX1234", response.params['payment_profile']['payment']['credit_card']['card_number'], "The card number should contain the last 4 digits of the card we passed in: 1234"
# Show that fields that were left out of the update were cleared
assert_nil response.params['payment_profile']['customer_type']
new_billing_address = response.params['payment_profile']['bill_to']
new_billing_address.update(:first_name => 'Frank', :last_name => 'Brown')
masked_credit_card = ActiveMerchant::Billing::CreditCard.new(:number => response.params['payment_profile']['payment']['credit_card']['card_number'])
# Update only the billing address with a masked card and expiration date
assert response = @gateway.update_customer_payment_profile(
:customer_profile_id => @customer_profile_id,
:payment_profile => {
:customer_payment_profile_id => customer_payment_profile_id,
:bill_to => new_billing_address,
:payment => {
:credit_card => masked_credit_card
}
}
)
# Get the updated payment profile
assert response = @gateway.get_customer_payment_profile(
:customer_profile_id => @customer_profile_id,
:customer_payment_profile_id => customer_payment_profile_id
)
# Show that the billing address on the payment profile was updated
assert_equal "Frank", response.params['payment_profile']['bill_to']['first_name'], "The billing address should contain the first name we passed in: Frank"
end
def test_successful_update_customer_shipping_address_request
# Create a new Customer Profile with Shipping Address
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
# Get the customerAddressId
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert customer_address_id = response.params['profile']['ship_to_list']['customer_address_id']
# Get the customerShippingAddress
assert response = @gateway.get_customer_shipping_address(
:customer_profile_id => @customer_profile_id,
:customer_address_id => customer_address_id
)
assert address = response.params['address']
# The value before updating
assert_equal "1234 Fake Street", address['address']
# Update the address and remove the phone_number
new_address = address.symbolize_keys.merge!(
:address => '5678 Fake Street'
)
new_address.delete(:phone_number)
#Update the shipping address
assert response = @gateway.update_customer_shipping_address(
:customer_profile_id => @customer_profile_id,
:address => new_address
)
assert response.test?
assert_success response
assert_nil response.authorization
# Get the updated shipping address
assert response = @gateway.get_customer_shipping_address(
:customer_profile_id => @customer_profile_id,
:customer_address_id => customer_address_id
)
# Show that the shipping address was updated
assert_equal "5678 Fake Street", response.params['address']['address']
# Show that fields that were left out of the update were cleared
assert_nil response.params['address']['phone_number']
end
def test_successful_validate_customer_payment_profile_request_live
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert @customer_payment_profile_id = response.params['profile']['payment_profiles']['customer_payment_profile_id']
assert @customer_address_id = response.params['profile']['ship_to_list']['customer_address_id']
assert response = @gateway.validate_customer_payment_profile(
:customer_profile_id => @customer_profile_id,
:customer_payment_profile_id => @customer_payment_profile_id,
:customer_address_id => @customer_address_id,
:validation_mode => :live
)
assert response.test?
assert_success response
assert_equal response.authorization, response.params['direct_response']['transaction_id']
assert_match %r{(?:(TESTMODE) )?This transaction has been approved.}, response.params['direct_response']['message']
end
def test_validate_customer_payment_profile_request_live_requires_billing_address
@options[:profile][:payment_profiles].delete(:bill_to)
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert @customer_payment_profile_id = response.params['profile']['payment_profiles']['customer_payment_profile_id']
assert @customer_address_id = response.params['profile']['ship_to_list']['customer_address_id']
assert response = @gateway.validate_customer_payment_profile(
:customer_profile_id => @customer_profile_id,
:customer_payment_profile_id => @customer_payment_profile_id,
:customer_address_id => @customer_address_id,
:validation_mode => :live
)
assert response.test?
assert_failure response
assert_equal "There is one or more missing or invalid required fields.", response.message
end
def test_validate_customer_payment_profile_request_old_does_not_require_billing_address
@options[:profile][:payment_profiles].delete(:bill_to)
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert @customer_payment_profile_id = response.params['profile']['payment_profiles']['customer_payment_profile_id']
assert @customer_address_id = response.params['profile']['ship_to_list']['customer_address_id']
assert response = @gateway.validate_customer_payment_profile(
:customer_profile_id => @customer_profile_id,
:customer_payment_profile_id => @customer_payment_profile_id,
:customer_address_id => @customer_address_id,
:validation_mode => :old
)
assert response.test?
assert_success response
assert_equal "Successful.", response.message
end
def test_should_create_duplicate_customer_profile_transactions_with_duplicate_window_alteration
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert @customer_payment_profile_id = response.params['profile']['payment_profiles']['customer_payment_profile_id']
key = (Time.now.to_f * 1000000).to_i.to_s
customer_profile_transaction = {
:transaction => {
:customer_profile_id => @customer_profile_id,
:customer_payment_profile_id => @customer_payment_profile_id,
:type => :auth_capture,
:order => {
:invoice_number => key.to_s,
:description => "Test Order Description #{key.to_s}",
:purchase_order_number => key.to_s
},
:amount => @amount
},
:extra_options => { "x_duplicate_window" => 1 }
}
assert response = @gateway.create_customer_profile_transaction(customer_profile_transaction)
assert_success response
assert_equal "Successful.", response.message
sleep(5)
assert response = @gateway.create_customer_profile_transaction(customer_profile_transaction)
assert_success response
assert_equal "Successful.", response.message
end
def test_should_create_customer_profile_transaction_auth_capture_and_then_void_request
response = get_and_validate_auth_capture_response
assert response = @gateway.create_customer_profile_transaction_for_void(
:transaction => {
:type => :void,
:trans_id => response.params['direct_response']['transaction_id']
}
)
assert_instance_of Response, response
assert_success response
assert_equal response.authorization, response.params['direct_response']['transaction_id']
assert_equal 'This transaction has been approved.', response.params['direct_response']['message']
end
def test_should_create_customer_profile_transaction_auth_capture_and_then_refund_using_profile_ids_request
response = get_and_validate_auth_capture_response
assert response = @gateway.create_customer_profile_transaction(
:transaction => {
:type => :refund,
:amount => 1,
:customer_profile_id => @customer_profile_id,
:customer_payment_profile_id => @customer_payment_profile_id,
:trans_id => response.params['direct_response']['transaction_id']
}
)
assert_instance_of Response, response
# You can't test refunds in TEST MODE. If you authorize or capture
# a transaction, and the transaction is not yet settled by the payment
# gateway, you cannot issue a refund. You get an error message
# saying "The referenced transaction does not meet the criteria for issuing a credit.".
assert_failure response
assert_equal 'The referenced transaction does not meet the criteria for issuing a credit.', response.params['direct_response']['message']
end
def test_should_create_customer_profile_transaction_auth_capture_and_then_refund_using_profile_ids_request_with_empty_order
response = get_and_validate_auth_capture_response
assert response = @gateway.create_customer_profile_transaction(
:transaction => {
:type => :refund,
:amount => 1,
:customer_profile_id => @customer_profile_id,
:customer_payment_profile_id => @customer_payment_profile_id,
:trans_id => response.params['direct_response']['transaction_id'],
:order => {}
}
)
assert_instance_of Response, response
# You can't test refunds in TEST MODE. If you authorize or capture
# a transaction, and the transaction is not yet settled by the payment
# gateway, you cannot issue a refund. You get an error message
# saying "The referenced transaction does not meet the criteria for issuing a credit.".
assert_failure response
assert_equal 'The referenced transaction does not meet the criteria for issuing a credit.', response.message
end
def test_should_create_customer_profile_transaction_auth_capture_and_then_refund_using_masked_credit_card_request
response = get_and_validate_auth_capture_response
assert response = @gateway.create_customer_profile_transaction(
:transaction => {
:type => :refund,
:amount => 1,
:credit_card_number_masked => 'XXXX4242',
:trans_id => response.params['direct_response']['transaction_id']
}
)
assert_instance_of Response, response
# You can't test refunds in TEST MODE. If you authorize or capture
# a transaction, and the transaction is not yet settled by the payment
# gateway, you cannot issue a refund. You get an error message
# saying "The referenced transaction does not meet the criteria for issuing a credit.".
assert_failure response
assert_equal 'The referenced transaction does not meet the criteria for issuing a credit.', response.params['direct_response']['message']
end
def test_should_create_customer_profile_transaction_auth_only_and_then_prior_auth_capture_request
response = get_and_validate_auth_only_response
assert response = @gateway.create_customer_profile_transaction(
:transaction => {
:type => :prior_auth_capture,
:trans_id => response.params['direct_response']['transaction_id'],
:amount => response.params['direct_response']['amount']
}
)
assert_instance_of Response, response
assert_success response
assert_equal response.authorization, response.params['direct_response']['transaction_id']
assert_equal 'This transaction has been approved.', response.params['direct_response']['message']
return response
end
def get_and_validate_customer_payment_profile_request_with_bank_account_response
payment_profile = @options[:profile].delete(:payment_profiles)
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
assert_nil response.params['profile']['payment_profiles']
assert response = @gateway.create_customer_payment_profile(
:customer_profile_id => @customer_profile_id,
:payment_profile => {
:customer_type => 'individual', # Optional
:bill_to => @address,
:payment => {
:bank_account => {
:account_type => :checking,
:name_on_account => 'John Doe',
:echeck_type => :ccd,
:bank_name => 'Bank of America',
:routing_number => '123456789',
:account_number => '12345678'
}
},
:drivers_license => {
:state => 'MD',
:number => '12345',
:date_of_birth => '1981-3-31'
},
:tax_id => '123456789'
}
)
assert response.test?
assert_success response
assert_nil response.authorization
assert @customer_payment_profile_id = response.params['customer_payment_profile_id']
assert @customer_payment_profile_id =~ /\d+/, "The customerPaymentProfileId should be numeric. It was #{@customer_payment_profile_id}"
return response
end
def get_and_validate_auth_capture_response
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
@customer_payment_profile_id = response.params['profile']['payment_profiles']['customer_payment_profile_id']
key = (Time.now.to_f * 1000000).to_i.to_s
assert response = @gateway.create_customer_profile_transaction(
:transaction => {
:customer_profile_id => @customer_profile_id,
:customer_payment_profile_id => @customer_payment_profile_id,
:type => :auth_capture,
:order => {
:invoice_number => key.to_s,
:description => "Test Order Description #{key.to_s}",
:purchase_order_number => key.to_s
},
:amount => @amount
}
)
assert response.test?
assert_success response
assert_equal response.authorization, response.params['direct_response']['transaction_id']
assert_match %r{(?:(TESTMODE) )?This transaction has been approved.}, response.params['direct_response']['message']
assert response.params['direct_response']['approval_code'] =~ /\w{6}/
assert_equal "auth_capture", response.params['direct_response']['transaction_type']
assert_equal "100.00", response.params['direct_response']['amount']
assert_equal response.params['direct_response']['invoice_number'], key.to_s
assert_equal response.params['direct_response']['order_description'], "Test Order Description #{key.to_s}"
assert_equal response.params['direct_response']['purchase_order_number'], key.to_s
return response
end
def get_and_validate_auth_only_response
assert response = @gateway.create_customer_profile(@options)
@customer_profile_id = response.authorization
key = (Time.now.to_f * 1000000).to_i.to_s
assert response = @gateway.get_customer_profile(:customer_profile_id => @customer_profile_id)
@customer_payment_profile_id = response.params['profile']['payment_profiles']['customer_payment_profile_id']
assert response = @gateway.create_customer_profile_transaction(
:transaction => {
:customer_profile_id => @customer_profile_id,
:customer_payment_profile_id => @customer_payment_profile_id,
:type => :auth_only,
:order => {
:invoice_number => key.to_s,
:description => "Test Order Description #{key.to_s}",
:purchase_order_number => key.to_s
},
:amount => @amount
}
)
assert response.test?
assert_success response
assert_equal response.authorization, response.params['direct_response']['transaction_id']
assert response.params['direct_response']['approval_code'] =~ /\w{6}/
assert_equal "auth_only", response.params['direct_response']['transaction_type']
assert_equal "100.00", response.params['direct_response']['amount']
return response
end
end
| mit |
kidwu/cocos2d-js-tiga | samples/js-tests/src/EffectsAdvancedTest/EffectsAdvancedTest.js | 12666 | /****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
var EffectsAdvancedTest = EffectsAdvancedTest || {};
EffectsAdvancedTest.TAG_TEXTLAYER = 1;
EffectsAdvancedTest.TAG_SPRITE1 = 1;
EffectsAdvancedTest.TAG_SPRITE2 = 2;
EffectsAdvancedTest.TAG_BACKGROUND = 1;
EffectsAdvancedTest.TAG_LABEL = 2;
EffectsAdvancedTest.IDC_NEXT = 100;
EffectsAdvancedTest.IDC_BACK = 101;
EffectsAdvancedTest.IDC_RESTART = 102;
var sceneIndex = -1;
var EffectAdvanceTextLayer = cc.Layer.extend({
_atlas:null,
_title:null,
rootNode: null,
ctor:function() {
this._super();
this.init();
},
onEnter:function () {
this._super();
// back gradient
this.rootNode = new cc.LayerGradient(cc.color(0, 0, 0, 255), cc.color(98, 99, 117, 255));
var nodeGrid = new cc.NodeGrid();
nodeGrid.addChild(this.rootNode);
this.addChild(nodeGrid, 0, EffectsAdvancedTest.TAG_BACKGROUND);
var bg = new cc.Sprite(s_back3);
//this.addChild(bg, 0, EffectsAdvancedTest.TAG_BACKGROUND);
this.rootNode.addChild(bg);
bg.x = winSize.width / 2;
bg.y = winSize.height / 2;
var grossini = new cc.Sprite(s_pathSister2);
var grossiniGrid = new cc.NodeGrid();
grossiniGrid.addChild(grossini);
this.rootNode.addChild(grossiniGrid, 1, EffectsAdvancedTest.TAG_SPRITE1);
grossini.x = winSize.width / 3;
grossini.y = winSize.height / 2;
var sc = cc.scaleBy(2, 5);
var sc_back = sc.reverse();
grossini.runAction(cc.sequence(sc, sc_back).repeatForever());
var tamara = new cc.Sprite(s_pathSister1);
var tamaraGrid = new cc.NodeGrid();
tamaraGrid.addChild(tamara);
this.rootNode.addChild(tamaraGrid, 1, EffectsAdvancedTest.TAG_SPRITE2);
tamara.x = winSize.width * 2 / 3;
tamara.y = winSize.height / 2;
var sc2 = cc.scaleBy(2, 5);
var sc2_back = sc2.reverse();
tamara.runAction(cc.sequence(sc2, sc2_back).repeatForever());
var label = new cc.LabelTTF(this.title(), "Arial", 28);
label.x = cc.visibleRect.center.x;
label.y = cc.visibleRect.top.y - 80;
this.addChild(label);
label.tag = EffectsAdvancedTest.TAG_LABEL;
var strSubtitle = this.subtitle();
if (strSubtitle != "") {
var subtitleLabel = new cc.LabelTTF(strSubtitle, "Arial", 16);
this.addChild(subtitleLabel, 101);
subtitleLabel.x = cc.visibleRect.center.x;
subtitleLabel.y = cc.visibleRect.top.y - 80;
}
var item1 = new cc.MenuItemImage(s_pathB1, s_pathB2, this.backCallback, this);
var item2 = new cc.MenuItemImage(s_pathR1, s_pathR2, this.restartCallback, this);
var item3 = new cc.MenuItemImage(s_pathF1, s_pathF2, this.nextCallback, this);
var menu = new cc.Menu(item1, item2, item3);
menu.x = 0;
menu.y = 0;
var centerx = cc.visibleRect.center.x, bottomy = cc.visibleRect.bottom.y;
item1.x = centerx - item2.width * 2;
item1.y = bottomy + item2.height / 2;
item2.x = centerx;
item2.y = bottomy + item2.height / 2;
item3.x = centerx + item2.width * 2;
item3.y = bottomy + item2.height / 2;
this.addChild(menu, 1);
},
title:function () {
return "No title";
},
subtitle:function () {
return "";
},
restartCallback:function (sender) {
var scene = new EffectAdvanceScene();
scene.addChild(restartEffectAdvanceAction());
cc.director.runScene(scene);
},
nextCallback:function (sender) {
var scene = new EffectAdvanceScene();
scene.addChild(nextEffectAdvanceAction());
cc.director.runScene(scene);
},
backCallback:function (sender) {
var scene = new EffectAdvanceScene();
scene.addChild(backEffectAdvanceAction());
cc.director.runScene(scene);
}
});
var Effect1 = EffectAdvanceTextLayer.extend({
title:function () {
return "Lens + Waves3d and OrbitCamera";
},
onEnter:function () {
this._super();
var target = this.getChildByTag(EffectsAdvancedTest.TAG_BACKGROUND);
// To reuse a grid the grid size and the grid type must be the same.
// in this case:
// Lens3D is Grid3D and it's size is (15,10)
// Waves3D is Grid3D and it's size is (15,10)
var size = cc.director.getWinSize();
var lens = cc.lens3D(0.0, cc.size(15, 10), cc.p(size.width / 2, size.height / 2), 240);
var waves = cc.waves3D(10, cc.size(15, 10), 18, 15);
var reuse = cc.reuseGrid(1);
var delay = cc.delayTime(8);
var orbit = cc.orbitCamera(5, 1, 2, 0, 180, 0, -90);
var orbit_back = orbit.reverse();
target.runAction(cc.sequence(orbit, orbit_back).repeatForever());
target.runAction(cc.sequence(lens, delay, reuse, waves));
}
});
var Effect2 = EffectAdvanceTextLayer.extend({
title:function () {
return "ShakyTiles + ShuffleTiles + TurnOffTiles";
},
onEnter:function () {
this._super();
var target = this.getChildByTag(EffectsAdvancedTest.TAG_BACKGROUND);
// To reuse a grid the grid size and the grid type must be the same.
// in this case:
// ShakyTiles is TiledGrid3D and it's size is (15,10)
// Shuffletiles is TiledGrid3D and it's size is (15,10)
// TurnOfftiles is TiledGrid3D and it's size is (15,10)
var shaky = cc.shakyTiles3D(5, cc.size(15, 10), 4, false);
var shuffle = cc.shuffleTiles(0, cc.size(15, 10), 3);
var turnoff = cc.turnOffTiles(0, cc.size(15, 10), 3);
var turnon = turnoff.reverse();
// reuse 2 times:
// 1 for shuffle
// 2 for turn off
// turnon tiles will use a new grid
var reuse = cc.reuseGrid(2);
var delay = cc.delayTime(1);
target.runAction(cc.sequence(shaky, delay, reuse, shuffle, delay.clone(), turnoff, turnon));
}
});
var Effect3 = EffectAdvanceTextLayer.extend({
title:function () {
return "Effects on 2 sprites";
},
onEnter:function () {
this._super();
var bg = this.getChildByTag(EffectsAdvancedTest.TAG_BACKGROUND);
var target1 = this.rootNode.getChildByTag(EffectsAdvancedTest.TAG_SPRITE1);
var target2 = this.rootNode.getChildByTag(EffectsAdvancedTest.TAG_SPRITE2);
var waves = cc.waves(5, cc.size(15, 10), 5, 20, true, false);
var shaky = cc.shaky3D(5, cc.size(15, 10), 4, false);
target1.runAction(waves.repeatForever());
target2.runAction(shaky.repeatForever());
// moving background. Testing issue #244
var move = cc.moveBy(3, cc.p(200, 0));
bg.runAction(cc.sequence(move, move.reverse()).repeatForever());
}
});
var Lens3DTarget = cc.Node.extend({
_lens3D:null,
ctor:function() {
this._super();
this.init();
},
update: function(dt) {
this._lens3D.x = this.x;
this._lens3D.y = this.y;
},
onEnter: function() {
cc.log("Lens3DTarget onEnter");
this.scheduleUpdate();
},
onExit: function() {
cc.log("Lens3DTarget onExit");
this.unscheduleUpdate();
}
});
Lens3DTarget.create = function (action) {
var target = new Lens3DTarget();
target._lens3D = action;
return target;
};
var Effect4 = EffectAdvanceTextLayer.extend({
title:function () {
return "Jumpy Lens3D";
},
onEnter:function () {
this._super();
var lens = cc.lens3D(10, cc.size(32, 24), cc.p(100, 180), 150);
var move = cc.jumpBy(5, cc.p(380, 0), 100, 4);
var move_back = move.reverse();
var seq = cc.sequence(move, move_back);
/* In cocos2d-iphone, the type of action's target is 'id', so it supports using the instance of 'CCLens3D' as its target.
While in cocos2d-x, the target of action only supports CCNode or its subclass,
so we make an encapsulation for CCLens3D to achieve that.
*/
var director = cc.director;
var target = Lens3DTarget.create(lens);
// Please make sure the target been added to its parent.
this.addChild(target);
director.getActionManager().addAction(seq, target, false);
this.runAction(cc.sequence(lens, cc.callFunc(
function(sender) {
sender.removeChild(target, true);
}
)));
}
});
var Effect5 = EffectAdvanceTextLayer.extend({
title:function () {
return "Test Stop-Copy-Restar";
},
onEnter:function () {
this._super();
var effect = cc.liquid(2, cc.size(32, 24), 1, 20);
var stopEffect = cc.sequence(effect, cc.delayTime(2), cc.stopGrid());
var bg = this.getChildByTag(EffectsAdvancedTest.TAG_BACKGROUND);
bg.runAction(stopEffect);
},
onExit:function () {
this._super();
cc.director.setProjection(cc.Director.PROJECTION_3D);
}
});
var Issue631 = EffectAdvanceTextLayer.extend({
title:function () {
return "Testing Opacity";
},
subtitle:function () {
return "Effect image should be 100% opaque. Testing issue #631";
},
onEnter:function () {
this._super();
var effect = cc.sequence(cc.delayTime(2.0), cc.shaky3D(5.0, cc.size(5, 5), 16, false));
// cleanup
var bg = this.getChildByTag(EffectsAdvancedTest.TAG_BACKGROUND);
this.removeChild(bg, true);
// background
var layer = new cc.LayerColor(cc.color(255, 0, 0, 255));
this.addChild(layer, -10);
var sprite = new cc.Sprite(s_pathGrossini);
sprite.x = 50;
sprite.y = 80;
layer.addChild(sprite, 10);
// foreground
var layer2 = new cc.LayerColor(cc.color(0, 255, 0, 255));
var fog = new cc.Sprite(s_pathFog);
fog.setBlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA);
var nodeGrid = new cc.NodeGrid();
layer2.addChild(fog, 1);
nodeGrid.addChild(layer2);
this.addChild(nodeGrid, 1);
nodeGrid.runAction(effect.repeatForever());
}
});
var arrayOfEffectsAdvancedTest = [
Effect3,
Effect2,
Effect1,
Effect5,
Issue631
];
if (!cc.sys.isNative)
arrayOfEffectsAdvancedTest.push(Effect4);
var nextEffectAdvanceAction = function () {
sceneIndex++;
sceneIndex = sceneIndex % arrayOfEffectsAdvancedTest.length;
if(window.sideIndexBar){
sceneIndex = window.sideIndexBar.changeTest(sceneIndex, 15);
}
return new arrayOfEffectsAdvancedTest[sceneIndex]();
};
var backEffectAdvanceAction = function () {
sceneIndex--;
if (sceneIndex < 0)
sceneIndex += arrayOfEffectsAdvancedTest.length;
if(window.sideIndexBar){
sceneIndex = window.sideIndexBar.changeTest(sceneIndex, 15);
}
return new arrayOfEffectsAdvancedTest[sceneIndex]();
};
var restartEffectAdvanceAction = function () {
return new arrayOfEffectsAdvancedTest[sceneIndex]();
};
var EffectAdvanceScene = TestScene.extend({
runThisTest:function () {
sceneIndex = -1;
var pLayer = nextEffectAdvanceAction();
this.addChild(pLayer);
cc.director.runScene(this);
}
});
| mit |
0814jimmy/jenkins | core/src/main/java/hudson/model/CheckPoint.java | 6307 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import hudson.tasks.BuildStep;
import hudson.tasks.Recorder;
import hudson.tasks.Builder;
import hudson.tasks.junit.JUnitResultArchiver;
import hudson.scm.SCM;
/**
* Provides a mechanism for synchronizing build executions in the face of concurrent builds.
*
* <p>
* At certain points of a build, {@link BuildStep}s and other extension points often need
* to refer to what happened in its earlier build. For example, a {@link SCM} check out
* can run concurrently, but the changelog computation requires that the check out of the
* earlier build has completed. Or if Hudson is sending out an e-mail, he needs to know
* the result of the previous build, so that he can decide an e-mail is necessary or not.
*
* <p>
* Check pointing is a primitive mechanism to provide this sort of synchronization.
* These methods can be only invoked from {@link Executor} threads.
*
* <p>
* Each {@link CheckPoint} instance represents unique check points. {@link CheckPoint}
* instances are normally created as a static instance, because two builds of the same project
* needs to refer to the same check point instance for synchronization to happen properly.
*
* <p>
* This class defines a few well-known check point instances. plugins can define
* their additional check points for their own use.
*
* <h2>Example</h2>
* <p>
* {@link JUnitResultArchiver} provides a good example of how a {@link Recorder} can
* depend on its earlier result.
*
* @author Kohsuke Kawaguchi
* @see BuildStep#getRequiredMonitorService()
* @since 1.319
*/
public final class CheckPoint {
private final Object identity;
private final String internalName;
/**
* For advanced uses. Creates a check point that uses the given object as its identity.
*/
public CheckPoint(String internalName, Object identity) {
this.internalName = internalName;
this.identity = identity;
}
/**
* @param internalName
* Name of this check point that's used in the logging, stack traces, debug messages, and so on.
* This is not displayed to users. No need for i18n.
*/
public CheckPoint(String internalName) {
this(internalName, new Object());
}
@Override
public boolean equals(Object that) {
if (that == null || getClass() != that.getClass()) return false;
return identity== ((CheckPoint) that).identity;
}
@Override
public int hashCode() {
return identity.hashCode();
}
@Override
public String toString() {
return "Check point "+internalName;
}
/**
* Records that the execution of the build has reached to a check point, idenified
* by the given identifier.
*
* <p>
* If the successive builds are {@linkplain #block() waiting for this check point},
* they'll be released.
*
* <p>
* This method can be only called from an {@link Executor} thread.
*/
public void report() {
Run.reportCheckpoint(this);
}
/**
* Waits until the previous build in progress reaches a check point, identified
* by the given identifier, or until the current executor becomes the youngest build in progress.
*
* <p>
* Note that "previous build in progress" should be interpreted as "previous (build in progress)" instead of
* "(previous build) if it's in progress". This makes a difference around builds that are aborted or
* failed very early without reporting the check points. Imagine the following time sequence:
*
* <ol>
* <li>Build #1, #2, and #3 happens around the same time
* <li>Build #3 waits for check point {@link JUnitResultArchiver}
* <li>Build #2 aborts before getting to that check point
* <li>Build #1 finally checks in {@link JUnitResultArchiver}
* </ol>
*
* <p>
* Using this method, build #3 correctly waits until the step 4. Because of this behavior,
* the {@link #report()}/{@link #block()} pair can normally
* be used without a try/finally block.
*
* <p>
* This method can be only called from an {@link Executor} thread.
*
* @throws InterruptedException
* If the build (represented by the calling executor thread) is aborted while it's waiting.
*/
public void block() throws InterruptedException {
Run.waitForCheckpoint(this);
}
/**
* {@link CheckPoint} that indicates that {@link AbstractBuild#getCulprits()} is computed.
*/
public static final CheckPoint CULPRITS_DETERMINED = new CheckPoint("CULPRITS_DETERMINED");
/**
* {@link CheckPoint} that indicates that the build is completed.
* ({@link AbstractBuild#isBuilding()}==false)
*/
public static final CheckPoint COMPLETED = new CheckPoint("COMPLETED");
/**
* {@link CheckPoint} that indicates that the build has finished executing the "main" portion
* ({@link Builder}s in case of {@link FreeStyleProject}) and now moving on to the post-build
* steps.
*/
public static final CheckPoint MAIN_COMPLETED = new CheckPoint("MAIN_COMPLETED");
}
| mit |
yangdd1205/spring-boot | spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java | 2357 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.condition;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.AnnotatedTypeMetadata;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link SpringBootCondition}.
*
* @author Phillip Webb
*/
@SuppressWarnings("resource")
class SpringBootConditionTests {
@Test
void sensibleClassException() {
assertThatIllegalStateException().isThrownBy(() -> new AnnotationConfigApplicationContext(ErrorOnClass.class))
.withMessageContaining("Error processing condition on " + ErrorOnClass.class.getName());
}
@Test
void sensibleMethodException() {
assertThatIllegalStateException().isThrownBy(() -> new AnnotationConfigApplicationContext(ErrorOnMethod.class))
.withMessageContaining("Error processing condition on " + ErrorOnMethod.class.getName() + ".myBean");
}
@Configuration(proxyBeanMethods = false)
@Conditional(AlwaysThrowsCondition.class)
static class ErrorOnClass {
}
@Configuration(proxyBeanMethods = false)
static class ErrorOnMethod {
@Bean
@Conditional(AlwaysThrowsCondition.class)
String myBean() {
return "bean";
}
}
static class AlwaysThrowsCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
throw new RuntimeException("Oh no!");
}
}
}
| mit |
vietvd88/developer-crawler | node_modules/react-bootstrap/es/Fade.js | 2310 | import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import Transition from 'react-overlays/lib/Transition';
var propTypes = {
/**
* Show the component; triggers the fade in or fade out animation
*/
'in': React.PropTypes.bool,
/**
* Unmount the component (remove it from the DOM) when it is faded out
*/
unmountOnExit: React.PropTypes.bool,
/**
* Run the fade in animation when the component mounts, if it is initially
* shown
*/
transitionAppear: React.PropTypes.bool,
/**
* Duration of the fade animation in milliseconds, to ensure that finishing
* callbacks are fired even if the original browser transition end events are
* canceled
*/
timeout: React.PropTypes.number,
/**
* Callback fired before the component fades in
*/
onEnter: React.PropTypes.func,
/**
* Callback fired after the component starts to fade in
*/
onEntering: React.PropTypes.func,
/**
* Callback fired after the has component faded in
*/
onEntered: React.PropTypes.func,
/**
* Callback fired before the component fades out
*/
onExit: React.PropTypes.func,
/**
* Callback fired after the component starts to fade out
*/
onExiting: React.PropTypes.func,
/**
* Callback fired after the component has faded out
*/
onExited: React.PropTypes.func
};
var defaultProps = {
'in': false,
timeout: 300,
unmountOnExit: false,
transitionAppear: false
};
var Fade = function (_React$Component) {
_inherits(Fade, _React$Component);
function Fade() {
_classCallCheck(this, Fade);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Fade.prototype.render = function render() {
return React.createElement(Transition, _extends({}, this.props, {
className: classNames(this.props.className, 'fade'),
enteredClassName: 'in',
enteringClassName: 'in'
}));
};
return Fade;
}(React.Component);
Fade.propTypes = propTypes;
Fade.defaultProps = defaultProps;
export default Fade; | mit |
guimurgel/gulp | node_modules/caniuse-lite/data/features/dom-manip-convenience.js | 803 | module.exports={A:{A:{"2":"J C G E B A TB"},B:{"2":"D X g H L"},C:{"1":"0 2 4 w x v z t s","2":"1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r PB OB"},D:{"1":"2 4 8 t s DB AB SB BB","2":"F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v","194":"0 z"},E:{"1":"B A IB JB","2":"7 F I J C G E CB EB FB GB HB"},F:{"1":"k l m n o p q r","2":"5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i KB LB MB NB QB y","194":"j"},G:{"1":"A aB bB","2":"3 7 9 G UB VB WB XB YB ZB"},H:{"2":"cB"},I:{"1":"s","2":"1 3 F dB eB fB gB hB iB"},J:{"2":"C B"},K:{"2":"5 6 B A D K y"},L:{"1":"8"},M:{"1":"t"},N:{"2":"B A"},O:{"2":"jB"},P:{"2":"F I"},Q:{"194":"kB"},R:{"2":"lB"}},B:1,C:"DOM manipulation convenience methods"};
| mit |
zaithottakath/mongoid | spec/mongoid/contextual/geo_near_spec.rb | 8140 | require "spec_helper"
describe Mongoid::Contextual::GeoNear do
describe "#average_distance" do
let!(:collection) do
Bar.collection
end
before do
Bar.create_indexes
end
let!(:bar_one) do
Bar.create(location: [ 52.30, 13.25 ])
end
let!(:bar_two) do
Bar.create(location: [ 52.30, 13.35 ])
end
context "when results are returned" do
let(:criteria) do
Bar.all
end
let(:geo_near) do
described_class.new(collection, criteria, [ 52, 13 ])
end
it "returns the average distance" do
expect(geo_near.average_distance).to_not be_nil
end
end
context "when no results are returned" do
let(:criteria) do
Bar.where(name: "Green Door")
end
let(:geo_near) do
described_class.new(collection, criteria, [ 52, 13 ])
end
it "returns 0.0" do
expect(geo_near.average_distance).to be_nil
end
end
end
describe "#each" do
let!(:collection) do
Bar.collection
end
before do
Bar.create_indexes
end
let!(:bar_one) do
Bar.create(location: [ 52.30, 13.25 ])
end
let!(:bar_two) do
Bar.create(location: [ 52.30, 13.35 ])
end
context "when no options are provided" do
let(:criteria) do
Bar.all
end
let(:geo_near) do
described_class.new(collection, criteria, [ 52, 13 ])
end
let(:results) do
geo_near.entries
end
it "returns all the documents" do
expect(results).to eq([ bar_one, bar_two ])
end
end
context "when the criteria has a limit" do
let(:criteria) do
Bar.limit(1)
end
let(:geo_near) do
described_class.new(collection, criteria, [ 52, 13 ])
end
let(:results) do
geo_near.entries
end
it "returns the limited documents" do
expect(results).to eq([ bar_one ])
end
end
context "when providing a max distance" do
let(:criteria) do
Bar.all
end
let(:geo_near) do
described_class.new(collection, criteria, [ 52, 13 ])
end
let(:results) do
geo_near.max_distance(0.40).entries
end
it "returns the limited documents" do
expect(results).to eq([ bar_one ])
end
end
context "when spcifying spherical" do
let(:criteria) do
Bar.all
end
let(:geo_near) do
described_class.new(collection, criteria, [ 52, 13 ])
end
let(:results) do
geo_near.spherical.entries
end
it "returns the documents" do
expect(results).to eq([ bar_one, bar_two ])
end
end
context "when providing a distance multiplier" do
let(:criteria) do
Bar.all
end
let(:geo_near) do
described_class.new(collection, criteria, [ 52, 13 ])
end
let(:results) do
geo_near.distance_multiplier(6378.1).entries
end
it "returns the documents" do
expect(results).to eq([ bar_one, bar_two ])
end
it "multiplies the distance factor" do
expect(results.first.geo_near_distance.to_i).to eq(2490)
end
end
context "when unique is false" do
let(:criteria) do
Bar.all
end
let(:geo_near) do
described_class.new(collection, criteria, [ 52, 13 ])
end
let(:results) do
geo_near.unique(false).entries
end
it "returns the documents" do
expect(results).to eq([ bar_one, bar_two ])
end
end
end
describe "#empty?" do
let!(:collection) do
Bar.collection
end
before do
Bar.create_indexes
end
let!(:bar_one) do
Bar.create(location: [ 52.30, 13.25 ])
end
let!(:bar_two) do
Bar.create(location: [ 52.30, 13.35 ])
end
let(:geo_near) do
described_class.new(collection, criteria, [ 52, 13 ])
end
context "when the $geoNear has results" do
let(:criteria) do
Bar.all
end
it "returns false" do
expect(geo_near).to_not be_empty
end
end
context "when the map/reduce has no results" do
let(:criteria) do
Bar.where(name: "Halo")
end
it "returns true" do
expect(geo_near).to be_empty
end
end
end
describe "#execute" do
let!(:collection) do
Bar.collection
end
before do
Bar.create_indexes
end
let!(:bar_one) do
Bar.create(location: [ 52.30, 13.25 ])
end
let!(:bar_two) do
Bar.create(location: [ 52.30, 13.35 ])
end
let(:criteria) do
Bar.all
end
let(:geo_near) do
described_class.new(collection, criteria, [ 52, 13 ])
end
let(:execution_results) do
geo_near.execute
end
it "returns a hash" do
expect(execution_results).to be_a_kind_of(Hash)
end
end
describe "#max_distance" do
let!(:collection) do
Bar.collection
end
before do
Bar.create_indexes
end
let!(:bar_one) do
Bar.create(location: [ 52.30, 13.25 ])
end
let!(:bar_two) do
Bar.create(location: [ 52.30, 13.35 ])
end
context "when results are returned" do
let(:criteria) do
Bar.all
end
let(:geo_near) do
described_class.new(collection, criteria, [ 52, 13 ])
end
it "returns the max distance" do
expect(geo_near.max_distance).to_not be_nil
end
end
context "when no results are returned" do
let(:criteria) do
Bar.where(name: "Green Door")
end
let(:geo_near) do
described_class.new(collection, criteria, [ 52, 13 ])
end
it "returns 0.0" do
expect(geo_near.max_distance).to eq(0.0)
end
end
end
describe "#min_distance" do
let!(:collection) do
Pub.collection
end
before do
Pub.create_indexes
end
let!(:bar_one) do
Pub.create(location: [ 52.30, 13.25 ])
end
let!(:bar_two) do
Pub.create(location: [ 52.30, 13.35 ])
end
context "when results are returned" do
let(:criteria) do
Pub.all
end
let(:geo_near) do
described_class.new(collection, criteria, [ 52, 13 ]).spherical.min_distance(0.0)
end
it "sets the min distance" do
expect(geo_near.to_a).to include(bar_one)
expect(geo_near.to_a).to include(bar_two)
end
end
end
describe "#inspect" do
let!(:collection) do
Bar.collection
end
before do
Bar.create_indexes
end
let!(:bar_one) do
Bar.create(location: [ 52.30, 13.25 ])
end
let!(:bar_two) do
Bar.create(location: [ 52.30, 13.35 ])
end
let(:criteria) do
Bar.all
end
let(:geo_near) do
described_class.new(collection, criteria, [ 52, 13 ])
end
it "contains the selector" do
expect(geo_near.inspect).to include("selector")
end
it "contains the class" do
expect(geo_near.inspect).to include("class")
end
it "contains the near" do
expect(geo_near.inspect).to include("near")
end
it "contains the multiplier" do
expect(geo_near.inspect).to include("multiplier")
end
it "contains the max" do
expect(geo_near.inspect).to include("max")
end
it "contains the unique" do
expect(geo_near.inspect).to include("unique")
end
it "contains the spherical" do
expect(geo_near.inspect).to include("spherical")
end
end
describe "#time" do
let!(:collection) do
Bar.collection
end
before do
Bar.create_indexes
end
let!(:bar_one) do
Bar.create(location: [ 52.30, 13.25 ])
end
let!(:bar_two) do
Bar.create(location: [ 52.30, 13.35 ])
end
let(:criteria) do
Bar.all
end
let(:geo_near) do
described_class.new(collection, criteria, [ 52, 13 ])
end
it "returns the execution time" do
expect(geo_near.time).to_not be_nil
end
end
end
| mit |
gkhanna79/corefx | src/System.DirectoryServices/src/Interop/AdsValue2.cs | 1138 | // 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.
namespace System.DirectoryServices.Interop
{
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
internal struct Ads_Pointer
{
public IntPtr value;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Ads_OctetString
{
public int length;
public IntPtr value;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Ads_Generic
{
public int a;
public int b;
public int c;
public int d;
}
[StructLayout(LayoutKind.Explicit)]
internal struct AdsValue
{
[FieldOffset(0)]
public int /*AdsType*/ dwType;
[FieldOffset(4)]
internal int pad;
[FieldOffset(8)]
public Ads_Pointer pointer;
[FieldOffset(8)]
public Ads_OctetString octetString;
[FieldOffset(8)]
public Ads_Generic generic;
}
}
| mit |
Jbartsch/onepage | profiles/onepage/modules/contrib/gmap/js/icon.js | 6739 | /**
* @file
* GIcon manager for GMap.
* Required for markers to operate properly.
*/
/*global jQuery, Drupal, GIcon, GPoint, GSize, G_DEFAULT_ICON */
/**
* Get the GIcon corresponding to a setname / sequence.
* There is only one GIcon for each slot in the sequence.
* The marker set wraps around when reaching the end of the sequence.
* @@@ TODO: Move this directly into the preparemarker event binding.
*/
Drupal.gmap.getIcon = function (setname, sequence) {
var othimg = ['printImage', 'mozPrintImage', 'printShadow', 'transparent'];
// If no setname, return google's default icon.
if (!setname) {
return;
}
if (!this.gicons) {
this.gicons = {};
}
if (!this.gshadows) {
this.gshadows = {};
}
// If no sequence, synthesise one.
if (!sequence) {
// @TODO make this per-map.
if (!this.sequences) {
this.sequences = {};
}
if (!this.sequences[setname]) {
this.sequences[setname] = -1;
}
this.sequences[setname]++;
sequence = this.sequences[setname];
}
if (!this.gicons[setname]) {
if (!Drupal.gmap.icons[setname]) {
alert('Request for invalid marker set ' + setname + '!');
}
this.gicons[setname] = [];
this.gshadows[setname] = [];
var q = Drupal.gmap.icons[setname];
var p, t;
for (var i = 0; i < q.sequence.length; i++) {
/*
t = new GIcon();
p = Drupal.gmap.iconpath + q.path;
t.image = p + q.sequence[i].f;
if (q.shadow.f !== '') {
t.shadow = p + q.shadow.f;
t.shadowSize = new GSize(q.shadow.w, q.shadow.h);
}
t.iconSize = new GSize(q.sequence[i].w, q.sequence[i].h);
t.iconAnchor = new GPoint(q.anchorX, q.anchorY);
t.infoWindowAnchor = new GPoint(q.infoX, q.infoY);
*/
p = Drupal.gmap.iconpath + q.path;
t = new google.maps.MarkerImage(p + q.sequence[i].f,
new google.maps.Size(q.sequence[i].w, q.sequence[i].h),
null,
new google.maps.Point(q.anchorX, q.anchorY)
);
if (q.shadow.f !== '') {
this.gshadows[setname][i] = new google.maps.MarkerImage(p + q.shadow.f,
new google.maps.Size(q.shadow.w, q.shadow.h),
null,
new google.maps.Point(q.anchorX, q.anchorY)
);
}
else {
this.gshadows[setname][i] = null;
}
for (var j = 0; j < othimg.length; j++) {
if (q[othimg[j]] !== '') {
t[othimg[j]] = p + q[othimg[j]];
}
}
// @@@ imageMap?
this.gicons[setname][i] = t;
}
delete Drupal.gmap.icons[setname];
}
// TODO: Random, other cycle methods.
return this.gicons[setname][sequence % this.gicons[setname].length];
};
Drupal.gmap.getShadow = function (setname, sequence) {
if (this.gshadows) return this.gshadows[setname][sequence % this.gicons[setname].length];
};
/**
* JSON callback to set up the icon defs.
* When doing the JSON call, the data comes back in a packed format.
* We need to expand it and file it away in a more useful format.
*/
Drupal.gmap.iconSetup = function () {
Drupal.gmap.icons = {};
var m = Drupal.gmap.icondata;
var filef, filew, fileh, files;
for (var path in m) {
if (m.hasOwnProperty(path)) {
// Reconstitute files array
filef = m[path].f;
filew = Drupal.gmap.expandArray(m[path].w, filef.length);
fileh = Drupal.gmap.expandArray(m[path].h, filef.length);
files = [];
for (var i = 0; i < filef.length; i++) {
files[i] = {f : filef[i], w : filew[i], h : fileh[i]};
}
for (var ini in m[path].i) {
if (m[path].i.hasOwnProperty(ini)) {
jQuery.extend(Drupal.gmap.icons, Drupal.gmap.expandIconDef(m[path].i[ini], path, files));
}
}
}
}
};
/**
* Expand a compressed array.
* This will pad arr up to len using the last value of the old array.
*/
Drupal.gmap.expandArray = function (arr, len) {
var d = arr[0];
for (var i = 0; i < len; i++) {
if (!arr[i]) {
arr[i] = d;
}
else {
d = arr[i];
}
}
return arr;
};
/**
* Expand icon definition.
* This helper function is the reverse of the packer function found in
* gmap_markerinfo.inc.
*/
Drupal.gmap.expandIconDef = function (c, path, files) {
var decomp = ['key', 'name', 'sequence', 'anchorX', 'anchorY', 'infoX',
'infoY', 'shadow', 'printImage', 'mozPrintImage', 'printShadow',
'transparent'];
var fallback = ['', '', [], 0, 0, 0, 0, {f: '', h: 0, w: 0}, '', '', '', ''];
var imagerep = ['shadow', 'printImage', 'mozPrintImage', 'printShadow',
'transparent'];
var defaults = {};
var sets = [];
var i, j;
// Part 1: Defaults / Markersets
// Expand arrays and fill in missing ones with fallbacks
for (i = 0; i < decomp.length; i++) {
if (!c[0][i]) {
c[0][i] = [ fallback[i] ];
}
c[0][i] = Drupal.gmap.expandArray(c[0][i], c[0][0].length);
}
for (i = 0; i < c[0][0].length; i++) {
for (j = 0; j < decomp.length; j++) {
if (i === 0) {
defaults[decomp[j]] = c[0][j][i];
}
else {
if (!sets[i - 1]) {
sets[i - 1] = {};
}
sets[i - 1][decomp[j]] = c[0][j][i];
}
}
}
for (i = 0; i < sets.length; i++) {
for (j = 0; j < decomp.length; j++) {
if (sets[i][decomp[j]] === fallback[j]) {
sets[i][decomp[j]] = defaults[decomp[j]];
}
}
}
var icons = {};
for (i = 0; i < sets.length; i++) {
var key = sets[i].key;
icons[key] = sets[i];
icons[key].path = path;
delete icons[key].key;
delete sets[i];
for (j = 0; j < icons[key].sequence.length; j++) {
icons[key].sequence[j] = files[icons[key].sequence[j]];
}
for (j = 0; j < imagerep.length; j++) {
if (typeof(icons[key][imagerep[j]]) === 'number') {
icons[key][imagerep[j]] = files[icons[key][imagerep[j]]];
}
}
}
return icons;
};
/**
* We attach ourselves if we find a map somewhere needing markers.
* Note: Since we broadcast our ready event to all maps, it doesn't
* matter which one we attached to!
*/
Drupal.gmap.addHandler('gmap', function (elem) {
var obj = this;
obj.bind('init', function () {
// Only expand once.
if (!Drupal.gmap.icons) {
Drupal.gmap.iconSetup();
}
});
obj.bind('ready', function () {
// Compatibility event.
if (Drupal.gmap.icondata) {
obj.deferChange('iconsready', -1);
}
});
if (!obj.vars.behavior.customicons) {
// Provide icons to markers.
obj.bind('preparemarker', function (marker) {
marker.opts.icon = Drupal.gmap.getIcon(marker.markername, marker.offset);
marker.opts.shadow = Drupal.gmap.getShadow(marker.markername, marker.offset);
});
}
});
| gpl-2.0 |
bz2/juju | apiserver/observer/package_test.go | 209 | // Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package observer_test
import (
"testing"
gc "gopkg.in/check.v1"
)
func Test(t *testing.T) {
gc.TestingT(t)
}
| agpl-3.0 |
tambora-org/dockerCRE | volumes/www/survey/third_party/ckeditor/plugins/specialchar/dialogs/lang/tr.js | 4486 | /*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("specialchar","tr",{euro:"Euro işareti",lsquo:"Sol tek tırnak işareti",rsquo:"Sağ tek tırnak işareti",ldquo:"Sol çift tırnak işareti",rdquo:"Sağ çift tırnak işareti",ndash:"En tire",mdash:"Em tire",iexcl:"Ters ünlem işareti",cent:"Cent işareti",pound:"Pound işareti",curren:"Para birimi işareti",yen:"Yen işareti",brvbar:"Kırık bar",sect:"Bölüm işareti",uml:"İki sesli harfin ayrılması",copy:"Telif hakkı işareti",ordf:"Dişil sıralı gösterge",laquo:"Sol-işaret çift açı tırnak işareti",
not:"Not işareti",reg:"Kayıtlı işareti",macr:"Makron",deg:"Derece işareti",sup2:"İkili üstsimge",sup3:"Üçlü üstsimge",acute:"Aksan işareti",micro:"Mikro işareti",para:"Pilcrow işareti",middot:"Orta nokta",cedil:"Kedilla",sup1:"Üstsimge",ordm:"Eril sıralı gösterge",raquo:"Sağ işaret çift açı tırnak işareti",frac14:"Bayağı kesrin dörtte biri",frac12:"Bayağı kesrin bir yarım",frac34:"Bayağı kesrin dörtte üç",iquest:"Ters soru işareti",Agrave:"Aksanlı latin harfi",Aacute:"Aşırı aksanıyla Latin harfi",
Acirc:"Çarpık Latin harfi",Atilde:"Tilde latin harfi",Auml:"Sesli harf ayrılımlıı latin harfi",Aring:"Halkalı latin büyük A harfi",AElig:"Latin büyük Æ harfi",Ccedil:"Latin büyük C harfi ile kedilla",Egrave:"Aksanlı latin büyük E harfi",Eacute:"Aşırı vurgulu latin büyük E harfi",Ecirc:"Çarpık latin büyük E harfi",Euml:"Sesli harf ayrılımlıı latin büyük E harfi",Igrave:"Aksanlı latin büyük I harfi",Iacute:"Aşırı aksanlı latin büyük I harfi",Icirc:"Çarpık latin büyük I harfi",Iuml:"Sesli harf ayrılımlıı latin büyük I harfi",
ETH:"Latin büyük Eth harfi",Ntilde:"Tildeli latin büyük N harfi",Ograve:"Aksanlı latin büyük O harfi",Oacute:"Aşırı aksanlı latin büyük O harfi",Ocirc:"Çarpık latin büyük O harfi",Otilde:"Tildeli latin büyük O harfi",Ouml:"Sesli harf ayrılımlı latin büyük O harfi",times:"Çarpma işareti",Oslash:"Vurgulu latin büyük O harfi",Ugrave:"Aksanlı latin büyük U harfi",Uacute:"Aşırı aksanlı latin büyük U harfi",Ucirc:"Çarpık latin büyük U harfi",Uuml:"Sesli harf ayrılımlı latin büyük U harfi",Yacute:"Aşırı aksanlı latin büyük Y harfi",
THORN:"Latin büyük Thorn harfi",szlig:"Latin küçük keskin s harfi",agrave:"Aksanlı latin küçük a harfi",aacute:"Aşırı aksanlı latin küçük a harfi",acirc:"Çarpık latin küçük a harfi",atilde:"Tildeli latin küçük a harfi",auml:"Sesli harf ayrılımlı latin küçük a harfi",aring:"Halkalı latin küçük a harfi",aelig:"Latin büyük æ harfi",ccedil:"Kedillalı latin küçük c harfi",egrave:"Aksanlı latin küçük e harfi",eacute:"Aşırı aksanlı latin küçük e harfi",ecirc:"Çarpık latin küçük e harfi",euml:"Sesli harf ayrılımlı latin küçük e harfi",
igrave:"Aksanlı latin küçük i harfi",iacute:"Aşırı aksanlı latin küçük i harfi",icirc:"Çarpık latin küçük i harfi",iuml:"Sesli harf ayrılımlı latin küçük i harfi",eth:"Latin küçük eth harfi",ntilde:"Tildeli latin küçük n harfi",ograve:"Aksanlı latin küçük o harfi",oacute:"Aşırı aksanlı latin küçük o harfi",ocirc:"Çarpık latin küçük o harfi",otilde:"Tildeli latin küçük o harfi",ouml:"Sesli harf ayrılımlı latin küçük o harfi",divide:"Bölme işareti",oslash:"Vurgulu latin küçük o harfi",ugrave:"Aksanlı latin küçük u harfi",
uacute:"Aşırı aksanlı latin küçük u harfi",ucirc:"Çarpık latin küçük u harfi",uuml:"Sesli harf ayrılımlı latin küçük u harfi",yacute:"Aşırı aksanlı latin küçük y harfi",thorn:"Latin küçük thorn harfi",yuml:"Sesli harf ayrılımlı latin küçük y harfi",OElig:"Latin büyük bağlı OE harfi",oelig:"Latin küçük bağlı oe harfi",372:"Çarpık latin büyük W harfi",374:"Çarpık latin büyük Y harfi",373:"Çarpık latin küçük w harfi",375:"Çarpık latin küçük y harfi",sbquo:"Tek düşük-9 tırnak işareti",8219:"Tek yüksek-ters-9 tırnak işareti",
bdquo:"Çift düşük-9 tırnak işareti",hellip:"Yatay elips",trade:"Marka tescili işareti",9658:"Siyah sağ işaret işaretçisi",bull:"Koyu nokta",rarr:"Sağa doğru ok",rArr:"Sağa doğru çift ok",hArr:"Sol, sağ çift ok",diams:"Siyah elmas takımı",asymp:"Hemen hemen eşit"}); | apache-2.0 |
ahb0327/intellij-community | java/debugger/impl/src/com/intellij/debugger/codeinsight/RuntimeTypeEvaluator.java | 4762 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.codeinsight;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.DebuggerInvocationUtil;
import com.intellij.debugger.EvaluatingComputable;
import com.intellij.debugger.engine.ContextUtil;
import com.intellij.debugger.engine.DebuggerUtils;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluateExceptionUtil;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.engine.evaluation.expression.EvaluatorBuilderImpl;
import com.intellij.debugger.engine.evaluation.expression.ExpressionEvaluator;
import com.intellij.debugger.impl.DebuggerContextImpl;
import com.intellij.debugger.ui.EditorEvaluationCommand;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.sun.jdi.ClassType;
import com.sun.jdi.InterfaceType;
import com.sun.jdi.Type;
import com.sun.jdi.Value;
import org.jetbrains.annotations.Nullable;
/**
* @author peter
*/
public abstract class RuntimeTypeEvaluator extends EditorEvaluationCommand<PsiType> {
public RuntimeTypeEvaluator(@Nullable Editor editor, PsiElement expression, DebuggerContextImpl context, final ProgressIndicator indicator) {
super(editor, expression, context, indicator);
}
public void threadAction() {
PsiType type = null;
try {
type = evaluate();
}
catch (ProcessCanceledException ignored) {
}
catch (EvaluateException ignored) {
}
finally {
typeCalculationFinished(type);
}
}
protected abstract void typeCalculationFinished(@Nullable PsiType type);
@Nullable
protected PsiType evaluate(final EvaluationContextImpl evaluationContext) throws EvaluateException {
final Project project = evaluationContext.getProject();
ExpressionEvaluator evaluator = DebuggerInvocationUtil.commitAndRunReadAction(project, new EvaluatingComputable<ExpressionEvaluator>() {
public ExpressionEvaluator compute() throws EvaluateException {
return EvaluatorBuilderImpl.getInstance().build(myElement, ContextUtil.getSourcePosition(evaluationContext));
}
});
final Value value = evaluator.evaluate(evaluationContext);
if(value != null){
return getCastableRuntimeType(project, value);
}
throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.surrounded.expression.null"));
}
@Nullable
public static PsiType getCastableRuntimeType(Project project, Value value) {
Type type = value.type();
PsiType psiType = findPsiType(project, type);
if (psiType != null) {
return psiType;
}
if (type instanceof ClassType) {
ClassType superclass = ((ClassType)type).superclass();
if (superclass != null && !CommonClassNames.JAVA_LANG_OBJECT.equals(superclass.name())) {
psiType = findPsiType(project, superclass);
if (psiType != null) {
return psiType;
}
}
for (InterfaceType interfaceType : ((ClassType)type).interfaces()) {
psiType = findPsiType(project, interfaceType);
if (psiType != null) {
return psiType;
}
}
}
return null;
}
private static PsiType findPsiType(Project project, Type type) {
AccessToken token = ReadAction.start();
try {
return DebuggerUtils.getType(type.name().replace('$', '.'), project);
}
finally {
token.finish();
}
}
public static boolean isSubtypeable(PsiExpression expr) {
final PsiType type = expr.getType();
if (type instanceof PsiPrimitiveType) {
return false;
}
if (type instanceof PsiClassType) {
final PsiClass psiClass = ((PsiClassType)type).resolve();
if (psiClass != null && psiClass.hasModifierProperty(PsiModifier.FINAL)) {
return false;
}
}
return true;
}
}
| apache-2.0 |
JeshRJ/myRepRJ | src/test/java/test/Test2.java | 2215 | package test;
import org.testng.Assert;
import org.testng.annotations.Configuration;
import org.testng.annotations.Test;
/**
*
* @author Cedric Beust, May 5, 2004
*
*/
public class Test2 extends BaseTest {
private boolean m_initializedCorrectly = false;
@Configuration(beforeTestMethod = true)
// @BeforeMethod
public void correctSetup() {
m_initializedCorrectly = true;
}
// Shouldn't be called
@Configuration(beforeTestMethod = true, groups = "excludeThisGroup")
// @BeforeMethod(groups = { "excludeThisGroup"} )
public void incorrectSetup() {
throw new RuntimeException("Should never be run");
}
@Test
public void noGroups() {
addClass("test.sample.Sample1");
run();
String[] passed = {
"method1",
"method2", "method3",
"broken", "throwExpectedException1ShouldPass",
"throwExpectedException2ShouldPass"
};
String[] failed = {
"throwExceptionShouldFail", "verifyLastNameShouldFail"
};
verifyTests("Passed", passed, getPassedTests());
verifyTests("Failed", failed, getFailedTests());
}
@Test
public void setUpWithGroups() {
run();
Assert.assertTrue(m_initializedCorrectly, "Should have run the correctSetup method");
}
@Test
public void partialGroupsClass() {
addClass("test.sample.PartialGroupTest");
addIncludedGroup("classGroup");
run();
String[] passed = {
"testMethodGroup", "testClassGroup"
};
String[] failed = {
"testMethodGroupShouldFail", "testClassGroupShouldFail"
};
verifyTests("Passed", passed, getPassedTests());
verifyTests("Failed", failed, getFailedTests());
// ppp("@@@@@@@@@@@@@@@@@@ PASSED TESTS");
// for (Object o : getPassedTests().values()) {
// ppp("@@@@@@@@@@ PASSED:" + o);
// }
}
@Test
public void partialGroupsMethod() {
addClass("test.sample.PartialGroupTest");
addIncludedGroup("methodGroup");
run();
String[] passed = {
"testMethodGroup",
};
String[] failed = {
"testMethodGroupShouldFail"
};
verifyTests("Passed", passed, getPassedTests());
verifyTests("Failed", failed, getFailedTests());
}
}
| apache-2.0 |
jessicastillop/geojsoncesium | ThirdParty/dojo-release-1.10.4/dojo/cldr/nls/ar/coptic.js | 2852 | define(
//begin v1.x content
{
"field-sat-relative+0": "السبت الحالي",
"field-sat-relative+1": "السبت التالي",
"field-dayperiod": "ص/م",
"field-sun-relative+-1": "الأحد الماضي",
"field-mon-relative+-1": "الاثنين الماضي",
"field-minute": "الدقائق",
"field-day-relative+-1": "أمس",
"field-weekday": "اليوم",
"field-day-relative+-2": "أول أمس",
"months-standAlone-narrow": [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13"
],
"field-era": "العصر",
"field-hour": "الساعات",
"field-sun-relative+0": "الأحد الحالي",
"field-sun-relative+1": "الأحد التالي",
"field-wed-relative+-1": "الأربعاء الماضي",
"field-day-relative+0": "اليوم",
"field-day-relative+1": "غدًا",
"field-day-relative+2": "بعد الغد",
"field-tue-relative+0": "الثلاثاء الحالي",
"field-zone": "التوقيت",
"field-tue-relative+1": "الثلاثاء التالي",
"field-week-relative+-1": "الأسبوع الماضي",
"field-year-relative+0": "هذه السنة",
"field-year-relative+1": "السنة التالية",
"field-sat-relative+-1": "السبت الماضي",
"field-year-relative+-1": "السنة الماضية",
"field-year": "السنة",
"field-fri-relative+0": "الجمعة الحالية",
"field-fri-relative+1": "الجمعة التالية",
"field-week": "الأسبوع",
"field-week-relative+0": "هذا الأسبوع",
"field-week-relative+1": "الأسبوع التالي",
"field-month-relative+0": "هذا الشهر",
"field-month": "الشهر",
"field-month-relative+1": "الشهر التالي",
"field-fri-relative+-1": "الجمعة الماضية",
"field-second": "الثواني",
"field-tue-relative+-1": "الثلاثاء الماضي",
"field-day": "يوم",
"months-format-narrow": [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13"
],
"field-mon-relative+0": "الاثنين الحالي",
"field-mon-relative+1": "الاثنين التالي",
"field-thu-relative+0": "الخميس الحالي",
"field-second-relative+0": "الآن",
"field-thu-relative+1": "الخميس التالي",
"field-wed-relative+0": "الأربعاء الحالي",
"months-format-wide": [
"توت",
"بابه",
"هاتور",
"كيهك",
"طوبة",
"أمشير",
"برمهات",
"برمودة",
"بشنس",
"بؤونة",
"أبيب",
"مسرى",
"نسيئ"
],
"field-wed-relative+1": "الأربعاء التالي",
"field-month-relative+-1": "الشهر الماضي",
"field-thu-relative+-1": "الخميس الماضي"
}
//end v1.x content
); | apache-2.0 |
delebash/orientdb-parent | tests/src/test/java/com/orientechnologies/orient/test/database/auto/DummyForTestFreeze.java | 127 | package com.orientechnologies.orient.test.database.auto;
/**
* @author Artem Loginov
*/
public class DummyForTestFreeze {
}
| apache-2.0 |
dotty-staging/dotty | tests/pos/t2421b_pos.scala | 398 | object Test {
class A
class B
class C
class F[X]
def f(implicit aa: F[A]) = println(aa)
implicit def a : F[A] = new F[A]()
implicit def b[X <: B]: Test.F[X] = new F[X]()
f
}
/* bug:
error: ambiguous implicit values:
both method b in object Test1 of type [X <: Test1.B]Test1.F[X]
and method a in object Test1 of type => Test1.F[Test1.A]
match expected type Test1.F[Test1.A]
*/
| apache-2.0 |
KevinLiLu/kafka | core/src/test/scala/unit/kafka/utils/MockTime.scala | 1617 | /**
* 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 kafka.utils
import org.apache.kafka.common.utils.{MockTime => JMockTime}
/**
* A class used for unit testing things which depend on the Time interface.
* There a couple of difference between this class and `org.apache.kafka.common.utils.MockTime`:
*
* 1. This has an associated scheduler instance for managing background tasks in a deterministic way.
* 2. This doesn't support the `auto-tick` functionality as it interacts badly with the current implementation of `MockScheduler`.
*/
class MockTime(currentTimeMs: Long, currentHiResTimeNs: Long) extends JMockTime(0, currentTimeMs, currentHiResTimeNs) {
def this() = this(System.currentTimeMillis(), System.nanoTime())
val scheduler = new MockScheduler(this)
override def sleep(ms: Long) {
super.sleep(ms)
scheduler.tick()
}
}
| apache-2.0 |
lottadot/mailcore2 | src/java/com/libmailcore/Multipart.java | 104 | package com.libmailcore;
/** Parsed multipart. */
public class Multipart extends AbstractMultipart {
}
| bsd-3-clause |
Fusion-Rom/android_external_chromium_org | chromeos/chromeos_switches.cc | 10169 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/chromeos_switches.h"
namespace chromeos {
namespace switches {
// Path for app's OEM manifest file.
const char kAppOemManifestFile[] = "app-mode-oem-manifest";
// When wallpaper boot animation is not disabled this switch
// is used to override OOBE/sign in WebUI init type.
// Possible values: parallel|postpone. Default: parallel.
const char kAshWebUIInit[] = "ash-webui-init";
// Specifies the URL of the consumer device management backend.
const char kConsumerDeviceManagementUrl[] = "consumer-device-management-url";
// Forces the stub implementation of dbus clients.
const char kDbusStub[] = "dbus-stub";
// Comma-spearated list of dbus clients that should be unstubbed.
// See chromeos/dbus/dbus_client_bundle.cc for the names of the dbus clients.
const char kDbusUnstubClients[] = "dbus-unstub-clients";
// Time before a machine at OOBE is considered derelict.
const char kDerelictDetectionTimeout[] = "derelict-detection-timeout";
// Time before a derelict machines starts demo mode.
const char kDerelictIdleTimeout[] = "derelict-idle-timeout";
// Disables wallpaper boot animation (except of OOBE case).
const char kDisableBootAnimation[] = "disable-boot-animation";
// Disables the ChromeOS demo.
const char kDisableDemoMode[] = "disable-demo-mode";
// Disable Easy sign-in.
const char kDisableEasySignin[] = "disable-easy-signin";
// Disable HID-detection OOBE screen.
const char kDisableHIDDetectionOnOOBE[] = "disable-hid-detection-on-oobe";
// Avoid doing expensive animations upon login.
const char kDisableLoginAnimations[] = "disable-login-animations";
// Disable login/lock UI (user pods) scrolling into view on JS side when virtual
// keyboard is shown.
const char kDisableLoginScrollIntoView[] = "disable-login-scroll-into-view";
// Disable new channel switcher UI.
const char kDisableNewChannelSwitcherUI[] = "disable-new-channel-switcher-ui";
// Disables new Kiosk UI when kiosk apps are represented as user pods.
const char kDisableNewKioskUI[] = "disable-new-kiosk-ui";
// Disable Office Editing for Docs, Sheets & Slides component app so handlers
// won't be registered, making it possible to install another version for
// testing.
const char kDisableOfficeEditingComponentApp[] =
"disable-office-editing-component-extension";
// Disables volume adjust sound.
const char kDisableVolumeAdjustSound[] = "disable-volume-adjust-sound";
// Disables notifications about captive portals in session.
const char kDisableNetworkPortalNotification[] =
"disable-network-portal-notification";
// Enables switching between different cellular carriers from the UI.
const char kEnableCarrierSwitching[] = "enable-carrier-switching";
// Enables the next generation version of ChromeVox.
const char kEnableChromeVoxNext[] = "enable-chromevox-next";
// Enables consumer management, which allows user to enroll, remotely lock and
// locate the device.
const char kEnableConsumerManagement[] = "enable-consumer-management";
// If this switch is set, Chrome OS login screen uses |EmbeddedSignin| endpoint
// of GAIA.
const char kEnableEmbeddedSignin[] = "enable-embedded-signin";
// Enabled sharing assets for installed default apps.
const char kEnableExtensionAssetsSharing[] = "enable-extension-assets-sharing";
// Enables notifications about captive portals in session.
const char kEnableNetworkPortalNotification[] =
"enable-network-portal-notification";
// Enables rollback option on reset screen.
const char kEnableRollbackOption[] = "enable-rollback-option";
// Enables touchpad three-finger-click as middle button.
const char kEnableTouchpadThreeFingerClick[]
= "enable-touchpad-three-finger-click";
// Enables using screenshots in tests and seets mode.
const char kEnableScreenshotTestingWithMode[] =
"enable-screenshot-testing-with-mode";
// Enable Kiosk mode for ChromeOS. Note this switch refers to retail mode rather
// than the kiosk app mode.
const char kEnableKioskMode[] = "enable-kiosk-mode";
// Enables request of tablet site (via user agent override).
const char kEnableRequestTabletSite[] = "enable-request-tablet-site";
// Whether to enable forced enterprise re-enrollment.
const char kEnterpriseEnableForcedReEnrollment[] =
"enterprise-enable-forced-re-enrollment";
// Power of the power-of-2 initial modulus that will be used by the
// auto-enrollment client. E.g. "4" means the modulus will be 2^4 = 16.
const char kEnterpriseEnrollmentInitialModulus[] =
"enterprise-enrollment-initial-modulus";
// Power of the power-of-2 maximum modulus that will be used by the
// auto-enrollment client.
const char kEnterpriseEnrollmentModulusLimit[] =
"enterprise-enrollment-modulus-limit";
// Don't create robot account on enrollment. Used when testing device
// enrollment against YAPS or the Python test server.
const char kEnterpriseEnrollmentSkipRobotAuth[] =
"enterprise-enrollment-skip-robot-auth";
// Enables the chromecast support for video player app.
const char kEnableVideoPlayerChromecastSupport[] =
"enable-video-player-chromecast-support";
// Passed to Chrome the first time that it's run after the system boots.
// Not passed on restart after sign out.
const char kFirstExecAfterBoot[] = "first-exec-after-boot";
// Usually in browser tests the usual login manager bringup is skipped so that
// tests can change how it's brought up. This flag disables that.
const char kForceLoginManagerInTests[] = "force-login-manager-in-tests";
// Indicates that the browser is in "browse without sign-in" (Guest session)
// mode. Should completely disable extensions, sync and bookmarks.
const char kGuestSession[] = "bwsi";
// If true, the Chromebook has a Chrome OS keyboard. Don't use the flag for
// Chromeboxes.
const char kHasChromeOSKeyboard[] = "has-chromeos-keyboard";
// If true, the Chromebook has a keyboard with a diamond key.
const char kHasChromeOSDiamondKey[] = "has-chromeos-diamond-key";
// Defines user homedir. This defaults to primary user homedir.
const char kHomedir[] = "homedir";
// With this switch, start remora OOBE with the pairing screen.
const char kHostPairingOobe[] = "host-pairing-oobe";
// If true, profile selection in UserManager will always return active user's
// profile.
// TODO(nkostlyev): http://crbug.com/364604 - Get rid of this switch after we
// turn on multi-profile feature on ChromeOS.
const char kIgnoreUserProfileMappingForTests[] =
"ignore-user-profile-mapping-for-tests";
// Path for the screensaver used in Kiosk mode
const char kKioskModeScreensaverPath[] = "kiosk-mode-screensaver-path";
// Enables Chrome-as-a-login-manager behavior.
const char kLoginManager[] = "login-manager";
// Specifies the profile to use once a chromeos user is logged in.
// This parameter is ignored if user goes through login screen since user_id
// hash defines which profile directory to use.
// In case of browser restart within active session this parameter is used
// to pass user_id hash for primary user.
const char kLoginProfile[] = "login-profile";
// Specifies the user which is already logged in.
const char kLoginUser[] = "login-user";
// Enables natural scroll by default.
const char kNaturalScrollDefault[] = "enable-natural-scroll-default";
// Skips all other OOBE pages after user login.
const char kOobeSkipPostLogin[] = "oobe-skip-postlogin";
// Disable GAIA services such as enrollment and OAuth session restore. Used by
// 'fake' telemetry login.
const char kDisableGaiaServices[] = "disable-gaia-services";
// Interval at which we check for total time on OOBE.
const char kOobeTimerInterval[] = "oobe-timer-interval";
// Indicates that a guest session has been started before OOBE completion.
const char kOobeGuestSession[] = "oobe-guest-session";
// Specifies power stub behavior:
// 'cycle=2' - Cycles power states every 2 seconds.
// See FakeDBusThreadManager::ParsePowerCommandLineSwitch for full details.
const char kPowerStub[] = "power-stub";
// Overrides network stub behavior. By default, ethernet, wifi and vpn are
// enabled, and transitions occur instantaneously. Multiple options can be
// comma separated (no spaces). Note: all options are in the format 'foo=x'.
// See FakeShillManagerClient::SetInitialNetworkState for implementation.
// Examples:
// 'clear=1' - Clears all default configurations
// 'wifi=on' - A wifi network is initially connected ('1' also works)
// 'wifi=off' - Wifi networks are all initially disconnected ('0' also works)
// 'wifi=disabled' - Wifi is initially disabled
// 'wifi=none' - Wifi is unavailable
// 'wifi=portal' - Wifi connection will be in Portal state
// 'cellular=1' - Cellular is initially connected
// 'interactive=3' - Interactive mode, connect/scan/etc requests take 3 secs
const char kShillStub[] = "shill-stub";
// Sends test messages on first call to RequestUpdate (stub only).
const char kSmsTestMessages[] = "sms-test-messages";
// Indicates that a stub implementation of CrosSettings that stores settings in
// memory without signing should be used, treating current user as the owner.
// This option is for testing the chromeos build of chrome on the desktop only.
const char kStubCrosSettings[] = "stub-cros-settings";
// Enables animated transitions during first-run tutorial.
const char kEnableFirstRunUITransitions[] = "enable-first-run-ui-transitions";
// Forces first-run UI to be shown for every login.
const char kForceFirstRunUI[] = "force-first-run-ui";
// Enables testing for auto update UI.
const char kTestAutoUpdateUI[] = "test-auto-update-ui";
// Enables waking the device based on the receipt of some network packets.
const char kWakeOnPackets[] = "wake-on-packets";
// Screenshot testing: specifies the directory where the golden screenshots are
// stored.
const char kGoldenScreenshotsDir[] = "golden-screenshots-dir";
// Screenshot testing: specifies the directoru where artifacts will be stored.
const char kArtifactsDir[] = "artifacts-dir";
} // namespace switches
} // namespace chromeos
| bsd-3-clause |
ROMFactory/android_external_chromium_org | net/dns/mapped_host_resolver.cc | 1853 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/dns/mapped_host_resolver.h"
#include "base/strings/string_util.h"
#include "net/base/host_port_pair.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
namespace net {
MappedHostResolver::MappedHostResolver(scoped_ptr<HostResolver> impl)
: impl_(impl.Pass()) {
}
MappedHostResolver::~MappedHostResolver() {
}
int MappedHostResolver::Resolve(const RequestInfo& original_info,
AddressList* addresses,
const CompletionCallback& callback,
RequestHandle* out_req,
const BoundNetLog& net_log) {
RequestInfo info = original_info;
int rv = ApplyRules(&info);
if (rv != OK)
return rv;
return impl_->Resolve(info, addresses, callback, out_req, net_log);
}
int MappedHostResolver::ResolveFromCache(const RequestInfo& original_info,
AddressList* addresses,
const BoundNetLog& net_log) {
RequestInfo info = original_info;
int rv = ApplyRules(&info);
if (rv != OK)
return rv;
return impl_->ResolveFromCache(info, addresses, net_log);
}
void MappedHostResolver::CancelRequest(RequestHandle req) {
impl_->CancelRequest(req);
}
HostCache* MappedHostResolver::GetHostCache() {
return impl_->GetHostCache();
}
int MappedHostResolver::ApplyRules(RequestInfo* info) const {
HostPortPair host_port(info->host_port_pair());
if (rules_.RewriteHost(&host_port)) {
if (host_port.host() == "~NOTFOUND")
return ERR_NAME_NOT_RESOLVED;
info->set_host_port_pair(host_port);
}
return OK;
}
} // namespace net
| bsd-3-clause |
ShinyROM/android_external_chromium_org | chrome/browser/ui/views/profile_reset_bubble_view.cc | 17021 | // 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 "chrome/browser/ui/views/profile_reset_bubble_view.h"
#include "base/memory/scoped_ptr.h"
#include "base/values.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/profile_resetter/profile_reset_global_error.h"
#include "chrome/browser/profile_resetter/resettable_settings_snapshot.h"
#include "chrome/browser/ui/global_error/global_error_service.h"
#include "chrome/browser/ui/global_error/global_error_service_factory.h"
#include "chrome/browser/ui/profile_reset_bubble.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/toolbar/toolbar_view.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/page_navigator.h"
#include "content/public/browser/user_metrics.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/image/image_skia_operations.h"
#include "ui/views/background.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/link.h"
#include "ui/views/controls/scroll_view.h"
#include "ui/views/controls/separator.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
using views::GridLayout;
namespace {
// Fixed width of the column holding the description label of the bubble.
const int kWidthOfDescriptionText = 370;
// Margins width for the top rows to compensate for the bottom panel for which
// we don't want any margin.
const int kMarginWidth = 12;
const int kMarginHeight = kMarginWidth;
// Width of a colum in the FeedbackView.
const int kFeedbackViewColumnWidth = kWidthOfDescriptionText / 2 + kMarginWidth;
// Width of the column used to disaplay the help button.
const int kHelpButtonColumnWidth = 30;
// Width of the reporting checkbox column.
const int kReportingCheckboxColumnWidth =
kWidthOfDescriptionText + 2 * kMarginWidth;
// Full width including all columns.
const int kAllColumnsWidth =
kReportingCheckboxColumnWidth + kHelpButtonColumnWidth;
// Maximum height of the scrollable feedback view.
const int kMaxFeedbackViewHeight = 450;
// The vertical padding between two values in the feedback view.
const int kInterFeedbackValuePadding = 4;
// We subtract 2 to account for the natural button padding, and
// to bring the separation visually in line with the row separation
// height.
const int kButtonPadding = views::kRelatedButtonHSpacing - 2;
// The color of the background of the sub panel to report current settings.
const SkColor kLightGrayBackgroundColor = 0xFFF5F5F5;
// This view is used to contain the scrollable contents that are shown the user
// to expose what feedback will be sent back to Google.
class FeedbackView : public views::View {
public:
FeedbackView() {}
// Setup the layout manager of the Feedback view using the content of the
// |feedback| ListValue which contains a list of key/value pairs stored in
// DictionaryValues. The key is to be displayed right aligned on the left, and
// the value as a left aligned multiline text on the right.
void SetupLayoutManager(const ListValue& feedback) {
RemoveAllChildViews(true);
set_background(views::Background::CreateSolidBackground(
kLightGrayBackgroundColor));
GridLayout* layout = new GridLayout(this);
SetLayoutManager(layout);
// We only need a single column set for left/right text and middle margin.
views::ColumnSet* cs = layout->AddColumnSet(0);
cs->AddColumn(GridLayout::FILL, GridLayout::LEADING, 1,
GridLayout::FIXED, kFeedbackViewColumnWidth, 0);
cs->AddPaddingColumn(0, kMarginWidth);
cs->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::FIXED, kFeedbackViewColumnWidth, 0);
for (size_t i = 0; i < feedback.GetSize(); ++i) {
const DictionaryValue* dictionary = NULL;
if (!feedback.GetDictionary(i, &dictionary) || !dictionary)
continue;
base::string16 key;
if (!dictionary->GetString("key", &key))
continue;
base::string16 value;
if (!dictionary->GetString("value", &value))
continue;
// The key is shown on the left, multi-line (required to allow wrapping in
// case the key name does not fit), and right-aligned.
views::Label* left_text_label = new views::Label(key);
left_text_label->SetMultiLine(true);
left_text_label->SetEnabledColor(SK_ColorGRAY);
left_text_label->SetHorizontalAlignment(gfx::ALIGN_RIGHT);
// The value is shown on the right, multi-line, left-aligned.
views::Label* right_text_label = new views::Label(value);
right_text_label->SetMultiLine(true);
right_text_label->SetEnabledColor(SK_ColorDKGRAY);
right_text_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
layout->StartRow(0, 0);
layout->AddView(left_text_label);
layout->AddView(right_text_label);
layout->AddPaddingRow(0, kInterFeedbackValuePadding);
}
// We need to set our size to our preferred size because our parent is a
// scroll view and doesn't know which size to set us to. Also since our
// parent scrolls, we are not bound to its size. So our size is based on the
// size computed by the our layout manager, which is what
// SizeToPreferredSize() does.
SizeToPreferredSize();
}
private:
DISALLOW_COPY_AND_ASSIGN(FeedbackView);
};
} // namespace
// ProfileResetBubbleView ---------------------------------------------------
// static
ProfileResetBubbleView* ProfileResetBubbleView::ShowBubble(
const base::WeakPtr<ProfileResetGlobalError>& global_error,
Browser* browser) {
views::View* anchor_view =
BrowserView::GetBrowserViewForBrowser(browser)->toolbar()->app_menu();
ProfileResetBubbleView* reset_bubble = new ProfileResetBubbleView(
global_error, anchor_view, browser, browser->profile());
views::BubbleDelegateView::CreateBubble(reset_bubble);
reset_bubble->StartFade(true);
content::RecordAction(content::UserMetricsAction("SettingsResetBubble.Show"));
return reset_bubble;
}
ProfileResetBubbleView::~ProfileResetBubbleView() {}
views::View* ProfileResetBubbleView::GetInitiallyFocusedView() {
return controls_.reset_button;
}
void ProfileResetBubbleView::WindowClosing() {
if (global_error_)
global_error_->OnBubbleViewDidClose();
}
ProfileResetBubbleView::ProfileResetBubbleView(
const base::WeakPtr<ProfileResetGlobalError>& global_error,
views::View* anchor_view,
content::PageNavigator* navigator,
Profile* profile)
: BubbleDelegateView(anchor_view, views::BubbleBorder::TOP_RIGHT),
navigator_(navigator),
profile_(profile),
global_error_(global_error),
resetting_(false),
chose_to_reset_(false),
show_help_pane_(false),
weak_factory_(this) {
}
void ProfileResetBubbleView::ResetAllChildren() {
controls_.Reset();
SetLayoutManager(NULL);
RemoveAllChildViews(true);
}
void ProfileResetBubbleView::Init() {
set_margins(gfx::Insets(kMarginHeight, 0, 0, 0));
SetupLayoutManager(true);
}
void ProfileResetBubbleView::SetupLayoutManager(bool report_checked) {
ResetAllChildren();
base::string16 product_name(
l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME));
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
// Bubble title label.
views::Label* title_label = new views::Label(
l10n_util::GetStringFUTF16(IDS_RESET_BUBBLE_TITLE, product_name));
title_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
title_label->SetFont(rb.GetFont(ui::ResourceBundle::BoldFont));
// Description text label.
views::Label* text_label = new views::Label(
l10n_util::GetStringFUTF16(IDS_RESET_BUBBLE_TEXT, product_name));
text_label->SetMultiLine(true);
text_label->SetLineHeight(20);
text_label->SetEnabledColor(SK_ColorDKGRAY);
text_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
// Learn more link.
views::Link* learn_more_link = new views::Link(
l10n_util::GetStringUTF16(IDS_LEARN_MORE));
learn_more_link->SetHorizontalAlignment(gfx::ALIGN_LEFT);
learn_more_link->set_listener(this);
learn_more_link->SetUnderline(false);
// Reset button's name is based on |resetting_| state.
int reset_button_string_id = IDS_RESET_PROFILE_SETTINGS_COMMIT_BUTTON;
if (resetting_)
reset_button_string_id = IDS_RESETTING;
controls_.reset_button = new views::LabelButton(
this, l10n_util::GetStringUTF16(reset_button_string_id));
controls_.reset_button->SetStyle(views::Button::STYLE_NATIVE_TEXTBUTTON);
controls_.reset_button->SetIsDefault(true);
controls_.reset_button->SetFont(rb.GetFont(ui::ResourceBundle::BoldFont));
controls_.reset_button->SetEnabled(!resetting_);
// For the Resetting... text to fit.
gfx::Size reset_button_size = controls_.reset_button->GetPreferredSize();
reset_button_size.set_width(100);
controls_.reset_button->set_min_size(reset_button_size);
// No thanks button.
controls_.no_thanks_button = new views::LabelButton(
this, l10n_util::GetStringUTF16(IDS_NO_THANKS));
controls_.no_thanks_button->SetStyle(views::Button::STYLE_NATIVE_TEXTBUTTON);
controls_.no_thanks_button->SetEnabled(!resetting_);
// Checkbox for reporting settings or not.
controls_.report_settings_checkbox = new views::Checkbox(
l10n_util::GetStringUTF16(IDS_REPORT_BUBBLE_TEXT));
controls_.report_settings_checkbox->SetTextColor(
views::Button::STATE_NORMAL, SK_ColorGRAY);
controls_.report_settings_checkbox->SetChecked(report_checked);
controls_.report_settings_checkbox->SetTextMultiLine(true);
controls_.report_settings_checkbox->set_background(
views::Background::CreateSolidBackground(kLightGrayBackgroundColor));
// Have a smaller margin on the right, to have the |controls_.help_button|
// closer to the edge.
controls_.report_settings_checkbox->set_border(
views::Border::CreateSolidSidedBorder(
kMarginWidth, kMarginWidth, kMarginWidth, kMarginWidth / 2,
kLightGrayBackgroundColor));
// Help button to toggle the bottom panel on or off.
controls_.help_button = new views::ImageButton(this);
const gfx::ImageSkia* help_image = rb.GetImageSkiaNamed(IDR_QUESTION_MARK);
color_utils::HSL hsl_shift = { -1, 0, 0.8 };
brighter_help_image_ = gfx::ImageSkiaOperations::CreateHSLShiftedImage(
*help_image, hsl_shift);
controls_.help_button->SetImage(
views::Button::STATE_NORMAL, &brighter_help_image_);
controls_.help_button->SetImage(views::Button::STATE_HOVERED, help_image);
controls_.help_button->SetImage(views::Button::STATE_PRESSED, help_image);
controls_.help_button->set_background(
views::Background::CreateSolidBackground(kLightGrayBackgroundColor));
controls_.help_button->SetImageAlignment(views::ImageButton::ALIGN_CENTER,
views::ImageButton::ALIGN_MIDDLE);
GridLayout* layout = new GridLayout(this);
SetLayoutManager(layout);
// Title row.
const int kTitleColumnSetId = 0;
views::ColumnSet* cs = layout->AddColumnSet(kTitleColumnSetId);
cs->AddPaddingColumn(0, kMarginWidth);
cs->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
cs->AddPaddingColumn(0, kMarginWidth);
// Text row.
const int kTextColumnSetId = 1;
cs = layout->AddColumnSet(kTextColumnSetId);
cs->AddPaddingColumn(0, kMarginWidth);
cs->AddColumn(GridLayout::FILL, GridLayout::FILL, 0,
GridLayout::FIXED, kWidthOfDescriptionText, 0);
cs->AddPaddingColumn(0, kMarginWidth);
// Learn more link & buttons row.
const int kButtonsColumnSetId = 2;
cs = layout->AddColumnSet(kButtonsColumnSetId);
cs->AddPaddingColumn(0, kMarginWidth);
cs->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
cs->AddPaddingColumn(1, views::kRelatedControlHorizontalSpacing);
cs->AddColumn(GridLayout::LEADING, GridLayout::TRAILING, 0,
GridLayout::USE_PREF, 0, 0);
cs->AddPaddingColumn(0, kButtonPadding);
cs->AddColumn(GridLayout::LEADING, GridLayout::TRAILING, 0,
GridLayout::USE_PREF, 0, 0);
cs->AddPaddingColumn(0, kMarginWidth);
// Separator.
const int kSeparatorColumnSetId = 3;
cs = layout->AddColumnSet(kSeparatorColumnSetId);
cs->AddColumn(GridLayout::FILL, GridLayout::FILL, 0,
GridLayout::FIXED, kAllColumnsWidth, 0);
// Reporting row.
const int kReportColumnSetId = 4;
cs = layout->AddColumnSet(kReportColumnSetId);
cs->AddColumn(GridLayout::FILL, GridLayout::FILL, 0,
GridLayout::FIXED, kReportingCheckboxColumnWidth, 0);
cs->AddColumn(GridLayout::FILL, GridLayout::FILL, 0,
GridLayout::FIXED, kHelpButtonColumnWidth, 0);
layout->StartRow(0, kTitleColumnSetId);
layout->AddView(title_label);
layout->AddPaddingRow(0, kMarginHeight);
layout->StartRow(0, kTextColumnSetId);
layout->AddView(text_label);
layout->AddPaddingRow(0, kMarginHeight);
layout->StartRow(0, kButtonsColumnSetId);
layout->AddView(learn_more_link);
layout->AddView(controls_.reset_button);
layout->AddView(controls_.no_thanks_button);
layout->AddPaddingRow(0, kMarginHeight);
layout->StartRow(0, kSeparatorColumnSetId);
layout->AddView(new views::Separator(views::Separator::HORIZONTAL));
layout->StartRow(0, kReportColumnSetId);
layout->AddView(controls_.report_settings_checkbox);
layout->AddView(controls_.help_button);
if (show_help_pane_) {
scoped_ptr<ListValue> feedback(GetReadableFeedback(profile_));
if (feedback.get()) {
// We need a single row to add the scroll view containing the feedback.
const int kReportDetailsColumnSetId = 5;
cs = layout->AddColumnSet(kReportDetailsColumnSetId);
cs->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::USE_PREF, 0, 0);
FeedbackView* feedback_view = new FeedbackView();
feedback_view->SetupLayoutManager(*feedback.get());
views::ScrollView* scroll_view = new views::ScrollView();
scroll_view->set_background(views::Background::CreateSolidBackground(
kLightGrayBackgroundColor));
scroll_view->SetContents(feedback_view);
layout->StartRow(1, kReportDetailsColumnSetId);
layout->AddView(scroll_view, 1, 1, GridLayout::FILL,
GridLayout::FILL, kAllColumnsWidth,
std::min(feedback_view->height() + kMarginHeight,
kMaxFeedbackViewHeight));
}
}
Layout();
AddAccelerator(ui::Accelerator(ui::VKEY_RETURN, ui::EF_NONE));
}
void ProfileResetBubbleView::ButtonPressed(views::Button* sender,
const ui::Event& event) {
if (sender == controls_.reset_button) {
DCHECK(!resetting_);
content::RecordAction(
content::UserMetricsAction("SettingsResetBubble.Reset"));
// Remember that the user chose to reset, and that resetting is underway.
chose_to_reset_ = true;
resetting_ = true;
controls_.reset_button->SetText(l10n_util::GetStringUTF16(IDS_RESETTING));
controls_.reset_button->SetEnabled(false);
controls_.no_thanks_button->SetEnabled(false);
SchedulePaint();
if (global_error_) {
global_error_->OnBubbleViewResetButtonPressed(
controls_.report_settings_checkbox->checked());
}
} else if (sender == controls_.no_thanks_button) {
DCHECK(!resetting_);
content::RecordAction(
content::UserMetricsAction("SettingsResetBubble.NoThanks"));
if (global_error_)
global_error_->OnBubbleViewNoThanksButtonPressed();
StartFade(false);
return;
} else if (sender == controls_.help_button) {
show_help_pane_ = !show_help_pane_;
SetupLayoutManager(controls_.report_settings_checkbox->checked());
SizeToContents();
}
}
void ProfileResetBubbleView::LinkClicked(views::Link* source, int flags) {
content::RecordAction(
content::UserMetricsAction("SettingsResetBubble.LearnMore"));
navigator_->OpenURL(content::OpenURLParams(
GURL(chrome::kResetProfileSettingsLearnMoreURL), content::Referrer(),
NEW_FOREGROUND_TAB, content::PAGE_TRANSITION_LINK, false));
}
void ProfileResetBubbleView::CloseBubbleView() {
resetting_ = false;
StartFade(false);
}
bool IsProfileResetBubbleSupported() {
return true;
}
GlobalErrorBubbleViewBase* ShowProfileResetBubble(
const base::WeakPtr<ProfileResetGlobalError>& global_error,
Browser* browser) {
return ProfileResetBubbleView::ShowBubble(global_error, browser);
}
| bsd-3-clause |
joone/chromium-crosswalk | ui/file_manager/gallery/js/slide_mode_unittest.js | 2571 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* Mock implementation of strf function.
*/
function strf(id, var_args) {
return `${id}-${Array.from(arguments).slice(1).join("-")}`;
}
var fallbackDir = {
fullPath: '/fallback'
};
/**
* Test case for writable format and writable volume.
*/
function testGetEditorWarningMessageWritableFormatAndVolumeCase(callback) {
var item = {
isWritableFormat: () => true
};
reportPromise(SlideMode.getEditorWarningMessage(
item, '', fallbackDir).then(function(message) {
assertEquals(message, null);
}), callback);
}
/**
* Test case for writable format and read only volume.
*/
function testGetEditorWarningMessageWritableFormatReadOnlyCase(callback) {
var item = {
isWritableFormat: () => true
};
reportPromise(SlideMode.getEditorWarningMessage(
item, 'NON_WRITABLE_VOLUME', fallbackDir).then(function(message) {
assertEquals(message, 'GALLERY_READONLY_WARNING-NON_WRITABLE_VOLUME');
}), callback);
}
/**
* Test case for non-writable format and writable volume.
*/
function testGetEditorWarningMessageNonWritableFormatAndWritableVolumeCase(
callback) {
var item = {
isWritableFormat: function() {
return false;
},
getEntry: function() {
return {
fullPath: '/parent/test.png',
getParent: function(callback) {
callback({ fullPath: '/parent' });
}
}
},
getCopyName: function(dirEntry) {
assertEquals(dirEntry.fullPath, '/parent');
return Promise.resolve('test - Edited.png');
}
};
reportPromise(SlideMode.getEditorWarningMessage(
item, '', fallbackDir).then(function(message) {
assertEquals(message,
'GALLERY_NON_WRITABLE_FORMAT_WARNING-test - Edited.png');
}), callback);
}
/**
* Test case for non-writable format and read only volume.
*/
function testGetEditorWarningMessageNonWritableFormatAndReadOnlyCase(callback) {
var item = {
isWritableFormat: function() {
return false;
},
getCopyName: function(dirEntry) {
assertEquals(dirEntry.fullPath, '/fallback');
return Promise.resolve('test - Edited.png');
}
};
reportPromise(SlideMode.getEditorWarningMessage(
item, 'NON_WRITABLE_VOLUME', fallbackDir).then(function(message) {
assertEquals(message,
"GALLERY_READONLY_AND_NON_WRITABLE_FORMAT_WARNING-" +
"NON_WRITABLE_VOLUME-test - Edited.png");
}), callback);
}
| bsd-3-clause |
badiniibrahim/concrete5 | concrete/core/controllers/single_pages/dashboard/system/seo.php | 327 | <?php
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Controller_Dashboard_System_Seo extends DashboardBaseController{
/**
* Dashboard view - automatically redirects to a default
* page in the category
*
* @return void
*/
public function view() {
$this->redirect('/dashboard/system/seo/urls');
}
}
?> | mit |
microapps/Nodify-Shopify | test/fixtures/usage-charge/req/index.js | 53 | 'use strict';
exports.create = require('./create');
| mit |
renyuneyun/core | js/lib/components/LinkButton.js | 948 | import Button from 'flarum/components/Button';
/**
* The `LinkButton` component defines a `Button` which links to a route.
*
* ### Props
*
* All of the props accepted by `Button`, plus:
*
* - `active` Whether or not the page that this button links to is currently
* active.
* - `href` The URL to link to. If the current URL `m.route()` matches this,
* the `active` prop will automatically be set to true.
*/
export default class LinkButton extends Button {
static initProps(props) {
props.active = this.isActive(props);
props.config = props.config || m.route;
}
view() {
const vdom = super.view();
vdom.tag = 'a';
return vdom;
}
/**
* Determine whether a component with the given props is 'active'.
*
* @param {Object} props
* @return {Boolean}
*/
static isActive(props) {
return typeof props.active !== 'undefined'
? props.active
: m.route() === props.href;
}
}
| mit |
evejweinberg/InverseKinetics | JAVASCRIPT/box2d-js_0/js/box2d/collision/b2OBB.js | 1238 | /*
* Copyright (c) 2006-2007 Erin Catto http:
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked, and must not be
* misrepresented the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
// A manifold for two touching convex shapes.
var b2OBB = Class.create();
b2OBB.prototype =
{
R: new b2Mat22(),
center: new b2Vec2(),
extents: new b2Vec2(),
initialize: function() {
// initialize instance variables for references
this.R = new b2Mat22();
this.center = new b2Vec2();
this.extents = new b2Vec2();
//
}};
| mit |
vibhatha/mean | App_55/node_modules/passport-google-oauth/node_modules/pkginfo/examples/object-argument.js | 567 | /*
* object-argument.js: Sample of including specific properties from a package.json file
* using Object argument syntax.
*
* (C) 2011, Charlie Robbins
*
*/
var util = require('util'),
pkginfo = require('../lib/pkginfo')(module, {
include: ['version', 'author']
});
exports.someFunction = function () {
console.log('some of your custom logic here');
};
console.log('Inspecting module:');
console.dir(module.exports);
console.log('\nAll exports exposed:');
console.error(Object.keys(module.exports)); | mit |
RolePlayGateway/roleplaygateway | shout-new/lib/class/AJAXChatMySQLiQuery.php | 1674 | <?php
/*
* @package AJAX_Chat
* @author Sebastian Tschan
* @copyright (c) Sebastian Tschan
* @license GNU Affero General Public License
* @link https://blueimp.net/ajax/
*/
// Class to perform SQL (MySQLi) queries:
class AJAXChatMySQLiQuery {
var $_connectionID;
var $_sql = '';
var $_result = 0;
var $_errno = 0;
var $_error = '';
// Constructor:
function AJAXChatMySQLiQuery($sql, $connectionID) {
$this->_sql = trim($sql);
$this->_connectionID = $connectionID;
$this->_result = $this->_connectionID->query($this->_sql);
if(!$this->_result) {
$this->_errno = $this->_connectionID->errno;
$this->_error = $this->_connectionID->error;
}
}
// Returns true if an error occured:
function error() {
// Returns true if the Result-ID is valid:
return !(bool)($this->_result);
}
// Returns an Error-String:
function getError() {
if($this->error()) {
$str = 'Query: ' .$this->_sql ."\n";
$str .= 'Error-Report: ' .$this->_error."\n";
$str .= 'Error-Code: '.$this->_errno;
} else {
$str = "No errors.";
}
return $str;
}
// Returns the content:
function fetch() {
if($this->error()) {
return null;
} else {
return $this->_result->fetch_assoc();
}
}
// Returns the number of rows (SELECT or SHOW):
function numRows() {
if($this->error()) {
return null;
} else {
return $this->_result->num_rows;
}
}
// Returns the number of affected rows (INSERT, UPDATE, REPLACE or DELETE):
function affectedRows() {
if($this->error()) {
return null;
} else {
return $this->_connectionID->affected_rows;
}
}
// Frees the memory:
function free() {
$this->_result->free();
}
}
?> | gpl-3.0 |
Aviio/SecGen | modules/services/unix/ntp/ntp/spec/acceptance/ntp_parameters_spec.rb | 5031 | require 'spec_helper_acceptance'
case fact('osfamily')
when 'FreeBSD'
packagename = 'net/ntp'
when 'Gentoo'
packagename = 'net-misc/ntp'
when 'Linux'
case fact('operatingsystem')
when 'ArchLinux'
packagename = 'ntp'
when 'Gentoo'
packagename = 'net-misc/ntp'
end
when 'AIX'
packagename = 'bos.net.tcp.client'
when 'Solaris'
case fact('kernelrelease')
when '5.10'
packagename = ['SUNWntpr','SUNWntpu']
when '5.11'
packagename = 'service/network/ntp'
end
else
if fact('operatingsystem') == 'SLES' and fact('operatingsystemmajrelease') == '12'
servicename = 'ntpd'
else
servicename = 'ntp'
end
end
if (fact('osfamily') == 'RedHat')
keysfile = '/etc/ntp/keys'
elsif (fact('osfamily') == 'Solaris')
keysfile = '/etc/inet/ntp.keys'
else
keysfile = '/etc/ntp.keys'
end
if (fact('osfamily') == 'Solaris')
config = '/etc/inet/ntp.conf'
else
config = '/etc/ntp.conf'
end
describe "ntp class:", :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do
it 'applies successfully' do
pp = "class { 'ntp': }"
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stderr).not_to match(/error/i)
end
end
describe 'autoconfig' do
it 'raises a deprecation warning' do
pp = "class { 'ntp': autoupdate => true }"
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/autoupdate parameter has been deprecated and replaced with package_ensure/)
end
end
end
describe 'config' do
it 'sets the ntp.conf location' do
pp = "class { 'ntp': config => '/etc/antp.conf' }"
apply_manifest(pp, :catch_failures => true)
end
describe file('/etc/antp.conf') do
it { should be_file }
end
end
describe 'config_template' do
it 'sets up template' do
modulepath = default['distmoduledir']
shell("mkdir -p #{modulepath}/test/templates")
shell("echo 'testcontent' >> #{modulepath}/test/templates/ntp.conf")
end
it 'sets the ntp.conf location' do
pp = "class { 'ntp': config_template => 'test/ntp.conf' }"
apply_manifest(pp, :catch_failures => true)
end
describe file("#{config}") do
it { should be_file }
its(:content) { should match 'testcontent' }
end
end
describe 'driftfile' do
it 'sets the driftfile location' do
pp = "class { 'ntp': driftfile => '/tmp/driftfile' }"
apply_manifest(pp, :catch_failures => true)
end
describe file("#{config}") do
it { should be_file }
its(:content) { should match 'driftfile /tmp/driftfile' }
end
end
describe 'keys' do
it 'enables the key parameters' do
pp = <<-EOS
class { 'ntp':
keys_enable => true,
keys_controlkey => '15',
keys_requestkey => '1',
keys_trusted => [ '1', '2' ],
keys => [ '1 M AAAABBBB' ],
}
EOS
apply_manifest(pp, :catch_failures => true)
end
describe file("#{config}") do
it { should be_file }
its(:content) { should match "keys #{keysfile}" }
its(:content) { should match 'controlkey 15' }
its(:content) { should match 'requestkey 1' }
its(:content) { should match 'trustedkey 1 2' }
end
describe file(keysfile) do
it { should be_file }
its(:content) { should match '1 M AAAABBBB' }
end
end
describe 'package' do
it 'installs the right package' do
pp = <<-EOS
class { 'ntp':
package_ensure => present,
package_name => #{Array(packagename).inspect},
}
EOS
apply_manifest(pp, :catch_failures => true)
end
Array(packagename).each do |package|
describe package(package) do
it { should be_installed }
end
end
end
describe 'panic => 0' do
it 'disables the tinker panic setting' do
pp = <<-EOS
class { 'ntp':
panic => 0,
}
EOS
apply_manifest(pp, :catch_failures => true)
end
describe file("#{config}") do
its(:content) { should match 'tinker panic 0' }
end
end
describe 'panic => 1' do
it 'enables the tinker panic setting' do
pp = <<-EOS
class { 'ntp':
panic => 1,
}
EOS
apply_manifest(pp, :catch_failures => true)
end
describe file("#{config}") do
its(:content) { should match 'tinker panic 1' }
end
end
describe 'udlc' do
it 'adds a udlc' do
pp = "class { 'ntp': udlc => true }"
apply_manifest(pp, :catch_failures => true)
end
describe file("#{config}") do
it { should be_file }
its(:content) { should match '127.127.1.0' }
end
end
describe 'udlc_stratum' do
it 'sets the stratum value when using udlc' do
pp = "class { 'ntp': udlc => true, udlc_stratum => 10 }"
apply_manifest(pp, :catch_failures => true)
end
describe file("#{config}") do
it { should be_file }
its(:content) { should match 'stratum 10' }
end
end
end
| gpl-3.0 |
GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/@fortawesome/free-solid-svg-icons/faBriefcaseMedical.d.ts | 404 | import { IconDefinition, IconPrefix, IconName } from "@fortawesome/fontawesome-common-types";
export const definition: IconDefinition;
export const faBriefcaseMedical: IconDefinition;
export const prefix: IconPrefix;
export const iconName: IconName;
export const width: number;
export const height: number;
export const ligatures: string[];
export const unicode: string;
export const svgPathData: string; | apache-2.0 |
martinwicke/tensorflow | tensorflow/core/kernels/cast_op_test.cc | 7167 | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"
#include "tensorflow/core/framework/fake_input.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/kernels/ops_testutil.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
using Eigen::half;
namespace tensorflow {
template <typename Src, typename Dst>
static Graph* Cast(int num) {
Graph* g = new Graph(OpRegistry::Global());
Tensor data(DataTypeToEnum<Src>::value,
TensorShape({64, 64, num / (64 * 64)}));
data.flat<Src>().setRandom();
test::graph::Cast(g, test::graph::Constant(g, data),
DataTypeToEnum<Dst>::value);
return g;
}
class CastOpTest : public OpsTestBase {
protected:
void MakeOp(DataType src, DataType dst) {
TF_EXPECT_OK(NodeDefBuilder("cast_op", "Cast")
.Input(FakeInput(src))
.Attr("SrcT", src)
.Attr("DstT", dst)
.Finalize(node_def()));
TF_EXPECT_OK(InitOp());
}
template <typename INPUT, typename OUTPUT>
void CheckCast() {
DataType in_type = DataTypeToEnum<INPUT>::v();
DataType out_type = DataTypeToEnum<OUTPUT>::v();
MakeOp(in_type, out_type);
AddInputFromArray<INPUT>(TensorShape({1, 2, 2, 1}),
{INPUT(1), INPUT(2), INPUT(3), INPUT(4)});
TF_ASSERT_OK(RunOpKernel());
Tensor expected(allocator(), out_type, TensorShape({1, 2, 2, 1}));
test::FillValues<OUTPUT>(&expected,
{OUTPUT(1), OUTPUT(2), OUTPUT(3), OUTPUT(4)});
test::ExpectTensorEqual<OUTPUT>(expected, *GetOutput(0));
}
};
#define TEST_CAST(in, out) \
TEST_F(CastOpTest, TestCast##_##in##_##out) { CheckCast<in, out>(); }
#define TEST_ALL_CASTS_FROM(in) \
TEST_CAST(in, uint8); \
TEST_CAST(in, uint16); \
TEST_CAST(in, int16); \
TEST_CAST(in, int32); \
TEST_CAST(in, int64); \
TEST_CAST(in, half); \
TEST_CAST(in, float); \
TEST_CAST(in, double)
TEST_ALL_CASTS_FROM(uint8)
TEST_ALL_CASTS_FROM(uint16)
TEST_ALL_CASTS_FROM(int16)
TEST_ALL_CASTS_FROM(int32)
TEST_ALL_CASTS_FROM(int64)
TEST_ALL_CASTS_FROM(half)
TEST_ALL_CASTS_FROM(float)
TEST_ALL_CASTS_FROM(double)
#undef TEST_ALL_CASTS_FROM
#undef TEST_CAST
// TODO(wicke): check conversions from/to bool, and bfloat16
static void BM_cpu_float_int64(int iters, int num) {
testing::ItemsProcessed(static_cast<int64>(iters) * num);
testing::BytesProcessed(static_cast<int64>(iters) * num *
(sizeof(float) + sizeof(int64)));
testing::UseRealTime();
test::Benchmark("cpu", Cast<float, int64>(num)).Run(iters);
}
BENCHMARK(BM_cpu_float_int64)->Arg(64 << 10)->Arg(32 << 20);
static void BM_gpu_float_int64(int iters, int num) {
testing::ItemsProcessed(static_cast<int64>(iters) * num);
testing::BytesProcessed(static_cast<int64>(iters) * num *
(sizeof(float) + sizeof(int64)));
testing::UseRealTime();
test::Benchmark("gpu", Cast<float, int64>(num)).Run(iters);
}
BENCHMARK(BM_gpu_float_int64)->Arg(64 << 10)->Arg(32 << 20);
static void BM_cpu_bool_float(int iters, int num) {
testing::ItemsProcessed(static_cast<int64>(iters) * num);
testing::BytesProcessed(static_cast<int64>(iters) * num *
(sizeof(bool) + sizeof(float)));
testing::UseRealTime();
test::Benchmark("cpu", Cast<bool, float>(num)).Run(iters);
}
BENCHMARK(BM_cpu_bool_float)->Arg(64 << 10)->Arg(32 << 20);
static void BM_gpu_bool_float(int iters, int num) {
testing::ItemsProcessed(static_cast<int64>(iters) * num);
testing::BytesProcessed(static_cast<int64>(iters) * num *
(sizeof(bool) + sizeof(float)));
testing::UseRealTime();
test::Benchmark("gpu", Cast<bool, float>(num)).Run(iters);
}
BENCHMARK(BM_gpu_bool_float)->Arg(64 << 10)->Arg(32 << 20);
static void BM_cpu_float_bfloat16(int iters, int num) {
testing::ItemsProcessed(static_cast<int64>(iters) * num);
testing::BytesProcessed(static_cast<int64>(iters) * num *
(sizeof(float) + sizeof(bfloat16)));
testing::UseRealTime();
test::Benchmark("cpu", Cast<float, bfloat16>(num)).Run(iters);
}
BENCHMARK(BM_cpu_float_bfloat16)->Arg(64 << 10)->Arg(32 << 20);
static void BM_cpu_bfloat16_float(int iters, int num) {
testing::ItemsProcessed(static_cast<int64>(iters) * num);
testing::BytesProcessed(static_cast<int64>(iters) * num *
(sizeof(float) + sizeof(bfloat16)));
testing::UseRealTime();
test::Benchmark("cpu", Cast<bfloat16, float>(num)).Run(iters);
}
BENCHMARK(BM_cpu_bfloat16_float)->Arg(64 << 10)->Arg(32 << 20);
static void BM_cpu_float_half(int iters, int num) {
testing::ItemsProcessed(static_cast<int64>(iters) * num);
testing::BytesProcessed(static_cast<int64>(iters) * num *
(sizeof(float) + sizeof(Eigen::half)));
testing::UseRealTime();
test::Benchmark("cpu", Cast<float, Eigen::half>(num)).Run(iters);
}
BENCHMARK(BM_cpu_float_half)->Arg(64 << 10)->Arg(32 << 20);
static void BM_cpu_half_float(int iters, int num) {
testing::ItemsProcessed(static_cast<int64>(iters) * num);
testing::BytesProcessed(static_cast<int64>(iters) * num *
(sizeof(float) + sizeof(Eigen::half)));
testing::UseRealTime();
test::Benchmark("cpu", Cast<Eigen::half, float>(num)).Run(iters);
}
BENCHMARK(BM_cpu_half_float)->Arg(64 << 10)->Arg(32 << 20);
static void BM_gpu_float_half(int iters, int num) {
testing::ItemsProcessed(static_cast<int64>(iters) * num);
testing::BytesProcessed(static_cast<int64>(iters) * num *
(sizeof(float) + sizeof(Eigen::half)));
testing::UseRealTime();
test::Benchmark("gpu", Cast<float, Eigen::half>(num)).Run(iters);
}
BENCHMARK(BM_gpu_float_half)->Arg(64 << 10)->Arg(32 << 20);
static void BM_gpu_half_float(int iters, int num) {
testing::ItemsProcessed(static_cast<int64>(iters) * num);
testing::BytesProcessed(static_cast<int64>(iters) * num *
(sizeof(float) + sizeof(Eigen::half)));
testing::UseRealTime();
test::Benchmark("gpu", Cast<Eigen::half, float>(num)).Run(iters);
}
BENCHMARK(BM_gpu_half_float)->Arg(64 << 10)->Arg(32 << 20);
} // end namespace tensorflow
| apache-2.0 |
potto007/druid-avro | processing/src/main/java/io/druid/query/QueryToolChestWarehouse.java | 986 | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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.druid.query;
/**
*/
public interface QueryToolChestWarehouse
{
public <T, QueryType extends Query<T>> QueryToolChest<T, QueryType> getToolChest(QueryType query);
}
| apache-2.0 |
PangZhi/flink | flink-tests/src/test/java/org/apache/flink/test/operators/DistinctITCase.java | 9950 | /*
* 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.test.operators;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple1;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.api.java.tuple.Tuple5;
import org.apache.flink.test.operators.util.CollectionDataSets;
import org.apache.flink.test.operators.util.CollectionDataSets.CustomType;
import org.apache.flink.test.operators.util.CollectionDataSets.POJO;
import org.apache.flink.test.util.MultipleProgramsTestBase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.List;
/**
* Integration tests for {@link DataSet#distinct}.
*/
@SuppressWarnings("serial")
@RunWith(Parameterized.class)
public class DistinctITCase extends MultipleProgramsTestBase {
public DistinctITCase(TestExecutionMode mode){
super(mode);
}
@Test
public void testCorrectnessOfDistinctOnTuplesWithKeyFieldSelector() throws Exception {
/*
* check correctness of distinct on tuples with key field selector
*/
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<Tuple3<Integer, Long, String>> ds = CollectionDataSets.getSmall3TupleDataSet(env);
DataSet<Tuple3<Integer, Long, String>> distinctDs = ds.union(ds).distinct(0, 1, 2);
List<Tuple3<Integer, Long, String>> result = distinctDs.collect();
String expected = "1,1,Hi\n" +
"2,2,Hello\n" +
"3,2,Hello world\n";
compareResultAsTuples(result, expected);
}
@Test
public void testCorrectnessOfDistinctOnTuplesWithKeyFieldSelectorWithNotAllFieldsSelected() throws Exception{
/*
* check correctness of distinct on tuples with key field selector with not all fields selected
*/
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<Tuple5<Integer, Long, Integer, String, Long>> ds = CollectionDataSets.getSmall5TupleDataSet(env);
DataSet<Tuple1<Integer>> distinctDs = ds.union(ds).distinct(0).project(0);
List<Tuple1<Integer>> result = distinctDs.collect();
String expected = "1\n" +
"2\n";
compareResultAsTuples(result, expected);
}
@Test
public void testCorrectnessOfDistinctOnTuplesWithKeyExtractorFunction() throws Exception {
/*
* check correctness of distinct on tuples with key extractor function
*/
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<Tuple5<Integer, Long, Integer, String, Long>> ds = CollectionDataSets.getSmall5TupleDataSet(env);
DataSet<Tuple1<Integer>> reduceDs = ds.union(ds).distinct(new KeySelector1()).project(0);
List<Tuple1<Integer>> result = reduceDs.collect();
String expected = "1\n" + "2\n";
compareResultAsTuples(result, expected);
}
private static class KeySelector1 implements KeySelector<Tuple5<Integer, Long, Integer, String, Long>, Integer> {
private static final long serialVersionUID = 1L;
@Override
public Integer getKey(Tuple5<Integer, Long, Integer, String, Long> in) {
return in.f0;
}
}
@Test
public void testCorrectnessOfDistinctOnCustomTypeWithTypeExtractor() throws Exception {
/*
* check correctness of distinct on custom type with type extractor
*/
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<CustomType> ds = CollectionDataSets.getCustomTypeDataSet(env);
DataSet<Tuple1<Integer>> reduceDs = ds
.distinct(new KeySelector3())
.map(new Mapper3());
List<Tuple1<Integer>> result = reduceDs.collect();
String expected = "1\n" +
"2\n" +
"3\n" +
"4\n" +
"5\n" +
"6\n";
compareResultAsTuples(result, expected);
}
private static class Mapper3 extends RichMapFunction<CustomType, Tuple1<Integer>> {
@Override
public Tuple1<Integer> map(CustomType value) throws Exception {
return new Tuple1<Integer>(value.myInt);
}
}
private static class KeySelector3 implements KeySelector<CustomType, Integer> {
private static final long serialVersionUID = 1L;
@Override
public Integer getKey(CustomType in) {
return in.myInt;
}
}
@Test
public void testCorrectnessOfDistinctOnTuples() throws Exception{
/*
* check correctness of distinct on tuples
*/
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<Tuple3<Integer, Long, String>> ds = CollectionDataSets.getSmall3TupleDataSet(env);
DataSet<Tuple3<Integer, Long, String>> distinctDs = ds.union(ds).distinct();
List<Tuple3<Integer, Long, String>> result = distinctDs.collect();
String expected = "1,1,Hi\n" +
"2,2,Hello\n" +
"3,2,Hello world\n";
compareResultAsTuples(result, expected);
}
@Test
public void testCorrectnessOfDistinctOnCustomTypeWithTupleReturningTypeExtractor() throws Exception{
/*
* check correctness of distinct on custom type with tuple-returning type extractor
*/
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<Tuple5<Integer, Long, Integer, String, Long>> ds = CollectionDataSets.get5TupleDataSet(env);
DataSet<Tuple2<Integer, Long>> reduceDs = ds
.distinct(new KeySelector2())
.project(0, 4);
List<Tuple2<Integer, Long>> result = reduceDs.collect();
String expected = "1,1\n" +
"2,1\n" +
"2,2\n" +
"3,2\n" +
"3,3\n" +
"4,1\n" +
"4,2\n" +
"5,1\n" +
"5,2\n" +
"5,3\n";
compareResultAsTuples(result, expected);
}
private static class KeySelector2 implements KeySelector<Tuple5<Integer, Long, Integer, String, Long>, Tuple2<Integer, Long>> {
private static final long serialVersionUID = 1L;
@Override
public Tuple2<Integer, Long> getKey(Tuple5<Integer, Long, Integer, String, Long> t) {
return new Tuple2<Integer, Long>(t.f0, t.f4);
}
}
@Test
public void testCorrectnessOfDistinctOnTuplesWithFieldExpressions() throws Exception {
/*
* check correctness of distinct on tuples with field expressions
*/
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<Tuple5<Integer, Long, Integer, String, Long>> ds = CollectionDataSets.getSmall5TupleDataSet(env);
DataSet<Tuple1<Integer>> reduceDs = ds.union(ds).distinct("f0").project(0);
List<Tuple1<Integer>> result = reduceDs.collect();
String expected = "1\n" +
"2\n";
compareResultAsTuples(result, expected);
}
@Test
public void testCorrectnessOfDistinctOnPojos() throws Exception {
/*
* check correctness of distinct on Pojos
*/
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<POJO> ds = CollectionDataSets.getDuplicatePojoDataSet(env);
DataSet<Integer> reduceDs = ds.distinct("nestedPojo.longNumber").map(new Mapper2());
List<Integer> result = reduceDs.collect();
String expected = "10000\n20000\n30000\n";
compareResultAsText(result, expected);
}
private static class Mapper2 implements MapFunction<CollectionDataSets.POJO, Integer> {
@Override
public Integer map(POJO value) throws Exception {
return (int) value.nestedPojo.longNumber;
}
}
@Test
public void testDistinctOnFullPojo() throws Exception {
/*
* distinct on full Pojo
*/
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<POJO> ds = CollectionDataSets.getDuplicatePojoDataSet(env);
DataSet<Integer> reduceDs = ds.distinct().map(new Mapper1());
List<Integer> result = reduceDs.collect();
String expected = "10000\n20000\n30000\n";
compareResultAsText(result, expected);
}
private static class Mapper1 implements MapFunction<CollectionDataSets.POJO, Integer> {
@Override
public Integer map(POJO value) throws Exception {
return (int) value.nestedPojo.longNumber;
}
}
@Test
public void testCorrectnessOfDistinctOnAtomic() throws Exception {
/*
* check correctness of distinct on Integers
*/
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<Integer> ds = CollectionDataSets.getIntegerDataSet(env);
DataSet<Integer> reduceDs = ds.distinct();
List<Integer> result = reduceDs.collect();
String expected = "1\n2\n3\n4\n5";
compareResultAsText(result, expected);
}
@Test
public void testCorrectnessOfDistinctOnAtomicWithSelectAllChar() throws Exception {
/*
* check correctness of distinct on Strings, using Keys.ExpressionKeys.SELECT_ALL_CHAR
*/
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<String> ds = CollectionDataSets.getStringDataSet(env);
DataSet<String> reduceDs = ds.union(ds).distinct("*");
List<String> result = reduceDs.collect();
String expected = "I am fine.\n" +
"Luke Skywalker\n" +
"LOL\n" +
"Hello world, how are you?\n" +
"Hi\n" +
"Hello world\n" +
"Hello\n" +
"Random comment\n";
compareResultAsText(result, expected);
}
}
| apache-2.0 |
nirosrepo/wso2-axis2 | modules/corba/src/org/apache/axis2/corba/idl/values/AbstractCollectionValue.java | 2734 | /*
* 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.axis2.corba.idl.values;
import org.apache.axis2.corba.idl.types.AbstractCollectionType;
import org.apache.axis2.corba.idl.types.CompositeDataType;
import org.omg.CORBA_2_3.portable.InputStream;
import org.omg.CORBA_2_3.portable.OutputStream;
public abstract class AbstractCollectionValue extends AbstractValue {
protected Object[] values = null;
public AbstractCollectionValue(CompositeDataType dataType) {
super(dataType);
}
public AbstractCollectionValue(AbstractCollectionType dataType) {
super(dataType);
}
public Object[] getValues() {
return values;
}
public void setValues(Object[] values) {
this.values = values;
}
public abstract void read(InputStream inputStream);
public abstract void write(OutputStream outputStream);
public String toString() {
AbstractCollectionType collectionType = (AbstractCollectionType) dataType;
String type = null;
if (collectionType.isArray())
type = "Array: ";
else if (collectionType.isSequence())
type = "Sequence: ";
return type + collection2String(values);
}
private String collection2String(Object[] collectionValues) {
StringBuffer str = new StringBuffer();
for (int i = 0; i < collectionValues.length; i++) {
Object value = collectionValues[i];
String elem;
if (value instanceof Object[]) {
elem = collection2String((Object[]) value);
} else {
if (value != null) {
elem = value.toString();
} else {
elem = "null";
}
}
str.append(", ");
str.append(elem);
}
return "{" + str.substring(2) + "}";
}
}
| apache-2.0 |
chenqifeng/CTK | Applications/ctkQtTesting/ctkQtTestingMain.cpp | 1217 | /*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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.
=============================================================================*/
// QT includes
#include <QApplication>
#include <QMainWindow>
// CTK includes
#include <ctkQtTestingMainWindow.h>
int main(int argv, char** argc)
{
QApplication app(argv, argc);
// qApp->setOrganizationName("CTK");
// qApp->setOrganizationDomain("commontk.org");
// qApp->setApplicationName("ctkQtTesting");
ctkQtTestingMainWindow mainWindow;
mainWindow.show();
return app.exec();
}
| apache-2.0 |
davidpelaez/kubernetes | pkg/kubectl/cmd/util/helpers_test.go | 8204 | /*
Copyright 2014 The Kubernetes 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.
*/
package util
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"syscall"
"testing"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api/testapi"
"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
"github.com/GoogleCloudPlatform/kubernetes/pkg/util/fielderrors"
)
func TestMerge(t *testing.T) {
tests := []struct {
obj runtime.Object
fragment string
expected runtime.Object
expectErr bool
kind string
}{
{
kind: "Pod",
obj: &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: "foo",
},
},
fragment: fmt.Sprintf(`{ "apiVersion": "%s" }`, testapi.Version()),
expected: &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: "foo",
},
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicyAlways,
DNSPolicy: api.DNSClusterFirst,
},
},
},
/* TODO: uncomment this test once Merge is updated to use
strategic-merge-patch. See #8449.
{
kind: "Pod",
obj: &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: "foo",
},
Spec: api.PodSpec{
Containers: []api.Container{
api.Container{
Name: "c1",
Image: "red-image",
},
api.Container{
Name: "c2",
Image: "blue-image",
},
},
},
},
fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "containers": [ { "name": "c1", "image": "green-image" } ] } }`, testapi.Version()),
expected: &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: "foo",
},
Spec: api.PodSpec{
Containers: []api.Container{
api.Container{
Name: "c1",
Image: "green-image",
},
api.Container{
Name: "c2",
Image: "blue-image",
},
},
},
},
}, */
{
kind: "Pod",
obj: &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: "foo",
},
},
fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "volumes": [ {"name": "v1"}, {"name": "v2"} ] } }`, testapi.Version()),
expected: &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: "foo",
},
Spec: api.PodSpec{
Volumes: []api.Volume{
{
Name: "v1",
VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}},
},
{
Name: "v2",
VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}},
},
},
RestartPolicy: api.RestartPolicyAlways,
DNSPolicy: api.DNSClusterFirst,
},
},
},
{
kind: "Pod",
obj: &api.Pod{},
fragment: "invalid json",
expected: &api.Pod{},
expectErr: true,
},
{
kind: "Service",
obj: &api.Service{},
fragment: `{ "apiVersion": "badVersion" }`,
expectErr: true,
},
{
kind: "Service",
obj: &api.Service{
Spec: api.ServiceSpec{},
},
fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "ports": [ { "port": 0 } ] } }`, testapi.Version()),
expected: &api.Service{
Spec: api.ServiceSpec{
SessionAffinity: "None",
Type: api.ServiceTypeClusterIP,
Ports: []api.ServicePort{
{
Protocol: api.ProtocolTCP,
Port: 0,
},
},
},
},
},
{
kind: "Service",
obj: &api.Service{
Spec: api.ServiceSpec{
Selector: map[string]string{
"version": "v1",
},
},
},
fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "selector": { "version": "v2" } } }`, testapi.Version()),
expected: &api.Service{
Spec: api.ServiceSpec{
SessionAffinity: "None",
Type: api.ServiceTypeClusterIP,
Selector: map[string]string{
"version": "v2",
},
},
},
},
}
for i, test := range tests {
out, err := Merge(test.obj, test.fragment, test.kind)
if !test.expectErr {
if err != nil {
t.Errorf("testcase[%d], unexpected error: %v", i, err)
} else if !reflect.DeepEqual(out, test.expected) {
t.Errorf("\n\ntestcase[%d]\nexpected:\n%+v\nsaw:\n%+v", i, test.expected, out)
}
}
if test.expectErr && err == nil {
t.Errorf("testcase[%d], unexpected non-error", i)
}
}
}
type fileHandler struct {
data []byte
}
func (f *fileHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/error" {
res.WriteHeader(http.StatusNotFound)
return
}
res.WriteHeader(http.StatusOK)
res.Write(f.data)
}
func TestReadConfigData(t *testing.T) {
httpData := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
server := httptest.NewServer(&fileHandler{data: httpData})
fileData := []byte{11, 12, 13, 14, 15, 16, 17, 18, 19}
f, err := ioutil.TempFile("", "config")
if err != nil {
t.Errorf("unexpected error setting up config file")
t.Fail()
}
defer syscall.Unlink(f.Name())
ioutil.WriteFile(f.Name(), fileData, 0644)
// TODO: test TLS here, requires making it possible to inject the HTTP client.
tests := []struct {
config string
data []byte
expectErr bool
}{
{
config: server.URL,
data: httpData,
},
{
config: server.URL + "/error",
expectErr: true,
},
{
config: "http://some.non.existent.foobar",
expectErr: true,
},
{
config: f.Name(),
data: fileData,
},
{
config: "some-non-existent-file",
expectErr: true,
},
{
config: "",
expectErr: true,
},
}
for _, test := range tests {
dataOut, err := ReadConfigData(test.config)
if err != nil && !test.expectErr {
t.Errorf("unexpected err: %v for %s", err, test.config)
}
if err == nil && test.expectErr {
t.Errorf("unexpected non-error for %s", test.config)
}
if !test.expectErr && !reflect.DeepEqual(test.data, dataOut) {
t.Errorf("unexpected data: %v, expected %v", dataOut, test.data)
}
}
}
func TestCheckInvalidErr(t *testing.T) {
tests := []struct {
err error
expected string
}{
{
errors.NewInvalid("Invalid1", "invalidation", fielderrors.ValidationErrorList{fielderrors.NewFieldInvalid("Cause", "single", "details")}),
`Error from server: Invalid1 "invalidation" is invalid: Cause: invalid value 'single': details`,
},
{
errors.NewInvalid("Invalid2", "invalidation", fielderrors.ValidationErrorList{fielderrors.NewFieldInvalid("Cause", "multi1", "details"), fielderrors.NewFieldInvalid("Cause", "multi2", "details")}),
`Error from server: Invalid2 "invalidation" is invalid: [Cause: invalid value 'multi1': details, Cause: invalid value 'multi2': details]`,
},
{
errors.NewInvalid("Invalid3", "invalidation", fielderrors.ValidationErrorList{}),
`Error from server: Invalid3 "invalidation" is invalid: <nil>`,
},
}
var errReturned string
errHandle := func(err string) {
errReturned = err
}
for _, test := range tests {
checkErr(test.err, errHandle)
if errReturned != test.expected {
t.Fatalf("Got: %s, expected: %s", errReturned, test.expected)
}
}
}
func TestDumpReaderToFile(t *testing.T) {
testString := "TEST STRING"
tempFile, err := ioutil.TempFile("", "hlpers_test_dump_")
if err != nil {
t.Errorf("unexpected error setting up a temporary file %v", err)
}
defer syscall.Unlink(tempFile.Name())
defer tempFile.Close()
err = DumpReaderToFile(strings.NewReader(testString), tempFile.Name())
if err != nil {
t.Errorf("error in DumpReaderToFile: %v", err)
}
data, err := ioutil.ReadFile(tempFile.Name())
if err != nil {
t.Errorf("error when reading %s: %v", tempFile, err)
}
stringData := string(data)
if stringData != testString {
t.Fatalf("Wrong file content %s != %s", testString, stringData)
}
}
| apache-2.0 |
cielly/cielly.github.io | node_modules/topojson/node_modules/d3-geo-projection/test/van-der-grinten4-test.js | 1486 | var vows = require("vows"),
assert = require("./assert"),
load = require("./load");
var suite = vows.describe("d3.geo.vanDerGrinten4");
suite.addBatch({
"vanDerGrinten4": {
topic: load("van-der-grinten4"),
"default": {
topic: function(geo) { return geo.vanDerGrinten4(); },
"doesn't generate NaNs": function(vanDerGrinten4) {
assert.inDelta(vanDerGrinten4([20, 1e-7]), [532.359877, 250], 1e-6);
assert.inDelta(vanDerGrinten4([180.0000000000001, -90.00000000000003]), [480, 485.619449], 1e-6);
assert.inDelta(vanDerGrinten4([-180, -90.00000000000003]), [480, 485.619449], 1e-6);
},
"projections and inverse projections": function(vanDerGrinten4) {
assert.equalInverse(vanDerGrinten4, [ 0, 0], [480, 250]);
assert.equalInverse(vanDerGrinten4, [ 0, -45], [480, 367.809724]);
assert.equalInverse(vanDerGrinten4, [ 0, 45], [480, 132.190275]);
assert.equalInverse(vanDerGrinten4, [-90, 0], [244.380550, 250]);
assert.equalInverse(vanDerGrinten4, [ 90, 0], [715.619449, 250]);
assert.equalInverse(vanDerGrinten4, [-80, 15], [274.023642, 209.610498]);
assert.equalInverse(vanDerGrinten4, [ 1, 1], [482.617670, 247.382005]);
assert.equalInverse(vanDerGrinten4, [ 15, 45], [509.605158, 131.892658]);
assert.equalInverse(vanDerGrinten4, [-180, 15], [ 12.226093, 204.955105]);
}
}
}
});
suite.export(module);
| mit |
pandamako/paperclip | lib/paperclip/attachment.rb | 21629 | # encoding: utf-8
require 'uri'
require 'paperclip/url_generator'
require 'active_support/deprecation'
module Paperclip
# The Attachment class manages the files for a given attachment. It saves
# when the model saves, deletes when the model is destroyed, and processes
# the file upon assignment.
class Attachment
def self.default_options
@default_options ||= {
:convert_options => {},
:default_style => :original,
:default_url => "/:attachment/:style/missing.png",
:escape_url => true,
:restricted_characters => /[&$+,\/:;=?@<>\[\]\{\}\|\\\^~%# ]/,
:filename_cleaner => nil,
:hash_data => ":class/:attachment/:id/:style/:updated_at",
:hash_digest => "SHA1",
:interpolator => Paperclip::Interpolations,
:only_process => [],
:path => ":rails_root/public:url",
:preserve_files => false,
:processors => [:thumbnail],
:source_file_options => {},
:storage => :filesystem,
:styles => {},
:url => "/system/:class/:attachment/:id_partition/:style/:filename",
:url_generator => Paperclip::UrlGenerator,
:use_default_time_zone => true,
:use_timestamp => true,
:whiny => Paperclip.options[:whiny] || Paperclip.options[:whiny_thumbnails],
:validate_media_type => true,
:check_validity_before_processing => true
}
end
attr_reader :name, :instance, :default_style, :convert_options, :queued_for_write, :whiny,
:options, :interpolator, :source_file_options
attr_accessor :post_processing
# Creates an Attachment object. +name+ is the name of the attachment,
# +instance+ is the model object instance it's attached to, and
# +options+ is the same as the hash passed to +has_attached_file+.
#
# Options include:
#
# +url+ - a relative URL of the attachment. This is interpolated using +interpolator+
# +path+ - where on the filesystem to store the attachment. This is interpolated using +interpolator+
# +styles+ - a hash of options for processing the attachment. See +has_attached_file+ for the details
# +only_process+ - style args to be run through the post-processor. This defaults to the empty list
# +default_url+ - a URL for the missing image
# +default_style+ - the style to use when an argument is not specified e.g. #url, #path
# +storage+ - the storage mechanism. Defaults to :filesystem
# +use_timestamp+ - whether to append an anti-caching timestamp to image URLs. Defaults to true
# +whiny+, +whiny_thumbnails+ - whether to raise when thumbnailing fails
# +use_default_time_zone+ - related to +use_timestamp+. Defaults to true
# +hash_digest+ - a string representing a class that will be used to hash URLs for obfuscation
# +hash_data+ - the relative URL for the hash data. This is interpolated using +interpolator+
# +hash_secret+ - a secret passed to the +hash_digest+
# +convert_options+ - flags passed to the +convert+ command for processing
# +source_file_options+ - flags passed to the +convert+ command that controls how the file is read
# +processors+ - classes that transform the attachment. Defaults to [:thumbnail]
# +preserve_files+ - whether to keep files on the filesystem when deleting or clearing the attachment. Defaults to false
# +filename_cleaner+ - An object that responds to #call(filename) that will strip unacceptable charcters from filename
# +interpolator+ - the object used to interpolate filenames and URLs. Defaults to Paperclip::Interpolations
# +url_generator+ - the object used to generate URLs, using the interpolator. Defaults to Paperclip::UrlGenerator
# +escape_url+ - Perform URI escaping to URLs. Defaults to true
def initialize(name, instance, options = {})
@name = name
@instance = instance
options = self.class.default_options.deep_merge(options)
@options = options
@post_processing = true
@queued_for_delete = []
@queued_for_write = {}
@errors = {}
@dirty = false
@interpolator = options[:interpolator]
@url_generator = options[:url_generator].new(self, @options)
@source_file_options = options[:source_file_options]
@whiny = options[:whiny]
initialize_storage
end
# What gets called when you call instance.attachment = File. It clears
# errors, assigns attributes, and processes the file. It also queues up the
# previous file for deletion, to be flushed away on #save of its host. In
# addition to form uploads, you can also assign another Paperclip
# attachment:
# new_user.avatar = old_user.avatar
def assign(uploaded_file)
@file = Paperclip.io_adapters.for(uploaded_file)
ensure_required_accessors!
ensure_required_validations!
if @file.assignment?
clear(*only_process)
if @file.nil?
nil
else
assign_attributes
post_process_file
reset_file_if_original_reprocessed
end
else
nil
end
end
# Returns the public URL of the attachment with a given style. This does
# not necessarily need to point to a file that your Web server can access
# and can instead point to an action in your app, for example for fine grained
# security; this has a serious performance tradeoff.
#
# Options:
#
# +timestamp+ - Add a timestamp to the end of the URL. Default: true.
# +escape+ - Perform URI escaping to the URL. Default: true.
#
# Global controls (set on has_attached_file):
#
# +interpolator+ - The object that fills in a URL pattern's variables.
# +default_url+ - The image to show when the attachment has no image.
# +url+ - The URL for a saved image.
# +url_generator+ - The object that generates a URL. Default: Paperclip::UrlGenerator.
#
# As mentioned just above, the object that generates this URL can be passed
# in, for finer control. This object must respond to two methods:
#
# +#new(Paperclip::Attachment, options_hash)+
# +#for(style_name, options_hash)+
def url(style_name = default_style, options = {})
if options == true || options == false # Backwards compatibility.
@url_generator.for(style_name, default_options.merge(:timestamp => options))
else
@url_generator.for(style_name, default_options.merge(options))
end
end
def default_options
{
:timestamp => @options[:use_timestamp],
:escape => @options[:escape_url]
}
end
# Alias to +url+ that allows using the expiring_url method provided by the cloud
# storage implementations, but keep using filesystem storage for development and
# testing.
def expiring_url(time = 3600, style_name = default_style)
url(style_name)
end
# Returns the path of the attachment as defined by the :path option. If the
# file is stored in the filesystem the path refers to the path of the file
# on disk. If the file is stored in S3, the path is the "key" part of the
# URL, and the :bucket option refers to the S3 bucket.
def path(style_name = default_style)
path = original_filename.nil? ? nil : interpolate(path_option, style_name)
path.respond_to?(:unescape) ? path.unescape : path
end
# :nodoc:
def staged_path(style_name = default_style)
if staged?
@queued_for_write[style_name].path
end
end
# :nodoc:
def staged?
! @queued_for_write.empty?
end
# Alias to +url+
def to_s style_name = default_style
url(style_name)
end
def as_json(options = nil)
to_s((options && options[:style]) || default_style)
end
def default_style
@options[:default_style]
end
def styles
if @options[:styles].respond_to?(:call) || @normalized_styles.nil?
styles = @options[:styles]
styles = styles.call(self) if styles.respond_to?(:call)
@normalized_styles = styles.dup
styles.each_pair do |name, options|
@normalized_styles[name.to_sym] = Paperclip::Style.new(name.to_sym, options.dup, self)
end
end
@normalized_styles
end
def only_process
only_process = @options[:only_process].dup
only_process = only_process.call(self) if only_process.respond_to?(:call)
only_process.map(&:to_sym)
end
def processors
processing_option = @options[:processors]
if processing_option.respond_to?(:call)
processing_option.call(instance)
else
processing_option
end
end
# Returns an array containing the errors on this attachment.
def errors
@errors
end
# Returns true if there are changes that need to be saved.
def dirty?
@dirty
end
# Saves the file, if there are no errors. If there are, it flushes them to
# the instance's errors and returns false, cancelling the save.
def save
flush_deletes unless @options[:keep_old_files]
flush_writes
@dirty = false
true
end
# Clears out the attachment. Has the same effect as previously assigning
# nil to the attachment. Does NOT save. If you wish to clear AND save,
# use #destroy.
def clear(*styles_to_clear)
if styles_to_clear.any?
queue_some_for_delete(*styles_to_clear)
else
queue_all_for_delete
@queued_for_write = {}
@errors = {}
end
end
# Destroys the attachment. Has the same effect as previously assigning
# nil to the attachment *and saving*. This is permanent. If you wish to
# wipe out the existing attachment but not save, use #clear.
def destroy
clear
save
end
# Returns the uploaded file if present.
def uploaded_file
instance_read(:uploaded_file)
end
# Returns the name of the file as originally assigned, and lives in the
# <attachment>_file_name attribute of the model.
def original_filename
instance_read(:file_name)
end
# Returns the size of the file as originally assigned, and lives in the
# <attachment>_file_size attribute of the model.
def size
instance_read(:file_size) || (@queued_for_write[:original] && @queued_for_write[:original].size)
end
# Returns the fingerprint of the file, if one's defined. The fingerprint is
# stored in the <attachment>_fingerprint attribute of the model.
def fingerprint
instance_read(:fingerprint)
end
# Returns the content_type of the file as originally assigned, and lives
# in the <attachment>_content_type attribute of the model.
def content_type
instance_read(:content_type)
end
# Returns the creation time of the file as originally assigned, and
# lives in the <attachment>_created_at attribute of the model.
def created_at
if able_to_store_created_at?
time = instance_read(:created_at)
time && time.to_f.to_i
end
end
# Returns the last modified time of the file as originally assigned, and
# lives in the <attachment>_updated_at attribute of the model.
def updated_at
time = instance_read(:updated_at)
time && time.to_f.to_i
end
# The time zone to use for timestamp interpolation. Using the default
# time zone ensures that results are consistent across all threads.
def time_zone
@options[:use_default_time_zone] ? Time.zone_default : Time.zone
end
# Returns a unique hash suitable for obfuscating the URL of an otherwise
# publicly viewable attachment.
def hash_key(style_name = default_style)
raise ArgumentError, "Unable to generate hash without :hash_secret" unless @options[:hash_secret]
require 'openssl' unless defined?(OpenSSL)
data = interpolate(@options[:hash_data], style_name)
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.const_get(@options[:hash_digest]).new, @options[:hash_secret], data)
end
# This method really shouldn't be called that often. It's expected use is
# in the paperclip:refresh rake task and that's it. It will regenerate all
# thumbnails forcefully, by reobtaining the original file and going through
# the post-process again.
# NOTE: Calling reprocess WILL NOT delete existing files. This is due to
# inconsistencies in timing of S3 commands. It's possible that calling
# #reprocess! will lose data if the files are not kept.
def reprocess!(*style_args)
saved_only_process, @options[:only_process] = @options[:only_process], style_args
saved_preserve_files, @options[:preserve_files] = @options[:preserve_files], true
begin
assign(self)
save
instance.save
rescue Errno::EACCES => e
warn "#{e} - skipping file."
false
ensure
@options[:only_process] = saved_only_process
@options[:preserve_files] = saved_preserve_files
end
end
# Returns true if a file has been assigned.
def file?
!original_filename.blank?
end
alias :present? :file?
def blank?
not present?
end
# Determines whether the instance responds to this attribute. Used to prevent
# calculations on fields we won't even store.
def instance_respond_to?(attr)
instance.respond_to?(:"#{name}_#{attr}")
end
# Writes the attachment-specific attribute on the instance. For example,
# instance_write(:file_name, "me.jpg") will write "me.jpg" to the instance's
# "avatar_file_name" field (assuming the attachment is called avatar).
def instance_write(attr, value)
setter = :"#{name}_#{attr}="
if instance.respond_to?(setter)
instance.send(setter, value)
end
end
# Reads the attachment-specific attribute on the instance. See instance_write
# for more details.
def instance_read(attr)
getter = :"#{name}_#{attr}"
if instance.respond_to?(getter)
instance.send(getter)
end
end
private
def path_option
@options[:path].respond_to?(:call) ? @options[:path].call(self) : @options[:path]
end
def active_validator_classes
@instance.class.validators.map(&:class)
end
def missing_required_validator?
(active_validator_classes.flat_map(&:ancestors) & Paperclip::REQUIRED_VALIDATORS).empty?
end
def ensure_required_validations!
if missing_required_validator?
raise Paperclip::Errors::MissingRequiredValidatorError
end
end
def ensure_required_accessors! #:nodoc:
%w(file_name).each do |field|
unless @instance.respond_to?("#{name}_#{field}") && @instance.respond_to?("#{name}_#{field}=")
raise Paperclip::Error.new("#{@instance.class} model missing required attr_accessor for '#{name}_#{field}'")
end
end
end
def log message #:nodoc:
Paperclip.log(message)
end
def initialize_storage #:nodoc:
storage_class_name = @options[:storage].to_s.downcase.camelize
begin
storage_module = Paperclip::Storage.const_get(storage_class_name)
rescue NameError
raise Errors::StorageMethodNotFound, "Cannot load storage module '#{storage_class_name}'"
end
self.extend(storage_module)
end
def assign_attributes
@queued_for_write[:original] = @file
assign_file_information
assign_fingerprint(@file.fingerprint)
assign_timestamps
end
def assign_file_information
instance_write(:file_name, cleanup_filename(@file.original_filename))
instance_write(:content_type, @file.content_type.to_s.strip)
instance_write(:file_size, @file.size)
end
def assign_fingerprint(fingerprint)
if instance_respond_to?(:fingerprint)
instance_write(:fingerprint, fingerprint)
end
end
def assign_timestamps
if has_enabled_but_unset_created_at?
instance_write(:created_at, Time.now)
end
instance_write(:updated_at, Time.now)
end
def post_process_file
dirty!
if post_processing
post_process(*only_process)
end
end
def dirty!
@dirty = true
end
def reset_file_if_original_reprocessed
instance_write(:file_size, @queued_for_write[:original].size)
assign_fingerprint(@queued_for_write[:original].fingerprint)
reset_updater
end
def reset_updater
if instance.respond_to?(updater)
instance.send(updater)
end
end
def updater
:"#{name}_file_name_will_change!"
end
def extra_options_for(style) #:nodoc:
process_options(:convert_options, style)
end
def extra_source_file_options_for(style) #:nodoc:
process_options(:source_file_options, style)
end
def process_options(options_type, style) #:nodoc:
all_options = @options[options_type][:all]
all_options = all_options.call(instance) if all_options.respond_to?(:call)
style_options = @options[options_type][style]
style_options = style_options.call(instance) if style_options.respond_to?(:call)
[ style_options, all_options ].compact.join(" ")
end
def post_process(*style_args) #:nodoc:
return if @queued_for_write[:original].nil?
instance.run_paperclip_callbacks(:post_process) do
instance.run_paperclip_callbacks(:"#{name}_post_process") do
unless @options[:check_validity_before_processing] && instance.errors.any?
post_process_styles(*style_args)
end
end
end
end
def post_process_styles(*style_args) #:nodoc:
post_process_style(:original, styles[:original]) if styles.include?(:original) && process_style?(:original, style_args)
styles.reject{ |name, style| name == :original }.each do |name, style|
post_process_style(name, style) if process_style?(name, style_args)
end
end
def post_process_style(name, style) #:nodoc:
begin
raise RuntimeError.new("Style #{name} has no processors defined.") if style.processors.blank?
intermediate_files = []
@queued_for_write[name] = style.processors.inject(@queued_for_write[:original]) do |file, processor|
file = Paperclip.processor(processor).make(file, style.processor_options, self)
intermediate_files << file
file
end
unadapted_file = @queued_for_write[name]
@queued_for_write[name] = Paperclip.io_adapters.for(@queued_for_write[name])
unadapted_file.close if unadapted_file.respond_to?(:close)
@queued_for_write[name]
rescue Paperclip::Errors::NotIdentifiedByImageMagickError => e
log("An error was received while processing: #{e.inspect}")
(@errors[:processing] ||= []) << e.message if @options[:whiny]
ensure
unlink_files(intermediate_files)
end
end
def process_style?(style_name, style_args) #:nodoc:
style_args.empty? || style_args.include?(style_name)
end
def interpolate(pattern, style_name = default_style) #:nodoc:
interpolator.interpolate(pattern, self, style_name)
end
def queue_some_for_delete(*styles)
@queued_for_delete += styles.uniq.map do |style|
path(style) if exists?(style)
end.compact
end
def queue_all_for_delete #:nodoc:
return if !file?
unless @options[:preserve_files]
@queued_for_delete += [:original, *styles.keys].uniq.map do |style|
path(style) if exists?(style)
end.compact
end
instance_write(:file_name, nil)
instance_write(:content_type, nil)
instance_write(:file_size, nil)
instance_write(:fingerprint, nil)
instance_write(:created_at, nil) if has_enabled_but_unset_created_at?
instance_write(:updated_at, nil)
end
def flush_errors #:nodoc:
@errors.each do |error, message|
[message].flatten.each {|m| instance.errors.add(name, m) }
end
end
# called by storage after the writes are flushed and before @queued_for_write is cleared
def after_flush_writes
unlink_files(@queued_for_write.values)
end
def unlink_files(files)
Array(files).each do |file|
file.close unless file.closed?
file.unlink if file.respond_to?(:unlink) && file.path.present? && File.exist?(file.path)
end
end
# You can either specifiy :restricted_characters or you can define your own
# :filename_cleaner object. This object needs to respond to #call and takes
# the filename that will be cleaned. It should return the cleaned filenme.
def filename_cleaner
@options[:filename_cleaner] || FilenameCleaner.new(@options[:restricted_characters])
end
def cleanup_filename(filename)
filename_cleaner.call(filename)
end
# Check if attachment database table has a created_at field
def able_to_store_created_at?
@instance.respond_to?("#{name}_created_at".to_sym)
end
# Check if attachment database table has a created_at field which is not yet set
def has_enabled_but_unset_created_at?
able_to_store_created_at? && !instance_read(:created_at)
end
end
end
| mit |
yvandouenel/learn_quizz | sites/all/modules/contrib/quiz/theme/quiz-results-browser-body.tpl.php | 2264 | <tbody id="quiz-browser-body">
<?php
// We need to separate the title and the checkbox. We make a custom options array...
$full_options = array();
foreach ($form['name']['#options'] as $key => $value) {
$full_options[$key] = $form['name'][$key];
$full_options[$key]['#title'] = '';
}
foreach ($form['name']['#options'] as $key => $value): ?>
<tr class="quiz-results-browser-row" id="browser-<?php print $key ?>">
<td valign="top">
<?php
// Find nid and rid
$matches = array();
preg_match('/([0-9]+)-([0-9]+)/', $key, $matches);
$res_nid = $matches[1];
$res_rid = $matches[2];?>
<span class = "container-inline" style = "white-space: nowrap;"><?php print drupal_render($full_options[$key]) . $value?></span>
<div class = "quiz-hover-menu"><?php print $form['hover_menu'][$key]['#value']?></div>
</td><td valign="top">
<?php print$form['started'][$key]['#value'] ?>
</td><td valign="top">
<?php print $form['finished'][$key]['#value'] ?>
<?php if ($form['finished'][$key]['#value'] != t('In progress')): ?>
<br/><em>(<?php print t('Duration') ?>: <?php print $form['duration'][$key]['#value'] ?>')</em>
<?php endif ?>
</td><td valign ="top">
<?php if (!is_numeric($form['score'][$key]['#value'])): ?>
<?php print $form['score'][$key]['#value'] ?>
<?php elseif ($form['evaluated'][$key]['#value'] == t('No')): ?>
<?php print t('Not evaluated') ?>
<?php else: ?>
<?php if (!empty($form['pass_rate'][$key]['#value']) && is_numeric($form['score'][$key]['#value'])) {
$pre_score = $form['score'][$key]['#value'] >= $form['pass_rate'][$key]['#value'] ? '<span class = "quiz-passed">' : '<span class = "quiz-failed">';
$post_score = $form['score'][$key]['#value'] >= $form['pass_rate'][$key]['#value'] ?' %<br><em>'. t('Passed') .'</em></span>' : ' %<br><em>'. t('Failed') .'</em></span>';
}
else {
$pre_score = '';
$post_score = ' %';
}
print $pre_score . $form['score'][$key]['#value'] . $post_score ?>
<?php endif ?>
</td><td valign="top">
<?php print $form['evaluated'][$key]['#value'] ?>
</td>
</tr>
<?php endforeach; ?>
</tbody> | gpl-2.0 |
qky1412/prestashop-local | modules/blockwishlist/upgrade/install-1.1.3.php | 491 | <?php
if (!defined('_PS_VERSION_'))
exit;
function upgrade_module_1_1_3()
{
$list_fields = Db::getInstance()->executeS('SHOW FIELDS FROM `'._DB_PREFIX_.'wishlist`');
if (is_array($list_fields))
{
foreach ($list_fields as $k => $field)
$list_fields[$k] = $field['Field'];
if (in_array('is_default', $list_fields))
return (bool)Db::getInstance()->execute('ALTER TABLE `'._DB_PREFIX_.'wishlist` CHANGE `is_default` `default` INT( 11 ) NOT NULL DEFAULT "0"');
}
return true;
}
| gpl-3.0 |
halberom/ansible | lib/ansible/modules/network/illumos/ipadm_addrprop.py | 7601 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2016, Adam Števko <adam.stevko@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
---
module: ipadm_addrprop
short_description: Manage IP address properties on Solaris/illumos systems.
description:
- Modify IP address properties on Solaris/illumos systems.
version_added: "2.3"
author: Adam Števko (@xen0l)
options:
addrobj:
description:
- Specifies the address object we want to manage.
required: true
aliases: [nic, interface]
property:
description:
- Specifies the name of the address property we want to manage.
required: true
aliases: [name]
value:
description:
- Specifies the value we want to set for the address property.
required: false
temporary:
description:
- Specifies that the address property value is temporary.
Temporary values do not persist across reboots.
required: false
default: false
state:
description:
- Set or reset the property value.
required: false
default: present
choices: [ "present", "absent", "reset" ]
'''
EXAMPLES = '''
name: Mark address on addrobj as deprecated
ipadm_addrprop: property=deprecated value=on addrobj=e1000g0/v6
name: Set network prefix length for addrobj
ipadm_addrprop: addrobj=bge0/v4 name=prefixlen value=26
'''
RETURN = '''
property:
description: property name
returned: always
type: string
sample: deprecated
addrobj:
description: address object name
returned: always
type: string
sample: bge0/v4
state:
description: state of the target
returned: always
type: string
sample: present
temporary:
description: specifies if operation will persist across reboots
returned: always
type: boolean
sample: True
value:
description: property value
returned: when value is provided
type: string
sample: 26
'''
from ansible.module_utils.basic import AnsibleModule
class AddrProp(object):
def __init__(self, module):
self.module = module
self.addrobj = module.params['addrobj']
self.property = module.params['property']
self.value = module.params['value']
self.temporary = module.params['temporary']
self.state = module.params['state']
def property_exists(self):
cmd = [self.module.get_bin_path('ipadm')]
cmd.append('show-addrprop')
cmd.append('-p')
cmd.append(self.property)
cmd.append(self.addrobj)
(rc, _, _) = self.module.run_command(cmd)
if rc == 0:
return True
else:
self.module.fail_json(msg='Unknown property "%s" on addrobj %s' %
(self.property, self.addrobj),
property=self.property,
addrobj=self.addrobj)
def property_is_modified(self):
cmd = [self.module.get_bin_path('ipadm')]
cmd.append('show-addrprop')
cmd.append('-c')
cmd.append('-o')
cmd.append('current,default')
cmd.append('-p')
cmd.append(self.property)
cmd.append(self.addrobj)
(rc, out, _) = self.module.run_command(cmd)
out = out.rstrip()
(value, default) = out.split(':')
if rc == 0 and value == default:
return True
else:
return False
def property_is_set(self):
cmd = [self.module.get_bin_path('ipadm')]
cmd.append('show-addrprop')
cmd.append('-c')
cmd.append('-o')
cmd.append('current')
cmd.append('-p')
cmd.append(self.property)
cmd.append(self.addrobj)
(rc, out, _) = self.module.run_command(cmd)
out = out.rstrip()
if rc == 0 and self.value == out:
return True
else:
return False
def set_property(self):
cmd = [self.module.get_bin_path('ipadm')]
cmd.append('set-addrprop')
if self.temporary:
cmd.append('-t')
cmd.append('-p')
cmd.append(self.property + '=' + self.value)
cmd.append(self.addrobj)
return self.module.run_command(cmd)
def reset_property(self):
cmd = [self.module.get_bin_path('ipadm')]
cmd.append('reset-addrprop')
if self.temporary:
cmd.append('-t')
cmd.append('-p')
cmd.append(self.property)
cmd.append(self.addrobj)
return self.module.run_command(cmd)
def main():
module = AnsibleModule(
argument_spec=dict(
addrobj=dict(required=True, default=None, aliases=['nic, interface']),
property=dict(required=True, aliases=['name']),
value=dict(required=False),
temporary=dict(default=False, type='bool'),
state=dict(
default='present', choices=['absent', 'present', 'reset']),
),
supports_check_mode=True
)
addrprop = AddrProp(module)
rc = None
out = ''
err = ''
result = {}
result['property'] = addrprop.property
result['addrobj'] = addrprop.addrobj
result['state'] = addrprop.state
result['temporary'] = addrprop.temporary
if addrprop.value:
result['value'] = addrprop.value
if addrprop.state == 'absent' or addrprop.state == 'reset':
if addrprop.property_exists():
if not addrprop.property_is_modified():
if module.check_mode:
module.exit_json(changed=True)
(rc, out, err) = addrprop.reset_property()
if rc != 0:
module.fail_json(property=addrprop.property,
addrobj=addrprop.addrobj,
msg=err,
rc=rc)
elif addrprop.state == 'present':
if addrprop.value is None:
module.fail_json(msg='Value is mandatory with state "present"')
if addrprop.property_exists():
if not addrprop.property_is_set():
if module.check_mode:
module.exit_json(changed=True)
(rc, out, err) = addrprop.set_property()
if rc != 0:
module.fail_json(property=addrprop.property,
addrobj=addrprop.addrobj,
msg=err,
rc=rc)
if rc is None:
result['changed'] = False
else:
result['changed'] = True
if out:
result['stdout'] = out
if err:
result['stderr'] = err
module.exit_json(**result)
if __name__ == '__main__':
main()
| gpl-3.0 |
sergecodd/FireFox-OS | B2G/libcore/luni/src/main/java/javax/sql/RowSetWriter.java | 2472 | /*
* 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 javax.sql;
import java.sql.SQLException;
/**
* An interface which provides functionality for a disconnected {@code RowSet}
* to put data updates back to the data source from which the {@code RowSet} was
* originally populated. An object implementing this interface is called a
* writer.
* <p>
* The writer must establish a connection to the {@code RowSet}'s database
* before writing the data. The {@code RowSet} calling this interface must
* implement the {@code RowSetInternal} interface.
* <p>
* The writer may encounter a situation where the updated data needs to be
* written back to the database, but has already been updated there in the mean
* time. How a conflict of this kind is handled is determined by the
* implementation of this writer.
*
* @see RowSetInternal
*/
public interface RowSetWriter {
/**
* Writes changes made in the {@code RowSet}, which is associated with this
* {@code RowSetWriter}, back to the database.
*
* @param theRowSet
* a row set that fulfills the following criteria:
* <ul>
* <li>it must implement the {@code RowSetInternal} interface,</li>
* <li>have this {@code RowSetWriter} registered with it,</li>
* <li>must call this method internally.</li>
* </ul>
* @return {@code true} if the modified data was written, {@code false}
* otherwise (which typically implies some form of conflict).
* @throws SQLException
* if a problem occurs accessing the database.
*/
public boolean writeData(RowSetInternal theRowSet) throws SQLException;
}
| apache-2.0 |
nguyenducnhaty/opengse | testing/server-side/webapps-src/servlet-tests/web/WEB-INF/java/tests/javax_servlet/ServletOutputStream/Println_doubleTestServlet.java | 3686 | /*
* $Header: /home/cvs/jakarta-watchdog-4.0/src/server/servlet-tests/WEB-INF/classes/tests/javax_servlet/ServletOutputStream/Println_doubleTestServlet.java,v 1.2 2002/01/11 22:20:57 rlubke Exp $
* $Revision: 1.2 $
* $Date: 2002/01/11 22:20:57 $
*
* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package tests.javax_servlet.ServletOutputStream;
import javax.servlet.*;
import java.io.IOException;
/* println(double) */
public class Println_doubleTestServlet extends GenericServlet {
public void service ( ServletRequest request, ServletResponse response ) throws ServletException, IOException {
ServletOutputStream sos = null;
double doubleval = 12345.6;
try {
sos = response.getOutputStream();
sos.println( doubleval );
sos.println( doubleval );
} catch ( Exception e ) {
sos.println( "Println_doubleTest test FAILED <BR>" );
sos.println( "Exception thrown by println(double) method <BR>" );
sos.println( "Exception Message:" + e.getMessage() );
}
}
}
| apache-2.0 |
leidenuniv-lacdr-abs/metabolomexchange | src/flight/Flight.php | 2893 | <?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
*/
/**
* The Flight class is a static representation of the framework.
*
* @method static void map($name, $callback) Creates a custom framework method.
* @method static void register($name, $class, array $params = array(), $callback = null) Registers a class to a framework method.
* @method static void before($name, $callback) Adds a filter before a framework method.
* @method static void after($name, $callback) Adds a filter after a framework method.
* @method static void path($path) Adds a path for autoloading classes.
* @method static void get($key) Gets a variable.
* @method static void set($key, $value) Sets a variable.
* @method static void has($key) Checks if a variable is set.
* @method static void clear($key = null) Clears a variable.
* @method static void start() Starts the framework.
* @method static void stop() Stops the framework and sends a response.
* @method static void halt($code = 200, $message = '') Stop the framework with an optional status code and message.
* @method static void route($pattern, $callback) Maps a URL pattern to a callback.
* @method static void redirect($url, $code = 303) Redirects to another URL.
* @method static void render($file, array $data = null, $key = null) Renders a template file.
* @method static void error($exception) Sends an HTTP 500 response.
* @method static void notFound() Sends an HTTP 404 response.
* @method static void etag($id, $type = 'strong') Performs ETag HTTP caching.
* @method static void lastModified($time) Performs last modified HTTP caching.
* @method static void json($data, $code = 200, $encode = true) Sends a JSON response.
* @method static void jsonp($data, $param = 'jsonp', $code = 200, $encode = true) Sends a JSONP response.
*/
class Flight {
/**
* Framework engine.
*
* @var object
*/
private static $engine;
// Don't allow object instantiation
private function __construct() {}
private function __destruct() {}
private function __clone() {}
/**
* Handles calls to static methods.
*
* @param string $name Method name
* @param array $params Method parameters
* @return mixed Callback results
*/
public static function __callStatic($name, $params) {
static $initialized = false;
if (!$initialized) {
require_once __DIR__.'/autoload.php';
self::$engine = new \flight\Engine();
$initialized = true;
}
return \flight\core\Dispatcher::invokeMethod(array(self::$engine, $name), $params);
}
/**
* @return object Application instance
*/
public static function app() {
return self::$engine;
}
}
| apache-2.0 |
blakeembrey/TypeScript | tests/baselines/reference/genericCallWithFunctionTypedArguments4.js | 1105 | //// [genericCallWithFunctionTypedArguments4.ts]
// No inference is made from function typed arguments which have multiple call signatures
class C { foo: string }
class D { bar: string }
var a: {
new(x: boolean): C;
new(x: string): D;
}
function foo4<T, U>(cb: new(x: T) => U) {
var u: U;
return u;
}
var r = foo4(a); // T is {} (candidates boolean and string), U is {} (candidates C and D)
var b: {
new<T>(x: boolean): T;
new<T>(x: T): any;
}
var r2 = foo4(b); // T is {} (candidates boolean and {}), U is any (candidates any and {})
//// [genericCallWithFunctionTypedArguments4.js]
// No inference is made from function typed arguments which have multiple call signatures
var C = (function () {
function C() {
}
return C;
}());
var D = (function () {
function D() {
}
return D;
}());
var a;
function foo4(cb) {
var u;
return u;
}
var r = foo4(a); // T is {} (candidates boolean and string), U is {} (candidates C and D)
var b;
var r2 = foo4(b); // T is {} (candidates boolean and {}), U is any (candidates any and {})
| apache-2.0 |
Medium/closure-library | closure/goog/testing/mockclock_test.js | 17298 | // Copyright 2007 The Closure Library 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.
goog.provide('goog.testing.MockClockTest');
goog.setTestOnly('goog.testing.MockClockTest');
goog.require('goog.Promise');
goog.require('goog.Timer');
goog.require('goog.events');
goog.require('goog.functions');
goog.require('goog.testing.MockClock');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.jsunit');
goog.require('goog.testing.recordFunction');
var stubs = new goog.testing.PropertyReplacer();
function tearDown() {
stubs.reset();
}
function testMockClockWasInstalled() {
var clock = new goog.testing.MockClock();
var originalTimeout = window.setTimeout;
clock.install();
assertNotEquals(window.setTimeout, originalTimeout);
setTimeout(function() {}, 100);
assertEquals(1, clock.getTimeoutsMade());
setInterval(function() {}, 200);
assertEquals(2, clock.getTimeoutsMade());
clock.uninstall();
assertEquals(window.setTimeout, originalTimeout);
assertNull(clock.replacer_);
}
function testSetTimeoutAndTick() {
var clock = new goog.testing.MockClock(true);
var m5 = false, m10 = false, m15 = false, m20 = false;
setTimeout(function() { m5 = true; }, 5);
setTimeout(function() { m10 = true; }, 10);
setTimeout(function() { m15 = true; }, 15);
setTimeout(function() { m20 = true; }, 20);
assertEquals(4, clock.getTimeoutsMade());
assertEquals(4, clock.tick(4));
assertEquals(4, clock.getCurrentTime());
assertEquals(0, clock.getCallbacksTriggered());
assertFalse(m5);
assertFalse(m10);
assertFalse(m15);
assertFalse(m20);
assertEquals(5, clock.tick(1));
assertEquals(5, clock.getCurrentTime());
assertEquals(1, clock.getCallbacksTriggered());
assertTrue('m5 should now be true', m5);
assertFalse(m10);
assertFalse(m15);
assertFalse(m20);
assertEquals(10, clock.tick(5));
assertEquals(10, clock.getCurrentTime());
assertEquals(2, clock.getCallbacksTriggered());
assertTrue('m5 should be true', m5);
assertTrue('m10 should now be true', m10);
assertFalse(m15);
assertFalse(m20);
assertEquals(15, clock.tick(5));
assertEquals(15, clock.getCurrentTime());
assertEquals(3, clock.getCallbacksTriggered());
assertTrue('m5 should be true', m5);
assertTrue('m10 should be true', m10);
assertTrue('m15 should now be true', m15);
assertFalse(m20);
assertEquals(20, clock.tick(5));
assertEquals(20, clock.getCurrentTime());
assertEquals(4, clock.getCallbacksTriggered());
assertTrue('m5 should be true', m5);
assertTrue('m10 should be true', m10);
assertTrue('m15 should be true', m15);
assertTrue('m20 should now be true', m20);
clock.uninstall();
}
function testSetImmediateAndTick() {
var clock = new goog.testing.MockClock(true);
var tick0 = false;
var tick1 = false;
setImmediate(function() { tick0 = true; });
setImmediate(function() { tick1 = true; });
assertEquals(2, clock.getTimeoutsMade());
assertEquals(0, clock.getCallbacksTriggered());
clock.tick(0);
assertEquals(2, clock.getCallbacksTriggered());
assertTrue(tick0);
assertTrue(tick1);
clock.uninstall();
}
function testSetInterval() {
var clock = new goog.testing.MockClock(true);
var times = 0;
setInterval(function() { times++; }, 100);
clock.tick(500);
assertEquals(5, clock.getCallbacksTriggered());
assertEquals(5, times);
clock.tick(100);
assertEquals(6, clock.getCallbacksTriggered());
assertEquals(6, times);
clock.tick(100);
assertEquals(7, clock.getCallbacksTriggered());
assertEquals(7, times);
clock.tick(50);
assertEquals(7, clock.getCallbacksTriggered());
assertEquals(7, times);
clock.tick(50);
assertEquals(8, clock.getCallbacksTriggered());
assertEquals(8, times);
clock.uninstall();
}
function testRequestAnimationFrame() {
goog.global.requestAnimationFrame = function() {};
var clock = new goog.testing.MockClock(true);
var times = [];
var recFunc = goog.testing.recordFunction(function(now) { times.push(now); });
goog.global.requestAnimationFrame(recFunc);
clock.tick(50);
assertEquals(1, clock.getCallbacksTriggered());
assertEquals(1, recFunc.getCallCount());
assertEquals(20, times[0]);
goog.global.requestAnimationFrame(recFunc);
clock.tick(100);
assertEquals(2, clock.getCallbacksTriggered());
assertEquals(2, recFunc.getCallCount());
assertEquals(70, times[1]);
clock.uninstall();
}
function testClearTimeout() {
var clock = new goog.testing.MockClock(true);
var ran = false;
var c = setTimeout(function() { ran = true; }, 100);
clock.tick(50);
assertFalse(ran);
clearTimeout(c);
clock.tick(100);
assertFalse(ran);
clock.uninstall();
}
function testClearInterval() {
var clock = new goog.testing.MockClock(true);
var times = 0;
var c = setInterval(function() { times++; }, 100);
clock.tick(500);
assertEquals(5, times);
clock.tick(100);
assertEquals(6, times);
clock.tick(100);
clearInterval(c);
assertEquals(7, times);
clock.tick(50);
assertEquals(7, times);
clock.tick(50);
assertEquals(7, times);
clock.uninstall();
}
function testClearInterval2() {
// Tests that we can clear the interval from inside the function
var clock = new goog.testing.MockClock(true);
var times = 0;
var c = setInterval(function() {
times++;
if (times == 6) {
clearInterval(c);
}
}, 100);
clock.tick(500);
assertEquals(5, times);
clock.tick(100);
assertEquals(6, times);
clock.tick(100);
assertEquals(6, times);
clock.tick(50);
assertEquals(6, times);
clock.tick(50);
assertEquals(6, times);
clock.uninstall();
}
function testCancelRequestAnimationFrame() {
goog.global.requestAnimationFrame = function() {};
goog.global.cancelRequestAnimationFrame = function() {};
var clock = new goog.testing.MockClock(true);
var ran = false;
var c = goog.global.requestAnimationFrame(function() { ran = true; });
clock.tick(10);
assertFalse(ran);
goog.global.cancelRequestAnimationFrame(c);
clock.tick(20);
assertFalse(ran);
clock.uninstall();
}
function testMockGoogNow() {
assertNotEquals(0, goog.now());
var clock = new goog.testing.MockClock(true);
assertEquals(0, goog.now());
clock.tick(50);
assertEquals(50, goog.now());
clock.uninstall();
assertNotEquals(50, goog.now());
}
function testTimeoutDelay() {
var clock = new goog.testing.MockClock(true);
var m5 = false, m10 = false, m20 = false;
setTimeout(function() { m5 = true; }, 5);
setTimeout(function() { m10 = true; }, 10);
setTimeout(function() { m20 = true; }, 20);
// Fire 3ms early, so m5 fires at t=2
clock.setTimeoutDelay(-3);
clock.tick(1);
assertFalse(m5);
assertFalse(m10);
clock.tick(1);
assertTrue(m5);
assertFalse(m10);
// Fire 3ms late, so m10 fires at t=13
clock.setTimeoutDelay(3);
assertEquals(12, clock.tick(10));
assertEquals(12, clock.getCurrentTime());
assertFalse(m10);
clock.tick(1);
assertTrue(m10);
assertFalse(m20);
// Fire 10ms early, so m20 fires now, since it's after t=10
clock.setTimeoutDelay(-10);
assertFalse(m20);
assertEquals(14, clock.tick(1));
assertEquals(14, clock.getCurrentTime());
assertTrue(m20);
clock.uninstall();
}
function testTimerCallbackCanCreateIntermediateTimer() {
var clock = new goog.testing.MockClock(true);
var sequence = [];
// Create 3 timers: 1, 2, and 3. Timer 1 should fire at T=1, timer 2 at
// T=2, and timer 3 at T=3. The catch: Timer 2 is created by the
// callback within timer 0.
// Testing method: Create a simple string sequencing each timer and at
// what time it fired.
setTimeout(function() {
sequence.push('timer1 at T=' + goog.now());
setTimeout(function() { sequence.push('timer2 at T=' + goog.now()); }, 1);
}, 1);
setTimeout(function() { sequence.push('timer3 at T=' + goog.now()); }, 3);
clock.tick(4);
assertEquals(
'Each timer should fire in sequence at the correct time.',
'timer1 at T=1, timer2 at T=2, timer3 at T=3', sequence.join(', '));
clock.uninstall();
}
function testCorrectArgumentsPassedToCallback() {
var clock = new goog.testing.MockClock(true);
var timeoutId;
var timeoutExecuted = false;
timeoutId = setTimeout(function(arg) {
assertEquals('"this" must be goog.global', goog.global, this);
assertEquals('The timeout ID must be the first parameter', timeoutId, arg);
assertEquals('Exactly one argument must be passed', 1, arguments.length);
timeoutExecuted = true;
}, 1);
clock.tick(4);
assertTrue('The timeout was not executed', timeoutExecuted);
clock.uninstall();
}
function testTickZero() {
var clock = new goog.testing.MockClock(true);
var calls = 0;
setTimeout(function() {
assertEquals('I need to be first', 0, calls);
calls++;
}, 0);
setTimeout(function() {
assertEquals('I need to be second', 1, calls);
calls++;
}, 0);
clock.tick(0);
assertEquals(2, calls);
setTimeout(function() {
assertEquals('I need to be third', 2, calls);
calls++;
}, 0);
clock.tick(0);
assertEquals(3, calls);
assertEquals('Time should still be zero', 0, goog.now());
clock.uninstall();
}
function testReset() {
var clock = new goog.testing.MockClock(true);
var id = setTimeout(function() {
fail('Timeouts should be cleared after a reset');
}, 0);
clock.reset();
clock.tick(999999);
var calls = 0;
setTimeout(function() { calls++; }, 10);
clearTimeout(id);
clock.tick(100);
assertEquals(
'New timeout should still run after clearing from before reset', 1,
calls);
clock.uninstall();
}
function testNewClockWithOldTimeoutId() {
var clock = new goog.testing.MockClock(true);
var id = setTimeout(function() {
fail('Timeouts should be cleared after uninstall');
}, 0);
clock.uninstall();
clock = new goog.testing.MockClock(true);
var calls = 0;
setTimeout(function() { calls++; }, 10);
clearTimeout(id);
clock.tick(100);
assertEquals(
'Timeout should still run after cancelling from old clock', 1, calls);
clock.uninstall();
}
function testQueueInsertionHelper() {
var queue = [];
function queueToString() {
var buffer = [];
for (var i = 0; i < queue.length; i++) {
buffer.push(queue[i].runAtMillis);
}
return buffer.join(',');
}
goog.testing.MockClock.insert_({runAtMillis: 2}, queue);
assertEquals('Only item', '2', queueToString());
goog.testing.MockClock.insert_({runAtMillis: 4}, queue);
assertEquals('Biggest item', '4,2', queueToString());
goog.testing.MockClock.insert_({runAtMillis: 5}, queue);
assertEquals('An even bigger item', '5,4,2', queueToString());
goog.testing.MockClock.insert_({runAtMillis: 1}, queue);
assertEquals('Smallest item', '5,4,2,1', queueToString());
goog.testing.MockClock.insert_({runAtMillis: 1, dup: true}, queue);
assertEquals('Duplicate smallest item', '5,4,2,1,1', queueToString());
assertTrue('Duplicate item comes at a smaller index', queue[3].dup);
goog.testing.MockClock.insert_({runAtMillis: 3}, queue);
goog.testing.MockClock.insert_({runAtMillis: 3, dup: true}, queue);
assertEquals('Duplicate a middle item', '5,4,3,3,2,1,1', queueToString());
assertTrue('Duplicate item comes at a smaller index', queue[2].dup);
}
function testIsTimeoutSet() {
var clock = new goog.testing.MockClock(true);
var timeoutKey = setTimeout(function() {}, 1);
assertTrue(
'Timeout ' + timeoutKey + ' should be set',
clock.isTimeoutSet(timeoutKey));
var nextTimeoutKey = timeoutKey + 1;
assertFalse(
'Timeout ' + nextTimeoutKey + ' should not be set',
clock.isTimeoutSet(nextTimeoutKey));
clearTimeout(timeoutKey);
assertFalse(
'Timeout ' + timeoutKey + ' should no longer be set',
clock.isTimeoutSet(timeoutKey));
var newTimeoutKey = setTimeout(function() {}, 1);
clock.tick(5);
assertFalse(
'Timeout ' + timeoutKey + ' should not be set',
clock.isTimeoutSet(timeoutKey));
assertTrue(
'Timeout ' + newTimeoutKey + ' should be set',
clock.isTimeoutSet(newTimeoutKey));
clock.uninstall();
}
function testBalksOnTimeoutsGreaterThanMaxInt() {
// Browsers have trouble with timeout greater than max int, so we
// want Mock Clock to fail if this happens.
var clock = new goog.testing.MockClock(true);
// Functions on window don't seem to be able to throw exceptions in
// IE6. Explicitly reading the property makes it work.
var setTimeout = window.setTimeout;
assertThrows('Timeouts > MAX_INT should fail', function() {
setTimeout(goog.nullFunction, 2147483648);
});
assertThrows('Timeouts much greater than MAX_INT should fail', function() {
setTimeout(goog.nullFunction, 2147483648 * 10);
});
clock.uninstall();
}
function testCorrectSetTimeoutIsRestored() {
var safe = goog.functions.error('should not have been called');
stubs.set(window, 'setTimeout', safe);
var clock = new goog.testing.MockClock(true);
assertNotEquals('setTimeout is replaced', safe, window.setTimeout);
clock.uninstall();
// NOTE: If this assertion proves to be flaky in IE, the string value of
// the two functions have to be compared as described in
// goog.testing.TestCase#finalize.
assertEquals('setTimeout is restored', safe, window.setTimeout);
}
function testMozRequestAnimationFrame() {
// Setting this function will indirectly tell the mock clock to mock it out.
stubs.set(window, 'mozRequestAnimationFrame', goog.nullFunction);
var clock = new goog.testing.MockClock(true);
var mozBeforePaint = goog.testing.recordFunction();
goog.events.listen(window, 'MozBeforePaint', mozBeforePaint);
window.mozRequestAnimationFrame(null);
assertEquals(0, mozBeforePaint.getCallCount());
clock.tick(goog.testing.MockClock.REQUEST_ANIMATION_FRAME_TIMEOUT);
assertEquals(1, mozBeforePaint.getCallCount());
clock.dispose();
}
function testClearBeforeSet() {
var clock = new goog.testing.MockClock(true);
var expectedId = goog.testing.MockClock.nextId;
window.clearTimeout(expectedId);
var fn = goog.testing.recordFunction();
var actualId = window.setTimeout(fn, 0);
assertEquals(
'In order for this test to work, we have to guess the ids in advance',
expectedId, actualId);
clock.tick(1);
assertEquals(1, fn.getCallCount());
clock.dispose();
}
function testNonFunctionArguments() {
var clock = new goog.testing.MockClock(true);
// Unlike normal setTimeout and friends, we only accept functions (not
// strings, not undefined, etc). Make sure that if we get a non-function, we
// fail early rather than on the next .tick() operation.
assertThrows('setTimeout with a non-function value should fail', function() {
window.setTimeout(undefined, 0);
});
clock.tick(1);
assertThrows('setTimeout with a string should fail', function() {
window.setTimeout('throw new Error("setTimeout string eval!");', 0);
});
clock.tick(1);
clock.dispose();
}
function testUnspecifiedTimeout() {
var clock = new goog.testing.MockClock(true);
var m0a = false, m0b = false, m10 = false;
setTimeout(function() { m0a = true; });
setTimeout(function() { m10 = true; }, 10);
assertEquals(2, clock.getTimeoutsMade());
assertFalse(m0a);
assertFalse(m0b);
assertFalse(m10);
assertEquals(0, clock.tick(0));
assertEquals(0, clock.getCurrentTime());
assertTrue(m0a);
assertFalse(m0b);
assertFalse(m10);
setTimeout(function() { m0b = true; });
assertEquals(3, clock.getTimeoutsMade());
assertEquals(0, clock.tick(0));
assertEquals(0, clock.getCurrentTime());
assertTrue(m0a);
assertTrue(m0b);
assertFalse(m10);
assertEquals(10, clock.tick(10));
assertEquals(10, clock.getCurrentTime());
assertTrue(m0a);
assertTrue(m0b);
assertTrue(m10);
clock.uninstall();
}
function testUnspecifiedInterval() {
var clock = new goog.testing.MockClock(true);
var times = 0;
var handle = setInterval(function() {
if (++times >= 5) {
clearInterval(handle);
}
});
clock.tick(0);
assertEquals(5, times);
clock.uninstall();
}
function testTickPromise() {
var clock = new goog.testing.MockClock(true);
var p = goog.Promise.resolve('foo');
assertEquals('foo', clock.tickPromise(p));
var rejected = goog.Promise.reject(new Error('failed'));
var e = assertThrows(function() { clock.tickPromise(rejected); });
assertEquals('failed', e.message);
var delayed = goog.Timer.promise(500, 'delayed');
e = assertThrows(function() { clock.tickPromise(delayed); });
assertEquals(
'Promise was expected to be resolved after mock clock tick.', e.message);
assertEquals('delayed', clock.tickPromise(delayed, 500));
clock.dispose();
}
| apache-2.0 |
TikhomirovSergey/selenium | java/client/src/org/openqa/selenium/remote/service/DriverCommandExecutor.java | 3534 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.remote.service;
import com.google.common.base.Throwables;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.remote.Command;
import org.openqa.selenium.remote.CommandInfo;
import org.openqa.selenium.remote.DriverCommand;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.openqa.selenium.remote.Response;
import java.io.IOException;
import java.net.ConnectException;
import java.util.Map;
/**
* A specialized {@link HttpCommandExecutor} that will use a {@link DriverService} that lives
* and dies with a single WebDriver session. The service will be restarted upon each new session
* request and shutdown after each quit command.
*/
public class DriverCommandExecutor extends HttpCommandExecutor {
private final DriverService service;
/**
* Creates a new DriverCommandExecutor which will communicate with the driver as configured
* by the given {@code service}.
*
* @param service The DriverService to send commands to.
*/
public DriverCommandExecutor(DriverService service) {
super(service.getUrl());
this.service = service;
}
/**
* Creates an {@link DriverCommandExecutor} that supports non-standard
* {@code additionalCommands} in addition to the standard.
*
* @param service driver server
* @param additionalCommands additional commands the remote end can process
*/
protected DriverCommandExecutor(
DriverService service, Map<String, CommandInfo> additionalCommands) {
super(additionalCommands, service.getUrl());
this.service = service;
}
/**
* Sends the {@code command} to the driver server for execution. The server will be started
* if requesting a new session. Likewise, if terminating a session, the server will be shutdown
* once a response is received.
*
* @param command The command to execute.
* @return The command response.
* @throws IOException If an I/O error occurs while sending the command.
*/
@Override
public Response execute(Command command) throws IOException {
if (DriverCommand.NEW_SESSION.equals(command.getName())) {
service.start();
}
try {
return super.execute(command);
} catch (Throwable t) {
Throwable rootCause = Throwables.getRootCause(t);
if (rootCause instanceof ConnectException &&
"Connection refused".equals(rootCause.getMessage()) &&
!service.isRunning()) {
throw new WebDriverException("The driver server has unexpectedly died!", t);
}
Throwables.propagateIfPossible(t);
throw new WebDriverException(t);
} finally {
if (DriverCommand.QUIT.equals(command.getName())) {
service.stop();
}
}
}
}
| apache-2.0 |
DirtyUnicorns/android_external_chromium-org | sandbox/linux/seccomp-bpf/codegen_unittest.cc | 16932 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <errno.h>
#include <algorithm>
#include <set>
#include <vector>
#include "sandbox/linux/seccomp-bpf/codegen.h"
#include "sandbox/linux/seccomp-bpf/sandbox_bpf.h"
#include "sandbox/linux/tests/unit_tests.h"
namespace sandbox {
class SandboxUnittestHelper : public SandboxBPF {
public:
typedef SandboxBPF::Program Program;
};
// We want to access some of the private methods in the code generator. We
// do so by defining a "friend" that makes these methods public for us.
class CodeGenUnittestHelper : public CodeGen {
public:
void FindBranchTargets(const Instruction& instructions,
BranchTargets *branch_targets) {
CodeGen::FindBranchTargets(instructions, branch_targets);
}
BasicBlock *CutGraphIntoBasicBlocks(Instruction *insns,
const BranchTargets& branch_targets,
TargetsToBlocks *blocks) {
return CodeGen::CutGraphIntoBasicBlocks(insns, branch_targets, blocks);
}
void MergeTails(TargetsToBlocks *blocks) {
CodeGen::MergeTails(blocks);
}
};
enum { NO_FLAGS = 0x0000,
HAS_MERGEABLE_TAILS = 0x0001,
};
Instruction *SampleProgramOneInstruction(CodeGen *codegen, int *flags) {
// Create the most basic valid BPF program:
// RET ERR_ALLOWED
*flags = NO_FLAGS;
return codegen->MakeInstruction(BPF_RET+BPF_K,
ErrorCode(ErrorCode::ERR_ALLOWED));
}
Instruction *SampleProgramSimpleBranch(CodeGen *codegen, int *flags) {
// Create a program with a single branch:
// JUMP if eq 42 then $0 else $1
// 0: RET EPERM
// 1: RET ERR_ALLOWED
*flags = NO_FLAGS;
return codegen->MakeInstruction(BPF_JMP+BPF_JEQ+BPF_K, 42,
codegen->MakeInstruction(BPF_RET+BPF_K,
ErrorCode(EPERM)),
codegen->MakeInstruction(BPF_RET+BPF_K,
ErrorCode(ErrorCode::ERR_ALLOWED)));
}
Instruction *SampleProgramAtypicalBranch(CodeGen *codegen, int *flags) {
// Create a program with a single branch:
// JUMP if eq 42 then $0 else $0
// 0: RET ERR_ALLOWED
// N.B.: As the instructions in both sides of the branch are already
// the same object, we do not actually have any "mergeable" branches.
// This needs to be reflected in our choice of "flags".
*flags = NO_FLAGS;
Instruction *ret =
codegen->MakeInstruction(BPF_RET+BPF_K,
ErrorCode(ErrorCode::ERR_ALLOWED));
return codegen->MakeInstruction(BPF_JMP+BPF_JEQ+BPF_K, 42, ret, ret);
}
Instruction *SampleProgramComplex(CodeGen *codegen, int *flags) {
// Creates a basic BPF program that we'll use to test some of the code:
// JUMP if eq 42 the $0 else $1 (insn6)
// 0: LD 23 (insn5)
// 1: JUMP if eq 42 then $2 else $4 (insn4)
// 2: JUMP to $3 (insn1)
// 3: LD 42 (insn0)
// RET ErrorCode(42) (insn2)
// 4: LD 42 (insn3)
// RET ErrorCode(42) (insn3+)
*flags = HAS_MERGEABLE_TAILS;
Instruction *insn0 = codegen->MakeInstruction(BPF_LD+BPF_W+BPF_ABS, 42);
SANDBOX_ASSERT(insn0);
SANDBOX_ASSERT(insn0->code == BPF_LD+BPF_W+BPF_ABS);
SANDBOX_ASSERT(insn0->k == 42);
SANDBOX_ASSERT(insn0->next == NULL);
Instruction *insn1 = codegen->MakeInstruction(BPF_JMP+BPF_JA, 0, insn0);
SANDBOX_ASSERT(insn1);
SANDBOX_ASSERT(insn1->code == BPF_JMP+BPF_JA);
SANDBOX_ASSERT(insn1->jt_ptr == insn0);
Instruction *insn2 = codegen->MakeInstruction(BPF_RET+BPF_K, ErrorCode(42));
SANDBOX_ASSERT(insn2);
SANDBOX_ASSERT(insn2->code == BPF_RET+BPF_K);
SANDBOX_ASSERT(insn2->next == NULL);
// We explicitly duplicate instructions so that MergeTails() can coalesce
// them later.
Instruction *insn3 = codegen->MakeInstruction(BPF_LD+BPF_W+BPF_ABS, 42,
codegen->MakeInstruction(BPF_RET+BPF_K, ErrorCode(42)));
Instruction *insn4 = codegen->MakeInstruction(BPF_JMP+BPF_JEQ+BPF_K, 42,
insn1, insn3);
SANDBOX_ASSERT(insn4);
SANDBOX_ASSERT(insn4->code == BPF_JMP+BPF_JEQ+BPF_K);
SANDBOX_ASSERT(insn4->k == 42);
SANDBOX_ASSERT(insn4->jt_ptr == insn1);
SANDBOX_ASSERT(insn4->jf_ptr == insn3);
codegen->JoinInstructions(insn0, insn2);
SANDBOX_ASSERT(insn0->next == insn2);
Instruction *insn5 = codegen->MakeInstruction(BPF_LD+BPF_W+BPF_ABS,
23, insn4);
SANDBOX_ASSERT(insn5);
SANDBOX_ASSERT(insn5->code == BPF_LD+BPF_W+BPF_ABS);
SANDBOX_ASSERT(insn5->k == 23);
SANDBOX_ASSERT(insn5->next == insn4);
// Force a basic block that ends in neither a jump instruction nor a return
// instruction. It only contains "insn5". This exercises one of the less
// common code paths in the topo-sort algorithm.
// This also gives us a diamond-shaped pattern in our graph, which stresses
// another aspect of the topo-sort algorithm (namely, the ability to
// correctly count the incoming branches for subtrees that are not disjunct).
Instruction *insn6 = codegen->MakeInstruction(BPF_JMP+BPF_JEQ+BPF_K, 42,
insn5, insn4);
return insn6;
}
void ForAllPrograms(void (*test)(CodeGenUnittestHelper *, Instruction *, int)){
Instruction *(*function_table[])(CodeGen *codegen, int *flags) = {
SampleProgramOneInstruction,
SampleProgramSimpleBranch,
SampleProgramAtypicalBranch,
SampleProgramComplex,
};
for (size_t i = 0; i < arraysize(function_table); ++i) {
CodeGenUnittestHelper codegen;
int flags = NO_FLAGS;
Instruction *prg = function_table[i](&codegen, &flags);
test(&codegen, prg, flags);
}
}
void MakeInstruction(CodeGenUnittestHelper *codegen,
Instruction *program, int) {
// Nothing to do here
}
SANDBOX_TEST(CodeGen, MakeInstruction) {
ForAllPrograms(MakeInstruction);
}
void FindBranchTargets(CodeGenUnittestHelper *codegen, Instruction *prg, int) {
BranchTargets branch_targets;
codegen->FindBranchTargets(*prg, &branch_targets);
// Verifying the general properties that should be true for every
// well-formed BPF program.
// Perform a depth-first traversal of the BPF program an verify that all
// targets of BPF_JMP instructions are represented in the "branch_targets".
// At the same time, compute a set of both the branch targets and all the
// instructions in the program.
std::vector<Instruction *> stack;
std::set<Instruction *> all_instructions;
std::set<Instruction *> target_instructions;
BranchTargets::const_iterator end = branch_targets.end();
for (Instruction *insn = prg;;) {
all_instructions.insert(insn);
if (BPF_CLASS(insn->code) == BPF_JMP) {
target_instructions.insert(insn->jt_ptr);
SANDBOX_ASSERT(insn->jt_ptr != NULL);
SANDBOX_ASSERT(branch_targets.find(insn->jt_ptr) != end);
if (BPF_OP(insn->code) != BPF_JA) {
target_instructions.insert(insn->jf_ptr);
SANDBOX_ASSERT(insn->jf_ptr != NULL);
SANDBOX_ASSERT(branch_targets.find(insn->jf_ptr) != end);
stack.push_back(insn->jf_ptr);
}
insn = insn->jt_ptr;
} else if (BPF_CLASS(insn->code) == BPF_RET) {
SANDBOX_ASSERT(insn->next == NULL);
if (stack.empty()) {
break;
}
insn = stack.back();
stack.pop_back();
} else {
SANDBOX_ASSERT(insn->next != NULL);
insn = insn->next;
}
}
SANDBOX_ASSERT(target_instructions.size() == branch_targets.size());
// We can now subtract the set of the branch targets from the set of all
// instructions. This gives us a set with the instructions that nobody
// ever jumps to. Verify that they are no included in the
// "branch_targets" that FindBranchTargets() computed for us.
Instructions non_target_instructions(all_instructions.size() -
target_instructions.size());
set_difference(all_instructions.begin(), all_instructions.end(),
target_instructions.begin(), target_instructions.end(),
non_target_instructions.begin());
for (Instructions::const_iterator iter = non_target_instructions.begin();
iter != non_target_instructions.end();
++iter) {
SANDBOX_ASSERT(branch_targets.find(*iter) == end);
}
}
SANDBOX_TEST(CodeGen, FindBranchTargets) {
ForAllPrograms(FindBranchTargets);
}
void CutGraphIntoBasicBlocks(CodeGenUnittestHelper *codegen,
Instruction *prg, int) {
BranchTargets branch_targets;
codegen->FindBranchTargets(*prg, &branch_targets);
TargetsToBlocks all_blocks;
BasicBlock *first_block =
codegen->CutGraphIntoBasicBlocks(prg, branch_targets, &all_blocks);
SANDBOX_ASSERT(first_block != NULL);
SANDBOX_ASSERT(first_block->instructions.size() > 0);
Instruction *first_insn = first_block->instructions[0];
// Basic blocks are supposed to start with a branch target and end with
// either a jump or a return instruction. It can also end, if the next
// instruction forms the beginning of a new basic block. There should be
// no other jumps or return instructions in the middle of a basic block.
for (TargetsToBlocks::const_iterator bb_iter = all_blocks.begin();
bb_iter != all_blocks.end();
++bb_iter) {
BasicBlock *bb = bb_iter->second;
SANDBOX_ASSERT(bb != NULL);
SANDBOX_ASSERT(bb->instructions.size() > 0);
Instruction *insn = bb->instructions[0];
SANDBOX_ASSERT(insn == first_insn ||
branch_targets.find(insn) != branch_targets.end());
for (Instructions::const_iterator insn_iter = bb->instructions.begin();;){
insn = *insn_iter;
if (++insn_iter != bb->instructions.end()) {
SANDBOX_ASSERT(BPF_CLASS(insn->code) != BPF_JMP);
SANDBOX_ASSERT(BPF_CLASS(insn->code) != BPF_RET);
} else {
SANDBOX_ASSERT(BPF_CLASS(insn->code) == BPF_JMP ||
BPF_CLASS(insn->code) == BPF_RET ||
branch_targets.find(insn->next) !=
branch_targets.end());
break;
}
SANDBOX_ASSERT(branch_targets.find(*insn_iter) == branch_targets.end());
}
}
}
SANDBOX_TEST(CodeGen, CutGraphIntoBasicBlocks) {
ForAllPrograms(CutGraphIntoBasicBlocks);
}
void MergeTails(CodeGenUnittestHelper *codegen, Instruction *prg,
int flags) {
BranchTargets branch_targets;
codegen->FindBranchTargets(*prg, &branch_targets);
TargetsToBlocks all_blocks;
BasicBlock *first_block =
codegen->CutGraphIntoBasicBlocks(prg, branch_targets, &all_blocks);
// The shape of our graph and thus the function of our program should
// still be unchanged after we run MergeTails(). We verify this by
// serializing the graph and verifying that it is still the same.
// We also verify that at least some of the edges changed because of
// tail merging.
std::string graph[2];
std::string edges[2];
// The loop executes twice. After the first run, we call MergeTails() on
// our graph.
for (int i = 0;;) {
// Traverse the entire program in depth-first order.
std::vector<BasicBlock *> stack;
for (BasicBlock *bb = first_block;;) {
// Serialize the instructions in this basic block. In general, we only
// need to serialize "code" and "k"; except for a BPF_JA instruction
// where "k" isn't set.
// The stream of instructions should be unchanged after MergeTails().
for (Instructions::const_iterator iter = bb->instructions.begin();
iter != bb->instructions.end();
++iter) {
graph[i].append(reinterpret_cast<char *>(&(*iter)->code),
sizeof((*iter)->code));
if (BPF_CLASS((*iter)->code) != BPF_JMP ||
BPF_OP((*iter)->code) != BPF_JA) {
graph[i].append(reinterpret_cast<char *>(&(*iter)->k),
sizeof((*iter)->k));
}
}
// Also serialize the addresses the basic blocks as we encounter them.
// This will change as basic blocks are coalesed by MergeTails().
edges[i].append(reinterpret_cast<char *>(&bb), sizeof(bb));
// Depth-first traversal of the graph. We only ever need to look at the
// very last instruction in the basic block, as that is the only one that
// can change code flow.
Instruction *insn = bb->instructions.back();
if (BPF_CLASS(insn->code) == BPF_JMP) {
// For jump instructions, we need to remember the "false" branch while
// traversing the "true" branch. This is not necessary for BPF_JA which
// only has a single branch.
if (BPF_OP(insn->code) != BPF_JA) {
stack.push_back(all_blocks[insn->jf_ptr]);
}
bb = all_blocks[insn->jt_ptr];
} else if (BPF_CLASS(insn->code) == BPF_RET) {
// After a BPF_RET, see if we need to back track.
if (stack.empty()) {
break;
}
bb = stack.back();
stack.pop_back();
} else {
// For "normal" instructions, just follow to the next basic block.
bb = all_blocks[insn->next];
}
}
// Our loop runs exactly two times.
if (++i > 1) {
break;
}
codegen->MergeTails(&all_blocks);
}
SANDBOX_ASSERT(graph[0] == graph[1]);
if (flags & HAS_MERGEABLE_TAILS) {
SANDBOX_ASSERT(edges[0] != edges[1]);
} else {
SANDBOX_ASSERT(edges[0] == edges[1]);
}
}
SANDBOX_TEST(CodeGen, MergeTails) {
ForAllPrograms(MergeTails);
}
void CompileAndCompare(CodeGenUnittestHelper *codegen, Instruction *prg, int) {
// TopoSortBasicBlocks() has internal checks that cause it to fail, if it
// detects a problem. Typically, if anything goes wrong, this looks to the
// TopoSort algorithm as if there had been cycles in the input data.
// This provides a pretty good unittest.
// We hand-crafted the program returned by SampleProgram() to exercise
// several of the more interesting code-paths. See comments in
// SampleProgram() for details.
// In addition to relying on the internal consistency checks in the compiler,
// we also serialize the graph and the resulting BPF program and compare
// them. With the exception of BPF_JA instructions that might have been
// inserted, both instruction streams should be equivalent.
// As Compile() modifies the instructions, we have to serialize the graph
// before calling Compile().
std::string source;
Instructions source_stack;
for (const Instruction *insn = prg, *next; insn; insn = next) {
if (BPF_CLASS(insn->code) == BPF_JMP) {
if (BPF_OP(insn->code) == BPF_JA) {
// Do not serialize BPF_JA instructions (see above).
next = insn->jt_ptr;
continue;
} else {
source_stack.push_back(insn->jf_ptr);
next = insn->jt_ptr;
}
} else if (BPF_CLASS(insn->code) == BPF_RET) {
if (source_stack.empty()) {
next = NULL;
} else {
next = source_stack.back();
source_stack.pop_back();
}
} else {
next = insn->next;
}
// Only serialize "code" and "k". That's all the information we need to
// compare. The rest of the information is encoded in the order of
// instructions.
source.append(reinterpret_cast<const char *>(&insn->code),
sizeof(insn->code));
source.append(reinterpret_cast<const char *>(&insn->k),
sizeof(insn->k));
}
// Compile the program
SandboxUnittestHelper::Program bpf;
codegen->Compile(prg, &bpf);
// Serialize the resulting BPF instructions.
std::string assembly;
std::vector<int> assembly_stack;
for (int idx = 0; idx >= 0;) {
SANDBOX_ASSERT(idx < (int)bpf.size());
struct sock_filter& insn = bpf[idx];
if (BPF_CLASS(insn.code) == BPF_JMP) {
if (BPF_OP(insn.code) == BPF_JA) {
// Do not serialize BPF_JA instructions (see above).
idx += insn.k + 1;
continue;
} else {
assembly_stack.push_back(idx + insn.jf + 1);
idx += insn.jt + 1;
}
} else if (BPF_CLASS(insn.code) == BPF_RET) {
if (assembly_stack.empty()) {
idx = -1;
} else {
idx = assembly_stack.back();
assembly_stack.pop_back();
}
} else {
++idx;
}
// Serialize the same information that we serialized before compilation.
assembly.append(reinterpret_cast<char *>(&insn.code), sizeof(insn.code));
assembly.append(reinterpret_cast<char *>(&insn.k), sizeof(insn.k));
}
SANDBOX_ASSERT(source == assembly);
}
SANDBOX_TEST(CodeGen, All) {
ForAllPrograms(CompileAndCompare);
}
} // namespace sandbox
| bsd-3-clause |
1wheel/shader-school | node_modules/gl-texture2d/node_modules/ndarray-ops/ndarray-ops.js | 13347 | "use strict"
var compile = require("cwise-compiler")
var EmptyProc = {
body: "",
args: [],
thisVars: [],
localVars: []
}
function fixup(x) {
if(!x) {
return EmptyProc
}
for(var i=0; i<x.args.length; ++i) {
var a = x.args[i]
if(i === 0) {
x.args[i] = {name: a, lvalue:true, rvalue: !!x.rvalue, count:x.count||1 }
} else {
x.args[i] = {name: a, lvalue:false, rvalue:true, count: 1}
}
}
if(!x.thisVars) {
x.thisVars = []
}
if(!x.localVars) {
x.localVars = []
}
return x
}
function pcompile(user_args) {
return compile({
args: user_args.args,
pre: fixup(user_args.pre),
body: fixup(user_args.body),
post: fixup(user_args.proc),
funcName: user_args.funcName
})
}
function makeOp(user_args) {
var args = []
for(var i=0; i<user_args.args.length; ++i) {
args.push("a"+i)
}
var wrapper = new Function("P", [
"return function ", user_args.funcName, "_ndarrayops(", args.join(","), ") {P(", args.join(","), ");return a0}"
].join(""))
return wrapper(pcompile(user_args))
}
var assign_ops = {
add: "+",
sub: "-",
mul: "*",
div: "/",
mod: "%",
band: "&",
bor: "|",
bxor: "^",
lshift: "<<",
rshift: ">>",
rrshift: ">>>"
}
;(function(){
for(var id in assign_ops) {
var op = assign_ops[id]
exports[id] = makeOp({
args: ["array","array","array"],
body: {args:["a","b","c"],
body: "a=b"+op+"c"},
funcName: id
})
exports[id+"eq"] = makeOp({
args: ["array","array"],
body: {args:["a","b"],
body:"a"+op+"=b"},
rvalue: true,
funcName: id+"eq"
})
exports[id+"s"] = makeOp({
args: ["array", "array", "scalar"],
body: {args:["a","b","s"],
body:"a=b"+op+"s"},
funcName: id+"s"
})
exports[id+"seq"] = makeOp({
args: ["array","scalar"],
body: {args:["a","s"],
body:"a"+op+"=s"},
rvalue: true,
funcName: id+"seq"
})
}
})();
var unary_ops = {
not: "!",
bnot: "~",
neg: "-",
recip: "1.0/"
}
;(function(){
for(var id in unary_ops) {
var op = unary_ops[id]
exports[id] = makeOp({
args: ["array", "array"],
body: {args:["a","b"],
body:"a="+op+"b"},
funcName: id
})
exports[id+"eq"] = makeOp({
args: ["array"],
body: {args:["a"],
body:"a="+op+"a"},
rvalue: true,
count: 2,
funcName: id+"eq"
})
}
})();
var binary_ops = {
and: "&&",
or: "||",
eq: "===",
neq: "!==",
lt: "<",
gt: ">",
leq: "<=",
geq: ">="
}
;(function() {
for(var id in binary_ops) {
var op = binary_ops[id]
exports[id] = makeOp({
args: ["array","array","array"],
body: {args:["a", "b", "c"],
body:"a=b"+op+"c"},
funcName: id
})
exports[id+"s"] = makeOp({
args: ["array","array","scalar"],
body: {args:["a", "b", "s"],
body:"a=b"+op+"s"},
funcName: id+"s"
})
exports[id+"eq"] = makeOp({
args: ["array", "array"],
body: {args:["a", "b"],
body:"a=a"+op+"b"},
rvalue:true,
count:2,
funcName: id+"eq"
})
exports[id+"seq"] = makeOp({
args: ["array", "scalar"],
body: {args:["a","s"],
body:"a=a"+op+"s"},
rvalue:true,
count:2,
funcName: id+"seq"
})
}
})();
var math_unary = [
"abs",
"acos",
"asin",
"atan",
"ceil",
"cos",
"exp",
"floor",
"log",
"round",
"sin",
"sqrt",
"tan"
]
;(function() {
for(var i=0; i<math_unary.length; ++i) {
var f = math_unary[i]
exports[f] = makeOp({
args: ["array", "array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b"], body:"a=this_f(b)", thisVars:["this_f"]},
funcName: f
})
exports[f+"eq"] = makeOp({
args: ["array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args: ["a"], body:"a=this_f(a)", thisVars:["this_f"]},
rvalue: true,
count: 2,
funcName: f+"eq"
})
}
})();
var math_comm = [
"max",
"min",
"atan2",
"pow"
]
;(function(){
for(var i=0; i<math_comm.length; ++i) {
var f= math_comm[i]
exports[f] = makeOp({
args:["array", "array", "array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b","c"], body:"a=this_f(b,c)", thisVars:["this_f"]},
funcName: f
})
exports[f+"s"] = makeOp({
args:["array", "array", "scalar"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b","c"], body:"a=this_f(b,c)", thisVars:["this_f"]},
funcName: f+"s"
})
exports[f+"eq"] = makeOp({ args:["array", "array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b"], body:"a=this_f(a,b)", thisVars:["this_f"]},
rvalue: true,
count: 2,
funcName: f+"eq"
})
exports[f+"seq"] = makeOp({ args:["array", "scalar"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b"], body:"a=this_f(a,b)", thisVars:["this_f"]},
rvalue:true,
count:2,
funcName: f+"seq"
})
}
})();
var math_noncomm = [
"atan2",
"pow"
]
;(function(){
for(var i=0; i<math_noncomm.length; ++i) {
var f= math_noncomm[i]
exports[f+"op"] = makeOp({
args:["array", "array", "array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b","c"], body:"a=this_f(c,b)", thisVars:["this_f"]},
funcName: f+"op"
})
exports[f+"ops"] = makeOp({
args:["array", "array", "scalar"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b","c"], body:"a=this_f(c,b)", thisVars:["this_f"]},
funcName: f+"ops"
})
exports[f+"opeq"] = makeOp({ args:["array", "array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b"], body:"a=this_f(b,a)", thisVars:["this_f"]},
rvalue: true,
count: 2,
funcName: f+"opeq"
})
exports[f+"opseq"] = makeOp({ args:["array", "scalar"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b"], body:"a=this_f(b,a)", thisVars:["this_f"]},
rvalue:true,
count:2,
funcName: f+"opseq"
})
}
})();
exports.any = compile({
args:["array"],
pre: EmptyProc,
body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "if(a){return true}", localVars: [], thisVars: []},
post: {args:[], localVars:[], thisVars:[], body:"return false"},
funcName: "any"
})
exports.all = compile({
args:["array"],
pre: EmptyProc,
body: {args:[{name:"x", lvalue:false, rvalue:true, count:1}], body: "if(!x){return false}", localVars: [], thisVars: []},
post: {args:[], localVars:[], thisVars:[], body:"return true"},
funcName: "all"
})
exports.sum = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s+=a", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
funcName: "sum"
})
exports.prod = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=1"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s*=a", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
funcName: "prod"
})
exports.norm2squared = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
funcName: "norm2squared"
})
exports.norm2 = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return Math.sqrt(this_s)"},
funcName: "norm2"
})
exports.norminf = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:4}], body:"if(-a>this_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
funcName: "norminf"
})
exports.norm1 = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:3}], body: "this_s+=a<0?-a:a", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
funcName: "norm1"
})
exports.sup = compile({
args: [ "array" ],
pre:
{ body: "this_h=-Infinity",
args: [],
thisVars: [ "this_h" ],
localVars: [] },
body:
{ body: "if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",
args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ],
thisVars: [ "this_h" ],
localVars: [] },
post:
{ body: "return this_h",
args: [],
thisVars: [ "this_h" ],
localVars: [] }
})
exports.inf = compile({
args: [ "array" ],
pre:
{ body: "this_h=Infinity",
args: [],
thisVars: [ "this_h" ],
localVars: [] },
body:
{ body: "if(_inline_1_arg0_<this_h)this_h=_inline_1_arg0_",
args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ],
thisVars: [ "this_h" ],
localVars: [] },
post:
{ body: "return this_h",
args: [],
thisVars: [ "this_h" ],
localVars: [] }
})
exports.argmin = compile({
args:["index","array","shape"],
pre:{
body:"{this_v=Infinity;this_i=_inline_0_arg2_.slice(0)}",
args:[
{name:"_inline_0_arg0_",lvalue:false,rvalue:false,count:0},
{name:"_inline_0_arg1_",lvalue:false,rvalue:false,count:0},
{name:"_inline_0_arg2_",lvalue:false,rvalue:true,count:1}
],
thisVars:["this_i","this_v"],
localVars:[]},
body:{
body:"{if(_inline_1_arg1_<this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",
args:[
{name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2},
{name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}],
thisVars:["this_i","this_v"],
localVars:["_inline_1_k"]},
post:{
body:"{return this_i}",
args:[],
thisVars:["this_i"],
localVars:[]}
})
exports.argmax = compile({
args:["index","array","shape"],
pre:{
body:"{this_v=-Infinity;this_i=_inline_0_arg2_.slice(0)}",
args:[
{name:"_inline_0_arg0_",lvalue:false,rvalue:false,count:0},
{name:"_inline_0_arg1_",lvalue:false,rvalue:false,count:0},
{name:"_inline_0_arg2_",lvalue:false,rvalue:true,count:1}
],
thisVars:["this_i","this_v"],
localVars:[]},
body:{
body:"{if(_inline_1_arg1_>this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",
args:[
{name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2},
{name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}],
thisVars:["this_i","this_v"],
localVars:["_inline_1_k"]},
post:{
body:"{return this_i}",
args:[],
thisVars:["this_i"],
localVars:[]}
})
exports.random = makeOp({
args: ["array"],
pre: {args:[], body:"this_f=Math.random", thisVars:["this_f"]},
body: {args: ["a"], body:"a=this_f()", thisVars:["this_f"]},
funcName: "random"
})
exports.assign = makeOp({
args:["array", "array"],
body: {args:["a", "b"], body:"a=b"},
funcName: "assign" })
exports.assigns = makeOp({
args:["array", "scalar"],
body: {args:["a", "b"], body:"a=b"},
funcName: "assigns" })
exports.equals = compile({
args:["array", "array"],
pre: EmptyProc,
body: {args:[{name:"x", lvalue:false, rvalue:true, count:1},
{name:"y", lvalue:false, rvalue:true, count:1}],
body: "if(x!==y){return false}",
localVars: [],
thisVars: []},
post: {args:[], localVars:[], thisVars:[], body:"return true"},
funcName: "equals"
})
| mit |
wout/cdnjs | ajax/libs/mediaelement-plugins/1.2.3/jump-forward/jump-forward.js | 2174 | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
'use strict';
/**
* Jump forward button
*
* This feature creates a button to forward media a specific number of seconds.
*/
// Translations (English required)
mejs.i18n.en["mejs.time-jump-forward"] = ["Jump forward 1 second", "Jump forward %1 seconds"];
Object.assign(mejs.MepDefaults, {
/**
* @type {Number}
*/
jumpForwardInterval: 30,
/**
* @type {?String}
*/
jumpForwardText: null
});
Object.assign(MediaElementPlayer.prototype, {
/**
* Feature constructor.
*
* Always has to be prefixed with `build` and the name that will be used in MepDefaults.features list
* @param {MediaElementPlayer} player
* @param {$} controls
* @param {$} layers
* @param {HTMLElement} media
*/
buildjumpforward: function buildjumpforward(player, controls, layers, media) {
var t = this,
defaultTitle = mejs.i18n.t('mejs.time-jump-forward', t.options.jumpForwardInterval),
forwardTitle = mejs.Utils.isString(t.options.jumpForwardText) ? t.options.jumpForwardText.replace('%1', t.options.jumpForwardInterval) : defaultTitle,
button = $("<div class=\"" + t.options.classPrefix + "button " + t.options.classPrefix + "jump-forward-button\">" + ("<button type=\"button\" aria-controls=\"" + t.id + "\" title=\"" + forwardTitle + "\" ") + ("aria-label=\"" + forwardTitle + "\" tabindex=\"0\">" + t.options.jumpForwardInterval + "</button>") + "</div>");
t.addControlElement(button, 'jumpforward');
// add a click toggle event
button.click(function () {
if (media.duration) {
media.setCurrentTime(Math.min(media.currentTime + t.options.jumpForwardInterval, media.duration));
$(this).find('button').blur();
}
});
}
});
},{}]},{},[1]);
| mit |
shi-yang/iisns | vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php | 10766 | <?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Sends Messages over SMTP with ESMTP support.
*
* @author Chris Corbyn
*/
class Swift_Transport_EsmtpTransport extends Swift_Transport_AbstractSmtpTransport implements Swift_Transport_SmtpAgent
{
/**
* ESMTP extension handlers.
*
* @var Swift_Transport_EsmtpHandler[]
*/
private $handlers = array();
/**
* ESMTP capabilities.
*
* @var string[]
*/
private $capabilities = array();
/**
* Connection buffer parameters.
*
* @var array
*/
private $params = array(
'protocol' => 'tcp',
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'blocking' => 1,
'tls' => false,
'type' => Swift_Transport_IoBuffer::TYPE_SOCKET,
'stream_context_options' => array(),
);
/**
* Creates a new EsmtpTransport using the given I/O buffer.
*
* @param Swift_Transport_IoBuffer $buf
* @param Swift_Transport_EsmtpHandler[] $extensionHandlers
* @param Swift_Events_EventDispatcher $dispatcher
* @param string $localDomain
*/
public function __construct(Swift_Transport_IoBuffer $buf, array $extensionHandlers, Swift_Events_EventDispatcher $dispatcher, $localDomain = '127.0.0.1')
{
parent::__construct($buf, $dispatcher, $localDomain);
$this->setExtensionHandlers($extensionHandlers);
}
/**
* Set the host to connect to.
*
* @param string $host
*
* @return $this
*/
public function setHost($host)
{
$this->params['host'] = $host;
return $this;
}
/**
* Get the host to connect to.
*
* @return string
*/
public function getHost()
{
return $this->params['host'];
}
/**
* Set the port to connect to.
*
* @param int $port
*
* @return $this
*/
public function setPort($port)
{
$this->params['port'] = (int) $port;
return $this;
}
/**
* Get the port to connect to.
*
* @return int
*/
public function getPort()
{
return $this->params['port'];
}
/**
* Set the connection timeout.
*
* @param int $timeout seconds
*
* @return $this
*/
public function setTimeout($timeout)
{
$this->params['timeout'] = (int) $timeout;
$this->buffer->setParam('timeout', (int) $timeout);
return $this;
}
/**
* Get the connection timeout.
*
* @return int
*/
public function getTimeout()
{
return $this->params['timeout'];
}
/**
* Set the encryption type (tls or ssl).
*
* @param string $encryption
*
* @return $this
*/
public function setEncryption($encryption)
{
$encryption = strtolower($encryption);
if ('tls' == $encryption) {
$this->params['protocol'] = 'tcp';
$this->params['tls'] = true;
} else {
$this->params['protocol'] = $encryption;
$this->params['tls'] = false;
}
return $this;
}
/**
* Get the encryption type.
*
* @return string
*/
public function getEncryption()
{
return $this->params['tls'] ? 'tls' : $this->params['protocol'];
}
/**
* Sets the stream context options.
*
* @param array $options
*
* @return $this
*/
public function setStreamOptions($options)
{
$this->params['stream_context_options'] = $options;
return $this;
}
/**
* Returns the stream context options.
*
* @return array
*/
public function getStreamOptions()
{
return $this->params['stream_context_options'];
}
/**
* Sets the source IP.
*
* @param string $source
*
* @return $this
*/
public function setSourceIp($source)
{
$this->params['sourceIp'] = $source;
return $this;
}
/**
* Returns the IP used to connect to the destination.
*
* @return string
*/
public function getSourceIp()
{
return $this->params['sourceIp'] ?? null;
}
/**
* Set ESMTP extension handlers.
*
* @param Swift_Transport_EsmtpHandler[] $handlers
*
* @return $this
*/
public function setExtensionHandlers(array $handlers)
{
$assoc = array();
foreach ($handlers as $handler) {
$assoc[$handler->getHandledKeyword()] = $handler;
}
uasort($assoc, function ($a, $b) {
return $a->getPriorityOver($b->getHandledKeyword());
});
$this->handlers = $assoc;
$this->setHandlerParams();
return $this;
}
/**
* Get ESMTP extension handlers.
*
* @return Swift_Transport_EsmtpHandler[]
*/
public function getExtensionHandlers()
{
return array_values($this->handlers);
}
/**
* Run a command against the buffer, expecting the given response codes.
*
* If no response codes are given, the response will not be validated.
* If codes are given, an exception will be thrown on an invalid response.
*
* @param string $command
* @param int[] $codes
* @param string[] $failures An array of failures by-reference
*
* @return string
*/
public function executeCommand($command, $codes = array(), &$failures = null)
{
$failures = (array) $failures;
$stopSignal = false;
$response = null;
foreach ($this->getActiveHandlers() as $handler) {
$response = $handler->onCommand(
$this, $command, $codes, $failures, $stopSignal
);
if ($stopSignal) {
return $response;
}
}
return parent::executeCommand($command, $codes, $failures);
}
/** Mixin handling method for ESMTP handlers */
public function __call($method, $args)
{
foreach ($this->handlers as $handler) {
if (in_array(strtolower($method),
array_map('strtolower', (array) $handler->exposeMixinMethods())
)) {
$return = call_user_func_array(array($handler, $method), $args);
// Allow fluid method calls
if (null === $return && substr($method, 0, 3) == 'set') {
return $this;
} else {
return $return;
}
}
}
trigger_error('Call to undefined method '.$method, E_USER_ERROR);
}
/** Get the params to initialize the buffer */
protected function getBufferParams()
{
return $this->params;
}
/** Overridden to perform EHLO instead */
protected function doHeloCommand()
{
try {
$response = $this->executeCommand(
sprintf("EHLO %s\r\n", $this->domain), array(250)
);
} catch (Swift_TransportException $e) {
return parent::doHeloCommand();
}
if ($this->params['tls']) {
try {
$this->executeCommand("STARTTLS\r\n", array(220));
if (!$this->buffer->startTLS()) {
throw new Swift_TransportException('Unable to connect with TLS encryption');
}
try {
$response = $this->executeCommand(
sprintf("EHLO %s\r\n", $this->domain), array(250)
);
} catch (Swift_TransportException $e) {
return parent::doHeloCommand();
}
} catch (Swift_TransportException $e) {
$this->throwException($e);
}
}
$this->capabilities = $this->getCapabilities($response);
$this->setHandlerParams();
foreach ($this->getActiveHandlers() as $handler) {
$handler->afterEhlo($this);
}
}
/** Overridden to add Extension support */
protected function doMailFromCommand($address)
{
$handlers = $this->getActiveHandlers();
$params = array();
foreach ($handlers as $handler) {
$params = array_merge($params, (array) $handler->getMailParams());
}
$paramStr = !empty($params) ? ' '.implode(' ', $params) : '';
$this->executeCommand(
sprintf("MAIL FROM:<%s>%s\r\n", $address, $paramStr), array(250)
);
}
/** Overridden to add Extension support */
protected function doRcptToCommand($address)
{
$handlers = $this->getActiveHandlers();
$params = array();
foreach ($handlers as $handler) {
$params = array_merge($params, (array) $handler->getRcptParams());
}
$paramStr = !empty($params) ? ' '.implode(' ', $params) : '';
$this->executeCommand(
sprintf("RCPT TO:<%s>%s\r\n", $address, $paramStr), array(250, 251, 252)
);
}
/** Determine ESMTP capabilities by function group */
private function getCapabilities($ehloResponse)
{
$capabilities = array();
$ehloResponse = trim($ehloResponse);
$lines = explode("\r\n", $ehloResponse);
array_shift($lines);
foreach ($lines as $line) {
if (preg_match('/^[0-9]{3}[ -]([A-Z0-9-]+)((?:[ =].*)?)$/Di', $line, $matches)) {
$keyword = strtoupper($matches[1]);
$paramStr = strtoupper(ltrim($matches[2], ' ='));
$params = !empty($paramStr) ? explode(' ', $paramStr) : array();
$capabilities[$keyword] = $params;
}
}
return $capabilities;
}
/** Set parameters which are used by each extension handler */
private function setHandlerParams()
{
foreach ($this->handlers as $keyword => $handler) {
if (array_key_exists($keyword, $this->capabilities)) {
$handler->setKeywordParams($this->capabilities[$keyword]);
}
}
}
/** Get ESMTP handlers which are currently ok to use */
private function getActiveHandlers()
{
$handlers = array();
foreach ($this->handlers as $keyword => $handler) {
if (array_key_exists($keyword, $this->capabilities)) {
$handlers[] = $handler;
}
}
return $handlers;
}
}
| mit |
cgourlay/msbuild | src/XMakeBuildEngine/BackEnd/Shared/ConfigurationMetadata.cs | 5617 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// </copyright>
// <summary>Class used for efficiently indexing BuildRequestConfigurations in the cache.</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Build.Collections;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Shared;
namespace Microsoft.Build.BackEnd
{
/// <summary>
/// A struct representing the uniquely-identifying portion of a BuildRequestConfiguration. Used for lookups.
/// </summary>
internal class ConfigurationMetadata : IEquatable<ConfigurationMetadata>
{
/// <summary>
/// Constructor over a BuildRequestConfiguration.
/// </summary>
public ConfigurationMetadata(BuildRequestConfiguration configuration)
{
ErrorUtilities.VerifyThrowArgumentNull(configuration, "configuration");
GlobalProperties = new PropertyDictionary<ProjectPropertyInstance>(configuration.Properties);
ProjectFullPath = FileUtilities.NormalizePath(configuration.ProjectFullPath);
ToolsVersion = configuration.ToolsVersion;
}
/// <summary>
/// Constructor over a Project.
/// </summary>
public ConfigurationMetadata(Project project)
{
ErrorUtilities.VerifyThrowArgumentNull(project, "project");
GlobalProperties = new PropertyDictionary<ProjectPropertyInstance>(project.GlobalProperties.Count);
foreach (KeyValuePair<string, string> entry in project.GlobalProperties)
{
this.GlobalProperties[entry.Key] = ProjectPropertyInstance.Create(entry.Key, entry.Value);
}
ToolsVersion = project.ToolsVersion;
ProjectFullPath = FileUtilities.NormalizePath(project.FullPath);
}
/// <summary>
/// The full path to the project to build.
/// </summary>
public string ProjectFullPath
{
get;
private set;
}
/// <summary>
/// The tools version specified for the configuration.
/// Always specified.
/// May have originated from a /tv switch, or an MSBuild task,
/// or a Project tag, or the default.
/// </summary>
public string ToolsVersion
{
get;
private set;
}
/// <summary>
/// The set of global properties which should be used when building this project.
/// </summary>
public PropertyDictionary<ProjectPropertyInstance> GlobalProperties
{
get;
private set;
}
/// <summary>
/// This override is used to provide a hash code for storage in dictionaries and the like.
/// </summary>
/// <remarks>
/// If two objects are Equal, they must have the same hash code, for dictionaries to work correctly.
/// Two configurations are Equal if their global properties are equivalent, not necessary reference equals.
/// So only include filename and tools version in the hashcode.
/// </remarks>
/// <returns>A hash code</returns>
public override int GetHashCode()
{
return StringComparer.OrdinalIgnoreCase.GetHashCode(ProjectFullPath) ^ StringComparer.OrdinalIgnoreCase.GetHashCode(ToolsVersion);
}
/// <summary>
/// Determines object equality
/// </summary>
/// <param name="obj">The object to compare with</param>
/// <returns>True if they contain the same data, false otherwise</returns>
public override bool Equals(object obj)
{
if (Object.ReferenceEquals(obj, null))
{
return false;
}
if (this.GetType() != obj.GetType())
{
return false;
}
return InternalEquals((ConfigurationMetadata)obj);
}
#region IEquatable<ConfigurationMetadata> Members
/// <summary>
/// Equality of the configuration is the product of the equality of its members.
/// </summary>
/// <param name="other">The other configuration to which we will compare ourselves.</param>
/// <returns>True if equal, false otherwise.</returns>
public bool Equals(ConfigurationMetadata other)
{
if (Object.ReferenceEquals(other, null))
{
return false;
}
return InternalEquals(other);
}
#endregion
/// <summary>
/// Compares this object with another for equality
/// </summary>
/// <param name="other">The object with which to compare this one.</param>
/// <returns>True if the objects contain the same data, false otherwise.</returns>
private bool InternalEquals(ConfigurationMetadata other)
{
if (Object.ReferenceEquals(this, other))
{
return true;
}
return ProjectFullPath.Equals(other.ProjectFullPath, StringComparison.OrdinalIgnoreCase) &&
ToolsVersion.Equals(other.ToolsVersion, StringComparison.OrdinalIgnoreCase) &&
GlobalProperties.Equals(other.GlobalProperties);
}
}
}
| mit |
phproberto/joomla-cms | libraries/cms/html/behavior.php | 31617 | <?php
/**
* @package Joomla.Libraries
* @subpackage HTML
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('JPATH_PLATFORM') or die;
/**
* Utility class for JavaScript behaviors
*
* @since 1.5
*/
abstract class JHtmlBehavior
{
/**
* Array containing information for loaded files
*
* @var array
* @since 2.5
*/
protected static $loaded = array();
/**
* Method to load the MooTools framework into the document head
*
* If debugging mode is on an uncompressed version of MooTools is included for easier debugging.
*
* @param boolean $extras Flag to determine whether to load MooTools More in addition to Core
* @param mixed $debug Is debugging mode on? [optional]
*
* @return void
*
* @since 1.6
* @deprecated 4.0 Update scripts to jquery
*/
public static function framework($extras = false, $debug = null)
{
$type = $extras ? 'more' : 'core';
// Only load once
if (!empty(static::$loaded[__METHOD__][$type]))
{
return;
}
JLog::add('JHtmlBehavior::framework is deprecated. Update to jquery scripts.', JLog::WARNING, 'deprecated');
// If no debugging value is set, use the configuration setting
if ($debug === null)
{
$debug = JDEBUG;
}
if ($type !== 'core' && empty(static::$loaded[__METHOD__]['core']))
{
static::framework(false, $debug);
}
JHtml::_('script', 'system/mootools-' . $type . '.js', array('version' => 'auto', 'relative' => true, 'detectDebug' => $debug));
// Keep loading core.js for BC reasons
static::core();
static::$loaded[__METHOD__][$type] = true;
return;
}
/**
* Method to load core.js into the document head.
*
* Core.js defines the 'Joomla' namespace and contains functions which are used across extensions
*
* @return void
*
* @since 3.3
*/
public static function core()
{
// Only load once
if (isset(static::$loaded[__METHOD__]))
{
return;
}
JHtml::_('form.csrf');
JHtml::_('script', 'system/core.js', array('version' => 'auto', 'relative' => true));
// Add core and base uri paths so javascript scripts can use them.
JFactory::getDocument()->addScriptOptions('system.paths', array('root' => JUri::root(true), 'base' => JUri::base(true)));
static::$loaded[__METHOD__] = true;
}
/**
* Add unobtrusive JavaScript support for image captions.
*
* @param string $selector The selector for which a caption behaviour is to be applied.
*
* @return void
*
* @since 1.5
*
* @Deprecated 4.0 Use native HTML figure tags.
*/
public static function caption($selector = 'img.caption')
{
JLog::add('JHtmlBehavior::caption is deprecated. Use native HTML figure tags.', JLog::WARNING, 'deprecated');
// Only load once
if (isset(static::$loaded[__METHOD__][$selector]))
{
return;
}
// Include jQuery
JHtml::_('jquery.framework');
JHtml::_('script', 'system/caption.js', array('version' => 'auto', 'relative' => true));
// Attach caption to document
JFactory::getDocument()->addScriptDeclaration(
"jQuery(window).on('load', function() {
new JCaption('" . $selector . "');
});"
);
// Set static array
static::$loaded[__METHOD__][$selector] = true;
}
/**
* Add unobtrusive JavaScript support for form validation.
*
* To enable form validation the form tag must have class="form-validate".
* Each field that needs to be validated needs to have class="validate".
* Additional handlers can be added to the handler for username, password,
* numeric and email. To use these add class="validate-email" and so on.
*
* @return void
*
* @since 1.5
*
* @Deprecated 3.4 Use formvalidator instead
*/
public static function formvalidation()
{
JLog::add('The use of formvalidation is deprecated use formvalidator instead.', JLog::WARNING, 'deprecated');
// Only load once
if (isset(static::$loaded[__METHOD__]))
{
return;
}
// Include MooTools framework
static::framework();
// Load the new jQuery code
static::formvalidator();
}
/**
* Add unobtrusive JavaScript support for form validation.
*
* To enable form validation the form tag must have class="form-validate".
* Each field that needs to be validated needs to have class="validate".
* Additional handlers can be added to the handler for username, password,
* numeric and email. To use these add class="validate-email" and so on.
*
* @return void
*
* @since 3.4
*/
public static function formvalidator()
{
// Only load once
if (isset(static::$loaded[__METHOD__]))
{
return;
}
// Include core
static::core();
// Include jQuery
JHtml::_('jquery.framework');
// Add validate.js language strings
JText::script('JLIB_FORM_FIELD_INVALID');
JHtml::_('script', 'system/punycode.js', array('version' => 'auto', 'relative' => true));
JHtml::_('script', 'system/validate.js', array('version' => 'auto', 'relative' => true));
static::$loaded[__METHOD__] = true;
}
/**
* Add unobtrusive JavaScript support for submenu switcher support
*
* @return void
*
* @since 1.5
*/
public static function switcher()
{
// Only load once
if (isset(static::$loaded[__METHOD__]))
{
return;
}
// Include jQuery
JHtml::_('jquery.framework');
JHtml::_('script', 'system/switcher.js', array('framework' => true, 'version' => 'auto', 'relative' => true));
$script = "
document.switcher = null;
jQuery(function($){
var toggler = document.getElementById('submenu');
var element = document.getElementById('config-document');
if (element) {
document.switcher = new JSwitcher(toggler, element);
}
});";
JFactory::getDocument()->addScriptDeclaration($script);
static::$loaded[__METHOD__] = true;
}
/**
* Add unobtrusive JavaScript support for a combobox effect.
*
* Note that this control is only reliable in absolutely positioned elements.
* Avoid using a combobox in a slider or dynamic pane.
*
* @return void
*
* @since 1.5
*/
public static function combobox()
{
if (isset(static::$loaded[__METHOD__]))
{
return;
}
// Include core
static::core();
JHtml::_('script', 'system/combobox.js', array('version' => 'auto', 'relative' => true));
static::$loaded[__METHOD__] = true;
}
/**
* Add unobtrusive JavaScript support for a hover tooltips.
*
* Add a title attribute to any element in the form
* title="title::text"
*
* Uses the core Tips class in MooTools.
*
* @param string $selector The class selector for the tooltip.
* @param array $params An array of options for the tooltip.
* Options for the tooltip can be:
* - maxTitleChars integer The maximum number of characters in the tooltip title (defaults to 50).
* - offsets object The distance of your tooltip from the mouse (defaults to {'x': 16, 'y': 16}).
* - showDelay integer The millisecond delay the show event is fired (defaults to 100).
* - hideDelay integer The millisecond delay the hide hide is fired (defaults to 100).
* - className string The className your tooltip container will get.
* - fixed boolean If set to true, the toolTip will not follow the mouse.
* - onShow function The default function for the show event, passes the tip element
* and the currently hovered element.
* - onHide function The default function for the hide event, passes the currently
* hovered element.
*
* @return void
*
* @since 1.5
*/
public static function tooltip($selector = '.hasTip', $params = array())
{
$sig = md5(serialize(array($selector, $params)));
if (isset(static::$loaded[__METHOD__][$sig]))
{
return;
}
// Include MooTools framework
static::framework(true);
// Setup options object
$opt['maxTitleChars'] = isset($params['maxTitleChars']) && $params['maxTitleChars'] ? (int) $params['maxTitleChars'] : 50;
// Offsets needs an array in the format: array('x'=>20, 'y'=>30)
$opt['offset'] = isset($params['offset']) && is_array($params['offset']) ? $params['offset'] : null;
$opt['showDelay'] = isset($params['showDelay']) ? (int) $params['showDelay'] : null;
$opt['hideDelay'] = isset($params['hideDelay']) ? (int) $params['hideDelay'] : null;
$opt['className'] = isset($params['className']) ? $params['className'] : null;
$opt['fixed'] = isset($params['fixed']) && $params['fixed'];
$opt['onShow'] = isset($params['onShow']) ? '\\' . $params['onShow'] : null;
$opt['onHide'] = isset($params['onHide']) ? '\\' . $params['onHide'] : null;
$options = JHtml::getJSObject($opt);
// Include jQuery
JHtml::_('jquery.framework');
// Attach tooltips to document
JFactory::getDocument()->addScriptDeclaration(
"jQuery(function($) {
$('$selector').each(function() {
var title = $(this).attr('title');
if (title) {
var parts = title.split('::', 2);
var mtelement = document.id(this);
mtelement.store('tip:title', parts[0]);
mtelement.store('tip:text', parts[1]);
}
});
var JTooltips = new Tips($('$selector').get(), $options);
});"
);
// Set static array
static::$loaded[__METHOD__][$sig] = true;
return;
}
/**
* Add unobtrusive JavaScript support for modal links.
*
* @param string $selector The selector for which a modal behaviour is to be applied.
* @param array $params An array of parameters for the modal behaviour.
* Options for the modal behaviour can be:
* - ajaxOptions
* - size
* - shadow
* - overlay
* - onOpen
* - onClose
* - onUpdate
* - onResize
* - onShow
* - onHide
*
* @return void
*
* @since 1.5
* @deprecated 4.0 Use the modal equivalent from bootstrap
*/
public static function modal($selector = 'a.modal', $params = array())
{
$document = JFactory::getDocument();
// Load the necessary files if they haven't yet been loaded
if (!isset(static::$loaded[__METHOD__]))
{
// Include MooTools framework
static::framework(true);
// Load the JavaScript and css
JHtml::_('script', 'system/modal.js', array('framework' => true, 'version' => 'auto', 'relative' => true));
JHtml::_('stylesheet', 'system/modal.css', array('version' => 'auto', 'relative' => true));
}
$sig = md5(serialize(array($selector, $params)));
if (isset(static::$loaded[__METHOD__][$sig]))
{
return;
}
JLog::add('JHtmlBehavior::modal is deprecated. Use the modal equivalent from bootstrap.', JLog::WARNING, 'deprecated');
// Setup options object
$opt['ajaxOptions'] = isset($params['ajaxOptions']) && is_array($params['ajaxOptions']) ? $params['ajaxOptions'] : null;
$opt['handler'] = isset($params['handler']) ? $params['handler'] : null;
$opt['parseSecure'] = isset($params['parseSecure']) ? (bool) $params['parseSecure'] : null;
$opt['closable'] = isset($params['closable']) ? (bool) $params['closable'] : null;
$opt['closeBtn'] = isset($params['closeBtn']) ? (bool) $params['closeBtn'] : null;
$opt['iframePreload'] = isset($params['iframePreload']) ? (bool) $params['iframePreload'] : null;
$opt['iframeOptions'] = isset($params['iframeOptions']) && is_array($params['iframeOptions']) ? $params['iframeOptions'] : null;
$opt['size'] = isset($params['size']) && is_array($params['size']) ? $params['size'] : null;
$opt['shadow'] = isset($params['shadow']) ? $params['shadow'] : null;
$opt['overlay'] = isset($params['overlay']) ? $params['overlay'] : null;
$opt['onOpen'] = isset($params['onOpen']) ? $params['onOpen'] : null;
$opt['onClose'] = isset($params['onClose']) ? $params['onClose'] : null;
$opt['onUpdate'] = isset($params['onUpdate']) ? $params['onUpdate'] : null;
$opt['onResize'] = isset($params['onResize']) ? $params['onResize'] : null;
$opt['onMove'] = isset($params['onMove']) ? $params['onMove'] : null;
$opt['onShow'] = isset($params['onShow']) ? $params['onShow'] : null;
$opt['onHide'] = isset($params['onHide']) ? $params['onHide'] : null;
// Include jQuery
JHtml::_('jquery.framework');
if (isset($params['fullScreen']) && (bool) $params['fullScreen'])
{
$opt['size'] = array('x' => '\\jQuery(window).width() - 80', 'y' => '\\jQuery(window).height() - 80');
}
$options = JHtml::getJSObject($opt);
// Attach modal behavior to document
$document
->addScriptDeclaration(
"
jQuery(function($) {
SqueezeBox.initialize(" . $options . ");
initSqueezeBox();
$(document).on('subform-row-add', initSqueezeBox);
function initSqueezeBox(event, container)
{
SqueezeBox.assign($(container || document).find('" . $selector . "').get(), {
parse: 'rel'
});
}
});
window.jModalClose = function () {
SqueezeBox.close();
};
// Add extra modal close functionality for tinyMCE-based editors
document.onreadystatechange = function () {
if (document.readyState == 'interactive' && typeof tinyMCE != 'undefined' && tinyMCE)
{
if (typeof window.jModalClose_no_tinyMCE === 'undefined')
{
window.jModalClose_no_tinyMCE = typeof(jModalClose) == 'function' ? jModalClose : false;
jModalClose = function () {
if (window.jModalClose_no_tinyMCE) window.jModalClose_no_tinyMCE.apply(this, arguments);
tinyMCE.activeEditor.windowManager.close();
};
}
if (typeof window.SqueezeBoxClose_no_tinyMCE === 'undefined')
{
if (typeof(SqueezeBox) == 'undefined') SqueezeBox = {};
window.SqueezeBoxClose_no_tinyMCE = typeof(SqueezeBox.close) == 'function' ? SqueezeBox.close : false;
SqueezeBox.close = function () {
if (window.SqueezeBoxClose_no_tinyMCE) window.SqueezeBoxClose_no_tinyMCE.apply(this, arguments);
tinyMCE.activeEditor.windowManager.close();
};
}
}
};
"
);
// Set static array
static::$loaded[__METHOD__][$sig] = true;
return;
}
/**
* JavaScript behavior to allow shift select in grids
*
* @param string $id The id of the form for which a multiselect behaviour is to be applied.
*
* @return void
*
* @since 1.7
*/
public static function multiselect($id = 'adminForm')
{
// Only load once
if (isset(static::$loaded[__METHOD__][$id]))
{
return;
}
// Include core
static::core();
// Include jQuery
JHtml::_('jquery.framework');
JHtml::_('script', 'system/multiselect.js', array('version' => 'auto', 'relative' => true));
// Attach multiselect to document
JFactory::getDocument()->addScriptDeclaration(
"jQuery(document).ready(function() {
Joomla.JMultiSelect('" . $id . "');
});"
);
// Set static array
static::$loaded[__METHOD__][$id] = true;
return;
}
/**
* Add unobtrusive javascript support for a collapsible tree.
*
* @param string $id An index
* @param array $params An array of options.
* @param array $root The root node
*
* @return void
*
* @since 1.5
*/
public static function tree($id, $params = array(), $root = array())
{
// Include MooTools framework
static::framework();
JHtml::_('script', 'system/mootree.js', array('framework' => true, 'version' => 'auto', 'relative' => true));
JHtml::_('stylesheet', 'system/mootree.css', array('version' => 'auto', 'relative' => true));
if (isset(static::$loaded[__METHOD__][$id]))
{
return;
}
// Include jQuery
JHtml::_('jquery.framework');
// Setup options object
$opt['div'] = array_key_exists('div', $params) ? $params['div'] : $id . '_tree';
$opt['mode'] = array_key_exists('mode', $params) ? $params['mode'] : 'folders';
$opt['grid'] = array_key_exists('grid', $params) ? '\\' . $params['grid'] : true;
$opt['theme'] = array_key_exists('theme', $params) ? $params['theme'] : JHtml::_('image', 'system/mootree.gif', '', array(), true, true);
// Event handlers
$opt['onExpand'] = array_key_exists('onExpand', $params) ? '\\' . $params['onExpand'] : null;
$opt['onSelect'] = array_key_exists('onSelect', $params) ? '\\' . $params['onSelect'] : null;
$opt['onClick'] = array_key_exists('onClick', $params) ? '\\' . $params['onClick']
: '\\function(node){ window.open(node.data.url, node.data.target != null ? node.data.target : \'_self\'); }';
$options = JHtml::getJSObject($opt);
// Setup root node
$rt['text'] = array_key_exists('text', $root) ? $root['text'] : 'Root';
$rt['id'] = array_key_exists('id', $root) ? $root['id'] : null;
$rt['color'] = array_key_exists('color', $root) ? $root['color'] : null;
$rt['open'] = array_key_exists('open', $root) ? '\\' . $root['open'] : true;
$rt['icon'] = array_key_exists('icon', $root) ? $root['icon'] : null;
$rt['openicon'] = array_key_exists('openicon', $root) ? $root['openicon'] : null;
$rt['data'] = array_key_exists('data', $root) ? $root['data'] : null;
$rootNode = JHtml::getJSObject($rt);
$treeName = array_key_exists('treeName', $params) ? $params['treeName'] : '';
$js = ' jQuery(function(){
tree' . $treeName . ' = new MooTreeControl(' . $options . ',' . $rootNode . ');
tree' . $treeName . '.adopt(\'' . $id . '\');})';
// Attach tooltips to document
$document = JFactory::getDocument();
$document->addScriptDeclaration($js);
// Set static array
static::$loaded[__METHOD__][$id] = true;
return;
}
/**
* Add unobtrusive JavaScript support for a calendar control.
*
* @return void
*
* @since 1.5
*
* @deprecated 4.0
*/
public static function calendar()
{
// Only load once
if (isset(static::$loaded[__METHOD__]))
{
return;
}
JLog::add('JHtmlBehavior::calendar is deprecated as the static assets are being loaded in the relative layout.', JLog::WARNING, 'deprecated');
$document = JFactory::getDocument();
$tag = JFactory::getLanguage()->getTag();
$attribs = array('title' => JText::_('JLIB_HTML_BEHAVIOR_GREEN'), 'media' => 'all');
JHtml::_('stylesheet', 'system/calendar-jos.css', array('version' => 'auto', 'relative' => true), $attribs);
JHtml::_('script', $tag . '/calendar.js', array('version' => 'auto', 'relative' => true));
JHtml::_('script', $tag . '/calendar-setup.js', array('version' => 'auto', 'relative' => true));
$translation = static::calendartranslation();
if ($translation)
{
$document->addScriptDeclaration($translation);
}
static::$loaded[__METHOD__] = true;
}
/**
* Add unobtrusive JavaScript support for a color picker.
*
* @return void
*
* @since 1.7
*
* @deprecated 4.0 Use directly the field or the layout
*/
public static function colorpicker()
{
// Only load once
if (isset(static::$loaded[__METHOD__]))
{
return;
}
// Include jQuery
JHtml::_('jquery.framework');
JHtml::_('script', 'jui/jquery.minicolors.min.js', array('version' => 'auto', 'relative' => true));
JHtml::_('stylesheet', 'jui/jquery.minicolors.css', array('version' => 'auto', 'relative' => true));
JFactory::getDocument()->addScriptDeclaration("
jQuery(document).ready(function (){
jQuery('.minicolors').each(function() {
jQuery(this).minicolors({
control: jQuery(this).attr('data-control') || 'hue',
format: jQuery(this).attr('data-validate') === 'color'
? 'hex'
: (jQuery(this).attr('data-format') === 'rgba'
? 'rgb'
: jQuery(this).attr('data-format'))
|| 'hex',
keywords: jQuery(this).attr('data-keywords') || '',
opacity: jQuery(this).attr('data-format') === 'rgba' ? true : false || false,
position: jQuery(this).attr('data-position') || 'default',
theme: 'bootstrap'
});
});
});
"
);
static::$loaded[__METHOD__] = true;
}
/**
* Add unobtrusive JavaScript support for a simple color picker.
*
* @return void
*
* @since 3.1
*
* @deprecated 4.0 Use directly the field or the layout
*/
public static function simplecolorpicker()
{
// Only load once
if (isset(static::$loaded[__METHOD__]))
{
return;
}
// Include jQuery
JHtml::_('jquery.framework');
JHtml::_('script', 'jui/jquery.simplecolors.min.js', array('version' => 'auto', 'relative' => true));
JHtml::_('stylesheet', 'jui/jquery.simplecolors.css', array('version' => 'auto', 'relative' => true));
JFactory::getDocument()->addScriptDeclaration("
jQuery(document).ready(function (){
jQuery('select.simplecolors').simplecolors();
});
"
);
static::$loaded[__METHOD__] = true;
}
/**
* Keep session alive, for example, while editing or creating an article.
*
* @return void
*
* @since 1.5
*/
public static function keepalive()
{
// Only load once
if (isset(static::$loaded[__METHOD__]))
{
return;
}
$session = JFactory::getSession();
// If the handler is not 'Database', we set a fixed, small refresh value (here: 5 min)
$refreshTime = 300;
if ($session->storeName === 'database')
{
$lifeTime = $session->getExpire();
$refreshTime = $lifeTime <= 60 ? 45 : $lifeTime - 60;
// The longest refresh period is one hour to prevent integer overflow.
if ($refreshTime > 3600 || $refreshTime <= 0)
{
$refreshTime = 3600;
}
}
// If we are in the frontend or logged in as a user, we can use the ajax component to reduce the load
$uri = 'index.php' . (JFactory::getApplication()->isClient('site') || !JFactory::getUser()->guest ? '?option=com_ajax&format=json' : '');
// Include core and polyfill for browsers lower than IE 9.
static::core();
static::polyfill('event', 'lt IE 9');
// Add keepalive script options.
JFactory::getDocument()->addScriptOptions('system.keepalive', array('interval' => $refreshTime * 1000, 'uri' => JRoute::_($uri)));
// Add script.
JHtml::_('script', 'system/keepalive.js', array('version' => 'auto', 'relative' => true));
static::$loaded[__METHOD__] = true;
return;
}
/**
* Highlight some words via Javascript.
*
* @param array $terms Array of words that should be highlighted.
* @param string $start ID of the element that marks the begin of the section in which words
* should be highlighted. Note this element will be removed from the DOM.
* @param string $end ID of the element that end this section.
* Note this element will be removed from the DOM.
* @param string $className Class name of the element highlights are wrapped in.
* @param string $tag Tag that will be used to wrap the highlighted words.
*
* @return void
*
* @since 2.5
*/
public static function highlighter(array $terms, $start = 'highlighter-start', $end = 'highlighter-end', $className = 'highlight', $tag = 'span')
{
$sig = md5(serialize(array($terms, $start, $end)));
if (isset(static::$loaded[__METHOD__][$sig]))
{
return;
}
$terms = array_filter($terms, 'strlen');
// Nothing to Highlight
if (empty($terms))
{
static::$loaded[__METHOD__][$sig] = true;
return;
}
// Include core
static::core();
// Include jQuery
JHtml::_('jquery.framework');
JHtml::_('script', 'system/highlighter.js', array('version' => 'auto', 'relative' => true));
foreach ($terms as $i => $term)
{
$terms[$i] = JFilterOutput::stringJSSafe($term);
}
$document = JFactory::getDocument();
$document->addScriptDeclaration("
jQuery(function ($) {
var start = document.getElementById('" . $start . "');
var end = document.getElementById('" . $end . "');
if (!start || !end || !Joomla.Highlighter) {
return true;
}
highlighter = new Joomla.Highlighter({
startElement: start,
endElement: end,
className: '" . $className . "',
onlyWords: false,
tag: '" . $tag . "'
}).highlight([\"" . implode('","', $terms) . "\"]);
$(start).remove();
$(end).remove();
});
");
static::$loaded[__METHOD__][$sig] = true;
return;
}
/**
* Break us out of any containing iframes
*
* @return void
*
* @since 1.5
*
* @deprecated 4.0 Add a X-Frame-Options HTTP Header with the SAMEORIGIN value instead.
*/
public static function noframes()
{
JLog::add(__METHOD__ . ' is deprecated, add a X-Frame-Options HTTP Header with the SAMEORIGIN value instead.', JLog::WARNING, 'deprecated');
// Only load once
if (isset(static::$loaded[__METHOD__]))
{
return;
}
// Include core
static::core();
// Include jQuery
JHtml::_('jquery.framework');
$js = 'jQuery(function () {
if (top == self) {
document.documentElement.style.display = "block";
}
else
{
top.location = self.location;
}
// Firefox fix
jQuery("input[autofocus]").focus();
})';
$document = JFactory::getDocument();
$document->addStyleDeclaration('html { display:none }');
$document->addScriptDeclaration($js);
JFactory::getApplication()->setHeader('X-Frame-Options', 'SAMEORIGIN');
static::$loaded[__METHOD__] = true;
}
/**
* Internal method to get a JavaScript object notation string from an array
*
* @param array $array The array to convert to JavaScript object notation
*
* @return string JavaScript object notation representation of the array
*
* @since 1.5
* @deprecated 4.0 - Use JHtml::getJSObject() instead.
*/
protected static function _getJSObject($array = array())
{
JLog::add('JHtmlBehavior::_getJSObject() is deprecated. JHtml::getJSObject() instead..', JLog::WARNING, 'deprecated');
return JHtml::getJSObject($array);
}
/**
* Add unobtrusive JavaScript support to keep a tab state.
*
* Note that keeping tab state only works for inner tabs if in accordance with the following example:
*
* ```
* parent tab = permissions
* child tab = permission-<identifier>
* ```
*
* Each tab header `<a>` tag also should have a unique href attribute
*
* @return void
*
* @since 3.2
*/
public static function tabstate()
{
if (isset(self::$loaded[__METHOD__]))
{
return;
}
// Include jQuery
JHtml::_('jquery.framework');
JHtml::_('behavior.polyfill', array('filter','xpath'));
JHtml::_('script', 'system/tabs-state.js', array('version' => 'auto', 'relative' => true));
self::$loaded[__METHOD__] = true;
}
/**
* Add javascript polyfills.
*
* @param string|array $polyfillTypes The polyfill type(s). Examples: event, array('event', 'classlist').
* @param string $conditionalBrowser An IE conditional expression. Example: lt IE 9 (lower than IE 9).
*
* @return void
*
* @since 3.7.0
*/
public static function polyfill($polyfillTypes = null, $conditionalBrowser = null)
{
if ($polyfillTypes === null)
{
return;
}
foreach ((array) $polyfillTypes as $polyfillType)
{
$sig = md5(serialize(array($polyfillType, $conditionalBrowser)));
// Only load once
if (isset(static::$loaded[__METHOD__][$sig]))
{
continue;
}
// If include according to browser.
$scriptOptions = array('version' => 'auto', 'relative' => true);
$scriptOptions = $conditionalBrowser !== null ? array_replace($scriptOptions, array('conditional' => $conditionalBrowser)) : $scriptOptions;
JHtml::_('script', 'system/polyfill.' . $polyfillType . '.js', $scriptOptions);
// Set static array
static::$loaded[__METHOD__][$sig] = true;
}
}
/**
* Internal method to translate the JavaScript Calendar
*
* @return string JavaScript that translates the object
*
* @since 1.5
*/
protected static function calendartranslation()
{
static $jsscript = 0;
// Guard clause, avoids unnecessary nesting
if ($jsscript)
{
return false;
}
$jsscript = 1;
// To keep the code simple here, run strings through JText::_() using array_map()
$callback = array('JText', '_');
$weekdays_full = array_map(
$callback, array(
'SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY',
)
);
$weekdays_short = array_map(
$callback,
array(
'SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN',
)
);
$months_long = array_map(
$callback, array(
'JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE',
'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER',
)
);
$months_short = array_map(
$callback, array(
'JANUARY_SHORT', 'FEBRUARY_SHORT', 'MARCH_SHORT', 'APRIL_SHORT', 'MAY_SHORT', 'JUNE_SHORT',
'JULY_SHORT', 'AUGUST_SHORT', 'SEPTEMBER_SHORT', 'OCTOBER_SHORT', 'NOVEMBER_SHORT', 'DECEMBER_SHORT',
)
);
// This will become an object in Javascript but define it first in PHP for readability
$today = " " . JText::_('JLIB_HTML_BEHAVIOR_TODAY') . " ";
$text = array(
'INFO' => JText::_('JLIB_HTML_BEHAVIOR_ABOUT_THE_CALENDAR'),
'ABOUT' => "DHTML Date/Time Selector\n"
. "(c) dynarch.com 20022005 / Author: Mihai Bazon\n"
. "For latest version visit: http://www.dynarch.com/projects/calendar/\n"
. "Distributed under GNU LGPL. See http://gnu.org/licenses/lgpl.html for details."
. "\n\n"
. JText::_('JLIB_HTML_BEHAVIOR_DATE_SELECTION')
. JText::_('JLIB_HTML_BEHAVIOR_YEAR_SELECT')
. JText::_('JLIB_HTML_BEHAVIOR_MONTH_SELECT')
. JText::_('JLIB_HTML_BEHAVIOR_HOLD_MOUSE'),
'ABOUT_TIME' => "\n\n"
. "Time selection:\n"
. " Click on any of the time parts to increase it\n"
. " or Shiftclick to decrease it\n"
. " or click and drag for faster selection.",
'PREV_YEAR' => JText::_('JLIB_HTML_BEHAVIOR_PREV_YEAR_HOLD_FOR_MENU'),
'PREV_MONTH' => JText::_('JLIB_HTML_BEHAVIOR_PREV_MONTH_HOLD_FOR_MENU'),
'GO_TODAY' => JText::_('JLIB_HTML_BEHAVIOR_GO_TODAY'),
'NEXT_MONTH' => JText::_('JLIB_HTML_BEHAVIOR_NEXT_MONTH_HOLD_FOR_MENU'),
'SEL_DATE' => JText::_('JLIB_HTML_BEHAVIOR_SELECT_DATE'),
'DRAG_TO_MOVE' => JText::_('JLIB_HTML_BEHAVIOR_DRAG_TO_MOVE'),
'PART_TODAY' => $today,
'DAY_FIRST' => JText::_('JLIB_HTML_BEHAVIOR_DISPLAY_S_FIRST'),
'WEEKEND' => JFactory::getLanguage()->getWeekEnd(),
'CLOSE' => JText::_('JLIB_HTML_BEHAVIOR_CLOSE'),
'TODAY' => JText::_('JLIB_HTML_BEHAVIOR_TODAY'),
'TIME_PART' => JText::_('JLIB_HTML_BEHAVIOR_SHIFT_CLICK_OR_DRAG_TO_CHANGE_VALUE'),
'DEF_DATE_FORMAT' => "%Y%m%d",
'TT_DATE_FORMAT' => JText::_('JLIB_HTML_BEHAVIOR_TT_DATE_FORMAT'),
'WK' => JText::_('JLIB_HTML_BEHAVIOR_WK'),
'TIME' => JText::_('JLIB_HTML_BEHAVIOR_TIME'),
);
return 'Calendar._DN = ' . json_encode($weekdays_full) . ';'
. ' Calendar._SDN = ' . json_encode($weekdays_short) . ';'
. ' Calendar._FD = 0;'
. ' Calendar._MN = ' . json_encode($months_long) . ';'
. ' Calendar._SMN = ' . json_encode($months_short) . ';'
. ' Calendar._TT = ' . json_encode($text) . ';';
}
}
| gpl-2.0 |
mossy2100/multiplanetary | core/modules/views/src/Tests/Plugin/DisplayFeedTest.php | 6499 | <?php
namespace Drupal\views\Tests\Plugin;
use Drupal\views\Views;
/**
* Tests the feed display plugin.
*
* @group views
* @see \Drupal\views\Plugin\views\display\Feed
*/
class DisplayFeedTest extends PluginTestBase {
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_display_feed', 'test_attached_disabled', 'test_feed_icon'];
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['block', 'node', 'views'];
protected function setUp($import_test_views = TRUE) {
parent::setUp($import_test_views);
$this->enableViewsTestModule();
$admin_user = $this->drupalCreateUser(['administer site configuration']);
$this->drupalLogin($admin_user);
}
/**
* Tests the rendered output.
*/
public function testFeedOutput() {
$this->drupalCreateContentType(['type' => 'page']);
// Verify a title with HTML entities is properly escaped.
$node_title = 'This "cool" & "neat" article\'s title';
$node = $this->drupalCreateNode([
'title' => $node_title,
'body' => [
0 => [
'value' => 'A paragraph',
'format' => filter_default_format(),
],
],
]);
// Test the site name setting.
$site_name = $this->randomMachineName();
$this->config('system.site')->set('name', $site_name)->save();
$this->drupalGet('test-feed-display.xml');
$result = $this->xpath('//title');
$this->assertEqual($result[0], $site_name, 'The site title is used for the feed title.');
$this->assertEqual($result[1], $node_title, 'Node title with HTML entities displays correctly.');
// Verify HTML is properly escaped in the description field.
$this->assertRaw('<p>A paragraph</p>');
$view = $this->container->get('entity.manager')->getStorage('view')->load('test_display_feed');
$display = &$view->getDisplay('feed_1');
$display['display_options']['sitename_title'] = 0;
$view->save();
$this->drupalGet('test-feed-display.xml');
$result = $this->xpath('//title');
$this->assertEqual($result[0], 'test_display_feed', 'The display title is used for the feed title.');
// Add a block display and attach the feed.
$view->getExecutable()->newDisplay('block', NULL, 'test');
$display = &$view->getDisplay('feed_1');
$display['display_options']['displays']['test'] = 'test';
$view->save();
// Test the feed display adds a feed icon to the block display.
$this->drupalPlaceBlock('views_block:test_display_feed-test');
$this->drupalGet('<front>');
$feed_icon = $this->cssSelect('div.view-id-test_display_feed a.feed-icon');
$this->assertTrue(strpos($feed_icon[0]['href'], 'test-feed-display.xml'), 'The feed icon was found.');
// Test feed display attached to page display with arguments.
$this->drupalGet('test-feed-icon/' . $node->id());
$page_url = $this->getUrl();
$icon_href = $this->cssSelect('a.feed-icon[href *= "test-feed-icon"]')[0]['href'];
$this->assertEqual($icon_href, $page_url . '/feed', 'The feed icon was found.');
$link_href = $this->cssSelect('link[type = "application/rss+xml"][href *= "test-feed-icon"]')[0]['href'];
$this->assertEqual($link_href, $page_url . '/feed', 'The RSS link was found.');
$feed_link = simplexml_load_string($this->drupalGet($icon_href))->channel->link;
$this->assertEqual($feed_link, $page_url, 'The channel link was found.');
}
/**
* Tests the rendered output for fields display.
*/
public function testFeedFieldOutput() {
$this->drupalCreateContentType(['type' => 'page']);
// Verify a title with HTML entities is properly escaped.
$node_title = 'This "cool" & "neat" article\'s title';
$this->drupalCreateNode([
'title' => $node_title,
'body' => [
0 => [
'value' => 'A paragraph',
'format' => filter_default_format(),
],
],
]);
$this->drupalGet('test-feed-display-fields.xml');
$result = $this->xpath('//title/a');
$this->assertEqual($result[0], $node_title, 'Node title with HTML entities displays correctly.');
// Verify HTML is properly escaped in the description field.
$this->assertRaw('<p>A paragraph</p>');
}
/**
* Tests that nothing is output when the feed display is disabled.
*/
public function testDisabledFeed() {
$this->drupalCreateContentType(['type' => 'page']);
$this->drupalCreateNode();
// Ensure that the feed_1 display is attached to the page_1 display.
$view = Views::getView('test_attached_disabled');
$view->setDisplay('page_1');
$attached_displays = $view->display_handler->getAttachedDisplays();
$this->assertTrue(in_array('feed_1', $attached_displays), 'The feed display is attached to the page display.');
// Check that the rss header is output on the page display.
$this->drupalGet('/test-attached-disabled');
$feed_header = $this->xpath('//link[@rel="alternate"]');
$this->assertEqual($feed_header[0]['type'], 'application/rss+xml', 'The feed link has the type application/rss+xml.');
$this->assertTrue(strpos($feed_header[0]['href'], 'test-attached-disabled.xml'), 'Page display contains the correct feed URL.');
// Disable the feed display.
$view->displayHandlers->get('feed_1')->setOption('enabled', FALSE);
$view->save();
// Ensure there is no link rel present on the page.
$this->drupalGet('/test-attached-disabled');
$result = $this->xpath('//link[@rel="alternate"]');
$this->assertTrue(empty($result), 'Page display does not contain a feed header.');
// Ensure the feed attachment returns 'Not found'.
$this->drupalGet('/test-attached-disabled.xml');
$this->assertResponse(404);
}
/**
* Tests that the feed display works when the linked display is disabled.
*/
public function testDisabledLinkedDisplay() {
$view = Views::getView('test_attached_disabled');
$view->setDisplay();
// Disable the page and link the feed to the page.
$view->displayHandlers->get('feed_1')->setOption('link_display', 'page_1');
$view->displayHandlers->get('page_1')->setOption('enabled', FALSE);
$view->save();
\Drupal::service('router.builder')->rebuild();
$this->drupalGet('test-attached-disabled');
$this->assertResponse(404);
// Ensure the feed can still be reached.
$this->drupalGet('test-attached-disabled.xml');
$this->assertResponse(200);
}
}
| gpl-2.0 |
zhongliangkang/GCS-SQL | storage/ndb/test/odbc/client/SQLExecuteTest.cpp | 3383 | /* Copyright (C) 2003 MySQL AB
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; version 2 of the License.
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 */
/**
* @file SQLExecuteTest.cpp
*/
#include <common.hpp>
#define ESQL_MAXIMUM_MESSAGE_LENGTH 200
using namespace std;
SQLHDBC Ehdbc;
SQLHSTMT Ehstmt;
SQLHENV Ehenv;
SQLHDESC Ehdesc;
void Execute_DisplayError(SQLSMALLINT EHandleType,
SQLHSTMT EInputHandle);
/**
* Test to execute a SQL statement in a data result set
*
* Tests:
* -# Test1 There is no executed statement
* @return Zero, if test succeeded
*/
int SQLExecuteTest()
{
SQLRETURN retcode;
/* hstmt */
retcode = SQLExecute(Ehstmt);
if (retcode == SQL_INVALID_HANDLE)
ndbout << "Handle Type is SQL_HANDLE_STMT, but SQL_INVALID_HANDLE" << endl;
ndbout << "still appeared. Please check programm" << endl;
if (retcode == SQL_ERROR || retcode == SQL_SUCCESS_WITH_INFO)
Execute_DisplayError(SQL_HANDLE_STMT, Ehstmt);
/* henv */
retcode = SQLExecute(Ehenv);
if (retcode == SQL_SUCCESS_WITH_INFO || retcode == SQL_SUCCESS)
ndbout << "Handle Type is SQL_HANDLE_ENV, but SQL_SUCCESS_WITH_INFO"
<< "still appeared. Please check programm" << endl;
// Execute_DisplayError(SQL_HANDLE_ENV, Ehenv);
/* hdbc */
retcode = SQLExecute(Ehdbc);
if (retcode == SQL_SUCCESS_WITH_INFO || retcode == SQL_SUCCESS)
ndbout << "Handle Type is SQL_HANDLE_DBC, but SQL_SUCCESS_WITH_INFO"
<<"still appeared. Please check programm" << endl;
// Execute_DisplayError(SQL_HANDLE_DBC, Ehdbc);
/* hdesc */
retcode = SQLExecute(Ehdesc);
if (retcode == SQL_SUCCESS_WITH_INFO || retcode == SQL_SUCCESS)
ndbout << "Handle Type is SQL_HANDLE_DESC, but SQL_SUCCESS_WITH_INFO"
<< "still appeared. Please check programm" << endl;
// Execute_DisplayError(SQL_HANDLE_DESC, Ehdesc);
return NDBT_OK;
}
void Execute_DisplayError(SQLSMALLINT EHandleType,
SQLHSTMT EInputHandle)
{
SQLCHAR Sqlstate[5];
SQLINTEGER NativeError;
SQLSMALLINT i, MsgLen;
SQLCHAR Msg[ESQL_MAXIMUM_MESSAGE_LENGTH];
SQLRETURN SQLSTATEs;
i = 1;
ndbout << "-------------------------------------------------" << endl;
ndbout << "Error diagnostics:" << endl;
while ((SQLSTATEs = SQLGetDiagRec(EHandleType,
EInputHandle,
i,
Sqlstate,
&NativeError,
Msg,
sizeof(Msg),
&MsgLen))
!= SQL_NO_DATA)
{
ndbout << "the HandleType is:" << EHandleType << endl;
ndbout << "the InputHandle is :" << EInputHandle << endl;
ndbout << "the Msg is :" << (char *)Msg << endl;
ndbout << "the output state is:" << (char *)Sqlstate << endl;
i ++;
break;
}
ndbout << "-------------------------------------------------" << endl;
}
| gpl-2.0 |
Mustaavalkosta/toolchain_gcc-4.9 | libstdc++-v3/testsuite/ext/random/arcsine_distribution/cons/parms.cc | 1209 | // { dg-options "-std=c++11" }
// { dg-require-cstdint "" }
//
// 2012-10-12 Edward M. Smith-Rowland <3dw4rd@verizon.net>
//
// Copyright (C) 2012-2013 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include <ext/random>
#include <testsuite_hooks.h>
void
test01()
{
bool test __attribute__((unused)) = true;
__gnu_cxx::arcsine_distribution<> u(-1.5, 3.0);
VERIFY( u.a() == -1.5 );
VERIFY( u.b() == 3.0 );
VERIFY( u.min() == -1.5 );
VERIFY( u.max() == 3.0 );
}
int
main()
{
test01();
return 0;
}
| gpl-2.0 |
mattbilson/Blog---wordpress | wp-content/plugins/code-highlighter/geshi/objc.php | 11653 | <?php
/*************************************************************************************
* objc.php
* --------
* Author: M. Uli Kusterer (witness.of.teachtext@gmx.net)
* Copyright: (c) 2004 M. Uli Kusterer, Nigel McNie (http://qbnz.com/highlighter/)
* Release Version: 1.0.7.20
* Date Started: 2004/06/04
*
* Objective C language file for GeSHi.
*
* CHANGES
* -------
* 2004/11/27 (1.0.0)
* - First Release
*
* TODO (updated 2004/11/27)
* -------------------------
*
*************************************************************************************
*
* This file is part of GeSHi.
*
* GeSHi 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.
*
* GeSHi 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 GeSHi; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
************************************************************************************/
$language_data = array (
'LANG_NAME' => 'Objective C',
'COMMENT_SINGLE' => array(1 => '//', 2 => '#'),
'COMMENT_MULTI' => array('/*' => '*/'),
'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE,
'QUOTEMARKS' => array("'", '"'),
'ESCAPE_CHAR' => '\\',
'KEYWORDS' => array(
1 => array(
'if', 'return', 'while', 'case', 'continue', 'default',
'do', 'else', 'for', 'switch', 'goto'
),
2 => array(
'NULL', 'false', 'break', 'true', 'enum', 'nil', 'Nil', 'errno', 'EDOM',
'ERANGE', 'FLT_RADIX', 'FLT_ROUNDS', 'FLT_DIG', 'DBL_DIG', 'LDBL_DIG',
'FLT_EPSILON', 'DBL_EPSILON', 'LDBL_EPSILON', 'FLT_MANT_DIG', 'DBL_MANT_DIG',
'LDBL_MANT_DIG', 'FLT_MAX', 'DBL_MAX', 'LDBL_MAX', 'FLT_MAX_EXP', 'DBL_MAX_EXP',
'LDBL_MAX_EXP', 'FLT_MIN', 'DBL_MIN', 'LDBL_MIN', 'FLT_MIN_EXP', 'DBL_MIN_EXP',
'LDBL_MIN_EXP', 'CHAR_BIT', 'CHAR_MAX', 'CHAR_MIN', 'SCHAR_MAX', 'SCHAR_MIN',
'UCHAR_MAX', 'SHRT_MAX', 'SHRT_MIN', 'USHRT_MAX', 'INT_MAX', 'INT_MIN',
'UINT_MAX', 'LONG_MAX', 'LONG_MIN', 'ULONG_MAX', 'HUGE_VAL', 'SIGABRT',
'SIGFPE', 'SIGILL', 'SIGINT', 'SIGSEGV', 'SIGTERM', 'SIG_DFL', 'SIG_ERR',
'SIG_IGN', 'BUFSIZ', 'EOF', 'FILENAME_MAX', 'FOPEN_MAX', 'L_tmpnam', 'NULL',
'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'stdin', 'stdout', 'stderr',
'EXIT_FAILURE', 'EXIT_SUCCESS', 'RAND_MAX', 'CLOCKS_PER_SEC'
),
3 => array(
'printf', 'fprintf', 'snprintf', 'sprintf', 'assert',
'isalnum', 'isalpha', 'isdigit', 'iscntrl', 'isgraph', 'islower', 'isprint',
'ispunct', 'isspace', 'ispunct', 'isupper', 'isxdigit', 'tolower', 'toupper',
'exp', 'log', 'log10', 'pow', 'sqrt', 'ceil', 'floor', 'fabs', 'ldexp',
'frexp', 'modf', 'fmod', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2',
'sinh', 'cosh', 'tanh', 'setjmp', 'longjmp', 'asin', 'acos', 'atan', 'atan2',
'va_start', 'va_arg', 'va_end', 'offsetof', 'sizeof', 'fopen', 'freopen',
'fflush', 'fclose', 'remove', 'rename', 'tmpfile', 'tmpname', 'setvbuf',
'setbuf', 'vfprintf', 'vprintf', 'vsprintf', 'fscanf', 'scanf', 'sscanf',
'fgetc', 'fgets', 'fputc', 'fputs', 'getc', 'getchar', 'gets', 'putc',
'putchar', 'puts', 'ungetc', 'fread', 'fwrite', 'fseek', 'ftell', 'rewind',
'fgetpos', 'fsetpos', 'clearerr', 'feof', 'ferror', 'perror', 'abs', 'labs',
'div', 'ldiv', 'atof', 'atoi', 'atol', 'strtod', 'strtol', 'strtoul', 'calloc',
'malloc', 'realloc', 'free', 'abort', 'exit', 'atexit', 'system', 'getenv',
'bsearch', 'qsort', 'rand', 'srand', 'strcpy', 'strncpy', 'strcat', 'strncat',
'strcmp', 'strncmp', 'strcoll', 'strchr', 'strrchr', 'strspn', 'strcspn',
'strpbrk', 'strstr', 'strlen', 'strerror', 'strtok', 'strxfrm', 'memcpy',
'memmove', 'memcmp', 'memchr', 'memset', 'clock', 'time', 'difftime', 'mktime',
'asctime', 'ctime', 'gmtime', 'localtime', 'strftime'
),
4 => array( // Data types:
'auto', 'char', 'const', 'double', 'float', 'int', 'long',
'register', 'short', 'signed', 'sizeof', 'static', 'string', 'struct',
'typedef', 'union', 'unsigned', 'void', 'volatile', 'extern', 'jmp_buf',
'signal', 'raise', 'va_list', 'ptrdiff_t', 'size_t', 'FILE', 'fpos_t',
'div_t', 'ldiv_t', 'clock_t', 'time_t', 'tm',
// OpenStep/GNUstep/Cocoa:
'SEL', 'id', 'NSRect', 'NSRange', 'NSPoint', 'NSZone', 'Class', 'IMP', 'BOOL',
// OpenStep/GNUstep/Cocoa @identifiers
'@selector', '@class', '@protocol', '@interface', '@implementation', '@end',
'@private', '@protected', '@public', '@try', '@throw', '@catch', '@finally',
'@encode', '@defs', '@synchronized'
),
5 => array( // OpenStep/GNUstep/Cocoa Foundation
'NSAppleEventDescriptor', 'NSNetService', 'NSAppleEventManager',
'NSNetServiceBrowser', 'NSAppleScript', 'NSNotification', 'NSArchiver',
'NSNotificationCenter', 'NSArray', 'NSNotificationQueue', 'NSAssertionHandler',
'NSNull', 'NSAttributedString', 'NSNumber', 'NSAutoreleasePool',
'NSNumberFormatter', 'NSBundle', 'NSObject', 'NSCachedURLResponse',
'NSOutputStream', 'NSCalendarDate', 'NSPipe', 'NSCharacterSet', 'NSPort',
'NSClassDescription', 'NSPortCoder', 'NSCloneCommand', 'NSPortMessage',
'NSCloseCommand', 'NSPortNameServer', 'NSCoder', 'NSPositionalSpecifier',
'NSConditionLock', 'NSProcessInfo', 'NSConnection', 'NSPropertyListSerialization',
'NSCountCommand', 'NSPropertySpecifier', 'NSCountedSet', 'NSProtocolChecker',
'NSCreateCommand', 'NSProxy', 'NSData', 'NSQuitCommand', 'NSDate',
'NSRandomSpecifier', 'NSDateFormatter', 'NSRangeSpecifier', 'NSDecimalNumber',
'NSRecursiveLock', 'NSDecimalNumberHandler', 'NSRelativeSpecifier',
'NSDeleteCommand', 'NSRunLoop', 'NSDeserializer', 'NSScanner', 'NSDictionary',
'NSScriptClassDescription', 'NSDirectoryEnumerator', 'NSScriptCoercionHandler',
'NSDistantObject', 'NSScriptCommand', 'NSDistantObjectRequest',
'NSScriptCommandDescription', 'NSDistributedLock', 'NSScriptExecutionContext',
'NSDistributedNotificationCenter', 'NSScriptObjectSpecifier', 'NSEnumerator',
'NSScriptSuiteRegistry', 'NSError', 'NSScriptWhoseTest', 'NSException',
'NSSerializer', 'NSExistsCommand', 'NSSet', 'NSFileHandle', 'NSSetCommand',
'NSFileManager', 'NSSocketPort', 'NSFormatter', 'NSSocketPortNameServer',
'NSGetCommand', 'NSSortDescriptor', 'NSHost', 'NSSpecifierTest', 'NSHTTPCookie',
'NSSpellServer', 'NSHTTPCookieStorage', 'NSStream', 'NSHTTPURLResponse',
'NSString', 'NSIndexSet', 'NSTask', 'NSIndexSpecifier', 'NSThread',
'NSInputStream', 'NSTimer', 'NSInvocation', 'NSTimeZone', 'NSKeyedArchiver',
'NSUnarchiver', 'NSKeyedUnarchiver', 'NSUndoManager', 'NSLock',
'NSUniqueIDSpecifier', 'NSLogicalTest', 'NSURL', 'NSMachBootstrapServer',
'NSURLAuthenticationChallenge', 'NSMachPort', 'NSURLCache', 'NSMessagePort',
'NSURLConnection', 'NSMessagePortNameServer', 'NSURLCredential',
'NSMethodSignature', 'NSURLCredentialStorage', 'NSMiddleSpecifier',
'NSURLDownload', 'NSMoveCommand', 'NSURLHandle', 'NSMutableArray',
'NSURLProtectionSpace', 'NSMutableAttributedString', 'NSURLProtocol',
'NSMutableCharacterSet', 'NSURLRequest', 'NSMutableData', 'NSURLResponse',
'NSMutableDictionary', 'NSUserDefaults', 'NSMutableIndexSet', 'NSValue',
'NSMutableSet', 'NSValueTransformer', 'NSMutableString', 'NSWhoseSpecifier',
'NSMutableURLRequest', 'NSXMLParser', 'NSNameSpecifier'
),
6 => array( // OpenStep/GNUstep/Cocoa AppKit
'NSActionCell', 'NSOpenGLPixelFormat', 'NSAffineTransform', 'NSOpenGLView',
'NSAlert', 'NSOpenPanel', 'NSAppleScript Additions', 'NSOutlineView',
'NSApplication', 'NSPageLayout', 'NSArrayController', 'NSPanel',
'NSATSTypesetter', 'NSParagraphStyle', 'NSPasteboard', 'NSBezierPath',
'NSPDFImageRep', 'NSBitmapImageRep', 'NSPICTImageRep', 'NSBox', 'NSPopUpButton',
'NSBrowser', 'NSPopUpButtonCell', 'NSBrowserCell', 'NSPrinter', 'NSPrintInfo',
'NSButton', 'NSPrintOperation', 'NSButtonCell', 'NSPrintPanel', 'NSCachedImageRep',
'NSProgressIndicator', 'NSCell', 'NSQuickDrawView', 'NSClipView', 'NSResponder',
'NSRulerMarker', 'NSColor', 'NSRulerView', 'NSColorList', 'NSSavePanel',
'NSColorPanel', 'NSScreen', 'NSColorPicker', 'NSScroller', 'NSColorWell',
'NSScrollView', 'NSComboBox', 'NSSearchField', 'NSComboBoxCell',
'NSSearchFieldCell', 'NSControl', 'NSSecureTextField', 'NSController',
'NSSecureTextFieldCell', 'NSCursor', 'NSSegmentedCell', 'NSCustomImageRep',
'NSSegmentedControl', 'NSDocument', 'NSShadow', 'NSDocumentController',
'NSSimpleHorizontalTypesetter', 'NSDrawer', 'NSSlider', 'NSEPSImageRep',
'NSSliderCell', 'NSEvent', 'NSSound', 'NSFileWrapper', 'NSSpeechRecognizer',
'NSFont', 'NSSpeechSynthesizer', 'NSFontDescriptor', 'NSSpellChecker',
'NSFontManager', 'NSSplitView', 'NSFontPanel', 'NSStatusBar', 'NSForm',
'NSStatusItem', 'NSFormCell', 'NSStepper', 'NSGlyphGenerator', 'NSStepperCell',
'NSGlyphInfo', 'NSGraphicsContext', 'NSTableColumn', 'NSHelpManager',
'NSTableHeaderCell', 'NSImage', 'NSTableHeaderView', 'NSImageCell', 'NSTableView',
'NSImageRep', 'NSTabView', 'NSImageView', 'NSTabViewItem', 'NSInputManager',
'NSText', 'NSInputServer', 'NSTextAttachment', 'NSLayoutManager',
'NSTextAttachmentCell', 'NSMatrix', 'NSTextContainer', 'NSMenu', 'NSTextField',
'NSMenuItem', 'NSTextFieldCell', 'NSMenuItemCell', 'NSTextStorage', 'NSMenuView',
'NSTextTab', 'NSMovie', 'NSTextView', 'NSMovieView', 'NSToolbar', 'NSToolbarItem',
'NSMutableParagraphStyle', 'NSTypesetter', 'NSNib', 'NSNibConnector',
'NSUserDefaultsController', 'NSNibControlConnector', 'NSView',
'NSNibOutletConnector', 'NSWindow', 'NSObjectController', 'NSWindowController',
'NSOpenGLContext', 'NSWorkspace', 'NSOpenGLPixelBuffer'
)
),
'SYMBOLS' => array(
'(', ')', '{', '}', '[', ']', '=', '+', '-', '*', '/', '!', '%', '^', '&', ':'
),
'CASE_SENSITIVE' => array(
GESHI_COMMENTS => true,
1 => false,
2 => false,
3 => false,
4 => false,
5 => false,
6 => false,
),
'STYLES' => array(
'KEYWORDS' => array(
1 => 'color: #0000ff;',
2 => 'color: #0000ff;',
3 => 'color: #0000dd;',
4 => 'color: #0000ff;',
5 => 'color: #0000ff;',
6 => 'color: #0000ff;'
),
'COMMENTS' => array(
1 => 'color: #ff0000;',
2 => 'color: #339900;',
'MULTI' => 'color: #ff0000; font-style: italic;'
),
'ESCAPE_CHAR' => array(
0 => 'color: #666666; font-weight: bold;'
),
'BRACKETS' => array(
0 => 'color: #002200;'
),
'STRINGS' => array(
0 => 'color: #666666;'
),
'NUMBERS' => array(
0 => 'color: #0000dd;'
),
'METHODS' => array(
),
'SYMBOLS' => array(
0 => 'color: #002200;'
),
'REGEXPS' => array(
),
'SCRIPT' => array(
)
),
'URLS' => array(
1 => '',
2 => '',
3 => 'http://www.opengroup.org/onlinepubs/009695399/functions/{FNAME}.html',
4 => '',
5 => 'http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/{FNAME}.html',
6 => 'http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/ObjC_classic/Classes/{FNAME}.html'
),
'OOLANG' => false,
'OBJECT_SPLITTERS' => array(
),
'REGEXPS' => array(
),
'STRICT_MODE_APPLIES' => GESHI_NEVER,
'SCRIPT_DELIMITERS' => array(
),
'HIGHLIGHT_STRICT_BLOCK' => array(
)
);
?>
| gpl-2.0 |
baslr/ArangoDB | 3rdParty/boost/1.62.0/libs/geometry/test/algorithms/relational_operations/equals/equals.cpp | 11632 | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// This file was modified by Oracle on 2013, 2014.
// Modifications copyright (c) 2013-2014 Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "test_equals.hpp"
#include <boost/type_traits/is_floating_point.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
namespace bgm = bg::model;
template <typename P>
void test_segment_segment()
{
typedef bgm::segment<P> seg;
test_geometry<seg, seg>("seg2d_1", "LINESTRING(0 0, 3 3)", "LINESTRING(0 0, 3 3)", true);
test_geometry<seg, seg>("seg2d_1", "LINESTRING(0 0, 3 3)", "LINESTRING(3 3, 0 0)", true);
test_geometry<seg, seg>("seg2d_1", "LINESTRING(0 0, 3 3)", "LINESTRING(0 0, 1 1)", false);
test_geometry<seg, seg>("seg2d_1", "LINESTRING(0 0, 3 3)", "LINESTRING(3 3, 2 2)", false);
test_geometry<seg, seg>("seg2d_1", "LINESTRING(0 0, 3 3)", "LINESTRING(1 1, 4 4)", false);
test_geometry<seg, seg>("seg2d_1", "LINESTRING(0 0, 3 3)", "LINESTRING(1 0, 2 0)", false);
}
template <typename P>
void test_linestring_linestring()
{
typedef bgm::linestring<P> ls;
test_geometry<ls, ls>("ls2d_1", "LINESTRING(1 1, 3 3)", "LINESTRING(3 3, 1 1)", true);
test_geometry<ls, ls>("ls2d_2", "LINESTRING(1 1, 3 3, 2 5)", "LINESTRING(1 1, 2 2, 3 3, 2 5)", true);
test_geometry<ls, ls>("ls2d_3", "LINESTRING(1 0, 3 3, 2 5)", "LINESTRING(1 1, 2 2, 3 3, 2 5)", false);
test_geometry<ls, ls>("ls2d_4", "LINESTRING(1 0, 3 3, 2 5)", "LINESTRING(1 1, 3 3, 2 5)", false);
test_geometry<ls, ls>("ls2d_5", "LINESTRING(0 5,5 5,10 5,10 0,5 0,5 5,5 10,10 10,15 10,15 5,10 5,10 10,10 15)",
"LINESTRING(0 5,15 5,15 10,5 10,5 0,10 0,10 15)", true);
test_geometry<ls, ls>("ls2d_6", "LINESTRING(0 5,5 5,10 5,10 10,5 10,5 5,5 0)", "LINESTRING(0 5,5 5,5 10,10 10,10 5,5 5,5 0)", true);
test_geometry<ls, ls>("ls2d_7", "LINESTRING(0 5,10 5,10 10,5 10,5 0)", "LINESTRING(0 5,5 5,5 10,10 10,10 5,5 5,5 0)", true);
test_geometry<ls, ls>("ls2d_8", "LINESTRING(0 0,5 0,5 0,6 0)", "LINESTRING(0 0,6 0)", true);
test_geometry<ls, ls>("ls2d_seg", "LINESTRING(1 1,2 2)", "LINESTRING(1 1,2 2)", true);
test_geometry<ls, ls>("ls2d_rev", "LINESTRING(1 1,2 2)", "LINESTRING(2 2,1 1)", true);
test_geometry<ls, ls>("ls2d_spike", "LINESTRING(0 0,5 0,3 0,6 0)", "LINESTRING(0 0,6 0)", true);
test_geometry<ls, ls>("ls2d_ring1", "LINESTRING(0 0,5 0,5 5,0 5,0 0)", "LINESTRING(5 5,0 5,0 0,5 0,5 5)", true);
test_geometry<ls, ls>("ls2d_ring2", "LINESTRING(0 0,5 0,5 5,0 5,0 0)", "LINESTRING(5 5,5 0,0 0,0 5,5 5)", true);
test_geometry<ls, ls>("ls2d_overl_ring1", "LINESTRING(0 0,5 0,5 5,0 5,0 0)", "LINESTRING(5 5,0 5,0 0,5 0,5 5,0 5)", true);
test_geometry<ls, ls>("ls2d_overl_ring2", "LINESTRING(0 0,5 0,5 5,0 5,0 0)", "LINESTRING(5 5,5 0,0 0,0 5,5 5,5 0)", true);
// https://svn.boost.org/trac/boost/ticket/10904
if ( BOOST_GEOMETRY_CONDITION(
boost::is_floating_point<typename bg::coordinate_type<ls>::type>::value ) )
{
test_geometry<ls, ls>("ls2d_small1",
"LINESTRING(5.6956521739130430148634331999347 -0.60869565217391330413931882503675,5.5 -0.50000000000000066613381477509392)",
"LINESTRING(5.5 -0.50000000000000066613381477509392,5.5 -0.5)",
false);
test_geometry<ls, ls>("ls2d_small2",
"LINESTRING(-3.2333333333333333925452279800083 5.5999999999999978683717927196994,-3.2333333333333333925452279800083 5.5999999999999996447286321199499)",
"LINESTRING(-3.2333333333333325043668082798831 5.5999999999999996447286321199499,-3.2333333333333333925452279800083 5.5999999999999996447286321199499)",
false);
}
}
template <typename P>
void test_linestring_multilinestring()
{
typedef bgm::linestring<P> ls;
typedef bgm::multi_linestring<ls> mls;
test_geometry<ls, mls>("ls_mls_1", "LINESTRING(0 0,1 0,2 0)", "MULTILINESTRING((0 0,2 0))", true);
test_geometry<ls, mls>("ls_mls_1", "LINESTRING(0 0,1 0,2 0)", "MULTILINESTRING((0 0,1 0),(1 0,2 0))", true);
test_geometry<ls, mls>("ls_mls_1", "LINESTRING(0 0,2 0,4 0)", "MULTILINESTRING((0 0,2 0),(2 0,3 0),(3 0,4 0))", true);
test_geometry<ls, mls>("ls_mls_1", "LINESTRING(0 0,2 0,4 0)", "MULTILINESTRING((0 0,2 0),(2 0,3 0),(2 0,3 0),(3 0,4 0))", true);
test_geometry<ls, mls>("ls_mls_1", "LINESTRING(0 0,2 0,4 0)", "MULTILINESTRING((0 0,2 0),(3 0,4 0))", false);
test_geometry<ls, mls>("ls_mls_spike", "LINESTRING(0 0,2 0,2 2,2 0,4 0)", "MULTILINESTRING((0 0,4 0),(2 2,2 0))", true);
test_geometry<ls, mls>("ls_mls_spike", "LINESTRING(0 0,2 0,2 2,2 0,4 0)", "MULTILINESTRING((0 0,4 0),(2 2,2 -1))", false);
test_geometry<ls, mls>("ls_mls_ring1", "LINESTRING(0 0,5 0,5 5,0 5,0 0)", "MULTILINESTRING((5 5,0 5,0 0),(0 0,5 0,5 5))", true);
test_geometry<ls, mls>("ls_mls_ring2", "LINESTRING(0 0,5 0,5 5,0 5,0 0)", "MULTILINESTRING((5 5,5 0,0 0),(0 0,0 5,5 5))", true);
test_geometry<ls, mls>("ls_mls_overl_ring1", "LINESTRING(0 0,5 0,5 5,0 5,0 0)", "MULTILINESTRING((5 5,0 5,0 0),(0 0,5 0,5 5,0 5))", true);
test_geometry<ls, mls>("ls_mls_overl_ring2", "LINESTRING(0 0,5 0,5 5,0 5,0 0)", "MULTILINESTRING((5 5,5 0,0 0),(0 0,0 5,5 5,5 0))", true);
}
template <typename P>
void test_multilinestring_multilinestring()
{
typedef bgm::linestring<P> ls;
typedef bgm::multi_linestring<ls> mls;
test_geometry<mls, mls>("ls_mls_mls",
"MULTILINESTRING((0 5,10 5,10 10,5 10),(5 10,5 0,5 2),(5 2,5 5,0 5))",
"MULTILINESTRING((5 5,0 5),(5 5,5 0),(10 10,10 5,5 5,5 10,10 10))",
true);
}
template <typename P>
void test_all()
{
typedef bg::model::box<P> box;
typedef bg::model::ring<P> ring;
typedef bg::model::polygon<P> polygon;
//typedef bg::model::linestring<P> linestring;
std::string case_p1 = "POLYGON((0 0,0 2,2 2,0 0))";
test_geometry<P, P>("p1", "POINT(1 1)", "POINT(1 1)", true);
test_geometry<P, P>("p2", "POINT(1 1)", "POINT(1 2)", false);
test_geometry<box, box>("b1", "BOX(1 1,2 2)", "BOX(1 2,2 2)", false);
test_geometry<box, box>("b1", "BOX(1 2,3 4)", "BOX(1 2,3 4)", true);
// Completely equal
test_geometry<ring, ring>("poly_eq", case_p1, case_p1, true);
// Shifted
test_geometry<ring, ring>("poly_sh", "POLYGON((2 2,0 0,0 2,2 2))", case_p1, true);
test_geometry<polygon, polygon>("poly_sh2", case_p1, "POLYGON((0 2,2 2,0 0,0 2))", true);
// Extra coordinate
test_geometry<ring, ring>("poly_extra", case_p1, "POLYGON((0 0,0 2,2 2,1 1,0 0))", true);
// Shifted + extra (redundant) coordinate
test_geometry<ring, ring>("poly_shifted_extra1", "POLYGON((2 2,1 1,0 0,0 2,2 2))", case_p1, true);
// Shifted + extra (redundant) coordinate being first/last point
test_geometry<ring, ring>("poly_shifted_extra2", "POLYGON((1 1,0 0,0 2,2 2,1 1))", case_p1, true);
// Degenerate (duplicate) points
test_geometry<ring, ring>("poly_degenerate", "POLYGON((0 0,0 2,2 2,2 2,0 0))", "POLYGON((0 0,0 2,0 2,2 2,0 0))", true);
// Two different bends, same area, unequal
test_geometry<ring, ring>("poly_bends",
"POLYGON((4 0,5 3,8 4,7 7,4 8,0 4,4 0))",
"POLYGON((4 0,7 1,8 4,5 5,4 8,0 4,4 0))", false);
// Unequal (but same area)
test_geometry<ring, ring>("poly_uneq", case_p1, "POLYGON((1 1,1 3,3 3,1 1))", false);
// One having hole
test_geometry<polygon, polygon>("poly_hole", "POLYGON((0 0,0 4,4 4,0 0))", "POLYGON((0 0,0 4,4 4,0 0),(1 1,2 1,2 2,1 2,1 1))", false);
// Both having holes
test_geometry<polygon, polygon>("poly_holes",
"POLYGON((0 0,0 4,4 4,0 0),(1 1,2 1,2 2,1 2,1 1))",
"POLYGON((0 0,0 4,4 4,0 0),(1 1,2 1,2 2,1 2,1 1))", true);
// Both having holes, outer equal, inner not equal
test_geometry<polygon, polygon>("poly_uneq_holes",
"POLYGON((0 0,0 4,4 4,0 0),(1 1,2 1,2 2,1 2,1 1))",
"POLYGON((0 0,0 4,4 4,0 0),(2 2,3 2,3 3,2 3,2 2))", false);
// Both having 2 holes, equal but in different order
test_geometry<polygon, polygon>("poly_holes_diff_order",
"POLYGON((0 0,0 4,4 4,0 0),(1 1,2 1,2 2,1 2,1 1),(2 2,3 2,3 3,2 3,2 2))",
"POLYGON((0 0,0 4,4 4,0 0),(2 2,3 2,3 3,2 3,2 2),(1 1,2 1,2 2,1 2,1 1))", true);
// Both having 3 holes, equal but in different order
test_geometry<polygon, polygon>("poly_holes_diff_order_3",
"POLYGON((0 0,0 10,10 10,0 0),(1 1,2 1,2 2,1 2,1 1),(4 1,5 1,5 2,4 2,4 1),(2 2,3 2,3 3,2 3,2 2))",
"POLYGON((0 0,0 10,10 10,0 0),(4 1,5 1,5 2,4 2,4 1),(2 2,3 2,3 3,2 3,2 2),(1 1,2 1,2 2,1 2,1 1))", true);
// polygon/ring vv
test_geometry<polygon, ring>("poly_sh2_pr", case_p1, case_p1, true);
test_geometry<ring, polygon>("poly_sh2_rp", case_p1, case_p1, true);
// box/ring/poly
test_geometry<box, ring>("boxring1", "BOX(1 1,2 2)", "POLYGON((1 1,1 2,2 2,2 1,1 1))", true);
test_geometry<ring, box>("boxring2", "POLYGON((1 1,1 2,2 2,2 1,1 1))", "BOX(1 1,2 2)", true);
test_geometry<box, polygon>("boxpoly1", "BOX(1 1,2 2)", "POLYGON((1 1,1 2,2 2,2 1,1 1))", true);
test_geometry<polygon, box>("boxpoly2", "POLYGON((1 1,1 2,2 2,2 1,1 1))", "BOX(1 1,2 2)", true);
test_geometry<polygon, box>("boxpoly2", "POLYGON((1 1,1 2,2 2,2 1,1 1))", "BOX(1 1,2 3)", false);
test_geometry<polygon, polygon>("poly_holes_shifted_points",
"POLYGON((0 0,0 3,3 3,3 0,0 0),(1 1,2 1,2 2,1 2,1 1))",
"POLYGON((0 0,0 3,3 3,3 0,0 0),(2 2,1 2,1 1,2 1,2 2))", true);
test_segment_segment<P>();
test_linestring_linestring<P>();
test_linestring_multilinestring<P>();
test_multilinestring_multilinestring<P>();
}
template <typename T>
void verify()
{
T dxn1, dyn1, dxn2, dyn2;
{
T x1 = "0", y1 = "0", x2 = "3", y2 = "3";
T dx = x2 - x1, dy = y2 - y1;
T mag = sqrt(dx * dx + dy * dy);
dxn1 = dx / mag;
dyn1 = dy / mag;
}
{
T x1 = "0", y1 = "0", x2 = "1", y2 = "1";
T dx = x2 - x1, dy = y2 - y1;
T mag = sqrt(dx * dx + dy * dy);
dxn2 = dx / mag;
dyn2 = dy / mag;
}
if (dxn1 == dxn2 && dyn1 == dyn2)
{
//std::cout << "vectors are equal, using ==" << std::endl;
}
if (boost::geometry::math::equals(dxn1, dxn2)
&& boost::geometry::math::equals(dyn1, dyn2))
{
//std::cout << "vectors are equal, using bg::math::equals" << std::endl;
}
bool equals = boost::geometry::math::equals_with_epsilon(dxn1, dxn2)
&& boost::geometry::math::equals_with_epsilon(dyn1, dyn2);
if (equals)
{
//std::cout << "vectors are equal, using bg::math::equals_with_epsilon" << std::endl;
}
BOOST_CHECK_EQUAL(equals, true);
}
int test_main( int , char* [] )
{
//verify<double>();
#if defined(HAVE_TTMATH)
verify<ttmath_big>();
#endif
test_all<bg::model::d2::point_xy<int> >();
test_all<bg::model::d2::point_xy<double> >();
#if defined(HAVE_TTMATH)
test_all<bg::model::d2::point_xy<ttmath_big> >();
#endif
return 0;
}
| apache-2.0 |
udayinfy/BroadleafCommerce | common/src/main/java/org/broadleafcommerce/common/dialect/Broadleaf2CompatibilityMySQL5InnoDBDialect.java | 1299 | /*
* #%L
* BroadleafCommerce Common Libraries
* %%
* Copyright (C) 2009 - 2013 Broadleaf Commerce
* %%
* 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 org.broadleafcommerce.common.dialect;
import org.hibernate.dialect.MySQL5InnoDBDialect;
/**
* Intended to allow installations migrating from BLC version 2.0 to not be forced to make a schema
* change for boolean fields when migrating to BLC version 3.0, and above.
*
* @deprecated use org.hibernate.dialect.MySQL5InnoDBDialect instead
* @author Jeff Fischer
*/
@Deprecated
public class Broadleaf2CompatibilityMySQL5InnoDBDialect extends MySQL5InnoDBDialect {
public Broadleaf2CompatibilityMySQL5InnoDBDialect() {
super();
registerColumnType( java.sql.Types.BOOLEAN, "bit" );
}
}
| apache-2.0 |
agoncharuk/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/local/GridCacheLocalTxMultiThreadedSelfTest.java | 2857 | /*
* 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.internal.processors.cache.local;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.processors.cache.GridCacheProcessor;
import org.apache.ignite.internal.processors.cache.IgniteTxMultiThreadedAbstractTest;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import static org.apache.ignite.cache.CacheMode.LOCAL;
/**
* Tests for local transactions.
*/
public class GridCacheLocalTxMultiThreadedSelfTest extends IgniteTxMultiThreadedAbstractTest {
/** Cache debug flag. */
private static final boolean CACHE_DEBUG = false;
/** {@inheritDoc} */
@SuppressWarnings({"ConstantConditions"})
@Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
IgniteConfiguration c = super.getConfiguration(gridName);
c.getTransactionConfiguration().setTxSerializableEnabled(true);
CacheConfiguration cc = defaultCacheConfiguration();
cc.setCacheMode(LOCAL);
cc.setEvictionPolicy(null);
c.setCacheConfiguration(cc);
// Disable log4j debug by default.
Logger log4j = Logger.getLogger(GridCacheProcessor.class.getPackage().getName());
log4j.setLevel(CACHE_DEBUG ? Level.DEBUG : Level.INFO);
return c;
}
/** {@inheritDoc} */
@Override protected int gridCount() {
return 1;
}
/** {@inheritDoc} */
@Override protected int keyCount() {
return 3;
}
/** {@inheritDoc} */
@Override protected int maxKeyValue() {
return 3;
}
/** {@inheritDoc} */
@Override protected int threadCount() {
return 8;
}
/** {@inheritDoc} */
@Override protected int iterations() {
return 1000;
}
/** {@inheritDoc} */
@Override protected boolean isTestDebug() {
return false;
}
/** {@inheritDoc} */
@Override protected boolean printMemoryStats() {
return true;
}
} | apache-2.0 |
rsc/kubernetes | test/e2e/autoscaling/horizontal_pod_autoscaling.go | 5922 | /*
Copyright 2015 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 autoscaling
import (
"time"
"k8s.io/kubernetes/test/e2e/common"
"k8s.io/kubernetes/test/e2e/framework"
. "github.com/onsi/ginkgo"
)
// These tests don't seem to be running properly in parallel: issue: #20338.
//
var _ = SIGDescribe("[HPA] Horizontal pod autoscaling (scale resource: CPU)", func() {
var rc *common.ResourceConsumer
f := framework.NewDefaultFramework("horizontal-pod-autoscaling")
titleUp := "Should scale from 1 pod to 3 pods and from 3 to 5"
titleDown := "Should scale from 5 pods to 3 pods and from 3 to 1"
SIGDescribe("[Serial] [Slow] Deployment", func() {
// CPU tests via deployments
It(titleUp, func() {
scaleUp("test-deployment", common.KindDeployment, false, rc, f)
})
It(titleDown, func() {
scaleDown("test-deployment", common.KindDeployment, false, rc, f)
})
})
SIGDescribe("[Serial] [Slow] ReplicaSet", func() {
// CPU tests via deployments
It(titleUp, func() {
scaleUp("rs", common.KindReplicaSet, false, rc, f)
})
It(titleDown, func() {
scaleDown("rs", common.KindReplicaSet, false, rc, f)
})
})
// These tests take ~20 minutes each.
SIGDescribe("[Serial] [Slow] ReplicationController", func() {
// CPU tests via replication controllers
It(titleUp+" and verify decision stability", func() {
scaleUp("rc", common.KindRC, true, rc, f)
})
It(titleDown+" and verify decision stability", func() {
scaleDown("rc", common.KindRC, true, rc, f)
})
})
SIGDescribe("ReplicationController light", func() {
It("Should scale from 1 pod to 2 pods", func() {
scaleTest := &HPAScaleTest{
initPods: 1,
totalInitialCPUUsage: 150,
perPodCPURequest: 200,
targetCPUUtilizationPercent: 50,
minPods: 1,
maxPods: 2,
firstScale: 2,
}
scaleTest.run("rc-light", common.KindRC, rc, f)
})
It("Should scale from 2 pods to 1 pod", func() {
scaleTest := &HPAScaleTest{
initPods: 2,
totalInitialCPUUsage: 50,
perPodCPURequest: 200,
targetCPUUtilizationPercent: 50,
minPods: 1,
maxPods: 2,
firstScale: 1,
}
scaleTest.run("rc-light", common.KindRC, rc, f)
})
})
})
// HPAScaleTest struct is used by the scale(...) function.
type HPAScaleTest struct {
initPods int32
totalInitialCPUUsage int32
perPodCPURequest int64
targetCPUUtilizationPercent int32
minPods int32
maxPods int32
firstScale int32
firstScaleStasis time.Duration
cpuBurst int
secondScale int32
secondScaleStasis time.Duration
}
// run is a method which runs an HPA lifecycle, from a starting state, to an expected
// The initial state is defined by the initPods parameter.
// The first state change is due to the CPU being consumed initially, which HPA responds to by changing pod counts.
// The second state change (optional) is due to the CPU burst parameter, which HPA again responds to.
// TODO The use of 3 states is arbitrary, we could eventually make this test handle "n" states once this test stabilizes.
func (scaleTest *HPAScaleTest) run(name, kind string, rc *common.ResourceConsumer, f *framework.Framework) {
const timeToWait = 15 * time.Minute
rc = common.NewDynamicResourceConsumer(name, kind, int(scaleTest.initPods), int(scaleTest.totalInitialCPUUsage), 0, 0, scaleTest.perPodCPURequest, 200, f)
defer rc.CleanUp()
hpa := common.CreateCPUHorizontalPodAutoscaler(rc, scaleTest.targetCPUUtilizationPercent, scaleTest.minPods, scaleTest.maxPods)
defer common.DeleteHorizontalPodAutoscaler(rc, hpa.Name)
rc.WaitForReplicas(int(scaleTest.firstScale), timeToWait)
if scaleTest.firstScaleStasis > 0 {
rc.EnsureDesiredReplicas(int(scaleTest.firstScale), scaleTest.firstScaleStasis)
}
if scaleTest.cpuBurst > 0 && scaleTest.secondScale > 0 {
rc.ConsumeCPU(scaleTest.cpuBurst)
rc.WaitForReplicas(int(scaleTest.secondScale), timeToWait)
}
}
func scaleUp(name, kind string, checkStability bool, rc *common.ResourceConsumer, f *framework.Framework) {
stasis := 0 * time.Minute
if checkStability {
stasis = 10 * time.Minute
}
scaleTest := &HPAScaleTest{
initPods: 1,
totalInitialCPUUsage: 250,
perPodCPURequest: 500,
targetCPUUtilizationPercent: 20,
minPods: 1,
maxPods: 5,
firstScale: 3,
firstScaleStasis: stasis,
cpuBurst: 700,
secondScale: 5,
}
scaleTest.run(name, kind, rc, f)
}
func scaleDown(name, kind string, checkStability bool, rc *common.ResourceConsumer, f *framework.Framework) {
stasis := 0 * time.Minute
if checkStability {
stasis = 10 * time.Minute
}
scaleTest := &HPAScaleTest{
initPods: 5,
totalInitialCPUUsage: 375,
perPodCPURequest: 500,
targetCPUUtilizationPercent: 30,
minPods: 1,
maxPods: 5,
firstScale: 3,
firstScaleStasis: stasis,
cpuBurst: 10,
secondScale: 1,
}
scaleTest.run(name, kind, rc, f)
}
| apache-2.0 |
wheelcomplex/SimianArmy | src/main/java/com/netflix/simianarmy/aws/janitor/crawler/edda/EddaLaunchConfigJanitorCrawler.java | 6724 | /*
*
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.simianarmy.aws.janitor.crawler.edda;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.simianarmy.Resource;
import com.netflix.simianarmy.ResourceType;
import com.netflix.simianarmy.aws.AWSResource;
import com.netflix.simianarmy.aws.AWSResourceType;
import com.netflix.simianarmy.client.edda.EddaClient;
import com.netflix.simianarmy.janitor.JanitorCrawler;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.codehaus.jackson.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* The crawler to crawl AWS launch configurations for janitor monkey using Edda.
*/
public class EddaLaunchConfigJanitorCrawler implements JanitorCrawler {
/** The name representing the additional field name of a flag indicating if the launch config
* if used by an auto scaling group. */
public static final String LAUNCH_CONFIG_FIELD_USED_BY_ASG = "USED_BY_ASG";
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(EddaLaunchConfigJanitorCrawler.class);
private final EddaClient eddaClient;
private final List<String> regions = Lists.newArrayList();
/**
* Instantiates a new basic launch configuration crawler.
* @param eddaClient
* the Edda client
* @param regions
* the regions the crawler will crawl resources for
*/
public EddaLaunchConfigJanitorCrawler(EddaClient eddaClient, String... regions) {
Validate.notNull(eddaClient);
this.eddaClient = eddaClient;
Validate.notNull(regions);
for (String region : regions) {
this.regions.add(region);
}
}
@Override
public EnumSet<? extends ResourceType> resourceTypes() {
return EnumSet.of(AWSResourceType.LAUNCH_CONFIG);
}
@Override
public List<Resource> resources(ResourceType resourceType) {
if ("LAUNCH_CONFIG".equals(resourceType.name())) {
return getLaunchConfigResources();
}
return Collections.emptyList();
}
@Override
public List<Resource> resources(String... resourceIds) {
return getLaunchConfigResources(resourceIds);
}
private List<Resource> getLaunchConfigResources(String... launchConfigNames) {
List<Resource> resources = Lists.newArrayList();
for (String region : regions) {
resources.addAll(getLaunchConfigResourcesInRegion(region, launchConfigNames));
}
return resources;
}
@Override
public String getOwnerEmailForResource(Resource resource) {
return null;
}
private List<Resource> getLaunchConfigResourcesInRegion(String region, String... launchConfigNames) {
String url = eddaClient.getBaseUrl(region) + "/aws/launchConfigurations;";
if (launchConfigNames != null && launchConfigNames.length != 0) {
url += StringUtils.join(launchConfigNames, ',');
LOGGER.info(String.format("Getting launch configurations in region %s for %d ids",
region, launchConfigNames.length));
} else {
LOGGER.info(String.format("Getting all launch configurations in region %s", region));
}
url += ";_expand:(launchConfigurationName,createdTime)";
JsonNode jsonNode = null;
try {
jsonNode = eddaClient.getJsonNodeFromUrl(url);
} catch (Exception e) {
LOGGER.error(String.format(
"Failed to get Jason node from edda for instances in region %s.", region), e);
}
if (jsonNode == null || !jsonNode.isArray()) {
throw new RuntimeException(String.format("Failed to get valid document from %s, got: %s", url, jsonNode));
}
List<Resource> resources = Lists.newArrayList();
Set<String> usedLCs = getLaunchConfigsInUse(region);
for (Iterator<JsonNode> it = jsonNode.getElements(); it.hasNext();) {
JsonNode launchConfiguration = it.next();
String lcName = launchConfiguration.get("launchConfigurationName").getTextValue();
Resource lcResource = new AWSResource().withId(lcName)
.withRegion(region).withResourceType(AWSResourceType.LAUNCH_CONFIG)
.withLaunchTime(new Date(launchConfiguration.get("createdTime").getLongValue()));
lcResource.setOwnerEmail(getOwnerEmailForResource(lcResource));
lcResource.setAdditionalField(LAUNCH_CONFIG_FIELD_USED_BY_ASG, String.valueOf(usedLCs.contains(lcName)));
resources.add(lcResource);
}
return resources;
}
/**
* Gets the launch configs that are currently in use by at least one ASG in a region.
* @param region the region
* @return the set of launch config names
*/
private Set<String> getLaunchConfigsInUse(String region) {
LOGGER.info(String.format("Getting all launch configurations in use in region %s", region));
String url = eddaClient.getBaseUrl(region) + "/aws/autoScalingGroups;_expand:(launchConfigurationName)";
JsonNode jsonNode = null;
try {
jsonNode = eddaClient.getJsonNodeFromUrl(url);
} catch (Exception e) {
LOGGER.error(String.format(
"Failed to get Jason node from edda for launch configs in use in region %s.", region), e);
}
if (jsonNode == null || !jsonNode.isArray()) {
throw new RuntimeException(String.format("Failed to get valid document from %s, got: %s", url, jsonNode));
}
Set<String> launchConfigs = Sets.newHashSet();
for (Iterator<JsonNode> it = jsonNode.getElements(); it.hasNext();) {
launchConfigs.add(it.next().get("launchConfigurationName").getTextValue());
}
return launchConfigs;
}
}
| apache-2.0 |
bartvde/ol3 | examples/layer-clipping.js | 1352 | goog.require('ol.Map');
goog.require('ol.View');
goog.require('ol.control');
goog.require('ol.layer.Tile');
goog.require('ol.source.OSM');
var osm = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [osm],
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
osm.on('precompose', function(event) {
var ctx = event.context;
ctx.save();
var pixelRatio = event.frameState.pixelRatio;
var size = map.getSize();
ctx.translate(size[0] / 2 * pixelRatio, size[1] / 2 * pixelRatio);
ctx.scale(3 * pixelRatio, 3 * pixelRatio);
ctx.translate(-75, -80);
ctx.beginPath();
ctx.moveTo(75, 40);
ctx.bezierCurveTo(75, 37, 70, 25, 50, 25);
ctx.bezierCurveTo(20, 25, 20, 62.5, 20, 62.5);
ctx.bezierCurveTo(20, 80, 40, 102, 75, 120);
ctx.bezierCurveTo(110, 102, 130, 80, 130, 62.5);
ctx.bezierCurveTo(130, 62.5, 130, 25, 100, 25);
ctx.bezierCurveTo(85, 25, 75, 37, 75, 40);
ctx.clip();
ctx.translate(75, 80);
ctx.scale(1 / 3 / pixelRatio, 1 / 3 / pixelRatio);
ctx.translate(-size[0] / 2 * pixelRatio, -size[1] / 2 * pixelRatio);
});
osm.on('postcompose', function(event) {
var ctx = event.context;
ctx.restore();
});
| bsd-2-clause |
lcunquei/AliPhysics | PWGGA/PHOSTasks/PHOS_Run2embedding/macros/Embedding.C | 16495 | Int_t Nevent=0;
const UInt_t trigger = AliVEvent::kINT7 | AliVEvent::kPHI7;
Int_t EventCounter(TChain *chain);
//==================================
void Embedding(const char* dataset="collection.xml")
{
const Bool_t embpi0 = kTRUE;
const Bool_t embeta = kTRUE;
const Bool_t embgamma = kTRUE;
gSystem->Load("libTree.so");
gSystem->Load("libGeom.so");
gSystem->Load("libVMC.so");
gSystem->Load("libPhysics.so");
//load analysis framework
gSystem->Load("libSTEERBase");
gSystem->Load("libANALYSIS");
gSystem->Load("libANALYSISalice"); //AliAnalysisTaskSE
gSystem->AddIncludePath("-I$ALICE_ROOT/include -I$ALICE_ROOT/PHOS -I$ALICE_PHYSICS/include");
// A task can be compiled dynamically with AClic
gROOT->LoadMacro("AliPHOSEmbeddingRun2.cxx++g");
// Connect to alien
TString token = gSystem->Getenv("GRID_TOKEN") ;
TGrid::Connect("alien://");
cout << "Pi0Analysis: processing collection " << dataset << endl;
// Create the chain
TChain* chain = new TChain("esdTree");
TGridCollection * collection = gGrid->OpenCollection(dataset);
TGridResult* result = collection->GetGridResult("", 0, 0);
TList* rawFileList = result->GetFileInfoList();
for (Int_t counter=0 ; counter < rawFileList->GetEntries() ; counter++) {
TFileInfo * fi = static_cast<TFileInfo*>(rawFileList->At(counter)) ;
const char * rawFile = fi->GetCurrentUrl()->GetUrl() ;
printf("Processing %s\n", rawFile) ;
chain->Add(rawFile);
printf("Chain: %d entries.\n",chain->GetEntries());
}
// chain->Add("../AliESDs.root") ;
TFileInfo * fi = static_cast<TFileInfo*>(rawFileList->At(0));
const char * fn = fi->GetCurrentUrl()->GetUrl() ;
char runNum[7]={"246982"};
for(Int_t i=0;i<6;i++)runNum[i]=fn[35+i] ;
runNum[6]=0 ;
Int_t iRunNum=atoi(runNum) ;
Nevent = EventCounter(chain);//get the number of event which we need for generating particles in advance.
printf("Run number=%d \n",iRunNum) ;
//Int_t nSimEvents=chain->GetEntries();
Int_t nSimEvents=Nevent;
gSystem->Exec("mkdir tmp") ;
gSystem->ChangeDirectory("tmp");
gSystem->Exec("mkdir Sim") ;
gSystem->Exec("cp ../Sim/* Sim") ;
if(embpi0){
gSystem->Exec(Form("../dpgsim.sh --run %d --generator kGeneratorCustom --particle 111 --system Pb-Pb --energy 5020. --nevents %d --mode simrecaod",iRunNum,nSimEvents)) ;
gSystem->Exec("mv AliAOD.root ../AliAODPi0.root") ; //use geometry from OCDB
gSystem->Exec("mv sim.log ../sim_pi0.log; mv rec.log ../rec_pi0.log; mv aod.log ../aod_pi0.log") ;
gSystem->Exec("rm *; rm -rf input; rm -rf GRP;") ; //only Sim directory will be left
}
if(embeta){
gSystem->Exec(Form("../dpgsim.sh --run %d --generator kGeneratorCustom --particle 221 --system Pb-Pb --energy 5020. --nevents %d --mode simrecaod",iRunNum,nSimEvents)) ;
gSystem->Exec("mv AliAOD.root ../AliAODEta.root") ; //use geometry from OCDB
gSystem->Exec("mv sim.log ../sim_eta.log; mv rec.log ../rec_eta.log; mv aod.log ../aod_eta.log") ;
gSystem->Exec("rm *; rm -rf input; rm -rf GRP;") ;//only Sim directory will be left
}
if(embgamma){
gSystem->Exec(Form("../dpgsim.sh --run %d --generator kGeneratorCustom --particle 22 --system Pb-Pb --energy 5020. --nevents %d --mode simrecaod",iRunNum,nSimEvents)) ;
gSystem->Exec("mv AliAOD.root ../AliAODGamma.root") ; //use geometry from OCDB
gSystem->Exec("mv sim.log ../sim_gamma.log; mv rec.log ../rec_gamma.log; mv aod.log ../aod_gamma.log") ;
gSystem->Exec("rm *; rm -rf input; rm -rf GRP;") ;//only Sim directory will be left
}
gSystem->ChangeDirectory("../");
// Make the analysis manager
AliAnalysisManager *mgr = new AliAnalysisManager("Pi0EmbeddingManager");
// ESD input handler
AliESDInputHandler* esdH = new AliESDInputHandler();
esdH->SetReadFriends(kFALSE);
mgr->SetInputEventHandler(esdH);
// Output
AliAODHandler* aodHandler = new AliAODHandler();
aodHandler->SetOutputFileName("AliAODout.root");
mgr->SetOutputEventHandler(aodHandler);
// Debug level
AliLog::SetGlobalLogLevel(AliLog::kError);
mgr->SetDebugLevel(2);
//mgr->SetDebugLevel(AliLog::kDebug);
//AliLog::SetGlobalLogLevel(AliLog::kDebug);
// CDB connection
gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/PilotTrain/AddTaskCDBconnect.C");
AliTaskCDBconnect *taskCDB = AddTaskCDBconnect("raw://");
if (!taskCDB){
printf("Can not connect to OCDB\n") ;
return;
}
AliCDBManager *cdb = AliCDBManager::Instance();
cdb->SetDefaultStorage("raw://");
const Bool_t useMC = kFALSE;
// Add physics selection
gROOT->LoadMacro("$ALICE_PHYSICS/OADB/macros/AddTaskPhysicsSelection.C");
mgr->RegisterExtraFile("event_stat.root");
AliPhysicsSelectionTask *physSelTask = AddTaskPhysicsSelection(useMC);
// AliOADBPhysicsSelection * oadbDefaultPbPb = CreateOADBphysicsSelection();
// physSelTask->GetPhysicsSelection()->SetCustomOADBObjects(oadbDefaultPbPb,0,0);
mgr->AddStatisticsTask(AliVEvent::kAny);
//gROOT->LoadMacro("$ALICE_PHYSICS/OADB/macros/AddTaskCentrality.C");
//AliCentralitySelectionTask *taskCentrality = AddTaskCentrality();
// taskCentrality->SetMCInput();
//for Run2
gROOT->LoadMacro("$ALICE_PHYSICS/OADB/COMMON/MULTIPLICITY/macros/AddTaskMultSelection.C");
AliMultSelectionTask *taskMult = AddTaskMultSelection();
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
AliAnalysisTaskPIDResponse *PIDResponse = AddTaskPIDResponse(kFALSE);
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskEventplane.C");
AliEPSelectionTask *taskEP = AddTaskEventplane() ;
AliPHOSEmbeddingRun2 *task1 = new AliPHOSEmbeddingRun2("Embedding");
//Add local just simlated input
TChain* chainAOD1=0;
TChain* chainAOD2=0;
TChain* chainAOD3=0;
if(embpi0){
chainAOD1 = new TChain("aodTree");
chainAOD1->AddFile("AliAODPi0.root") ;
}
if(embeta){
chainAOD2 = new TChain("aodTree");
chainAOD2->AddFile("AliAODEta.root") ;
}
if(embgamma){
chainAOD3 = new TChain("aodTree");
chainAOD3->AddFile("AliAODGamma.root") ;
}
task1->SetSignalChains(chainAOD1,chainAOD2,chainAOD3) ;
task1->SetEmbeddedFlag(embpi0,embeta,embgamma);
task1->SelectCollisionCandidates(trigger);
const TString path = "alien:///alice/cern.ch/user/d/dsekihat/EmbeddingRun2/PrivateOADB/PHOSCalibrations_vAN20161220.root";
cout << "path = " << path << endl;
task1->SetPrivateOADBPath(path);
task1->SetSignalCalibration(0.985*1.006);
mgr->AddTask(task1);
// Connect input/output
mgr->ConnectInput(task1 , 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task1, 0, mgr->GetCommonOutputContainer());// daiki changed to 0
//mgr->ConnectOutput(task1, 1, mgr->GetCommonOutputContainer()); //it was set to 1 by Dmitri originally.
//-------------Parameters for filtering
Bool_t useKineFilter=kFALSE ;
Bool_t writeMuonAOD=kFALSE ;
Bool_t usePhysicsSelection=kFALSE;
Bool_t enableTPCOnlyAODTracks=kFALSE;
Bool_t disableCascades=kTRUE ;
Bool_t disableKinks=kTRUE ;
Int_t runFlag = 1500; // The first 2 digits are the year, the second
//2 digits are used to distinguish sub-periods (if needed)
Int_t muonMCMode = 3;
Bool_t useV0Filter=kFALSE;
Bool_t muonWithSPDTracklets=kFALSE;
Bool_t isMuonCaloPass=kFALSE;
if (disableCascades) task1->DisableCascades();
if (disableKinks) task1->DisableKinks();
if ( isMuonCaloPass )task1->SetMuonCaloPass(); // this will call a bunch of DisableXXX methods.
// Muons
// Bool_t onlyMuon=kTRUE;
// Bool_t keepAllEvents=kTRUE;
// Int_t mcMode= useKineFilter ? muonMCMode : 0;
// AliAnalysisTaskESDMuonFilter *esdmuonfilter = new AliAnalysisTaskESDMuonFilter("ESD Muon Filter",onlyMuon,keepAllEvents,mcMode,muonWithSPDTracklets);
// mgr->AddTask(esdmuonfilter);
// if(usePhysicsSelection)task1->SelectCollisionCandidates(AliVEvent::kAny);
// // Filtering of MC particles (decays conversions etc)
// // this task has to go AFTER all other filter tasks
// // since it fills the AODMC array with all
// // selected MC Particles, only this way we have the
// // AODMCparticle information available for following tasks
// AliAnalysisTaskMCParticleFilter *kinefilter = 0;
// if (useKineFilter) {
// kinefilter = new AliAnalysisTaskMCParticleFilter("Particle Kine Filter");
// mgr->AddTask(kinefilter);
// }
Bool_t enableTPCOnlyAODTracksLocalFlag= enableTPCOnlyAODTracks;
if (!isMuonCaloPass)
{
if ((runFlag/100)==15){
AddTrackCutsLHC15f(task1,enableTPCOnlyAODTracksLocalFlag);
}
}
// Filter with cuts on V0s
if (useV0Filter && !isMuonCaloPass) {
AliESDv0Cuts* esdV0Cuts = new AliESDv0Cuts("Standard V0 Cuts pp", "ESD V0 Cuts");
esdV0Cuts->SetMinRadius(0.2);
esdV0Cuts->SetMaxRadius(200);
esdV0Cuts->SetMinDcaPosToVertex(0.05);
esdV0Cuts->SetMinDcaNegToVertex(0.05);
esdV0Cuts->SetMaxDcaV0Daughters(1.5);
esdV0Cuts->SetMinCosinePointingAngle(0.99);
AliAnalysisFilter* v0Filter = new AliAnalysisFilter("v0Filter");
v0Filter->AddCuts(esdV0Cuts);
task1->SetV0Filter(v0Filter);
}
//----------------
printf("RunNunm===%d \n",iRunNum) ;
if (mgr->InitAnalysis()) {
mgr->PrintStatus();
mgr->StartAnalysis("local", chain);
}
// gSystem->Exec("aliroot -b -q AnalyzeDiff.C> analyze3.log 2>&1");
}
Bool_t AddTrackCutsLHC15f(AliAnalysisTaskESDfilter* esdfilter,Bool_t enableTPCOnlyAODTracksLocalFlag){
//
// filter cuts for RunII pp in 2015
// basically a duplication of 11h, but with stricter cluster requirement
//
Printf("%s%d: Creating Track Cuts for LHC15f",(char*)__FILE__,__LINE__);
//
// Cuts on primary tracks
AliESDtrackCuts* esdTrackCutsL = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
// ITS stand-alone tracks
AliESDtrackCuts* esdTrackCutsITSsa = new AliESDtrackCuts("ITS stand-alone Track Cuts", "ESD Track Cuts");
esdTrackCutsITSsa->SetRequireITSStandAlone(kTRUE);
// Pixel OR necessary for the electrons
AliESDtrackCuts *itsStrong = new AliESDtrackCuts("ITSorSPD", "pixel requirement for ITS");
itsStrong->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny);
// PID for the electrons
AliESDpidCuts *electronID = new AliESDpidCuts("Electrons", "Electron PID cuts");
electronID->SetTPCnSigmaCut(AliPID::kElectron, 3.5);
// standard cuts with very loose DCA
AliESDtrackCuts* esdTrackCutsH = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kFALSE);
esdTrackCutsH->SetMaxDCAToVertexXY(2.4);
esdTrackCutsH->SetMaxDCAToVertexZ(3.2);
esdTrackCutsH->SetDCAToVertex2D(kTRUE);
// standard cuts with tight DCA cut
AliESDtrackCuts* esdTrackCutsH2 = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011();
// standard cuts with tight DCA but with requiring the first SDD cluster instead of an SPD cluster
// tracks selected by this cut are exclusive to those selected by the previous cut
AliESDtrackCuts* esdTrackCutsH3 = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011();
esdTrackCutsH3->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kNone);
esdTrackCutsH3->SetClusterRequirementITS(AliESDtrackCuts::kSDD, AliESDtrackCuts::kFirst);
// TPC only tracks: Optionally enable the writing of TPConly information
// constrained to SPD vertex in the filter below
AliESDtrackCuts* esdTrackCutsTPCOnly = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
// The following line is needed for 2010 PbPb reprocessing and pp, but not for 2011 PbPb
//esdTrackCutsTPCOnly->SetMinNClustersTPC(70);
// Extra cuts for hybrids
// first the global tracks we want to take
AliESDtrackCuts* esdTrackCutsHTG = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kFALSE);
esdTrackCutsHTG->SetName("Global Hybrid tracks, loose DCA");
esdTrackCutsHTG->SetMaxDCAToVertexXY(2.4);
esdTrackCutsHTG->SetMaxDCAToVertexZ(3.2);
esdTrackCutsHTG->SetDCAToVertex2D(kTRUE);
esdTrackCutsHTG->SetMaxChi2TPCConstrainedGlobal(36);
esdTrackCutsHTG->SetMaxFractionSharedTPCClusters(0.4);
// Than the complementary tracks which will be stored as global
// constraint, complement is done in the ESDFilter task
AliESDtrackCuts* esdTrackCutsHTGC = new AliESDtrackCuts(*esdTrackCutsHTG);
esdTrackCutsHTGC->SetName("Global Constraint Hybrid tracks, loose DCA no it requirement");
esdTrackCutsHTGC->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kOff);
esdTrackCutsHTGC->SetRequireITSRefit(kTRUE);
// standard cuts with tight DCA cut, using cluster cut instead of crossed rows (a la 2010 default)
AliESDtrackCuts* esdTrackCutsH2Cluster = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kTRUE, 0);
esdTrackCutsH2Cluster->SetMinNClustersTPC(70); // gain in 2015 is higher than in 2011
// duplication of 1<<5 = 32 and 1<<6 = 64 with looser requirement
// on CrossedRows and CrossedRowsOverFindable in order to go to forward eta (To be used with care!)
AliESDtrackCuts* esdTrackCutsH2Forward = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011();
esdTrackCutsH2Forward->SetMinNCrossedRowsTPC(50);
esdTrackCutsH2Forward->SetMinRatioCrossedRowsOverFindableClustersTPC(0.6);
AliESDtrackCuts* esdTrackCutsH3Forward = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011();
esdTrackCutsH3Forward->SetMinNCrossedRowsTPC(50);
esdTrackCutsH3Forward->SetMinRatioCrossedRowsOverFindableClustersTPC(0.6);
esdTrackCutsH3Forward->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kNone);
esdTrackCutsH3Forward->SetClusterRequirementITS(AliESDtrackCuts::kSDD, AliESDtrackCuts::kFirst);
// Compose the filter
AliAnalysisFilter* trackFilter = new AliAnalysisFilter("trackFilter");
// 1, 1<<0
trackFilter->AddCuts(esdTrackCutsL);
// 2, 1<<1
trackFilter->AddCuts(esdTrackCutsITSsa);
// 4, 1<<2
trackFilter->AddCuts(itsStrong);
itsStrong->SetFilterMask(1); // AND with Standard track cuts
// 8, 1<<3
trackFilter->AddCuts(electronID);
electronID->SetFilterMask(4); // AND with Pixel Cuts
// 16, 1<<4
trackFilter->AddCuts(esdTrackCutsH);
// 32, 1<<5
trackFilter->AddCuts(esdTrackCutsH2);
// 64, 1<<6
trackFilter->AddCuts(esdTrackCutsH3);
// 128 , 1 << 7
trackFilter->AddCuts(esdTrackCutsTPCOnly);
if(enableTPCOnlyAODTracksLocalFlag)esdfilter->SetTPCOnlyFilterMask(128);
// 256, 1 << 8 Global Hybrids
trackFilter->AddCuts(esdTrackCutsHTG);
esdfilter->SetHybridFilterMaskGlobalConstrainedGlobal((1<<8)); // these normal global tracks will be marked as hybrid
// 512, 1<< 9 GlobalConstraint Hybrids
trackFilter->AddCuts(esdTrackCutsHTGC);
esdfilter->SetGlobalConstrainedFilterMask(1<<9); // these tracks are written out as global constrained tracks
esdfilter->SetWriteHybridGlobalConstrainedOnly(kTRUE); // write only the complement
// 1024, 1<< 10 // tight DCA cuts
trackFilter->AddCuts(esdTrackCutsH2Cluster);
// 2048, 1<<11 // duplication of 1<<5 with looser CrossedRows requirements for forward eta
trackFilter->AddCuts(esdTrackCutsH2Forward);
// 4096, 1<<12 // duplication of 1<<6 with looser CrossedRows requirements for forward eta
trackFilter->AddCuts(esdTrackCutsH3Forward);
esdfilter->SetTrackFilter(trackFilter);
return kTRUE;
}
//____________________________________________________________________
Int_t EventCounter(TChain *chain)
{
gROOT->LoadMacro("AliPHOSEventCounter.cxx++g");
// Make the analysis manager
AliAnalysisManager *mgr = new AliAnalysisManager("EventCounterManager");
// ESD input handler
AliESDInputHandler* esdH = new AliESDInputHandler();
esdH->SetReadFriends(kFALSE);
mgr->SetInputEventHandler(esdH);
const Bool_t useMC = kFALSE;
// Add physics selection
gROOT->LoadMacro("$ALICE_PHYSICS/OADB/macros/AddTaskPhysicsSelection.C");
//mgr->RegisterExtraFile("event_stat.root");
AliPhysicsSelectionTask *physSelTask = AddTaskPhysicsSelection(useMC);
//mgr->AddStatisticsTask(AliVEvent::kAny);
AliPHOSEventCounter *task1 = new AliPHOSEventCounter("PHOSCounter");
task1->SelectCollisionCandidates(trigger);
mgr->AddTask(task1);
// Connect input/output
mgr->ConnectInput(task1 , 0, mgr->GetCommonInputContainer());
//mgr->ConnectOutput(task1, 0, mgr->GetCommonOutputContainer());// daiki changed to 0
if (mgr->InitAnalysis()) {
mgr->PrintStatus();
mgr->StartAnalysis("local", chain);
}
Int_t N = task1->GetAnalyzedEvent();
return N;
}
| bsd-3-clause |
e-gob/plataforma-kioscos-autoatencion | scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/remote_management/hpilo/hpilo_facts.py | 7752 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2012 Dag Wieers <dag@wieers.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: hpilo_facts
version_added: "2.3"
author: Dag Wieers (@dagwieers)
short_description: Gather facts through an HP iLO interface
description:
- This module gathers facts for a specific system using its HP iLO interface.
These facts include hardware and network related information useful
for provisioning (e.g. macaddress, uuid).
- This module requires the hpilo python module.
options:
host:
description:
- The HP iLO hostname/address that is linked to the physical system.
required: true
login:
description:
- The login name to authenticate to the HP iLO interface.
default: Administrator
password:
description:
- The password to authenticate to the HP iLO interface.
default: admin
ssl_version:
description:
- Change the ssl_version used.
default: TLSv1
choices: [ "SSLv3", "SSLv23", "TLSv1", "TLSv1_1", "TLSv1_2" ]
version_added: '2.4'
requirements:
- hpilo
notes:
- This module ought to be run from a system that can access the HP iLO
interface directly, either by using C(local_action) or using C(delegate_to).
'''
EXAMPLES = r'''
# Task to gather facts from a HP iLO interface only if the system is an HP server
- hpilo_facts:
host: YOUR_ILO_ADDRESS
login: YOUR_ILO_LOGIN
password: YOUR_ILO_PASSWORD
when: cmdb_hwmodel.startswith('HP ')
delegate_to: localhost
- fail:
msg: 'CMDB serial ({{ cmdb_serialno }}) does not match hardware serial ({{ hw_system_serial }}) !'
when: cmdb_serialno != hw_system_serial
'''
RETURN = r'''
# Typical output of HP iLO_facts for a physical system
hw_bios_date:
description: BIOS date
returned: always
type: string
sample: 05/05/2011
hw_bios_version:
description: BIOS version
returned: always
type: string
sample: P68
hw_ethX:
description: Interface information (for each interface)
returned: always
type: dictionary
sample:
- macaddress: 00:11:22:33:44:55
macaddress_dash: 00-11-22-33-44-55
hw_eth_ilo:
description: Interface information (for the iLO network interface)
returned: always
type: dictionary
sample:
- macaddress: 00:11:22:33:44:BA
- macaddress_dash: 00-11-22-33-44-BA
hw_product_name:
description: Product name
returned: always
type: string
sample: ProLiant DL360 G7
hw_product_uuid:
description: Product UUID
returned: always
type: string
sample: ef50bac8-2845-40ff-81d9-675315501dac
hw_system_serial:
description: System serial number
returned: always
type: string
sample: ABC12345D6
hw_uuid:
description: Hardware UUID
returned: always
type: string
sample: 123456ABC78901D2
'''
import re
import warnings
try:
import hpilo
HAS_HPILO = True
except ImportError:
HAS_HPILO = False
from ansible.module_utils.basic import AnsibleModule
# Suppress warnings from hpilo
warnings.simplefilter('ignore')
def parse_flat_interface(entry, non_numeric='hw_eth_ilo'):
try:
factname = 'hw_eth' + str(int(entry['Port']) - 1)
except:
factname = non_numeric
facts = {
'macaddress': entry['MAC'].replace('-', ':'),
'macaddress_dash': entry['MAC']
}
return (factname, facts)
def main():
module = AnsibleModule(
argument_spec=dict(
host=dict(type='str', required=True),
login=dict(type='str', default='Administrator'),
password=dict(type='str', default='admin', no_log=True),
ssl_version=dict(type='str', default='TLSv1', choices=['SSLv3', 'SSLv23', 'TLSv1', 'TLSv1_1', 'TLSv1_2']),
),
supports_check_mode=True,
)
if not HAS_HPILO:
module.fail_json(msg='The hpilo python module is required')
host = module.params['host']
login = module.params['login']
password = module.params['password']
ssl_version = getattr(hpilo.ssl, 'PROTOCOL_' + module.params.get('ssl_version').upper().replace('V', 'v'))
ilo = hpilo.Ilo(host, login=login, password=password, ssl_version=ssl_version)
facts = {
'module_hw': True,
}
# TODO: Count number of CPUs, DIMMs and total memory
data = ilo.get_host_data()
for entry in data:
if 'type' not in entry:
continue
elif entry['type'] == 0: # BIOS Information
facts['hw_bios_version'] = entry['Family']
facts['hw_bios_date'] = entry['Date']
elif entry['type'] == 1: # System Information
facts['hw_uuid'] = entry['UUID']
facts['hw_system_serial'] = entry['Serial Number'].rstrip()
facts['hw_product_name'] = entry['Product Name']
facts['hw_product_uuid'] = entry['cUUID']
elif entry['type'] == 209: # Embedded NIC MAC Assignment
if 'fields' in entry:
for (name, value) in [(e['name'], e['value']) for e in entry['fields']]:
if name.startswith('Port'):
try:
factname = 'hw_eth' + str(int(value) - 1)
except:
factname = 'hw_eth_ilo'
elif name.startswith('MAC'):
facts[factname] = {
'macaddress': value.replace('-', ':'),
'macaddress_dash': value
}
else:
(factname, entry_facts) = parse_flat_interface(entry, 'hw_eth_ilo')
facts[factname] = entry_facts
elif entry['type'] == 209: # HPQ NIC iSCSI MAC Info
for (name, value) in [(e['name'], e['value']) for e in entry['fields']]:
if name.startswith('Port'):
try:
factname = 'hw_iscsi' + str(int(value) - 1)
except:
factname = 'hw_iscsi_ilo'
elif name.startswith('MAC'):
facts[factname] = {
'macaddress': value.replace('-', ':'),
'macaddress_dash': value
}
elif entry['type'] == 233: # Embedded NIC MAC Assignment (Alternate data format)
(factname, entry_facts) = parse_flat_interface(entry, 'hw_eth_ilo')
facts[factname] = entry_facts
# Collect health (RAM/CPU data)
health = ilo.get_embedded_health()
facts['hw_health'] = health
memory_details_summary = health.get('memory', {}).get('memory_details_summary')
# RAM as reported by iLO 2.10 on ProLiant BL460c Gen8
if memory_details_summary:
facts['hw_memory_details_summary'] = memory_details_summary
facts['hw_memory_total'] = 0
for cpu, details in memory_details_summary.items():
cpu_total_memory_size = details.get('total_memory_size')
if cpu_total_memory_size:
ram = re.search('(\d+)\s+(\w+)', cpu_total_memory_size)
if ram:
if ram.group(2) == 'GB':
facts['hw_memory_total'] = facts['hw_memory_total'] + int(ram.group(1))
# reformat into a text friendly format
facts['hw_memory_total'] = "{0} GB".format(facts['hw_memory_total'])
module.exit_json(ansible_facts=facts)
if __name__ == '__main__':
main()
| bsd-3-clause |
cdnjs/cdnjs | ajax/libs/primereact/5.0.2/inputtextarea.js | 84 | 'use strict';
module.exports = require('./components/inputtextarea/InputTextarea'); | mit |
jack8z/TODOP | third_party/boost_1_65_1/boost/qvm/map_mat_mat.hpp | 33311 | //Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.
//Distributed under the Boost Software License, Version 1.0. (See accompanying
//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef UUID_20D98340A3EB11DEB2180CD156D89593
#define UUID_20D98340A3EB11DEB2180CD156D89593
#include <boost/qvm/inline.hpp>
#include <boost/qvm/deduce_mat.hpp>
#include <boost/qvm/assert.hpp>
#include <boost/qvm/enable_if.hpp>
#include <boost/qvm/detail/transp_impl.hpp>
namespace
boost
{
namespace
qvm
{
////////////////////////////////////////////////
namespace
qvm_detail
{
template <int Row,class OriginalMatrix>
class
del_row_
{
del_row_( del_row_ const & );
del_row_ & operator=( del_row_ const & );
~del_row_();
public:
template <class T>
BOOST_QVM_INLINE_TRIVIAL
del_row_ &
operator=( T const & x )
{
assign(*this,x);
return *this;
}
template <class R>
BOOST_QVM_INLINE_TRIVIAL
operator R() const
{
R r;
assign(r,*this);
return r;
}
};
}
template <int I,class OriginalMatrix>
struct
mat_traits< qvm_detail::del_row_<I,OriginalMatrix> >
{
typedef qvm_detail::del_row_<I,OriginalMatrix> this_matrix;
typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;
static int const rows=mat_traits<OriginalMatrix>::rows-1;
static int const cols=mat_traits<OriginalMatrix>::cols;
template <int Row,int Col>
static
BOOST_QVM_INLINE_CRITICAL
scalar_type
read_element( this_matrix const & x )
{
BOOST_QVM_STATIC_ASSERT(Row>=0);
BOOST_QVM_STATIC_ASSERT(Row<rows);
BOOST_QVM_STATIC_ASSERT(Col>=0);
BOOST_QVM_STATIC_ASSERT(Col<cols);
return mat_traits<OriginalMatrix>::template read_element<Row+(Row>=I),Col>(reinterpret_cast<OriginalMatrix const &>(x));
}
template <int Row,int Col>
static
BOOST_QVM_INLINE_CRITICAL
scalar_type &
write_element( this_matrix & x )
{
BOOST_QVM_STATIC_ASSERT(Row>=0);
BOOST_QVM_STATIC_ASSERT(Row<rows);
BOOST_QVM_STATIC_ASSERT(Col>=0);
BOOST_QVM_STATIC_ASSERT(Col<cols);
return mat_traits<OriginalMatrix>::template write_element<Row+(Row>=I),Col>(reinterpret_cast<OriginalMatrix &>(x));
}
static
BOOST_QVM_INLINE_CRITICAL
scalar_type
read_element_idx( int row, int col, this_matrix const & x )
{
BOOST_QVM_ASSERT(row>=0);
BOOST_QVM_ASSERT(row<rows);
BOOST_QVM_ASSERT(col>=0);
BOOST_QVM_ASSERT(col<cols);
return mat_traits<OriginalMatrix>::read_element_idx(row+(row>=I),col,reinterpret_cast<OriginalMatrix const &>(x));
}
static
BOOST_QVM_INLINE_CRITICAL
scalar_type &
write_element_idx( int row, int col, this_matrix & x )
{
BOOST_QVM_ASSERT(row>=0);
BOOST_QVM_ASSERT(row<rows);
BOOST_QVM_ASSERT(col>=0);
BOOST_QVM_ASSERT(col<cols);
return mat_traits<OriginalMatrix>::write_element_idx(row+(row>=I),col,reinterpret_cast<OriginalMatrix &>(x));
}
};
template <int J,class OriginalMatrix,int R,int C>
struct
deduce_mat<qvm_detail::del_row_<J,OriginalMatrix>,R,C>
{
typedef mat<typename mat_traits<OriginalMatrix>::scalar_type,R,C> type;
};
template <int J,class OriginalMatrix,int R,int C>
struct
deduce_mat2<qvm_detail::del_row_<J,OriginalMatrix>,qvm_detail::del_row_<J,OriginalMatrix>,R,C>
{
typedef mat<typename mat_traits<OriginalMatrix>::scalar_type,R,C> type;
};
template <int Row,class A>
typename boost::enable_if_c<
is_mat<A>::value,
qvm_detail::del_row_<Row,A> const &>::type
BOOST_QVM_INLINE_TRIVIAL
del_row( A const & a )
{
return reinterpret_cast<typename qvm_detail::del_row_<Row,A> const &>(a);
}
template <int Row,class A>
typename boost::enable_if_c<
is_mat<A>::value,
qvm_detail::del_row_<Row,A> &>::type
BOOST_QVM_INLINE_TRIVIAL
del_row( A & a )
{
return reinterpret_cast<typename qvm_detail::del_row_<Row,A> &>(a);
}
////////////////////////////////////////////////
namespace
qvm_detail
{
template <int Col,class OriginalMatrix>
class
del_col_
{
del_col_( del_col_ const & );
del_col_ & operator=( del_col_ const & );
~del_col_();
public:
template <class T>
BOOST_QVM_INLINE_TRIVIAL
del_col_ &
operator=( T const & x )
{
assign(*this,x);
return *this;
}
template <class R>
BOOST_QVM_INLINE_TRIVIAL
operator R() const
{
R r;
assign(r,*this);
return r;
}
};
}
template <int J,class OriginalMatrix>
struct
mat_traits< qvm_detail::del_col_<J,OriginalMatrix> >
{
typedef qvm_detail::del_col_<J,OriginalMatrix> this_matrix;
typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;
static int const rows=mat_traits<OriginalMatrix>::rows;
static int const cols=mat_traits<OriginalMatrix>::cols-1;
template <int Row,int Col>
static
BOOST_QVM_INLINE_CRITICAL
scalar_type
read_element( this_matrix const & x )
{
BOOST_QVM_STATIC_ASSERT(Row>=0);
BOOST_QVM_STATIC_ASSERT(Row<rows);
BOOST_QVM_STATIC_ASSERT(Col>=0);
BOOST_QVM_STATIC_ASSERT(Col<cols);
return mat_traits<OriginalMatrix>::template read_element<Row,Col+(Col>=J)>(reinterpret_cast<OriginalMatrix const &>(x));
}
template <int Row,int Col>
static
BOOST_QVM_INLINE_CRITICAL
scalar_type &
write_element( this_matrix & x )
{
BOOST_QVM_STATIC_ASSERT(Row>=0);
BOOST_QVM_STATIC_ASSERT(Row<rows);
BOOST_QVM_STATIC_ASSERT(Col>=0);
BOOST_QVM_STATIC_ASSERT(Col<cols);
return mat_traits<OriginalMatrix>::template write_element<Row,Col+(Col>=J)>(reinterpret_cast<OriginalMatrix &>(x));
}
static
BOOST_QVM_INLINE_CRITICAL
scalar_type
read_element_idx( int row, int col, this_matrix const & x )
{
BOOST_QVM_ASSERT(row>=0);
BOOST_QVM_ASSERT(row<rows);
BOOST_QVM_ASSERT(col>=0);
BOOST_QVM_ASSERT(col<cols);
return mat_traits<OriginalMatrix>::read_element_idx(row,col+(col>=J),reinterpret_cast<OriginalMatrix const &>(x));
}
static
BOOST_QVM_INLINE_CRITICAL
scalar_type &
write_element_idx( int row, int col, this_matrix & x )
{
BOOST_QVM_ASSERT(row>=0);
BOOST_QVM_ASSERT(row<rows);
BOOST_QVM_ASSERT(col>=0);
BOOST_QVM_ASSERT(col<cols);
return mat_traits<OriginalMatrix>::write_element_idx(row,col+(col>=J),reinterpret_cast<OriginalMatrix &>(x));
}
};
template <int J,class OriginalMatrix,int R,int C>
struct
deduce_mat<qvm_detail::del_col_<J,OriginalMatrix>,R,C>
{
typedef mat<typename mat_traits<OriginalMatrix>::scalar_type,R,C> type;
};
template <int J,class OriginalMatrix,int R,int C>
struct
deduce_mat2<qvm_detail::del_col_<J,OriginalMatrix>,qvm_detail::del_col_<J,OriginalMatrix>,R,C>
{
typedef mat<typename mat_traits<OriginalMatrix>::scalar_type,R,C> type;
};
template <int Col,class A>
typename boost::enable_if_c<
is_mat<A>::value,
qvm_detail::del_col_<Col,A> const &>::type
BOOST_QVM_INLINE_TRIVIAL
del_col( A const & a )
{
return reinterpret_cast<typename qvm_detail::del_col_<Col,A> const &>(a);
}
template <int Col,class A>
typename boost::enable_if_c<
is_mat<A>::value,
qvm_detail::del_col_<Col,A> &>::type
BOOST_QVM_INLINE_TRIVIAL
del_col( A & a )
{
return reinterpret_cast<typename qvm_detail::del_col_<Col,A> &>(a);
}
////////////////////////////////////////////////
namespace
qvm_detail
{
template <int Row,int Col,class OriginalMatrix>
class
del_row_col_
{
del_row_col_( del_row_col_ const & );
~del_row_col_();
public:
BOOST_QVM_INLINE_TRIVIAL
del_row_col_ &
operator=( del_row_col_ const & x )
{
assign(*this,x);
return *this;
}
template <class T>
BOOST_QVM_INLINE_TRIVIAL
del_row_col_ &
operator=( T const & x )
{
assign(*this,x);
return *this;
}
template <class R>
BOOST_QVM_INLINE_TRIVIAL
operator R() const
{
R r;
assign(r,*this);
return r;
}
};
}
template <int I,int J,class OriginalMatrix>
struct
mat_traits< qvm_detail::del_row_col_<I,J,OriginalMatrix> >
{
typedef qvm_detail::del_row_col_<I,J,OriginalMatrix> this_matrix;
typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;
static int const rows=mat_traits<OriginalMatrix>::rows-1;
static int const cols=mat_traits<OriginalMatrix>::cols-1;
template <int Row,int Col>
static
BOOST_QVM_INLINE_CRITICAL
scalar_type
read_element( this_matrix const & x )
{
BOOST_QVM_STATIC_ASSERT(Row>=0);
BOOST_QVM_STATIC_ASSERT(Row<rows);
BOOST_QVM_STATIC_ASSERT(Col>=0);
BOOST_QVM_STATIC_ASSERT(Col<cols);
return mat_traits<OriginalMatrix>::template read_element<Row+(Row>=I),Col+(Col>=J)>(reinterpret_cast<OriginalMatrix const &>(x));
}
template <int Row,int Col>
static
BOOST_QVM_INLINE_CRITICAL
scalar_type &
write_element( this_matrix & x )
{
BOOST_QVM_STATIC_ASSERT(Row>=0);
BOOST_QVM_STATIC_ASSERT(Row<rows);
BOOST_QVM_STATIC_ASSERT(Col>=0);
BOOST_QVM_STATIC_ASSERT(Col<cols);
return mat_traits<OriginalMatrix>::template write_element<Row+(Row>=I),Col+(Col>=J)>(reinterpret_cast<OriginalMatrix &>(x));
}
static
BOOST_QVM_INLINE_CRITICAL
scalar_type
read_element_idx( int row, int col, this_matrix const & x )
{
BOOST_QVM_ASSERT(row>=0);
BOOST_QVM_ASSERT(row<rows);
BOOST_QVM_ASSERT(col>=0);
BOOST_QVM_ASSERT(col<cols);
return mat_traits<OriginalMatrix>::read_element_idx(row+(row>=I),col+(col>=J),reinterpret_cast<OriginalMatrix const &>(x));
}
static
BOOST_QVM_INLINE_CRITICAL
scalar_type &
write_element_idx( int row, int col, this_matrix & x )
{
BOOST_QVM_ASSERT(row>=0);
BOOST_QVM_ASSERT(row<rows);
BOOST_QVM_ASSERT(col>=0);
BOOST_QVM_ASSERT(col<cols);
return mat_traits<OriginalMatrix>::write_element_idx(row+(row>=I),col+(col>=J),reinterpret_cast<OriginalMatrix &>(x));
}
};
template <int I,int J,class OriginalMatrix,int R,int C>
struct
deduce_mat<qvm_detail::del_row_col_<I,J,OriginalMatrix>,R,C>
{
typedef mat<typename mat_traits<OriginalMatrix>::scalar_type,R,C> type;
};
template <int I,int J,class OriginalMatrix,int R,int C>
struct
deduce_mat2<qvm_detail::del_row_col_<I,J,OriginalMatrix>,qvm_detail::del_row_col_<I,J,OriginalMatrix>,R,C>
{
typedef mat<typename mat_traits<OriginalMatrix>::scalar_type,R,C> type;
};
template <int Row,int Col,class A>
typename boost::enable_if_c<
is_mat<A>::value,
qvm_detail::del_row_col_<Row,Col,A> const &>::type
BOOST_QVM_INLINE_TRIVIAL
del_row_col( A const & a )
{
return reinterpret_cast<typename qvm_detail::del_row_col_<Row,Col,A> const &>(a);
}
template <int Row,int Col,class A>
typename boost::enable_if_c<
is_mat<A>::value,
qvm_detail::del_row_col_<Row,Col,A> &>::type
BOOST_QVM_INLINE_TRIVIAL
del_row_col( A & a )
{
return reinterpret_cast<typename qvm_detail::del_row_col_<Row,Col,A> &>(a);
}
////////////////////////////////////////////////
namespace
qvm_detail
{
template <int Row,class OriginalMatrix>
class
neg_row_
{
neg_row_( neg_row_ const & );
neg_row_ & operator=( neg_row_ const & );
~neg_row_();
public:
template <class T>
BOOST_QVM_INLINE_TRIVIAL
neg_row_ &
operator=( T const & x )
{
assign(*this,x);
return *this;
}
template <class R>
BOOST_QVM_INLINE_TRIVIAL
operator R() const
{
R r;
assign(r,*this);
return r;
}
};
}
template <int I,class OriginalMatrix>
struct
mat_traits< qvm_detail::neg_row_<I,OriginalMatrix> >
{
typedef qvm_detail::neg_row_<I,OriginalMatrix> this_matrix;
typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;
static int const rows=mat_traits<OriginalMatrix>::rows;
static int const cols=mat_traits<OriginalMatrix>::cols;
template <int Row,int Col>
static
BOOST_QVM_INLINE_CRITICAL
scalar_type
read_element( this_matrix const & x )
{
BOOST_QVM_STATIC_ASSERT(Row>=0);
BOOST_QVM_STATIC_ASSERT(Row<rows);
BOOST_QVM_STATIC_ASSERT(Col>=0);
BOOST_QVM_STATIC_ASSERT(Col<cols);
return Row==I ?
-mat_traits<OriginalMatrix>::template read_element<Row,Col>(reinterpret_cast<OriginalMatrix const &>(x)) :
mat_traits<OriginalMatrix>::template read_element<Row,Col>(reinterpret_cast<OriginalMatrix const &>(x));
}
static
BOOST_QVM_INLINE_CRITICAL
scalar_type
read_element_idx( int row, int col, this_matrix const & x )
{
BOOST_QVM_ASSERT(row>=0);
BOOST_QVM_ASSERT(row<rows);
BOOST_QVM_ASSERT(col>=0);
BOOST_QVM_ASSERT(col<cols);
return row==I?
-mat_traits<OriginalMatrix>::read_element_idx(row,col,reinterpret_cast<OriginalMatrix const &>(x)) :
mat_traits<OriginalMatrix>::read_element_idx(row,col,reinterpret_cast<OriginalMatrix const &>(x));
}
};
template <int J,class OriginalMatrix,int R,int C>
struct
deduce_mat<qvm_detail::neg_row_<J,OriginalMatrix>,R,C>
{
typedef mat<typename mat_traits<OriginalMatrix>::scalar_type,R,C> type;
};
template <int J,class OriginalMatrix,int R,int C>
struct
deduce_mat2<qvm_detail::neg_row_<J,OriginalMatrix>,qvm_detail::neg_row_<J,OriginalMatrix>,R,C>
{
typedef mat<typename mat_traits<OriginalMatrix>::scalar_type,R,C> type;
};
template <int Row,class A>
typename boost::enable_if_c<
is_mat<A>::value,
qvm_detail::neg_row_<Row,A> const &>::type
BOOST_QVM_INLINE_TRIVIAL
neg_row( A const & a )
{
return reinterpret_cast<typename qvm_detail::neg_row_<Row,A> const &>(a);
}
////////////////////////////////////////////////
namespace
qvm_detail
{
template <int Col,class OriginalMatrix>
class
neg_col_
{
neg_col_( neg_col_ const & );
neg_col_ & operator=( neg_col_ const & );
~neg_col_();
public:
template <class T>
BOOST_QVM_INLINE_TRIVIAL
neg_col_ &
operator=( T const & x )
{
assign(*this,x);
return *this;
}
template <class R>
BOOST_QVM_INLINE_TRIVIAL
operator R() const
{
R r;
assign(r,*this);
return r;
}
};
}
template <int J,class OriginalMatrix>
struct
mat_traits< qvm_detail::neg_col_<J,OriginalMatrix> >
{
typedef qvm_detail::neg_col_<J,OriginalMatrix> this_matrix;
typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;
static int const rows=mat_traits<OriginalMatrix>::rows;
static int const cols=mat_traits<OriginalMatrix>::cols;
template <int Row,int Col>
static
BOOST_QVM_INLINE_CRITICAL
scalar_type
read_element( this_matrix const & x )
{
BOOST_QVM_STATIC_ASSERT(Row>=0);
BOOST_QVM_STATIC_ASSERT(Row<rows);
BOOST_QVM_STATIC_ASSERT(Col>=0);
BOOST_QVM_STATIC_ASSERT(Col<cols);
return Col==J?
-mat_traits<OriginalMatrix>::template read_element<Row,Col>(reinterpret_cast<OriginalMatrix const &>(x)) :
mat_traits<OriginalMatrix>::template read_element<Row,Col>(reinterpret_cast<OriginalMatrix const &>(x));
}
static
BOOST_QVM_INLINE_CRITICAL
scalar_type
read_element_idx( int row, int col, this_matrix const & x )
{
BOOST_QVM_ASSERT(row>=0);
BOOST_QVM_ASSERT(row<rows);
BOOST_QVM_ASSERT(col>=0);
BOOST_QVM_ASSERT(col<cols);
return col==J?
-mat_traits<OriginalMatrix>::read_element_idx(row,col,reinterpret_cast<OriginalMatrix const &>(x)) :
mat_traits<OriginalMatrix>::read_element_idx(row,col,reinterpret_cast<OriginalMatrix const &>(x));
}
};
template <int J,class OriginalMatrix,int R,int C>
struct
deduce_mat<qvm_detail::neg_col_<J,OriginalMatrix>,R,C>
{
typedef mat<typename mat_traits<OriginalMatrix>::scalar_type,R,C> type;
};
template <int J,class OriginalMatrix,int R,int C>
struct
deduce_mat2<qvm_detail::neg_col_<J,OriginalMatrix>,qvm_detail::neg_col_<J,OriginalMatrix>,R,C>
{
typedef mat<typename mat_traits<OriginalMatrix>::scalar_type,R,C> type;
};
template <int Col,class A>
typename boost::enable_if_c<
is_mat<A>::value,
qvm_detail::neg_col_<Col,A> const &>::type
BOOST_QVM_INLINE_TRIVIAL
neg_col( A const & a )
{
return reinterpret_cast<typename qvm_detail::neg_col_<Col,A> const &>(a);
}
////////////////////////////////////////////////
template <class A>
typename boost::enable_if_c<
is_mat<A>::value,
qvm_detail::transposed_<A> const &>::type
BOOST_QVM_INLINE_TRIVIAL
transposed( A const & a )
{
return reinterpret_cast<typename qvm_detail::transposed_<A> const &>(a);
}
template <class A>
typename boost::enable_if_c<
is_mat<A>::value,
qvm_detail::transposed_<A> &>::type
BOOST_QVM_INLINE_TRIVIAL
transposed( A & a )
{
return reinterpret_cast<typename qvm_detail::transposed_<A> &>(a);
}
////////////////////////////////////////////////
namespace
qvm_detail
{
template <int Row1,int Row2,class OriginalMatrix>
class
swap_rows_
{
swap_rows_( swap_rows_ const & );
swap_rows_ & operator=( swap_rows_ const & );
~swap_rows_();
public:
template <class T>
BOOST_QVM_INLINE_TRIVIAL
swap_rows_ &
operator=( T const & x )
{
assign(*this,x);
return *this;
}
template <class R>
BOOST_QVM_INLINE_TRIVIAL
operator R() const
{
R r;
assign(r,*this);
return r;
}
};
}
template <int R1,int R2,class OriginalMatrix>
struct
mat_traits< qvm_detail::swap_rows_<R1,R2,OriginalMatrix> >
{
typedef qvm_detail::swap_rows_<R1,R2,OriginalMatrix> this_matrix;
typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;
static int const rows=mat_traits<OriginalMatrix>::rows;
static int const cols=mat_traits<OriginalMatrix>::cols;
template <int Row,int Col>
static
BOOST_QVM_INLINE_CRITICAL
scalar_type
read_element( this_matrix const & x )
{
BOOST_QVM_STATIC_ASSERT(Row>=0);
BOOST_QVM_STATIC_ASSERT(Row<rows);
BOOST_QVM_STATIC_ASSERT(Col>=0);
BOOST_QVM_STATIC_ASSERT(Col<cols);
return mat_traits<OriginalMatrix>::template read_element<(Row==R1 && R1!=R2)*R2+(Row==R2 && R1!=R2)*R1+((Row!=R1 && Row!=R2) || R1==R2)*Row,Col>(reinterpret_cast<OriginalMatrix const &>(x));
}
template <int Row,int Col>
static
BOOST_QVM_INLINE_CRITICAL
scalar_type &
write_element( this_matrix & x )
{
BOOST_QVM_STATIC_ASSERT(Row>=0);
BOOST_QVM_STATIC_ASSERT(Row<rows);
BOOST_QVM_STATIC_ASSERT(Col>=0);
BOOST_QVM_STATIC_ASSERT(Col<cols);
return mat_traits<OriginalMatrix>::template write_element<(Row==R1 && R1!=R2)*R2+(Row==R2 && R1!=R2)*R1+((Row!=R1 && Row!=R2) || R1==R2)*Row,Col>(reinterpret_cast<OriginalMatrix &>(x));
}
static
BOOST_QVM_INLINE_CRITICAL
scalar_type
read_element_idx( int row, int col, this_matrix const & x )
{
BOOST_QVM_ASSERT(row>=0);
BOOST_QVM_ASSERT(row<rows);
BOOST_QVM_ASSERT(col>=0);
BOOST_QVM_ASSERT(col<cols);
return mat_traits<OriginalMatrix>::read_element_idx(row==R1?R2:row==R2?R1:row,col,reinterpret_cast<OriginalMatrix const &>(x));
}
static
BOOST_QVM_INLINE_CRITICAL
scalar_type &
write_element_idx( int row, int col, this_matrix & x )
{
BOOST_QVM_ASSERT(row>=0);
BOOST_QVM_ASSERT(row<rows);
BOOST_QVM_ASSERT(col>=0);
BOOST_QVM_ASSERT(col<cols);
return mat_traits<OriginalMatrix>::write_element_idx(row==R1?R2:row==R2?R1:row,col,reinterpret_cast<OriginalMatrix &>(x));
}
};
template <int R1,int R2,class OriginalMatrix,int R,int C>
struct
deduce_mat<qvm_detail::swap_rows_<R1,R2,OriginalMatrix>,R,C>
{
typedef mat<typename mat_traits<OriginalMatrix>::scalar_type,R,C> type;
};
template <int R1,int R2,class OriginalMatrix,int R,int C>
struct
deduce_mat2<qvm_detail::swap_rows_<R1,R2,OriginalMatrix>,qvm_detail::swap_rows_<R1,R2,OriginalMatrix>,R,C>
{
typedef mat<typename mat_traits<OriginalMatrix>::scalar_type,R,C> type;
};
template <int R1,int R2,class A>
typename boost::enable_if_c<
is_mat<A>::value,
qvm_detail::swap_rows_<R1,R2,A> const &>::type
BOOST_QVM_INLINE_TRIVIAL
swap_rows( A const & a )
{
return reinterpret_cast<typename qvm_detail::swap_rows_<R1,R2,A> const &>(a);
}
template <int R1,int R2,class A>
typename boost::enable_if_c<
is_mat<A>::value,
qvm_detail::swap_rows_<R1,R2,A> &>::type
BOOST_QVM_INLINE_TRIVIAL
swap_rows( A & a )
{
return reinterpret_cast<typename qvm_detail::swap_rows_<R1,R2,A> &>(a);
}
////////////////////////////////////////////////
namespace
qvm_detail
{
template <int Row1,int Row2,class OriginalMatrix>
class
swap_cols_
{
swap_cols_( swap_cols_ const & );
swap_cols_ & operator=( swap_cols_ const & );
~swap_cols_();
public:
template <class T>
BOOST_QVM_INLINE_TRIVIAL
swap_cols_ &
operator=( T const & x )
{
assign(*this,x);
return *this;
}
template <class R>
BOOST_QVM_INLINE_TRIVIAL
operator R() const
{
R r;
assign(r,*this);
return r;
}
};
}
template <int C1,int C2,class OriginalMatrix>
struct
mat_traits< qvm_detail::swap_cols_<C1,C2,OriginalMatrix> >
{
typedef qvm_detail::swap_cols_<C1,C2,OriginalMatrix> this_matrix;
typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;
static int const rows=mat_traits<OriginalMatrix>::rows;
static int const cols=mat_traits<OriginalMatrix>::cols;
template <int Row,int Col>
static
BOOST_QVM_INLINE_CRITICAL
scalar_type
read_element( this_matrix const & x )
{
BOOST_QVM_STATIC_ASSERT(Row>=0);
BOOST_QVM_STATIC_ASSERT(Row<rows);
BOOST_QVM_STATIC_ASSERT(Col>=0);
BOOST_QVM_STATIC_ASSERT(Col<cols);
return mat_traits<OriginalMatrix>::template read_element<Row,(Col==C1 && C1!=C2)*C2+(Col==C2 && C1!=C2)*C1+((Col!=C1 && Col!=C2) || C1==C2)*Col>(reinterpret_cast<OriginalMatrix const &>(x));
}
template <int Row,int Col>
static
BOOST_QVM_INLINE_CRITICAL
scalar_type &
write_element( this_matrix & x )
{
BOOST_QVM_STATIC_ASSERT(Row>=0);
BOOST_QVM_STATIC_ASSERT(Row<rows);
BOOST_QVM_STATIC_ASSERT(Col>=0);
BOOST_QVM_STATIC_ASSERT(Col<cols);
return mat_traits<OriginalMatrix>::template write_element<Row,(Col==C1 && C1!=C2)*C2+(Col==C2 && C1!=C2)*C1+((Col!=C1 && Col!=C2) || C1==C2)*Col>(reinterpret_cast<OriginalMatrix &>(x));
}
static
BOOST_QVM_INLINE_CRITICAL
scalar_type
read_element_idx( int row, int col, this_matrix const & x )
{
BOOST_QVM_ASSERT(row>=0);
BOOST_QVM_ASSERT(row<rows);
BOOST_QVM_ASSERT(col>=0);
BOOST_QVM_ASSERT(col<cols);
return mat_traits<OriginalMatrix>::read_element_idx(row,col==C1?C2:col==C2?C1:col,reinterpret_cast<OriginalMatrix const &>(x));
}
static
BOOST_QVM_INLINE_CRITICAL
scalar_type &
write_element_idx( int row, int col, this_matrix & x )
{
BOOST_QVM_ASSERT(row>=0);
BOOST_QVM_ASSERT(row<rows);
BOOST_QVM_ASSERT(col>=0);
BOOST_QVM_ASSERT(col<cols);
return mat_traits<OriginalMatrix>::write_element_idx(row,col==C1?C2:col==C2?C1:col,reinterpret_cast<OriginalMatrix &>(x));
}
};
template <int C1,int C2,class OriginalMatrix,int R,int C>
struct
deduce_mat<qvm_detail::swap_cols_<C1,C2,OriginalMatrix>,R,C>
{
typedef mat<typename mat_traits<OriginalMatrix>::scalar_type,R,C> type;
};
template <int C1,int C2,class OriginalMatrix,int R,int C>
struct
deduce_mat2<qvm_detail::swap_cols_<C1,C2,OriginalMatrix>,qvm_detail::swap_cols_<C1,C2,OriginalMatrix>,R,C>
{
typedef mat<typename mat_traits<OriginalMatrix>::scalar_type,R,C> type;
};
template <int C1,int C2,class A>
typename boost::enable_if_c<
is_mat<A>::value,
qvm_detail::swap_cols_<C1,C2,A> const &>::type
BOOST_QVM_INLINE_TRIVIAL
swap_cols( A const & a )
{
return reinterpret_cast<typename qvm_detail::swap_cols_<C1,C2,A> const &>(a);
}
template <int C1,int C2,class A>
typename boost::enable_if_c<
is_mat<A>::value,
qvm_detail::swap_cols_<C1,C2,A> &>::type
BOOST_QVM_INLINE_TRIVIAL
swap_cols( A & a )
{
return reinterpret_cast<typename qvm_detail::swap_cols_<C1,C2,A> &>(a);
}
////////////////////////////////////////////////
}
}
#endif
| gpl-2.0 |
wrgeorge1983/librenms | vendor/amenadiel/jpgraph/Examples/examples_general/example16.2.php | 1188 | <?php // content="text/plain; charset=utf-8"
require_once '../../vendor/autoload.php';
use Amenadiel\JpGraph\Graph;
use Amenadiel\JpGraph\Plot;
$l1datay = array(11, 9, 2, 4, 3, 13, 17);
$l2datay = array(23, 12, 5, 19, 17, 10, 15);
$datax = array("Jan", "Feb", "Mar", "Apr", "May");
// Create the graph.
$graph = new Graph\Graph(400, 200);
$graph->SetScale("textlin");
$graph->img->SetMargin(40, 130, 20, 40);
$graph->SetShadow();
// Create the linear error plot
$l1plot = new Plot\LinePlot($l1datay);
$l1plot->SetColor("red");
$l1plot->SetWeight(2);
$l1plot->SetLegend("Prediction");
// Create the bar plot
$bplot = new Plot\BarPlot($l2datay);
$bplot->SetFillColor("orange");
$bplot->SetLegend("Result");
// Add the plots to t'he graph
$graph->Add($l1plot);
$graph->Add($bplot);
$graph->title->Set("Adding a line plot to a bar graph v1");
$graph->xaxis->title->Set("X-title");
$graph->yaxis->title->Set("Y-title");
$graph->title->SetFont(FF_FONT1, FS_BOLD);
$graph->yaxis->title->SetFont(FF_FONT1, FS_BOLD);
$graph->xaxis->title->SetFont(FF_FONT1, FS_BOLD);
//$graph->xaxis->SetTickLabels($datax);
//$graph->xaxis->SetTextTickInterval(2);
// Display the graph
$graph->Stroke();
| gpl-3.0 |
socialengineers/phing | classes/phing/filters/IconvFilter.php | 4611 | <?php
/*
* $Id$
*
* 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://phing.info>.
*/
include_once 'phing/filters/BaseParamFilterReader.php';
include_once 'phing/filters/ChainableReader.php';
/**
* Encode data from <code>in</code> encoding to <code>out</code> encoding.
*
* Example:
* <pre>
* <iconvfilter inputencoding="UTF-8" outputencoding="CP1251" />
* </pre>
* Or:
* <pre>
* <filterreader classname="phing.filters.IconvFilter">
* <param name="inputencoding" value="UTF-8" />
* <param name="outputencoding" value="CP1251" />
* </filterreader>
* </pre>
*
* @author Alexey Shockov, <alexey@shockov.com>
* @version $Id$
* @package phing.filters
*/
class IconvFilter
extends BaseParamFilterReader
implements ChainableReader
{
private $_inputEncoding;
private $_outputEncoding;
/**
* Returns first n lines of stream.
* @param null $len
* @return the resulting stream, or -1
* if the end of the resulting stream has been reached
*
* @exception IOException if the underlying stream throws an IOException
* during reading
*/
public function read($len = null)
{
$this->_initialize();
// Process whole text at once.
$text = null;
while (($data = $this->in->read($len)) !== -1) {
$text .= $data;
}
// At the end.
if (null === $text) {
return -1;
}
$this->log(
"Encoding " . $this->in->getResource() . " from " . $this->getInputEncoding(
) . " to " . $this->getOutputEncoding(),
Project::MSG_VERBOSE
);
return iconv($this->_inputEncoding, $this->_outputEncoding, $text);
}
/**
*
* @param string $encoding Input encoding.
*/
public function setInputEncoding($encoding)
{
$this->_inputEncoding = $encoding;
}
/**
*
* @return string
*/
public function getInputEncoding()
{
return $this->_inputEncoding;
}
/**
*
* @param string $encoding Output encoding.
*/
public function setOutputEncoding($encoding)
{
$this->_outputEncoding = $encoding;
}
/**
*
* @return string
*/
public function getOutputEncoding()
{
return $this->_outputEncoding;
}
/**
* Creates a new IconvFilter using the passed in Reader for instantiation.
*
* @param Reader $reader
* @internal param A $object Reader object providing the underlying stream. Must not be <code>null</code>.
*
* @return object A new filter based on this configuration, but filtering the specified reader.
*/
public function chain(Reader $reader)
{
$filter = new self($reader);
$filter->setInputEncoding($this->getInputEncoding());
$filter->setOutputEncoding($this->getOutputEncoding());
$filter->setInitialized(true);
$filter->setProject($this->getProject());
return $filter;
}
/**
* Configuring object from the parameters list.
*/
private function _initialize()
{
if ($this->getInitialized()) {
return;
}
$params = $this->getParameters();
if ($params !== null) {
foreach ($params as $param) {
if ('in' == $param->getName()) {
$this->setInputEncoding($param->getValue());
} else {
if ('out' == $param->getName()) {
$this->setOutputEncoding($param->getValue());
}
}
}
}
$this->setInitialized(true);
}
}
| lgpl-3.0 |