code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/*
*
* Copyright (C) 2011 Pierre Malarme
*
* Authors: Pierre Malarme <pmalarme at ulb.ac.be>
*
* Institution: Laboratory of Image Synthesis and Analysis (LISA)
* Faculty of Applied Science
* Universite Libre de Bruxelles (U.L.B.)
*
* Website: http://lisa.ulb.ac.be
*
* This file <CLUTMode.java> is part of Droid Dicom Viewer.
*
* Droid Dicom Viewer 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.
*
* Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>.
*
* Released date: 17-02-2011
*
* Version: 1.0
*
*/
package be.ac.ulb.lisa.idot.android.dicomviewer.mode;
/**
* The class CLUTMode contains the LUT/CLUT modes.
*
* @author Pierre Malarme
* @version 1.0
*
*/
public final class CLUTMode {
/**
* Normal grayscale LUT.
*/
public static final short NORMAL = 0;
/**
* Inverse LUT.
*/
public static final short INVERSE = 1;
/**
* Color rainbow CLUT.
*/
public static final short RAINBOW = 2;
}
| carlosqueiroz/droid-dicom-viewer | src/be/ac/ulb/lisa/idot/android/dicomviewer/mode/CLUTMode.java | Java | gpl-3.0 | 1,510 |
/*
* 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.streaming.api.operators;
import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
/**
* A {@link StreamOperator} for executing {@link FlatMapFunction FlatMapFunctions}.
*/
@Internal
public class StreamFlatMap<IN, OUT>
extends AbstractUdfStreamOperator<OUT, FlatMapFunction<IN, OUT>>
implements OneInputStreamOperator<IN, OUT> {
private static final long serialVersionUID = 1L;
private transient TimestampedCollector<OUT> collector;
public StreamFlatMap(FlatMapFunction<IN, OUT> flatMapper) {
super(flatMapper);
chainingStrategy = ChainingStrategy.ALWAYS;
}
@Override
public void open() throws Exception {
super.open();
collector = new TimestampedCollector<>(output);
}
@Override
public void processElement(StreamRecord<IN> element) throws Exception {
collector.setTimestamp(element);
userFunction.flatMap(element.getValue(), collector);
}
}
| tzulitai/flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/StreamFlatMap.java | Java | apache-2.0 | 1,822 |
// Copyright 2016 The etcd 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 integration
import (
"bytes"
"os"
"reflect"
"strings"
"testing"
"time"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
"github.com/coreos/etcd/integration"
"github.com/coreos/etcd/mvcc/mvccpb"
"github.com/coreos/etcd/pkg/testutil"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
func TestKVPutError(t *testing.T) {
defer testutil.AfterTest(t)
var (
maxReqBytes = 1.5 * 1024 * 1024 // hard coded max in v3_server.go
quota = int64(int(maxReqBytes) + 8*os.Getpagesize())
)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1, QuotaBackendBytes: quota, ClientMaxCallSendMsgSize: 100 * 1024 * 1024})
defer clus.Terminate(t)
kv := clus.RandClient()
ctx := context.TODO()
_, err := kv.Put(ctx, "", "bar")
if err != rpctypes.ErrEmptyKey {
t.Fatalf("expected %v, got %v", rpctypes.ErrEmptyKey, err)
}
_, err = kv.Put(ctx, "key", strings.Repeat("a", int(maxReqBytes+100)))
if err != rpctypes.ErrRequestTooLarge {
t.Fatalf("expected %v, got %v", rpctypes.ErrRequestTooLarge, err)
}
_, err = kv.Put(ctx, "foo1", strings.Repeat("a", int(maxReqBytes-50)))
if err != nil { // below quota
t.Fatal(err)
}
time.Sleep(1 * time.Second) // give enough time for commit
_, err = kv.Put(ctx, "foo2", strings.Repeat("a", int(maxReqBytes-50)))
if err != rpctypes.ErrNoSpace { // over quota
t.Fatalf("expected %v, got %v", rpctypes.ErrNoSpace, err)
}
}
func TestKVPut(t *testing.T) {
defer testutil.AfterTest(t)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
defer clus.Terminate(t)
lapi := clus.RandClient()
kv := clus.RandClient()
ctx := context.TODO()
resp, err := lapi.Grant(context.Background(), 10)
if err != nil {
t.Fatalf("failed to create lease %v", err)
}
tests := []struct {
key, val string
leaseID clientv3.LeaseID
}{
{"foo", "bar", clientv3.NoLease},
{"hello", "world", resp.ID},
}
for i, tt := range tests {
if _, err := kv.Put(ctx, tt.key, tt.val, clientv3.WithLease(tt.leaseID)); err != nil {
t.Fatalf("#%d: couldn't put %q (%v)", i, tt.key, err)
}
resp, err := kv.Get(ctx, tt.key)
if err != nil {
t.Fatalf("#%d: couldn't get key (%v)", i, err)
}
if len(resp.Kvs) != 1 {
t.Fatalf("#%d: expected 1 key, got %d", i, len(resp.Kvs))
}
if !bytes.Equal([]byte(tt.val), resp.Kvs[0].Value) {
t.Errorf("#%d: val = %s, want %s", i, tt.val, resp.Kvs[0].Value)
}
if tt.leaseID != clientv3.LeaseID(resp.Kvs[0].Lease) {
t.Errorf("#%d: val = %d, want %d", i, tt.leaseID, resp.Kvs[0].Lease)
}
}
}
// TestKVPutWithIgnoreValue ensures that Put with WithIgnoreValue does not clobber the old value.
func TestKVPutWithIgnoreValue(t *testing.T) {
defer testutil.AfterTest(t)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
defer clus.Terminate(t)
kv := clus.RandClient()
_, err := kv.Put(context.TODO(), "foo", "", clientv3.WithIgnoreValue())
if err != rpctypes.ErrKeyNotFound {
t.Fatalf("err expected %v, got %v", rpctypes.ErrKeyNotFound, err)
}
if _, err := kv.Put(context.TODO(), "foo", "bar"); err != nil {
t.Fatal(err)
}
if _, err := kv.Put(context.TODO(), "foo", "", clientv3.WithIgnoreValue()); err != nil {
t.Fatal(err)
}
rr, rerr := kv.Get(context.TODO(), "foo")
if rerr != nil {
t.Fatal(rerr)
}
if len(rr.Kvs) != 1 {
t.Fatalf("len(rr.Kvs) expected 1, got %d", len(rr.Kvs))
}
if !bytes.Equal(rr.Kvs[0].Value, []byte("bar")) {
t.Fatalf("value expected 'bar', got %q", rr.Kvs[0].Value)
}
}
// TestKVPutWithIgnoreLease ensures that Put with WithIgnoreLease does not affect the existing lease for the key.
func TestKVPutWithIgnoreLease(t *testing.T) {
defer testutil.AfterTest(t)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
defer clus.Terminate(t)
kv := clus.RandClient()
lapi := clus.RandClient()
resp, err := lapi.Grant(context.Background(), 10)
if err != nil {
t.Errorf("failed to create lease %v", err)
}
if _, err := kv.Put(context.TODO(), "zoo", "bar", clientv3.WithIgnoreLease()); err != rpctypes.ErrKeyNotFound {
t.Fatalf("err expected %v, got %v", rpctypes.ErrKeyNotFound, err)
}
if _, err := kv.Put(context.TODO(), "zoo", "bar", clientv3.WithLease(resp.ID)); err != nil {
t.Fatal(err)
}
if _, err := kv.Put(context.TODO(), "zoo", "bar1", clientv3.WithIgnoreLease()); err != nil {
t.Fatal(err)
}
rr, rerr := kv.Get(context.TODO(), "zoo")
if rerr != nil {
t.Fatal(rerr)
}
if len(rr.Kvs) != 1 {
t.Fatalf("len(rr.Kvs) expected 1, got %d", len(rr.Kvs))
}
if rr.Kvs[0].Lease != int64(resp.ID) {
t.Fatalf("lease expected %v, got %v", resp.ID, rr.Kvs[0].Lease)
}
}
func TestKVPutWithRequireLeader(t *testing.T) {
defer testutil.AfterTest(t)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
defer clus.Terminate(t)
clus.Members[1].Stop(t)
clus.Members[2].Stop(t)
// wait for election timeout, then member[0] will not have a leader.
var (
electionTicks = 10
tickDuration = 10 * time.Millisecond
)
time.Sleep(time.Duration(3*electionTicks) * tickDuration)
kv := clus.Client(0)
_, err := kv.Put(clientv3.WithRequireLeader(context.Background()), "foo", "bar")
if err != rpctypes.ErrNoLeader {
t.Fatal(err)
}
// clients may give timeout errors since the members are stopped; take
// the clients so that terminating the cluster won't complain
clus.Client(1).Close()
clus.Client(2).Close()
clus.TakeClient(1)
clus.TakeClient(2)
}
func TestKVRange(t *testing.T) {
defer testutil.AfterTest(t)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
defer clus.Terminate(t)
kv := clus.RandClient()
ctx := context.TODO()
keySet := []string{"a", "b", "c", "c", "c", "foo", "foo/abc", "fop"}
for i, key := range keySet {
if _, err := kv.Put(ctx, key, ""); err != nil {
t.Fatalf("#%d: couldn't put %q (%v)", i, key, err)
}
}
resp, err := kv.Get(ctx, keySet[0])
if err != nil {
t.Fatalf("couldn't get key (%v)", err)
}
wheader := resp.Header
tests := []struct {
begin, end string
rev int64
opts []clientv3.OpOption
wantSet []*mvccpb.KeyValue
}{
// range first two
{
"a", "c",
0,
nil,
[]*mvccpb.KeyValue{
{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
},
},
// range first two with serializable
{
"a", "c",
0,
[]clientv3.OpOption{clientv3.WithSerializable()},
[]*mvccpb.KeyValue{
{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
},
},
// range all with rev
{
"a", "x",
2,
nil,
[]*mvccpb.KeyValue{
{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
},
},
// range all with countOnly
{
"a", "x",
2,
[]clientv3.OpOption{clientv3.WithCountOnly()},
nil,
},
// range all with SortByKey, SortAscend
{
"a", "x",
0,
[]clientv3.OpOption{clientv3.WithSort(clientv3.SortByKey, clientv3.SortAscend)},
[]*mvccpb.KeyValue{
{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
{Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
{Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
},
},
// range all with SortByKey, missing sorting order (ASCEND by default)
{
"a", "x",
0,
[]clientv3.OpOption{clientv3.WithSort(clientv3.SortByKey, clientv3.SortNone)},
[]*mvccpb.KeyValue{
{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
{Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
{Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
},
},
// range all with SortByCreateRevision, SortDescend
{
"a", "x",
0,
[]clientv3.OpOption{clientv3.WithSort(clientv3.SortByCreateRevision, clientv3.SortDescend)},
[]*mvccpb.KeyValue{
{Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
{Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
},
},
// range all with SortByCreateRevision, missing sorting order (ASCEND by default)
{
"a", "x",
0,
[]clientv3.OpOption{clientv3.WithSort(clientv3.SortByCreateRevision, clientv3.SortNone)},
[]*mvccpb.KeyValue{
{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
{Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
{Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
},
},
// range all with SortByModRevision, SortDescend
{
"a", "x",
0,
[]clientv3.OpOption{clientv3.WithSort(clientv3.SortByModRevision, clientv3.SortDescend)},
[]*mvccpb.KeyValue{
{Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
{Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
},
},
// WithPrefix
{
"foo", "",
0,
[]clientv3.OpOption{clientv3.WithPrefix()},
[]*mvccpb.KeyValue{
{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
},
},
// WithFromKey
{
"fo", "",
0,
[]clientv3.OpOption{clientv3.WithFromKey()},
[]*mvccpb.KeyValue{
{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
{Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
},
},
// fetch entire keyspace using WithFromKey
{
"\x00", "",
0,
[]clientv3.OpOption{clientv3.WithFromKey(), clientv3.WithSort(clientv3.SortByKey, clientv3.SortAscend)},
[]*mvccpb.KeyValue{
{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
{Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
{Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
},
},
// fetch entire keyspace using WithPrefix
{
"", "",
0,
[]clientv3.OpOption{clientv3.WithPrefix(), clientv3.WithSort(clientv3.SortByKey, clientv3.SortAscend)},
[]*mvccpb.KeyValue{
{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
{Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
{Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
},
},
}
for i, tt := range tests {
opts := []clientv3.OpOption{clientv3.WithRange(tt.end), clientv3.WithRev(tt.rev)}
opts = append(opts, tt.opts...)
resp, err := kv.Get(ctx, tt.begin, opts...)
if err != nil {
t.Fatalf("#%d: couldn't range (%v)", i, err)
}
if !reflect.DeepEqual(wheader, resp.Header) {
t.Fatalf("#%d: wheader expected %+v, got %+v", i, wheader, resp.Header)
}
if !reflect.DeepEqual(tt.wantSet, resp.Kvs) {
t.Fatalf("#%d: resp.Kvs expected %+v, got %+v", i, tt.wantSet, resp.Kvs)
}
}
}
func TestKVGetErrConnClosed(t *testing.T) {
defer testutil.AfterTest(t)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
defer clus.Terminate(t)
cli := clus.Client(0)
donec := make(chan struct{})
go func() {
defer close(donec)
_, err := cli.Get(context.TODO(), "foo")
if err != nil && err != context.Canceled && err != grpc.ErrClientConnClosing {
t.Fatalf("expected %v or %v, got %v", context.Canceled, grpc.ErrClientConnClosing, err)
}
}()
if err := cli.Close(); err != nil {
t.Fatal(err)
}
clus.TakeClient(0)
select {
case <-time.After(3 * time.Second):
t.Fatal("kv.Get took too long")
case <-donec:
}
}
func TestKVNewAfterClose(t *testing.T) {
defer testutil.AfterTest(t)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
defer clus.Terminate(t)
cli := clus.Client(0)
clus.TakeClient(0)
if err := cli.Close(); err != nil {
t.Fatal(err)
}
donec := make(chan struct{})
go func() {
_, err := cli.Get(context.TODO(), "foo")
if err != context.Canceled && err != grpc.ErrClientConnClosing {
t.Fatalf("expected %v or %v, got %v", context.Canceled, grpc.ErrClientConnClosing, err)
}
close(donec)
}()
select {
case <-time.After(3 * time.Second):
t.Fatal("kv.Get took too long")
case <-donec:
}
}
func TestKVDeleteRange(t *testing.T) {
defer testutil.AfterTest(t)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
defer clus.Terminate(t)
kv := clus.RandClient()
ctx := context.TODO()
tests := []struct {
key string
opts []clientv3.OpOption
wkeys []string
}{
// [a, c)
{
key: "a",
opts: []clientv3.OpOption{clientv3.WithRange("c")},
wkeys: []string{"c", "c/abc", "d"},
},
// >= c
{
key: "c",
opts: []clientv3.OpOption{clientv3.WithFromKey()},
wkeys: []string{"a", "b"},
},
// c*
{
key: "c",
opts: []clientv3.OpOption{clientv3.WithPrefix()},
wkeys: []string{"a", "b", "d"},
},
// *
{
key: "\x00",
opts: []clientv3.OpOption{clientv3.WithFromKey()},
wkeys: []string{},
},
}
for i, tt := range tests {
keySet := []string{"a", "b", "c", "c/abc", "d"}
for j, key := range keySet {
if _, err := kv.Put(ctx, key, ""); err != nil {
t.Fatalf("#%d: couldn't put %q (%v)", j, key, err)
}
}
_, err := kv.Delete(ctx, tt.key, tt.opts...)
if err != nil {
t.Fatalf("#%d: couldn't delete range (%v)", i, err)
}
resp, err := kv.Get(ctx, "a", clientv3.WithFromKey())
if err != nil {
t.Fatalf("#%d: couldn't get keys (%v)", i, err)
}
keys := []string{}
for _, kv := range resp.Kvs {
keys = append(keys, string(kv.Key))
}
if !reflect.DeepEqual(tt.wkeys, keys) {
t.Errorf("#%d: resp.Kvs got %v, expected %v", i, keys, tt.wkeys)
}
}
}
func TestKVDelete(t *testing.T) {
defer testutil.AfterTest(t)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
defer clus.Terminate(t)
kv := clus.RandClient()
ctx := context.TODO()
presp, err := kv.Put(ctx, "foo", "")
if err != nil {
t.Fatalf("couldn't put 'foo' (%v)", err)
}
if presp.Header.Revision != 2 {
t.Fatalf("presp.Header.Revision got %d, want %d", presp.Header.Revision, 2)
}
resp, err := kv.Delete(ctx, "foo")
if err != nil {
t.Fatalf("couldn't delete key (%v)", err)
}
if resp.Header.Revision != 3 {
t.Fatalf("resp.Header.Revision got %d, want %d", resp.Header.Revision, 3)
}
gresp, err := kv.Get(ctx, "foo")
if err != nil {
t.Fatalf("couldn't get key (%v)", err)
}
if len(gresp.Kvs) > 0 {
t.Fatalf("gresp.Kvs got %+v, want none", gresp.Kvs)
}
}
func TestKVCompactError(t *testing.T) {
defer testutil.AfterTest(t)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
defer clus.Terminate(t)
kv := clus.RandClient()
ctx := context.TODO()
for i := 0; i < 5; i++ {
if _, err := kv.Put(ctx, "foo", "bar"); err != nil {
t.Fatalf("couldn't put 'foo' (%v)", err)
}
}
_, err := kv.Compact(ctx, 6)
if err != nil {
t.Fatalf("couldn't compact 6 (%v)", err)
}
_, err = kv.Compact(ctx, 6)
if err != rpctypes.ErrCompacted {
t.Fatalf("expected %v, got %v", rpctypes.ErrCompacted, err)
}
_, err = kv.Compact(ctx, 100)
if err != rpctypes.ErrFutureRev {
t.Fatalf("expected %v, got %v", rpctypes.ErrFutureRev, err)
}
}
func TestKVCompact(t *testing.T) {
defer testutil.AfterTest(t)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
defer clus.Terminate(t)
kv := clus.RandClient()
ctx := context.TODO()
for i := 0; i < 10; i++ {
if _, err := kv.Put(ctx, "foo", "bar"); err != nil {
t.Fatalf("couldn't put 'foo' (%v)", err)
}
}
_, err := kv.Compact(ctx, 7)
if err != nil {
t.Fatalf("couldn't compact kv space (%v)", err)
}
_, err = kv.Compact(ctx, 7)
if err == nil || err != rpctypes.ErrCompacted {
t.Fatalf("error got %v, want %v", err, rpctypes.ErrCompacted)
}
wcli := clus.RandClient()
// new watcher could precede receiving the compaction without quorum first
wcli.Get(ctx, "quorum-get")
wchan := wcli.Watch(ctx, "foo", clientv3.WithRev(3))
if wr := <-wchan; wr.CompactRevision != 7 {
t.Fatalf("wchan CompactRevision got %v, want 7", wr.CompactRevision)
}
if wr, ok := <-wchan; ok {
t.Fatalf("wchan got %v, expected closed", wr)
}
_, err = kv.Compact(ctx, 1000)
if err == nil || err != rpctypes.ErrFutureRev {
t.Fatalf("error got %v, want %v", err, rpctypes.ErrFutureRev)
}
}
// TestKVGetRetry ensures get will retry on disconnect.
func TestKVGetRetry(t *testing.T) {
defer testutil.AfterTest(t)
clusterSize := 3
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: clusterSize})
defer clus.Terminate(t)
// because killing leader and following election
// could give no other endpoints for client reconnection
fIdx := (clus.WaitLeader(t) + 1) % clusterSize
kv := clus.Client(fIdx)
ctx := context.TODO()
if _, err := kv.Put(ctx, "foo", "bar"); err != nil {
t.Fatal(err)
}
clus.Members[fIdx].Stop(t)
donec := make(chan struct{})
go func() {
// Get will fail, but reconnect will trigger
gresp, gerr := kv.Get(ctx, "foo")
if gerr != nil {
t.Fatal(gerr)
}
wkvs := []*mvccpb.KeyValue{
{
Key: []byte("foo"),
Value: []byte("bar"),
CreateRevision: 2,
ModRevision: 2,
Version: 1,
},
}
if !reflect.DeepEqual(gresp.Kvs, wkvs) {
t.Fatalf("bad get: got %v, want %v", gresp.Kvs, wkvs)
}
donec <- struct{}{}
}()
time.Sleep(100 * time.Millisecond)
clus.Members[fIdx].Restart(t)
select {
case <-time.After(5 * time.Second):
t.Fatalf("timed out waiting for get")
case <-donec:
}
}
// TestKVPutFailGetRetry ensures a get will retry following a failed put.
func TestKVPutFailGetRetry(t *testing.T) {
defer testutil.AfterTest(t)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
defer clus.Terminate(t)
kv := clus.Client(0)
clus.Members[0].Stop(t)
ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
defer cancel()
_, err := kv.Put(ctx, "foo", "bar")
if err == nil {
t.Fatalf("got success on disconnected put, wanted error")
}
donec := make(chan struct{})
go func() {
// Get will fail, but reconnect will trigger
gresp, gerr := kv.Get(context.TODO(), "foo")
if gerr != nil {
t.Fatal(gerr)
}
if len(gresp.Kvs) != 0 {
t.Fatalf("bad get kvs: got %+v, want empty", gresp.Kvs)
}
donec <- struct{}{}
}()
time.Sleep(100 * time.Millisecond)
clus.Members[0].Restart(t)
select {
case <-time.After(5 * time.Second):
t.Fatalf("timed out waiting for get")
case <-donec:
}
}
// TestKVGetCancel tests that a context cancel on a Get terminates as expected.
func TestKVGetCancel(t *testing.T) {
defer testutil.AfterTest(t)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
defer clus.Terminate(t)
oldconn := clus.Client(0).ActiveConnection()
kv := clus.Client(0)
ctx, cancel := context.WithCancel(context.TODO())
cancel()
resp, err := kv.Get(ctx, "abc")
if err == nil {
t.Fatalf("cancel on get response %v, expected context error", resp)
}
newconn := clus.Client(0).ActiveConnection()
if oldconn != newconn {
t.Fatalf("cancel on get broke client connection")
}
}
// TestKVGetStoppedServerAndClose ensures closing after a failed Get works.
func TestKVGetStoppedServerAndClose(t *testing.T) {
defer testutil.AfterTest(t)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
defer clus.Terminate(t)
cli := clus.Client(0)
clus.Members[0].Stop(t)
ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
// this Get fails and triggers an asynchronous connection retry
_, err := cli.Get(ctx, "abc")
cancel()
if err != nil && err != context.DeadlineExceeded {
t.Fatal(err)
}
}
// TestKVPutStoppedServerAndClose ensures closing after a failed Put works.
func TestKVPutStoppedServerAndClose(t *testing.T) {
defer testutil.AfterTest(t)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
defer clus.Terminate(t)
cli := clus.Client(0)
clus.Members[0].Stop(t)
ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
// get retries on all errors.
// so here we use it to eat the potential broken pipe error for the next put.
// grpc client might see a broken pipe error when we issue the get request before
// grpc finds out the original connection is down due to the member shutdown.
_, err := cli.Get(ctx, "abc")
cancel()
if err != nil && err != context.DeadlineExceeded {
t.Fatal(err)
}
// this Put fails and triggers an asynchronous connection retry
_, err = cli.Put(ctx, "abc", "123")
cancel()
if err != nil && err != context.DeadlineExceeded {
t.Fatal(err)
}
}
// TestKVPutAtMostOnce ensures that a Put will only occur at most once
// in the presence of network errors.
func TestKVPutAtMostOnce(t *testing.T) {
defer testutil.AfterTest(t)
clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
defer clus.Terminate(t)
if _, err := clus.Client(0).Put(context.TODO(), "k", "1"); err != nil {
t.Fatal(err)
}
for i := 0; i < 10; i++ {
clus.Members[0].DropConnections()
donec := make(chan struct{})
go func() {
defer close(donec)
for i := 0; i < 10; i++ {
clus.Members[0].DropConnections()
time.Sleep(5 * time.Millisecond)
}
}()
_, err := clus.Client(0).Put(context.TODO(), "k", "v")
<-donec
if err != nil {
break
}
}
resp, err := clus.Client(0).Get(context.TODO(), "k")
if err != nil {
t.Fatal(err)
}
if resp.Kvs[0].Version > 11 {
t.Fatalf("expected version <= 10, got %+v", resp.Kvs[0])
}
}
// TestKVLargeRequests tests various client/server side request limits.
func TestKVLargeRequests(t *testing.T) {
defer testutil.AfterTest(t)
tests := []struct {
// make sure that "MaxCallSendMsgSize" < server-side default send/recv limit
maxRequestBytesServer uint
maxCallSendBytesClient int
maxCallRecvBytesClient int
valueSize int
expectError error
}{
{
maxRequestBytesServer: 1,
maxCallSendBytesClient: 0,
maxCallRecvBytesClient: 0,
valueSize: 1024,
expectError: rpctypes.ErrRequestTooLarge,
},
// without proper client-side receive size limit
// "code = ResourceExhausted desc = grpc: received message larger than max (5242929 vs. 4194304)"
{
maxRequestBytesServer: 7*1024*1024 + 512*1024,
maxCallSendBytesClient: 7 * 1024 * 1024,
maxCallRecvBytesClient: 0,
valueSize: 5 * 1024 * 1024,
expectError: nil,
},
{
maxRequestBytesServer: 10 * 1024 * 1024,
maxCallSendBytesClient: 100 * 1024 * 1024,
maxCallRecvBytesClient: 0,
valueSize: 10 * 1024 * 1024,
expectError: rpctypes.ErrRequestTooLarge,
},
{
maxRequestBytesServer: 10 * 1024 * 1024,
maxCallSendBytesClient: 10 * 1024 * 1024,
maxCallRecvBytesClient: 0,
valueSize: 10 * 1024 * 1024,
expectError: grpc.Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max "),
},
{
maxRequestBytesServer: 10 * 1024 * 1024,
maxCallSendBytesClient: 100 * 1024 * 1024,
maxCallRecvBytesClient: 0,
valueSize: 10*1024*1024 + 5,
expectError: rpctypes.ErrRequestTooLarge,
},
{
maxRequestBytesServer: 10 * 1024 * 1024,
maxCallSendBytesClient: 10 * 1024 * 1024,
maxCallRecvBytesClient: 0,
valueSize: 10*1024*1024 + 5,
expectError: grpc.Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max "),
},
}
for i, test := range tests {
clus := integration.NewClusterV3(t,
&integration.ClusterConfig{
Size: 1,
MaxRequestBytes: test.maxRequestBytesServer,
ClientMaxCallSendMsgSize: test.maxCallSendBytesClient,
ClientMaxCallRecvMsgSize: test.maxCallRecvBytesClient,
},
)
cli := clus.Client(0)
_, err := cli.Put(context.TODO(), "foo", strings.Repeat("a", test.valueSize))
if _, ok := err.(rpctypes.EtcdError); ok {
if err != test.expectError {
t.Errorf("#%d: expected %v, got %v", i, test.expectError, err)
}
} else if err != nil && !strings.HasPrefix(err.Error(), test.expectError.Error()) {
t.Errorf("#%d: expected %v, got %v", i, test.expectError, err)
}
// put request went through, now expects large response back
if err == nil {
_, err = cli.Get(context.TODO(), "foo")
if err != nil {
t.Errorf("#%d: get expected no error, got %v", i, err)
}
}
clus.Terminate(t)
}
}
| wjiangjay/origin | vendor/github.com/coreos/etcd/clientv3/integration/kv_test.go | GO | apache-2.0 | 27,477 |
/*
* Copyright (c) 2011 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include <string.h>
#include <android/log.h>
#include <pthread.h>
#include <unistd.h>
#include "org_webrtc_vieautotest_vie_autotest.h"
#include "vie_autotest_android.h"
#define WEBRTC_LOG_TAG "*WEBRTCN*"
// VideoEngine data struct
typedef struct
{
JavaVM* jvm;
} VideoEngineData;
// Global variables
JavaVM* webrtcGlobalVM;
// Global variables visible in this file
static VideoEngineData vieData;
// "Local" functions (i.e. not Java accessible)
#define WEBRTC_TRACE_MAX_MESSAGE_SIZE 1024
static bool GetSubAPIs(VideoEngineData& vieData);
static bool ReleaseSubAPIs(VideoEngineData& vieData);
//
// General functions
//
// JNI_OnLoad
jint JNI_OnLoad(JavaVM* vm, void* /*reserved*/) {
if (!vm) {
__android_log_write(ANDROID_LOG_ERROR, WEBRTC_LOG_TAG,
"JNI_OnLoad did not receive a valid VM pointer");
return -1;
}
JNIEnv* env;
if (JNI_OK != vm->GetEnv(reinterpret_cast<void**> (&env),
JNI_VERSION_1_4)) {
__android_log_write(ANDROID_LOG_ERROR, WEBRTC_LOG_TAG,
"JNI_OnLoad could not get JNI env");
return -1;
}
// Init ViE data
vieData.jvm = vm;
return JNI_VERSION_1_4;
}
// Class: org_webrtc_vieautotest_ViEAutotest
// Method: RunTest
// Signature: (IILandroid/opengl/GLSurfaceView;Landroid/opengl/GLSurfaceView;)I
JNIEXPORT jint JNICALL
Java_org_webrtc_vieautotest_ViEAutotest_RunTest__IILandroid_opengl_GLSurfaceView_2Landroid_opengl_GLSurfaceView_2(
JNIEnv* env,
jobject context,
jint testType,
jint subtestType,
jobject glView1,
jobject glView2)
{
int numErrors = -1;
numErrors = ViEAutoTestAndroid::RunAutotest(testType, subtestType, glView1,
glView2, vieData.jvm, env,
context);
return numErrors;
}
// Class: org_webrtc_vieautotest_ViEAutotest
// Method: RunTest
// Signature: (IILandroid/view/SurfaceView;Landroid/view/SurfaceView;)I
JNIEXPORT jint JNICALL
Java_org_webrtc_vieautotest_ViEAutotest_RunTest__IILandroid_view_SurfaceView_2Landroid_view_SurfaceView_2(
JNIEnv* env,
jobject context,
jint testType,
jint subtestType,
jobject surfaceHolder1,
jobject surfaceHolder2)
{
int numErrors = -1;
numErrors = ViEAutoTestAndroid::RunAutotest(testType, subtestType,
surfaceHolder1, surfaceHolder2,
vieData.jvm, env, context);
return numErrors;
}
//
//local function
//
bool GetSubAPIs(VideoEngineData& vieData) {
bool retVal = true;
//vieData.base = ViEBase::GetInterface(vieData.vie);
//if (vieData.base == NULL)
{
__android_log_write(ANDROID_LOG_ERROR, WEBRTC_LOG_TAG,
"Could not get Base API");
retVal = false;
}
return retVal;
}
bool ReleaseSubAPIs(VideoEngineData& vieData) {
bool releaseOk = true;
//if (vieData.base)
{
//if (vieData.base->Release() != 0)
if (false) {
__android_log_write(ANDROID_LOG_ERROR, WEBRTC_LOG_TAG,
"Release base sub-API failed");
releaseOk = false;
}
else {
//vieData.base = NULL;
}
}
return releaseOk;
}
| xhook/webrtc | video_engine/test/auto_test/android/jni/vie_autotest_jni.cc | C++ | bsd-3-clause | 3,679 |
/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkPath.h"
// Reproduces https://code.google.com/p/chromium/issues/detail?id=279014
static const int kWidth = 640;
static const int kHeight = 480;
static const SkScalar kAngle = 0.305f;
// Renders a string art shape.
// The particular shape rendered can be controlled by adjusting kAngle, from 0 to 1
class StringArtGM : public skiagm::GM {
public:
StringArtGM() {}
protected:
virtual SkString onShortName() {
return SkString("stringart");
}
virtual SkISize onISize() {
return SkISize::Make(kWidth, kHeight);
}
virtual void onDraw(SkCanvas* canvas) {
SkScalar angle = kAngle*SK_ScalarPI + SkScalarHalf(SK_ScalarPI);
SkScalar size = SkIntToScalar(SkMin32(kWidth, kHeight));
SkPoint center = SkPoint::Make(SkScalarHalf(kWidth), SkScalarHalf(kHeight));
SkScalar length = 5;
SkScalar step = angle;
SkPath path;
path.moveTo(center);
while (length < (SkScalarHalf(size) - 10.f))
{
SkPoint rp = SkPoint::Make(length*SkScalarCos(step) + center.fX,
length*SkScalarSin(step) + center.fY);
path.lineTo(rp);
length += SkScalarDiv(angle, SkScalarHalf(SK_ScalarPI));
step += angle;
}
path.close();
SkPaint paint;
paint.setAntiAlias(true);
paint.setStyle(SkPaint::kStroke_Style);
paint.setColor(0xFF007700);
canvas->drawPath(path, paint);
}
private:
typedef GM INHERITED;
};
DEF_GM( return new StringArtGM; )
| TeamCarbonXtremeARMv6/android_external_skia | gm/stringart.cpp | C++ | bsd-3-clause | 1,762 |
'use strict';
function create (env, entries, settings, treatments, profile, devicestatus) {
var express = require('express'),
app = express( )
;
var wares = require('../middleware/')(env);
// set up express app with our options
app.set('name', env.name);
app.set('version', env.version);
// app.set('head', env.head);
function get_head ( ) {
return env.head;
}
wares.get_head = get_head;
app.set('units', env.DISPLAY_UNITS);
// Only allow access to the API if API_SECRET is set on the server.
app.disable('api');
if (env.api_secret) {
console.log("API_SECRET", env.api_secret);
app.enable('api');
}
if (env.enable) {
app.enabledOptions = env.enable || '';
env.enable.toLowerCase().split(' ').forEach(function (value) {
var enable = value.trim();
console.info("enabling feature:", enable);
app.enable(enable);
});
}
app.defaults = env.defaults || '';
app.set('title', [app.get('name'), 'API', app.get('version')].join(' '));
app.thresholds = env.thresholds;
app.alarm_types = env.alarm_types;
// Start setting up routes
if (app.enabled('api')) {
// experiments
app.use('/experiments', require('./experiments/')(app, wares));
}
// Entries and settings
app.use('/', require('./entries/')(app, wares, entries));
app.use('/', require('./settings/')(app, wares, settings));
app.use('/', require('./treatments/')(app, wares, treatments));
app.use('/', require('./profile/')(app, wares, profile));
app.use('/', require('./devicestatus/')(app, wares, devicestatus));
// Status
app.use('/', require('./status')(app, wares));
return app;
}
module.exports = create;
| johnyburd/cgm-remote-monitor | lib/api/index.js | JavaScript | agpl-3.0 | 1,687 |
// Copyright 2006 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.
/**
* @fileoverview Datastructure: Circular Buffer.
*
* Implements a buffer with a maximum size. New entries override the oldest
* entries when the maximum size has been reached.
*
*/
goog.provide('goog.structs.CircularBuffer');
/**
* Class for CircularBuffer.
* @param {number=} opt_maxSize The maximum size of the buffer.
* @constructor
*/
goog.structs.CircularBuffer = function(opt_maxSize) {
/**
* Index of the next element in the circular array structure.
* @private {number}
*/
this.nextPtr_ = 0;
/**
* Maximum size of the the circular array structure.
* @private {number}
*/
this.maxSize_ = opt_maxSize || 100;
/**
* Underlying array for the CircularBuffer.
* @private {Array}
*/
this.buff_ = [];
};
/**
* Adds an item to the buffer. May remove the oldest item if the buffer is at
* max size.
* @param {*} item The item to add.
* @return {*} The removed old item, if the buffer is at max size.
* Return undefined, otherwise.
*/
goog.structs.CircularBuffer.prototype.add = function(item) {
var previousItem = this.buff_[this.nextPtr_];
this.buff_[this.nextPtr_] = item;
this.nextPtr_ = (this.nextPtr_ + 1) % this.maxSize_;
return previousItem;
};
/**
* Returns the item at the specified index.
* @param {number} index The index of the item. The index of an item can change
* after calls to {@code add()} if the buffer is at maximum size.
* @return {*} The item at the specified index.
*/
goog.structs.CircularBuffer.prototype.get = function(index) {
index = this.normalizeIndex_(index);
return this.buff_[index];
};
/**
* Sets the item at the specified index.
* @param {number} index The index of the item. The index of an item can change
* after calls to {@code add()} if the buffer is at maximum size.
* @param {*} item The item to add.
*/
goog.structs.CircularBuffer.prototype.set = function(index, item) {
index = this.normalizeIndex_(index);
this.buff_[index] = item;
};
/**
* Returns the current number of items in the buffer.
* @return {number} The current number of items in the buffer.
*/
goog.structs.CircularBuffer.prototype.getCount = function() {
return this.buff_.length;
};
/**
* @return {boolean} Whether the buffer is empty.
*/
goog.structs.CircularBuffer.prototype.isEmpty = function() {
return this.buff_.length == 0;
};
/**
* Empties the current buffer.
*/
goog.structs.CircularBuffer.prototype.clear = function() {
this.buff_.length = 0;
this.nextPtr_ = 0;
};
/**
* @return {Array} The values in the buffer.
*/
goog.structs.CircularBuffer.prototype.getValues = function() {
// getNewestValues returns all the values if the maxCount parameter is the
// count
return this.getNewestValues(this.getCount());
};
/**
* Returns the newest values in the buffer up to {@code count}.
* @param {number} maxCount The maximum number of values to get. Should be a
* positive number.
* @return {Array} The newest values in the buffer up to {@code count}.
*/
goog.structs.CircularBuffer.prototype.getNewestValues = function(maxCount) {
var l = this.getCount();
var start = this.getCount() - maxCount;
var rv = [];
for (var i = start; i < l; i++) {
rv.push(this.get(i));
}
return rv;
};
/**
* @return {Array} The indexes in the buffer.
*/
goog.structs.CircularBuffer.prototype.getKeys = function() {
var rv = [];
var l = this.getCount();
for (var i = 0; i < l; i++) {
rv[i] = i;
}
return rv;
};
/**
* Whether the buffer contains the key/index.
* @param {number} key The key/index to check for.
* @return {boolean} Whether the buffer contains the key/index.
*/
goog.structs.CircularBuffer.prototype.containsKey = function(key) {
return key < this.getCount();
};
/**
* Whether the buffer contains the given value.
* @param {*} value The value to check for.
* @return {boolean} Whether the buffer contains the given value.
*/
goog.structs.CircularBuffer.prototype.containsValue = function(value) {
var l = this.getCount();
for (var i = 0; i < l; i++) {
if (this.get(i) == value) {
return true;
}
}
return false;
};
/**
* Returns the last item inserted into the buffer.
* @return {*} The last item inserted into the buffer, or null if the buffer is
* empty.
*/
goog.structs.CircularBuffer.prototype.getLast = function() {
if (this.getCount() == 0) {
return null;
}
return this.get(this.getCount() - 1);
};
/**
* Helper function to convert an index in the number space of oldest to
* newest items in the array to the position that the element will be at in the
* underlying array.
* @param {number} index The index of the item in a list ordered from oldest to
* newest.
* @return {number} The index of the item in the CircularBuffer's underlying
* array.
* @private
*/
goog.structs.CircularBuffer.prototype.normalizeIndex_ = function(index) {
if (index >= this.buff_.length) {
throw Error('Out of bounds exception');
}
if (this.buff_.length < this.maxSize_) {
return index;
}
return (this.nextPtr_ + Number(index)) % this.maxSize_;
};
| metamolecular/closure-library | closure/goog/structs/circularbuffer.js | JavaScript | apache-2.0 | 5,746 |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for SavedModel Reader."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from tensorflow.contrib.saved_model.python.saved_model import reader
from tensorflow.python.framework import ops
from tensorflow.python.lib.io import file_io
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.saved_model import builder as saved_model_builder
from tensorflow.python.saved_model import tag_constants
def tearDownModule():
file_io.delete_recursively(test.get_temp_dir())
class ReaderTest(test.TestCase):
def _init_and_validate_variable(self, sess, variable_name, variable_value):
v = variables.Variable(variable_value, name=variable_name)
sess.run(variables.global_variables_initializer())
self.assertEqual(variable_value, v.eval())
def testReadSavedModelValid(self):
saved_model_dir = os.path.join(test.get_temp_dir(), "valid_saved_model")
builder = saved_model_builder.SavedModelBuilder(saved_model_dir)
with self.test_session(graph=ops.Graph()) as sess:
self._init_and_validate_variable(sess, "v", 42)
builder.add_meta_graph_and_variables(sess, [tag_constants.TRAINING])
builder.save()
actual_saved_model_pb = reader.read_saved_model(saved_model_dir)
self.assertEqual(len(actual_saved_model_pb.meta_graphs), 1)
self.assertEqual(
len(actual_saved_model_pb.meta_graphs[0].meta_info_def.tags), 1)
self.assertEqual(actual_saved_model_pb.meta_graphs[0].meta_info_def.tags[0],
tag_constants.TRAINING)
def testReadSavedModelInvalid(self):
saved_model_dir = os.path.join(test.get_temp_dir(), "invalid_saved_model")
with self.assertRaisesRegexp(
IOError, "SavedModel file does not exist at: %s" % saved_model_dir):
reader.read_saved_model(saved_model_dir)
def testGetSavedModelTagSets(self):
saved_model_dir = os.path.join(test.get_temp_dir(), "test_tags")
builder = saved_model_builder.SavedModelBuilder(saved_model_dir)
# Graph with a single variable. SavedModel invoked to:
# - add with weights.
# - a single tag (from predefined constants).
with self.test_session(graph=ops.Graph()) as sess:
self._init_and_validate_variable(sess, "v", 42)
builder.add_meta_graph_and_variables(sess, [tag_constants.TRAINING])
# Graph that updates the single variable. SavedModel invoked to:
# - simply add the model (weights are not updated).
# - a single tag (from predefined constants).
with self.test_session(graph=ops.Graph()) as sess:
self._init_and_validate_variable(sess, "v", 43)
builder.add_meta_graph([tag_constants.SERVING])
# Graph that updates the single variable. SavedModel is invoked:
# - to add the model (weights are not updated).
# - multiple predefined tags.
with self.test_session(graph=ops.Graph()) as sess:
self._init_and_validate_variable(sess, "v", 44)
builder.add_meta_graph([tag_constants.SERVING, tag_constants.GPU])
# Graph that updates the single variable. SavedModel is invoked:
# - to add the model (weights are not updated).
# - multiple predefined tags for serving on TPU.
with self.test_session(graph=ops.Graph()) as sess:
self._init_and_validate_variable(sess, "v", 44)
builder.add_meta_graph([tag_constants.SERVING, tag_constants.TPU])
# Graph that updates the single variable. SavedModel is invoked:
# - to add the model (weights are not updated).
# - multiple custom tags.
with self.test_session(graph=ops.Graph()) as sess:
self._init_and_validate_variable(sess, "v", 45)
builder.add_meta_graph(["foo", "bar"])
# Save the SavedModel to disk.
builder.save()
actual_tags = reader.get_saved_model_tag_sets(saved_model_dir)
expected_tags = [["train"], ["serve"], ["serve", "gpu"], ["serve", "tpu"],
["foo", "bar"]]
self.assertEqual(expected_tags, actual_tags)
if __name__ == "__main__":
test.main()
| jalexvig/tensorflow | tensorflow/contrib/saved_model/python/saved_model/reader_test.py | Python | apache-2.0 | 4,761 |
/*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.memcache.binary;
import io.netty.channel.CombinedChannelDuplexHandler;
import io.netty.util.internal.UnstableApi;
/**
* The full server codec that combines the correct encoder and decoder.
* <p/>
* Use this codec if you need to implement a server that speaks the memcache binary protocol.
* Internally, it combines the {@link BinaryMemcacheRequestDecoder} and the
* {@link BinaryMemcacheResponseEncoder} to request decoding and response encoding.
*/
@UnstableApi
public class BinaryMemcacheServerCodec extends
CombinedChannelDuplexHandler<BinaryMemcacheRequestDecoder, BinaryMemcacheResponseEncoder> {
public BinaryMemcacheServerCodec() {
this(AbstractBinaryMemcacheDecoder.DEFAULT_MAX_CHUNK_SIZE);
}
public BinaryMemcacheServerCodec(int decodeChunkSize) {
super(new BinaryMemcacheRequestDecoder(decodeChunkSize), new BinaryMemcacheResponseEncoder());
}
}
| wangcy6/storm_app | frame/java/netty-4.1/codec-memcache/src/main/java/io/netty/handler/codec/memcache/binary/BinaryMemcacheServerCodec.java | Java | apache-2.0 | 1,572 |
// Copyright JS Foundation and other contributors, http://js.foundation
//
// 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.
var a = new String('example')
var c = 'length' in a
assert(c) | bsdelf/jerryscript | tests/jerry-test-suite/11/11.08/11.08.07/11.08.07-011.js | JavaScript | apache-2.0 | 691 |
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// test bitset<N>& set(size_t pos, bool val = true);
#include <bitset>
#include <cassert>
template <std::size_t N>
void test_set_one()
{
std::bitset<N> v;
try
{
v.set(50);
if (50 >= v.size())
assert(false);
assert(v[50]);
}
catch (std::out_of_range&)
{
}
try
{
v.set(50, false);
if (50 >= v.size())
assert(false);
assert(!v[50]);
}
catch (std::out_of_range&)
{
}
}
int main()
{
test_set_one<0>();
test_set_one<1>();
test_set_one<31>();
test_set_one<32>();
test_set_one<33>();
test_set_one<63>();
test_set_one<64>();
test_set_one<65>();
test_set_one<1000>();
}
| mxOBS/deb-pkg_trusty_chromium-browser | third_party/libc++/trunk/test/utilities/template.bitset/bitset.members/set_one.pass.cpp | C++ | bsd-3-clause | 1,080 |
// RUN: %clang_cc1 -fexceptions -fcxx-exceptions -std=c++1z -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s
// CHECK-LABEL: define {{.*}} @_Z11builtin_newm(
// CHECK: call {{.*}} @_Znwm(
void *builtin_new(unsigned long n) { return __builtin_operator_new(n); }
// CHECK-LABEL: define {{.*}} @_Z14builtin_deletePv(
// CHECK: call {{.*}} @_ZdlPv(
void builtin_delete(void *p) { return __builtin_operator_delete(p); }
| endlessm/chromium-browser | third_party/llvm/clang/test/CodeGenCXX/cxx1z-noexcept-function-type.cpp | C++ | bsd-3-clause | 427 |
// RUN: %clang -g -std=c++11 -S -emit-llvm %s -o - | FileCheck %s
template<typename T>
struct foo {
};
namespace x {
// splitting these over multiple lines to make sure the right token is used for
// the location
template<typename T>
using
# 42
bar
= foo<T*>;
}
// CHECK: !DIGlobalVariable(name: "bi",{{.*}} type: [[BINT:![0-9]+]]
x::bar<int> bi;
// CHECK: !DIGlobalVariable(name: "bf",{{.*}} type: [[BFLOAT:![0-9]+]]
// CHECK: [[BFLOAT]] = !DIDerivedType(tag: DW_TAG_typedef, name: "bar<float>"
x::bar<float> bf;
using
// CHECK: !DIGlobalVariable(name: "n",{{.*}} type: [[NARF:![0-9]+]]
# 142
narf // CHECK: [[NARF]] = !DIDerivedType(tag: DW_TAG_typedef, name: "narf"
// CHECK-SAME: line: 142
= int;
narf n;
template <typename T>
using tv = void;
// CHECK: !DIDerivedType(tag: DW_TAG_typedef, name: "tv<int>"
tv<int> *tvp;
using v = void;
// CHECK: !DIDerivedType(tag: DW_TAG_typedef, name: "v"
v *vp;
// CHECK: [[BINT]] = !DIDerivedType(tag: DW_TAG_typedef, name: "bar<int>"
// CHECK-SAME: line: 42,
| endlessm/chromium-browser | third_party/llvm/clang/test/CodeGenCXX/debug-info-alias.cpp | C++ | bsd-3-clause | 1,055 |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file and, per its terms, should not be removed:
*
* Copyright (c) 2004 World Wide Web Consortium,
*
* (Massachusetts Institute of Technology, European Research Consortium for
* Informatics and Mathematics, Keio University). All Rights Reserved. This
* work is distributed under the W3C(r) Software License [1] 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.
*
* [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
*/
package org.w3c.dom;
/**
* The <code>Document</code> interface represents the entire HTML or XML
* document. Conceptually, it is the root of the document tree, and provides
* the primary access to the document's data.
* <p>Since elements, text nodes, comments, processing instructions, etc.
* cannot exist outside the context of a <code>Document</code>, the
* <code>Document</code> interface also contains the factory methods needed
* to create these objects. The <code>Node</code> objects created have a
* <code>ownerDocument</code> attribute which associates them with the
* <code>Document</code> within whose context they were created.
* <p>See also the <a href='http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407'>Document Object Model (DOM) Level 3 Core Specification</a>.
*/
public interface Document extends Node {
/**
* The Document Type Declaration (see <code>DocumentType</code>)
* associated with this document. For XML documents without a document
* type declaration this returns <code>null</code>. For HTML documents,
* a <code>DocumentType</code> object may be returned, independently of
* the presence or absence of document type declaration in the HTML
* document.
* <br>This provides direct access to the <code>DocumentType</code> node,
* child node of this <code>Document</code>. This node can be set at
* document creation time and later changed through the use of child
* nodes manipulation methods, such as <code>Node.insertBefore</code>,
* or <code>Node.replaceChild</code>. Note, however, that while some
* implementations may instantiate different types of
* <code>Document</code> objects supporting additional features than the
* "Core", such as "HTML" [<a href='http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109'>DOM Level 2 HTML</a>]
* , based on the <code>DocumentType</code> specified at creation time,
* changing it afterwards is very unlikely to result in a change of the
* features supported.
*
* @since DOM Level 3
*/
public DocumentType getDoctype();
/**
* The <code>DOMImplementation</code> object that handles this document. A
* DOM application may use objects from multiple implementations.
*/
public DOMImplementation getImplementation();
/**
* This is a convenience attribute that allows direct access to the child
* node that is the document element of the document.
*/
public Element getDocumentElement();
/**
* Creates an element of the type specified. Note that the instance
* returned implements the <code>Element</code> interface, so attributes
* can be specified directly on the returned object.
* <br>In addition, if there are known attributes with default values,
* <code>Attr</code> nodes representing them are automatically created
* and attached to the element.
* <br>To create an element with a qualified name and namespace URI, use
* the <code>createElementNS</code> method.
* @param tagName The name of the element type to instantiate. For XML,
* this is case-sensitive, otherwise it depends on the
* case-sensitivity of the markup language in use. In that case, the
* name is mapped to the canonical form of that markup by the DOM
* implementation.
* @return A new <code>Element</code> object with the
* <code>nodeName</code> attribute set to <code>tagName</code>, and
* <code>localName</code>, <code>prefix</code>, and
* <code>namespaceURI</code> set to <code>null</code>.
* @exception DOMException
* INVALID_CHARACTER_ERR: Raised if the specified name is not an XML
* name according to the XML version in use specified in the
* <code>Document.xmlVersion</code> attribute.
*/
public Element createElement(String tagName)
throws DOMException;
/**
* Creates an empty <code>DocumentFragment</code> object.
* @return A new <code>DocumentFragment</code>.
*/
public DocumentFragment createDocumentFragment();
/**
* Creates a <code>Text</code> node given the specified string.
* @param data The data for the node.
* @return The new <code>Text</code> object.
*/
public Text createTextNode(String data);
/**
* Creates a <code>Comment</code> node given the specified string.
* @param data The data for the node.
* @return The new <code>Comment</code> object.
*/
public Comment createComment(String data);
/**
* Creates a <code>CDATASection</code> node whose value is the specified
* string.
* @param data The data for the <code>CDATASection</code> contents.
* @return The new <code>CDATASection</code> object.
* @exception DOMException
* NOT_SUPPORTED_ERR: Raised if this document is an HTML document.
*/
public CDATASection createCDATASection(String data)
throws DOMException;
/**
* Creates a <code>ProcessingInstruction</code> node given the specified
* name and data strings.
* @param target The target part of the processing instruction.Unlike
* <code>Document.createElementNS</code> or
* <code>Document.createAttributeNS</code>, no namespace well-formed
* checking is done on the target name. Applications should invoke
* <code>Document.normalizeDocument()</code> with the parameter "
* namespaces" set to <code>true</code> in order to ensure that the
* target name is namespace well-formed.
* @param data The data for the node.
* @return The new <code>ProcessingInstruction</code> object.
* @exception DOMException
* INVALID_CHARACTER_ERR: Raised if the specified target is not an XML
* name according to the XML version in use specified in the
* <code>Document.xmlVersion</code> attribute.
* <br>NOT_SUPPORTED_ERR: Raised if this document is an HTML document.
*/
public ProcessingInstruction createProcessingInstruction(String target,
String data)
throws DOMException;
/**
* Creates an <code>Attr</code> of the given name. Note that the
* <code>Attr</code> instance can then be set on an <code>Element</code>
* using the <code>setAttributeNode</code> method.
* <br>To create an attribute with a qualified name and namespace URI, use
* the <code>createAttributeNS</code> method.
* @param name The name of the attribute.
* @return A new <code>Attr</code> object with the <code>nodeName</code>
* attribute set to <code>name</code>, and <code>localName</code>,
* <code>prefix</code>, and <code>namespaceURI</code> set to
* <code>null</code>. The value of the attribute is the empty string.
* @exception DOMException
* INVALID_CHARACTER_ERR: Raised if the specified name is not an XML
* name according to the XML version in use specified in the
* <code>Document.xmlVersion</code> attribute.
*/
public Attr createAttribute(String name)
throws DOMException;
/**
* Creates an <code>EntityReference</code> object. In addition, if the
* referenced entity is known, the child list of the
* <code>EntityReference</code> node is made the same as that of the
* corresponding <code>Entity</code> node.
* <p ><b>Note:</b> If any descendant of the <code>Entity</code> node has
* an unbound namespace prefix, the corresponding descendant of the
* created <code>EntityReference</code> node is also unbound; (its
* <code>namespaceURI</code> is <code>null</code>). The DOM Level 2 and
* 3 do not support any mechanism to resolve namespace prefixes in this
* case.
* @param name The name of the entity to reference.Unlike
* <code>Document.createElementNS</code> or
* <code>Document.createAttributeNS</code>, no namespace well-formed
* checking is done on the entity name. Applications should invoke
* <code>Document.normalizeDocument()</code> with the parameter "
* namespaces" set to <code>true</code> in order to ensure that the
* entity name is namespace well-formed.
* @return The new <code>EntityReference</code> object.
* @exception DOMException
* INVALID_CHARACTER_ERR: Raised if the specified name is not an XML
* name according to the XML version in use specified in the
* <code>Document.xmlVersion</code> attribute.
* <br>NOT_SUPPORTED_ERR: Raised if this document is an HTML document.
*/
public EntityReference createEntityReference(String name)
throws DOMException;
/**
* Returns a <code>NodeList</code> of all the <code>Elements</code> in
* document order with a given tag name and are contained in the
* document.
* @param tagname The name of the tag to match on. The special value "*"
* matches all tags. For XML, the <code>tagname</code> parameter is
* case-sensitive, otherwise it depends on the case-sensitivity of the
* markup language in use.
* @return A new <code>NodeList</code> object containing all the matched
* <code>Elements</code>.
*/
public NodeList getElementsByTagName(String tagname);
/**
* Imports a node from another document to this document, without altering
* or removing the source node from the original document; this method
* creates a new copy of the source node. The returned node has no
* parent; (<code>parentNode</code> is <code>null</code>).
* <br>For all nodes, importing a node creates a node object owned by the
* importing document, with attribute values identical to the source
* node's <code>nodeName</code> and <code>nodeType</code>, plus the
* attributes related to namespaces (<code>prefix</code>,
* <code>localName</code>, and <code>namespaceURI</code>). As in the
* <code>cloneNode</code> operation, the source node is not altered.
* User data associated to the imported node is not carried over.
* However, if any <code>UserDataHandlers</code> has been specified
* along with the associated data these handlers will be called with the
* appropriate parameters before this method returns.
* <br>Additional information is copied as appropriate to the
* <code>nodeType</code>, attempting to mirror the behavior expected if
* a fragment of XML or HTML source was copied from one document to
* another, recognizing that the two documents may have different DTDs
* in the XML case. The following list describes the specifics for each
* type of node.
* <dl>
* <dt>ATTRIBUTE_NODE</dt>
* <dd>The <code>ownerElement</code> attribute
* is set to <code>null</code> and the <code>specified</code> flag is
* set to <code>true</code> on the generated <code>Attr</code>. The
* descendants of the source <code>Attr</code> are recursively imported
* and the resulting nodes reassembled to form the corresponding subtree.
* Note that the <code>deep</code> parameter has no effect on
* <code>Attr</code> nodes; they always carry their children with them
* when imported.</dd>
* <dt>DOCUMENT_FRAGMENT_NODE</dt>
* <dd>If the <code>deep</code> option
* was set to <code>true</code>, the descendants of the source
* <code>DocumentFragment</code> are recursively imported and the
* resulting nodes reassembled under the imported
* <code>DocumentFragment</code> to form the corresponding subtree.
* Otherwise, this simply generates an empty
* <code>DocumentFragment</code>.</dd>
* <dt>DOCUMENT_NODE</dt>
* <dd><code>Document</code>
* nodes cannot be imported.</dd>
* <dt>DOCUMENT_TYPE_NODE</dt>
* <dd><code>DocumentType</code>
* nodes cannot be imported.</dd>
* <dt>ELEMENT_NODE</dt>
* <dd><em>Specified</em> attribute nodes of the source element are imported, and the generated
* <code>Attr</code> nodes are attached to the generated
* <code>Element</code>. Default attributes are <em>not</em> copied, though if the document being imported into defines default
* attributes for this element name, those are assigned. If the
* <code>importNode</code> <code>deep</code> parameter was set to
* <code>true</code>, the descendants of the source element are
* recursively imported and the resulting nodes reassembled to form the
* corresponding subtree.</dd>
* <dt>ENTITY_NODE</dt>
* <dd><code>Entity</code> nodes can be
* imported, however in the current release of the DOM the
* <code>DocumentType</code> is readonly. Ability to add these imported
* nodes to a <code>DocumentType</code> will be considered for addition
* to a future release of the DOM.On import, the <code>publicId</code>,
* <code>systemId</code>, and <code>notationName</code> attributes are
* copied. If a <code>deep</code> import is requested, the descendants
* of the the source <code>Entity</code> are recursively imported and
* the resulting nodes reassembled to form the corresponding subtree.</dd>
* <dt>
* ENTITY_REFERENCE_NODE</dt>
* <dd>Only the <code>EntityReference</code> itself is
* copied, even if a <code>deep</code> import is requested, since the
* source and destination documents might have defined the entity
* differently. If the document being imported into provides a
* definition for this entity name, its value is assigned.</dd>
* <dt>NOTATION_NODE</dt>
* <dd>
* <code>Notation</code> nodes can be imported, however in the current
* release of the DOM the <code>DocumentType</code> is readonly. Ability
* to add these imported nodes to a <code>DocumentType</code> will be
* considered for addition to a future release of the DOM.On import, the
* <code>publicId</code> and <code>systemId</code> attributes are copied.
* Note that the <code>deep</code> parameter has no effect on this type
* of nodes since they cannot have any children.</dd>
* <dt>
* PROCESSING_INSTRUCTION_NODE</dt>
* <dd>The imported node copies its
* <code>target</code> and <code>data</code> values from those of the
* source node.Note that the <code>deep</code> parameter has no effect
* on this type of nodes since they cannot have any children.</dd>
* <dt>TEXT_NODE,
* CDATA_SECTION_NODE, COMMENT_NODE</dt>
* <dd>These three types of nodes inheriting
* from <code>CharacterData</code> copy their <code>data</code> and
* <code>length</code> attributes from those of the source node.Note
* that the <code>deep</code> parameter has no effect on these types of
* nodes since they cannot have any children.</dd>
* </dl>
* @param importedNode The node to import.
* @param deep If <code>true</code>, recursively import the subtree under
* the specified node; if <code>false</code>, import only the node
* itself, as explained above. This has no effect on nodes that cannot
* have any children, and on <code>Attr</code>, and
* <code>EntityReference</code> nodes.
* @return The imported node that belongs to this <code>Document</code>.
* @exception DOMException
* NOT_SUPPORTED_ERR: Raised if the type of node being imported is not
* supported.
* <br>INVALID_CHARACTER_ERR: Raised if one of the imported names is not
* an XML name according to the XML version in use specified in the
* <code>Document.xmlVersion</code> attribute. This may happen when
* importing an XML 1.1 [<a href='http://www.w3.org/TR/2004/REC-xml11-20040204/'>XML 1.1</a>] element
* into an XML 1.0 document, for instance.
* @since DOM Level 2
*/
public Node importNode(Node importedNode,
boolean deep)
throws DOMException;
/**
* Creates an element of the given qualified name and namespace URI.
* <br>Per [<a href='http://www.w3.org/TR/1999/REC-xml-names-19990114/'>XML Namespaces</a>]
* , applications must use the value <code>null</code> as the
* namespaceURI parameter for methods if they wish to have no namespace.
* @param namespaceURI The namespace URI of the element to create.
* @param qualifiedName The qualified name of the element type to
* instantiate.
* @return A new <code>Element</code> object with the following
* attributes:
* <table border='1' cellpadding='3'>
* <tr>
* <th>Attribute</th>
* <th>Value</th>
* </tr>
* <tr>
* <td valign='top' rowspan='1' colspan='1'><code>Node.nodeName</code></td>
* <td valign='top' rowspan='1' colspan='1'>
* <code>qualifiedName</code></td>
* </tr>
* <tr>
* <td valign='top' rowspan='1' colspan='1'><code>Node.namespaceURI</code></td>
* <td valign='top' rowspan='1' colspan='1'>
* <code>namespaceURI</code></td>
* </tr>
* <tr>
* <td valign='top' rowspan='1' colspan='1'><code>Node.prefix</code></td>
* <td valign='top' rowspan='1' colspan='1'>prefix, extracted
* from <code>qualifiedName</code>, or <code>null</code> if there is
* no prefix</td>
* </tr>
* <tr>
* <td valign='top' rowspan='1' colspan='1'><code>Node.localName</code></td>
* <td valign='top' rowspan='1' colspan='1'>local name, extracted from
* <code>qualifiedName</code></td>
* </tr>
* <tr>
* <td valign='top' rowspan='1' colspan='1'><code>Element.tagName</code></td>
* <td valign='top' rowspan='1' colspan='1'>
* <code>qualifiedName</code></td>
* </tr>
* </table>
* @exception DOMException
* INVALID_CHARACTER_ERR: Raised if the specified
* <code>qualifiedName</code> is not an XML name according to the XML
* version in use specified in the <code>Document.xmlVersion</code>
* attribute.
* <br>NAMESPACE_ERR: Raised if the <code>qualifiedName</code> is a
* malformed qualified name, if the <code>qualifiedName</code> has a
* prefix and the <code>namespaceURI</code> is <code>null</code>, or
* if the <code>qualifiedName</code> has a prefix that is "xml" and
* the <code>namespaceURI</code> is different from "<a href='http://www.w3.org/XML/1998/namespace'>
* http://www.w3.org/XML/1998/namespace</a>" [<a href='http://www.w3.org/TR/1999/REC-xml-names-19990114/'>XML Namespaces</a>]
* , or if the <code>qualifiedName</code> or its prefix is "xmlns" and
* the <code>namespaceURI</code> is different from "<a href='http://www.w3.org/2000/xmlns/'>http://www.w3.org/2000/xmlns/</a>", or if the <code>namespaceURI</code> is "<a href='http://www.w3.org/2000/xmlns/'>http://www.w3.org/2000/xmlns/</a>" and neither the <code>qualifiedName</code> nor its prefix is "xmlns".
* <br>NOT_SUPPORTED_ERR: Always thrown if the current document does not
* support the <code>"XML"</code> feature, since namespaces were
* defined by XML.
* @since DOM Level 2
*/
public Element createElementNS(String namespaceURI,
String qualifiedName)
throws DOMException;
/**
* Creates an attribute of the given qualified name and namespace URI.
* <br>Per [<a href='http://www.w3.org/TR/1999/REC-xml-names-19990114/'>XML Namespaces</a>]
* , applications must use the value <code>null</code> as the
* <code>namespaceURI</code> parameter for methods if they wish to have
* no namespace.
* @param namespaceURI The namespace URI of the attribute to create.
* @param qualifiedName The qualified name of the attribute to
* instantiate.
* @return A new <code>Attr</code> object with the following attributes:
* <table border='1' cellpadding='3'>
* <tr>
* <th>
* Attribute</th>
* <th>Value</th>
* </tr>
* <tr>
* <td valign='top' rowspan='1' colspan='1'><code>Node.nodeName</code></td>
* <td valign='top' rowspan='1' colspan='1'>qualifiedName</td>
* </tr>
* <tr>
* <td valign='top' rowspan='1' colspan='1'>
* <code>Node.namespaceURI</code></td>
* <td valign='top' rowspan='1' colspan='1'><code>namespaceURI</code></td>
* </tr>
* <tr>
* <td valign='top' rowspan='1' colspan='1'>
* <code>Node.prefix</code></td>
* <td valign='top' rowspan='1' colspan='1'>prefix, extracted from
* <code>qualifiedName</code>, or <code>null</code> if there is no
* prefix</td>
* </tr>
* <tr>
* <td valign='top' rowspan='1' colspan='1'><code>Node.localName</code></td>
* <td valign='top' rowspan='1' colspan='1'>local name, extracted from
* <code>qualifiedName</code></td>
* </tr>
* <tr>
* <td valign='top' rowspan='1' colspan='1'><code>Attr.name</code></td>
* <td valign='top' rowspan='1' colspan='1'>
* <code>qualifiedName</code></td>
* </tr>
* <tr>
* <td valign='top' rowspan='1' colspan='1'><code>Node.nodeValue</code></td>
* <td valign='top' rowspan='1' colspan='1'>the empty
* string</td>
* </tr>
* </table>
* @exception DOMException
* INVALID_CHARACTER_ERR: Raised if the specified
* <code>qualifiedName</code> is not an XML name according to the XML
* version in use specified in the <code>Document.xmlVersion</code>
* attribute.
* <br>NAMESPACE_ERR: Raised if the <code>qualifiedName</code> is a
* malformed qualified name, if the <code>qualifiedName</code> has a
* prefix and the <code>namespaceURI</code> is <code>null</code>, if
* the <code>qualifiedName</code> has a prefix that is "xml" and the
* <code>namespaceURI</code> is different from "<a href='http://www.w3.org/XML/1998/namespace'>
* http://www.w3.org/XML/1998/namespace</a>", if the <code>qualifiedName</code> or its prefix is "xmlns" and the
* <code>namespaceURI</code> is different from "<a href='http://www.w3.org/2000/xmlns/'>http://www.w3.org/2000/xmlns/</a>", or if the <code>namespaceURI</code> is "<a href='http://www.w3.org/2000/xmlns/'>http://www.w3.org/2000/xmlns/</a>" and neither the <code>qualifiedName</code> nor its prefix is "xmlns".
* <br>NOT_SUPPORTED_ERR: Always thrown if the current document does not
* support the <code>"XML"</code> feature, since namespaces were
* defined by XML.
* @since DOM Level 2
*/
public Attr createAttributeNS(String namespaceURI,
String qualifiedName)
throws DOMException;
/**
* Returns a <code>NodeList</code> of all the <code>Elements</code> with a
* given local name and namespace URI in document order.
* @param namespaceURI The namespace URI of the elements to match on. The
* special value <code>"*"</code> matches all namespaces.
* @param localName The local name of the elements to match on. The
* special value "*" matches all local names.
* @return A new <code>NodeList</code> object containing all the matched
* <code>Elements</code>.
* @since DOM Level 2
*/
public NodeList getElementsByTagNameNS(String namespaceURI,
String localName);
/**
* Returns the <code>Element</code> that has an ID attribute with the
* given value. If no such element exists, this returns <code>null</code>
* . If more than one element has an ID attribute with that value, what
* is returned is undefined.
* <br> The DOM implementation is expected to use the attribute
* <code>Attr.isId</code> to determine if an attribute is of type ID.
* <p ><b>Note:</b> Attributes with the name "ID" or "id" are not of type
* ID unless so defined.
* @param elementId The unique <code>id</code> value for an element.
* @return The matching element or <code>null</code> if there is none.
* @since DOM Level 2
*/
public Element getElementById(String elementId);
/**
* An attribute specifying the encoding used for this document at the time
* of the parsing. This is <code>null</code> when it is not known, such
* as when the <code>Document</code> was created in memory.
* @since DOM Level 3
*/
public String getInputEncoding();
/**
* An attribute specifying, as part of the <a href='http://www.w3.org/TR/2004/REC-xml-20040204#NT-XMLDecl'>XML declaration</a>, the encoding of this document. This is <code>null</code> when
* unspecified or when it is not known, such as when the
* <code>Document</code> was created in memory.
* @since DOM Level 3
*/
public String getXmlEncoding();
/**
* An attribute specifying, as part of the <a href='http://www.w3.org/TR/2004/REC-xml-20040204#NT-XMLDecl'>XML declaration</a>, whether this document is standalone. This is <code>false</code> when
* unspecified.
* <p ><b>Note:</b> No verification is done on the value when setting
* this attribute. Applications should use
* <code>Document.normalizeDocument()</code> with the "validate"
* parameter to verify if the value matches the <a href='http://www.w3.org/TR/2004/REC-xml-20040204#sec-rmd'>validity
* constraint for standalone document declaration</a> as defined in [<a href='http://www.w3.org/TR/2004/REC-xml-20040204'>XML 1.0</a>].
* @since DOM Level 3
*/
public boolean getXmlStandalone();
/**
* An attribute specifying, as part of the <a href='http://www.w3.org/TR/2004/REC-xml-20040204#NT-XMLDecl'>XML declaration</a>, whether this document is standalone. This is <code>false</code> when
* unspecified.
* <p ><b>Note:</b> No verification is done on the value when setting
* this attribute. Applications should use
* <code>Document.normalizeDocument()</code> with the "validate"
* parameter to verify if the value matches the <a href='http://www.w3.org/TR/2004/REC-xml-20040204#sec-rmd'>validity
* constraint for standalone document declaration</a> as defined in [<a href='http://www.w3.org/TR/2004/REC-xml-20040204'>XML 1.0</a>].
* @exception DOMException
* NOT_SUPPORTED_ERR: Raised if this document does not support the
* "XML" feature.
* @since DOM Level 3
*/
public void setXmlStandalone(boolean xmlStandalone)
throws DOMException;
/**
* An attribute specifying, as part of the <a href='http://www.w3.org/TR/2004/REC-xml-20040204#NT-XMLDecl'>XML declaration</a>, the version number of this document. If there is no declaration and if
* this document supports the "XML" feature, the value is
* <code>"1.0"</code>. If this document does not support the "XML"
* feature, the value is always <code>null</code>. Changing this
* attribute will affect methods that check for invalid characters in
* XML names. Application should invoke
* <code>Document.normalizeDocument()</code> in order to check for
* invalid characters in the <code>Node</code>s that are already part of
* this <code>Document</code>.
* <br> DOM applications may use the
* <code>DOMImplementation.hasFeature(feature, version)</code> method
* with parameter values "XMLVersion" and "1.0" (respectively) to
* determine if an implementation supports [<a href='http://www.w3.org/TR/2004/REC-xml-20040204'>XML 1.0</a>]. DOM
* applications may use the same method with parameter values
* "XMLVersion" and "1.1" (respectively) to determine if an
* implementation supports [<a href='http://www.w3.org/TR/2004/REC-xml11-20040204/'>XML 1.1</a>]. In both
* cases, in order to support XML, an implementation must also support
* the "XML" feature defined in this specification. <code>Document</code>
* objects supporting a version of the "XMLVersion" feature must not
* raise a <code>NOT_SUPPORTED_ERR</code> exception for the same version
* number when using <code>Document.xmlVersion</code>.
* @since DOM Level 3
*/
public String getXmlVersion();
/**
* An attribute specifying, as part of the <a href='http://www.w3.org/TR/2004/REC-xml-20040204#NT-XMLDecl'>XML declaration</a>, the version number of this document. If there is no declaration and if
* this document supports the "XML" feature, the value is
* <code>"1.0"</code>. If this document does not support the "XML"
* feature, the value is always <code>null</code>. Changing this
* attribute will affect methods that check for invalid characters in
* XML names. Application should invoke
* <code>Document.normalizeDocument()</code> in order to check for
* invalid characters in the <code>Node</code>s that are already part of
* this <code>Document</code>.
* <br> DOM applications may use the
* <code>DOMImplementation.hasFeature(feature, version)</code> method
* with parameter values "XMLVersion" and "1.0" (respectively) to
* determine if an implementation supports [<a href='http://www.w3.org/TR/2004/REC-xml-20040204'>XML 1.0</a>]. DOM
* applications may use the same method with parameter values
* "XMLVersion" and "1.1" (respectively) to determine if an
* implementation supports [<a href='http://www.w3.org/TR/2004/REC-xml11-20040204/'>XML 1.1</a>]. In both
* cases, in order to support XML, an implementation must also support
* the "XML" feature defined in this specification. <code>Document</code>
* objects supporting a version of the "XMLVersion" feature must not
* raise a <code>NOT_SUPPORTED_ERR</code> exception for the same version
* number when using <code>Document.xmlVersion</code>.
* @exception DOMException
* NOT_SUPPORTED_ERR: Raised if the version is set to a value that is
* not supported by this <code>Document</code> or if this document
* does not support the "XML" feature.
* @since DOM Level 3
*/
public void setXmlVersion(String xmlVersion)
throws DOMException;
/**
* An attribute specifying whether error checking is enforced or not. When
* set to <code>false</code>, the implementation is free to not test
* every possible error case normally defined on DOM operations, and not
* raise any <code>DOMException</code> on DOM operations or report
* errors while using <code>Document.normalizeDocument()</code>. In case
* of error, the behavior is undefined. This attribute is
* <code>true</code> by default.
* @since DOM Level 3
*/
public boolean getStrictErrorChecking();
/**
* An attribute specifying whether error checking is enforced or not. When
* set to <code>false</code>, the implementation is free to not test
* every possible error case normally defined on DOM operations, and not
* raise any <code>DOMException</code> on DOM operations or report
* errors while using <code>Document.normalizeDocument()</code>. In case
* of error, the behavior is undefined. This attribute is
* <code>true</code> by default.
* @since DOM Level 3
*/
public void setStrictErrorChecking(boolean strictErrorChecking);
/**
* The location of the document or <code>null</code> if undefined or if
* the <code>Document</code> was created using
* <code>DOMImplementation.createDocument</code>. No lexical checking is
* performed when setting this attribute; this could result in a
* <code>null</code> value returned when using <code>Node.baseURI</code>
* .
* <br> Beware that when the <code>Document</code> supports the feature
* "HTML" [<a href='http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109'>DOM Level 2 HTML</a>]
* , the href attribute of the HTML BASE element takes precedence over
* this attribute when computing <code>Node.baseURI</code>.
* @since DOM Level 3
*/
public String getDocumentURI();
/**
* The location of the document or <code>null</code> if undefined or if
* the <code>Document</code> was created using
* <code>DOMImplementation.createDocument</code>. No lexical checking is
* performed when setting this attribute; this could result in a
* <code>null</code> value returned when using <code>Node.baseURI</code>
* .
* <br> Beware that when the <code>Document</code> supports the feature
* "HTML" [<a href='http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109'>DOM Level 2 HTML</a>]
* , the href attribute of the HTML BASE element takes precedence over
* this attribute when computing <code>Node.baseURI</code>.
* @since DOM Level 3
*/
public void setDocumentURI(String documentURI);
/**
* Attempts to adopt a node from another document to this document. If
* supported, it changes the <code>ownerDocument</code> of the source
* node, its children, as well as the attached attribute nodes if there
* are any. If the source node has a parent it is first removed from the
* child list of its parent. This effectively allows moving a subtree
* from one document to another (unlike <code>importNode()</code> which
* create a copy of the source node instead of moving it). When it
* fails, applications should use <code>Document.importNode()</code>
* instead. Note that if the adopted node is already part of this
* document (i.e. the source and target document are the same), this
* method still has the effect of removing the source node from the
* child list of its parent, if any. The following list describes the
* specifics for each type of node.
* <dl>
* <dt>ATTRIBUTE_NODE</dt>
* <dd>The
* <code>ownerElement</code> attribute is set to <code>null</code> and
* the <code>specified</code> flag is set to <code>true</code> on the
* adopted <code>Attr</code>. The descendants of the source
* <code>Attr</code> are recursively adopted.</dd>
* <dt>DOCUMENT_FRAGMENT_NODE</dt>
* <dd>The
* descendants of the source node are recursively adopted.</dd>
* <dt>DOCUMENT_NODE</dt>
* <dd>
* <code>Document</code> nodes cannot be adopted.</dd>
* <dt>DOCUMENT_TYPE_NODE</dt>
* <dd>
* <code>DocumentType</code> nodes cannot be adopted.</dd>
* <dt>ELEMENT_NODE</dt>
* <dd><em>Specified</em> attribute nodes of the source element are adopted. Default attributes
* are discarded, though if the document being adopted into defines
* default attributes for this element name, those are assigned. The
* descendants of the source element are recursively adopted.</dd>
* <dt>ENTITY_NODE</dt>
* <dd>
* <code>Entity</code> nodes cannot be adopted.</dd>
* <dt>ENTITY_REFERENCE_NODE</dt>
* <dd>Only
* the <code>EntityReference</code> node itself is adopted, the
* descendants are discarded, since the source and destination documents
* might have defined the entity differently. If the document being
* imported into provides a definition for this entity name, its value
* is assigned.</dd>
* <dt>NOTATION_NODE</dt>
* <dd><code>Notation</code> nodes cannot be
* adopted.</dd>
* <dt>PROCESSING_INSTRUCTION_NODE, TEXT_NODE, CDATA_SECTION_NODE,
* COMMENT_NODE</dt>
* <dd>These nodes can all be adopted. No specifics.</dd>
* </dl>
* <p ><b>Note:</b> Since it does not create new nodes unlike the
* <code>Document.importNode()</code> method, this method does not raise
* an <code>INVALID_CHARACTER_ERR</code> exception, and applications
* should use the <code>Document.normalizeDocument()</code> method to
* check if an imported name is not an XML name according to the XML
* version in use.
* @param source The node to move into this document.
* @return The adopted node, or <code>null</code> if this operation
* fails, such as when the source node comes from a different
* implementation.
* @exception DOMException
* NOT_SUPPORTED_ERR: Raised if the source node is of type
* <code>DOCUMENT</code>, <code>DOCUMENT_TYPE</code>.
* <br>NO_MODIFICATION_ALLOWED_ERR: Raised when the source node is
* readonly.
* @since DOM Level 3
*/
public Node adoptNode(Node source)
throws DOMException;
/**
* The configuration used when <code>Document.normalizeDocument()</code>
* is invoked.
* @since DOM Level 3
*/
public DOMConfiguration getDomConfig();
/**
* This method acts as if the document was going through a save and load
* cycle, putting the document in a "normal" form. As a consequence,
* this method updates the replacement tree of
* <code>EntityReference</code> nodes and normalizes <code>Text</code>
* nodes, as defined in the method <code>Node.normalize()</code>.
* <br> Otherwise, the actual result depends on the features being set on
* the <code>Document.domConfig</code> object and governing what
* operations actually take place. Noticeably this method could also
* make the document namespace well-formed according to the algorithm
* described in , check the character normalization, remove the
* <code>CDATASection</code> nodes, etc. See
* <code>DOMConfiguration</code> for details.
* <pre>// Keep in the document
* the information defined // in the XML Information Set (Java example)
* DOMConfiguration docConfig = myDocument.getDomConfig();
* docConfig.setParameter("infoset", Boolean.TRUE);
* myDocument.normalizeDocument();</pre>
*
* <br>Mutation events, when supported, are generated to reflect the
* changes occurring on the document.
* <br> If errors occur during the invocation of this method, such as an
* attempt to update a read-only node or a <code>Node.nodeName</code>
* contains an invalid character according to the XML version in use,
* errors or warnings (<code>DOMError.SEVERITY_ERROR</code> or
* <code>DOMError.SEVERITY_WARNING</code>) will be reported using the
* <code>DOMErrorHandler</code> object associated with the "error-handler
* " parameter. Note this method might also report fatal errors (
* <code>DOMError.SEVERITY_FATAL_ERROR</code>) if an implementation
* cannot recover from an error.
* @since DOM Level 3
*/
public void normalizeDocument();
/**
* Rename an existing node of type <code>ELEMENT_NODE</code> or
* <code>ATTRIBUTE_NODE</code>.
* <br>When possible this simply changes the name of the given node,
* otherwise this creates a new node with the specified name and
* replaces the existing node with the new node as described below.
* <br>If simply changing the name of the given node is not possible, the
* following operations are performed: a new node is created, any
* registered event listener is registered on the new node, any user
* data attached to the old node is removed from that node, the old node
* is removed from its parent if it has one, the children are moved to
* the new node, if the renamed node is an <code>Element</code> its
* attributes are moved to the new node, the new node is inserted at the
* position the old node used to have in its parent's child nodes list
* if it has one, the user data that was attached to the old node is
* attached to the new node.
* <br>When the node being renamed is an <code>Element</code> only the
* specified attributes are moved, default attributes originated from
* the DTD are updated according to the new element name. In addition,
* the implementation may update default attributes from other schemas.
* Applications should use <code>Document.normalizeDocument()</code> to
* guarantee these attributes are up-to-date.
* <br>When the node being renamed is an <code>Attr</code> that is
* attached to an <code>Element</code>, the node is first removed from
* the <code>Element</code> attributes map. Then, once renamed, either
* by modifying the existing node or creating a new one as described
* above, it is put back.
* <br>In addition,
* <ul>
* <li> a user data event <code>NODE_RENAMED</code> is fired,
* </li>
* <li>
* when the implementation supports the feature "MutationNameEvents",
* each mutation operation involved in this method fires the appropriate
* event, and in the end the event {
* <code>http://www.w3.org/2001/xml-events</code>,
* <code>DOMElementNameChanged</code>} or {
* <code>http://www.w3.org/2001/xml-events</code>,
* <code>DOMAttributeNameChanged</code>} is fired.
* </li>
* </ul>
* @param n The node to rename.
* @param namespaceURI The new namespace URI.
* @param qualifiedName The new qualified name.
* @return The renamed node. This is either the specified node or the new
* node that was created to replace the specified node.
* @exception DOMException
* NOT_SUPPORTED_ERR: Raised when the type of the specified node is
* neither <code>ELEMENT_NODE</code> nor <code>ATTRIBUTE_NODE</code>,
* or if the implementation does not support the renaming of the
* document element.
* <br>INVALID_CHARACTER_ERR: Raised if the new qualified name is not an
* XML name according to the XML version in use specified in the
* <code>Document.xmlVersion</code> attribute.
* <br>WRONG_DOCUMENT_ERR: Raised when the specified node was created
* from a different document than this document.
* <br>NAMESPACE_ERR: Raised if the <code>qualifiedName</code> is a
* malformed qualified name, if the <code>qualifiedName</code> has a
* prefix and the <code>namespaceURI</code> is <code>null</code>, or
* if the <code>qualifiedName</code> has a prefix that is "xml" and
* the <code>namespaceURI</code> is different from "<a href='http://www.w3.org/XML/1998/namespace'>
* http://www.w3.org/XML/1998/namespace</a>" [<a href='http://www.w3.org/TR/1999/REC-xml-names-19990114/'>XML Namespaces</a>]
* . Also raised, when the node being renamed is an attribute, if the
* <code>qualifiedName</code>, or its prefix, is "xmlns" and the
* <code>namespaceURI</code> is different from "<a href='http://www.w3.org/2000/xmlns/'>http://www.w3.org/2000/xmlns/</a>".
* @since DOM Level 3
*/
public Node renameNode(Node n,
String namespaceURI,
String qualifiedName)
throws DOMException;
}
| rokn/Count_Words_2015 | testing/openjdk2/jaxp/src/org/w3c/dom/Document.java | Java | mit | 45,108 |
// { dg-options "-std=gnu++11 -lstdc++fs" }
// { dg-require-filesystem-ts "" }
// Copyright (C) 2014-2015 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/>.
// 8.4.9 path decomposition [path.decompose]
#include <experimental/filesystem>
#include <vector>
#include <testsuite_hooks.h>
#include <testsuite_fs.h>
using std::experimental::filesystem::path;
void
test01()
{
for (const path& p : __gnu_test::test_paths)
{
VERIFY( p.has_root_directory() == !p.root_directory().empty() );
}
}
int
main()
{
test01();
}
| zjh171/gcc | libstdc++-v3/testsuite/experimental/filesystem/path/query/has_root_directory.cc | C++ | gpl-2.0 | 1,213 |
<?php
namespace Drupal\search_api\ParamConverter;
use Drupal\Core\Config\Entity\ConfigEntityStorageInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\ParamConverter\EntityConverter;
use Drupal\Core\ParamConverter\ParamConverterInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\search_api\UnsavedIndexConfiguration;
use Drupal\user\SharedTempStoreFactory;
use Symfony\Component\Routing\Route;
/**
* Converts search indexes from path parameters to a temporary copy.
*
* This is done so that certain pages (like the "Fields" tab) can modify indexes
* over several page requests without permanently saving the index in between.
*
* The code for this is largely taken from the views_ui module.
*/
class SearchApiConverter extends EntityConverter implements ParamConverterInterface {
/**
* The shared temporary storage factory.
*
* @var \Drupal\user\SharedTempStoreFactory
*/
protected $tempStoreFactory;
/**
* The currently logged-in user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* Constructs a new SearchApiConverter.
*
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager.
* @param \Drupal\user\SharedTempStoreFactory $temp_store_factory
* The factory for the temp store object.
* @param \Drupal\Core\Session\AccountInterface $user
* The current user.
*/
public function __construct(EntityManagerInterface $entity_manager, SharedTempStoreFactory $temp_store_factory, AccountInterface $user) {
parent::__construct($entity_manager);
$this->tempStoreFactory = $temp_store_factory;
$this->currentUser = $user;
}
/**
* {@inheritdoc}
*/
public function convert($value, $definition, $name, array $defaults) {
/** @var \Drupal\search_api\IndexInterface $entity */
$storage = $this->entityManager->getStorage('search_api_index');
if (!($storage instanceof ConfigEntityStorageInterface)) {
return NULL;
}
if (!($entity = $storage->loadOverrideFree($value))) {
return NULL;
}
// Get the temp store for this variable if it needs one. Attempt to load the
// index from the temp store, update the currently logged-in user's ID and
// store the lock metadata.
$store = $this->tempStoreFactory->get('search_api_index');
$current_user_id = $this->currentUser->id() ?: session_id();
/** @var \Drupal\search_api\IndexInterface|\Drupal\search_api\UnsavedIndexConfiguration $index */
if ($index = $store->get($value)) {
$index = new UnsavedIndexConfiguration($index, $store, $current_user_id);
$index->setLockInformation($store->getMetadata($value));
$index->setEntityTypeManager($this->entityManager);
}
// Otherwise, create a new temporary copy of the search index.
else {
$index = new UnsavedIndexConfiguration($entity, $store, $current_user_id);
}
return $index;
}
/**
* {@inheritdoc}
*/
public function applies($definition, $name, Route $route) {
if (parent::applies($definition, $name, $route)) {
return !empty($definition['tempstore']) && $definition['type'] === 'entity:search_api_index';
}
return FALSE;
}
}
| 1ns/project-r2 | web/modules/contrib/search_api/src/ParamConverter/SearchApiConverter.php | PHP | gpl-2.0 | 3,256 |
<?php
/**
* @file
* Contains \Drupal\views_ui\Tests\CustomBooleanTest.
*/
namespace Drupal\views_ui\Tests;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\views\Views;
/**
* Tests the UI and functionality for the Custom boolean field handler options.
*
* @group views_ui
* @see \Drupal\views\Plugin\views\field\Boolean
*/
class CustomBooleanTest extends UITestBase {
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = array('test_view');
/**
* \Drupal\views\Tests\ViewTestBase::viewsData().
*/
public function viewsData() {
$data = parent::viewsData();
$data['views_test_data']['age']['field']['id'] = 'boolean';
return $data;
}
/**
* Overrides \Drupal\views\Tests\ViewTestBase::dataSet().
*/
public function dataSet() {
$data = parent::dataSet();
$data[0]['age'] = 0;
$data[3]['age'] = 0;
return $data;
}
/**
* Tests the setting and output of custom labels for boolean values.
*/
public function testCustomOption() {
// Add the boolean field handler to the test view.
$view = Views::getView('test_view');
$view->setDisplay();
$view->displayHandlers->get('default')->overrideOption('fields', array(
'age' => array(
'id' => 'age',
'table' => 'views_test_data',
'field' => 'age',
'relationship' => 'none',
'plugin_id' => 'boolean',
),
));
$view->save();
$this->executeView($view);
$custom_true = 'Yay';
$custom_false = 'Nay';
// Set up some custom value mappings for different types.
$custom_values = array(
'plain' => array(
'true' => $custom_true,
'false' => $custom_false,
'test' => 'assertTrue',
),
'allowed tag' => array(
'true' => '<p>' . $custom_true . '</p>',
'false' => '<p>' . $custom_false . '</p>',
'test' => 'assertTrue',
),
'disallowed tag' => array(
'true' => '<script>' . $custom_true . '</script>',
'false' => '<script>' . $custom_false . '</script>',
'test' => 'assertFalse',
),
);
// Run the same tests on each type.
foreach ($custom_values as $type => $values) {
$options = array(
'options[type]' => 'custom',
'options[type_custom_true]' => $values['true'],
'options[type_custom_false]' => $values['false'],
);
$this->drupalPostForm('admin/structure/views/nojs/handler/test_view/default/field/age', $options, 'Apply');
// Save the view.
$this->drupalPostForm('admin/structure/views/view/test_view', array(), 'Save');
$view = Views::getView('test_view');
$output = $view->preview();
$output = \Drupal::service('renderer')->renderRoot($output);
$this->{$values['test']}(strpos($output, $values['true']), SafeMarkup::format('Expected custom boolean TRUE value %value in output for %type', ['%value' => $values['true'], '%type' => $type]));
$this->{$values['test']}(strpos($output, $values['false']), SafeMarkup::format('Expected custom boolean FALSE value %value in output for %type', ['%value' => $values['false'], '%type' => $type]));
}
}
/**
* Tests the setting and output of custom labels for boolean values.
*/
public function testCustomOptionTemplate() {
// Install theme to test with template system.
\Drupal::service('theme_handler')->install(['views_test_theme']);
// Set the default theme for Views preview.
$this->config('system.theme')
->set('default', 'views_test_theme')
->save();
$this->assertEqual($this->config('system.theme')->get('default'), 'views_test_theme');
// Add the boolean field handler to the test view.
$view = Views::getView('test_view');
$view->setDisplay();
$view->displayHandlers->get('default')->overrideOption('fields', [
'age' => [
'id' => 'age',
'table' => 'views_test_data',
'field' => 'age',
'relationship' => 'none',
'plugin_id' => 'boolean',
],
]);
$view->save();
$this->executeView($view);
$custom_true = 'Yay';
$custom_false = 'Nay';
// Set up some custom value mappings for different types.
$custom_values = array(
'plain' => array(
'true' => $custom_true,
'false' => $custom_false,
'test' => 'assertTrue',
),
'allowed tag' => array(
'true' => '<p>' . $custom_true . '</p>',
'false' => '<p>' . $custom_false . '</p>',
'test' => 'assertTrue',
),
'disallowed tag' => array(
'true' => '<script>' . $custom_true . '</script>',
'false' => '<script>' . $custom_false . '</script>',
'test' => 'assertFalse',
),
);
// Run the same tests on each type.
foreach ($custom_values as $type => $values) {
$options = array(
'options[type]' => 'custom',
'options[type_custom_true]' => $values['true'],
'options[type_custom_false]' => $values['false'],
);
$this->drupalPostForm('admin/structure/views/nojs/handler/test_view/default/field/age', $options, 'Apply');
// Save the view.
$this->drupalPostForm('admin/structure/views/view/test_view', array(), 'Save');
$view = Views::getView('test_view');
$output = $view->preview();
$output = \Drupal::service('renderer')->renderRoot($output);
$this->{$values['test']}(strpos($output, $values['true']), SafeMarkup::format('Expected custom boolean TRUE value %value in output for %type', ['%value' => $values['true'], '%type' => $type]));
$this->{$values['test']}(strpos($output, $values['false']), SafeMarkup::format('Expected custom boolean FALSE value %value in output for %type', ['%value' => $values['false'], '%type' => $type]));
// Assert that we are using the correct template.
$this->setRawContent($output);
$this->assertText('llama', 'Loaded the correct views-view-field.html.twig template');
}
}
}
| komejo/article-test | web/core/modules/views_ui/src/Tests/CustomBooleanTest.php | PHP | gpl-2.0 | 6,007 |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Structure.MetadataAsSource
{
internal abstract class AbstractMetadataAsSourceStructureProvider<TSyntaxNode> : AbstractSyntaxNodeStructureProvider<TSyntaxNode>
where TSyntaxNode : SyntaxNode
{
protected override void CollectBlockSpans(
TSyntaxNode node,
ArrayBuilder<BlockSpan> spans,
OptionSet options,
CancellationToken cancellationToken)
{
var startToken = node.GetFirstToken();
var endToken = GetEndToken(node);
if (startToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
// if valid tokens can't be found then a meaningful span can't be generated
return;
}
var firstComment = startToken.LeadingTrivia.FirstOrNullable(t => t.Kind() == SyntaxKind.SingleLineCommentTrivia);
var startPosition = firstComment.HasValue ? firstComment.Value.SpanStart : startToken.SpanStart;
var endPosition = endToken.SpanStart;
// TODO (tomescht): Mark the regions to be collapsed by default.
if (startPosition != endPosition)
{
var hintTextEndToken = GetHintTextEndToken(node);
spans.Add(new BlockSpan(
isCollapsible: true,
type: BlockTypes.Comment,
textSpan: TextSpan.FromBounds(startPosition, endPosition),
hintSpan: TextSpan.FromBounds(startPosition, hintTextEndToken.Span.End),
bannerText: CSharpStructureHelpers.Ellipsis,
autoCollapse: true));
}
}
protected override bool SupportedInWorkspaceKind(string kind)
{
return kind == WorkspaceKind.MetadataAsSource;
}
/// <summary>
/// Returns the last token to be included in the regions hint text.
/// </summary>
/// <remarks>
/// Note that the text of this token is included in the hint text, but not its
/// trailing trivia. See also <seealso cref="GetEndToken"/>.
/// </remarks>
protected virtual SyntaxToken GetHintTextEndToken(TSyntaxNode node)
{
return node.GetLastToken();
}
/// <summary>
/// Returns the token that marks the end of the collapsible region for the given node.
/// </summary>
/// <remarks>
/// Note that the text of the returned token is *not* included in the region, but any
/// leading trivia will be. This allows us to put the banner text for the collapsed
/// region immediately before the type or member.
/// See also <seealso cref="GetHintTextEndToken"/>.
/// </remarks>
protected abstract SyntaxToken GetEndToken(TSyntaxNode node);
}
}
| mmitche/roslyn | src/Features/CSharp/Portable/Structure/Providers/MetadataAsSource/AbstractMetadataAsSourceStructureProvider.cs | C# | apache-2.0 | 3,303 |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.spoon.dialog;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Shell;
import org.pentaho.di.core.ProgressMonitorAdapter;
import org.pentaho.di.core.SQLStatement;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
/**
* Takes care of displaying a dialog that will handle the wait while getting the SQL for a transformation...
*
* @author Matt
* @since 15-mrt-2005
*/
public class GetSQLProgressDialog {
private static Class<?> PKG = GetSQLProgressDialog.class; // for i18n purposes, needed by Translator2!!
private Shell shell;
private TransMeta transMeta;
private List<SQLStatement> stats;
/**
* Creates a new dialog that will handle the wait while getting the SQL for a transformation...
*/
public GetSQLProgressDialog( Shell shell, TransMeta transMeta ) {
this.shell = shell;
this.transMeta = transMeta;
}
public List<SQLStatement> open() {
IRunnableWithProgress op = new IRunnableWithProgress() {
public void run( IProgressMonitor monitor ) throws InvocationTargetException, InterruptedException {
// This is running in a new process: copy some KettleVariables info
// LocalVariables.getInstance().createKettleVariables(Thread.currentThread(), parentThread, true);
// --> don't set variables if not running in different thread --> pmd.run(true,true, op);
try {
stats = transMeta.getSQLStatements( new ProgressMonitorAdapter( monitor ) );
} catch ( KettleException e ) {
throw new InvocationTargetException( e, BaseMessages.getString(
PKG, "GetSQLProgressDialog.RuntimeError.UnableToGenerateSQL.Exception", e.getMessage() ) );
}
}
};
try {
ProgressMonitorDialog pmd = new ProgressMonitorDialog( shell );
pmd.run( false, false, op );
} catch ( InvocationTargetException e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "GetSQLProgressDialog.Dialog.UnableToGenerateSQL.Title" ),
BaseMessages.getString( PKG, "GetSQLProgressDialog.Dialog.UnableToGenerateSQL.Message" ), e );
stats = null;
} catch ( InterruptedException e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "GetSQLProgressDialog.Dialog.UnableToGenerateSQL.Title" ),
BaseMessages.getString( PKG, "GetSQLProgressDialog.Dialog.UnableToGenerateSQL.Message" ), e );
stats = null;
}
return stats;
}
}
| tkafalas/pentaho-kettle | ui/src/main/java/org/pentaho/di/ui/spoon/dialog/GetSQLProgressDialog.java | Java | apache-2.0 | 3,688 |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.repository;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.pentaho.di.core.Const;
import org.pentaho.di.imp.rule.ImportValidationFeedback;
import org.pentaho.di.i18n.BaseMessages;
/**
* This class is used to write export feedback. Usually it is transaction or job export result info.
*
* Every time this object is created it gets time created info automatically.
*
* Usually every ExportFeedback instance is related with one transformation or job export result. They are organized as
* a List. In special cases when we want a record not-about job or transformation - we can set {@link #isSimpleString()}
* to true. In this case {@link #getItemName()} will be used as a simple string. Others fields will not be used.
*
* To get a String representation of this item call to {@link #toString()}.
*
*/
public final class ExportFeedback {
private static Class<?> PKG = ExportFeedback.class;
static SimpleDateFormat sdf = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" );
private Date time = new Date();
private Type type;
private Status status;
private String itemPath;
private String itemName;
private List<ImportValidationFeedback> result;
private boolean isSimpleString;
public enum Status {
REJECTED( BaseMessages.getString( PKG, "ExportFeedback.Status.Rejected" ) ), EXPORTED( BaseMessages.getString( PKG,
"ExportFeedback.Status.Exported" ) );
private String status;
Status( String status ) {
this.status = status;
}
public String getStatus() {
return this.status;
}
}
public enum Type {
JOB( BaseMessages.getString( PKG, "ExportFeedback.Type.Job" ) ), TRANSFORMATION( BaseMessages.getString( PKG,
"ExportFeedback.Type.Transformation" ) );
private String type;
Type( String type ) {
this.type = type;
}
public String getType() {
return type;
}
}
public Type getType() {
return type;
}
public void setType( Type type ) {
this.type = type;
}
public Date getTime() {
return time;
}
public void setTime( Date time ) {
this.time = time;
}
public Status getStatus() {
return status;
}
public void setStatus( Status status ) {
this.status = status;
}
public String getItemPath() {
return itemPath;
}
public void setItemPath( String itemPath ) {
this.itemPath = itemPath;
}
public String getItemName() {
return itemName;
}
public void setItemName( String itemName ) {
this.itemName = itemName;
}
public List<ImportValidationFeedback> getResult() {
return result;
}
public void setResult( List<ImportValidationFeedback> result ) {
this.result = result;
}
public boolean isSimpleString() {
return isSimpleString;
}
public void setSimpleString( boolean isSimpleString ) {
this.isSimpleString = isSimpleString;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ( ( itemName == null ) ? 0 : itemName.hashCode() );
result = prime * result + ( ( itemPath == null ) ? 0 : itemPath.hashCode() );
return result;
}
@Override
public boolean equals( Object obj ) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
ExportFeedback other = (ExportFeedback) obj;
if ( itemName == null ) {
if ( other.itemName != null ) {
return false;
}
} else if ( !itemName.equals( other.itemName ) ) {
return false;
}
if ( itemPath == null ) {
if ( other.itemPath != null ) {
return false;
}
} else if ( !itemPath.equals( other.itemPath ) ) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
String message = null;
if ( this.isSimpleString ) {
message =
BaseMessages.getString( PKG, "ExportFeedback.Message.Simple", sdf.format( this.getTime() ), this
.getItemName() );
sb.append( message );
sb.append( Const.CR );
return sb.toString();
}
message =
BaseMessages.getString( PKG, "ExportFeedback.Message.Main", sdf.format( this.getTime() ), this.getStatus()
.getStatus(), this.getItemName(), this.getItemPath() );
sb.append( message );
sb.append( Const.CR );
// write some about rejected rules.
// note - this list contains only errors in current implementation
// so we skip additional checks. If someday this behavior will be changed -
// that the reason why are you read this comments.
if ( getStatus().equals( ExportFeedback.Status.REJECTED ) ) {
List<ImportValidationFeedback> fList = this.getResult();
for ( ImportValidationFeedback res : fList ) {
message = BaseMessages.getString( PKG, "ExportFeedback.Message.RuleViolated", res.getComment() );
sb.append( message );
sb.append( Const.CR );
}
}
return sb.toString();
}
}
| tkafalas/pentaho-kettle | engine/src/main/java/org/pentaho/di/repository/ExportFeedback.java | Java | apache-2.0 | 6,051 |
class AddSshKeyToUsers < ActiveRecord::Migration
def self.up
add_column :users, :ssh_key, :text
end
def self.down
remove_column :users, :ssh_key
end
end
| fcoury/gitorious | db/migrate/005_add_ssh_key_to_users.rb | Ruby | agpl-3.0 | 170 |
// @target: es6
// @module: system
export let { toString } = 1;
{
let { toFixed } = 1;
}
| Microsoft/TypeScript | tests/cases/compiler/destructuringInVariableDeclarations7.ts | TypeScript | apache-2.0 | 99 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import DS from 'ember-data';
export default DS.Model.extend({
totalVmemAllocatedContainersMB: DS.attr('number'),
totalPmemAllocatedContainersMB: DS.attr('number'),
totalVCoresAllocatedContainers: DS.attr('number'),
vmemCheckEnabled: DS.attr('boolean'),
pmemCheckEnabled: DS.attr('boolean'),
nodeHealthy: DS.attr('boolean'),
lastNodeUpdateTime: DS.attr('string'),
healthReport: DS.attr('string'),
nmStartupTime: DS.attr('string'),
nodeManagerBuildVersion: DS.attr('string'),
hadoopBuildVersion: DS.attr('string'),
});
| dennishuo/hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-ui/src/main/webapp/app/models/yarn-node.js | JavaScript | apache-2.0 | 1,348 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Provides testable_flexible_table class.
*
* @package core
* @subpackage fixtures
* @category test
* @copyright 2015 David Mudrak <david@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* Testable subclass of flexible_table providing access to some protected methods.
*
* @copyright 2015 David Mudrak <david@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class testable_flexible_table extends flexible_table {
/**
* Provides access to flexible_table::can_be_reset() method.
*
* @return bool
*/
public function can_be_reset() {
return parent::can_be_reset();
}
}
| parksandwildlife/learning | moodle/lib/tests/fixtures/testable_flexible_table.php | PHP | gpl-3.0 | 1,440 |
<?php
/**
* @file
* Contains \Drupal\migrate_drupal\Tests\Table\d7\History.
*
* THIS IS A GENERATED FILE. DO NOT EDIT.
*
* @see core/scripts/migrate-db.sh
* @see https://www.drupal.org/sandbox/benjy/2405029
*/
namespace Drupal\migrate_drupal\Tests\Table\d7;
use Drupal\migrate_drupal\Tests\Dump\DrupalDumpBase;
/**
* Generated file to represent the history table.
*/
class History extends DrupalDumpBase {
public function load() {
$this->createTable("history", array(
'primary key' => array(
'uid',
'nid',
),
'fields' => array(
'uid' => array(
'type' => 'int',
'not null' => TRUE,
'length' => '11',
'default' => '0',
),
'nid' => array(
'type' => 'int',
'not null' => TRUE,
'length' => '11',
'default' => '0',
),
'timestamp' => array(
'type' => 'int',
'not null' => TRUE,
'length' => '11',
'default' => '0',
),
),
'mysql_character_set' => 'utf8',
));
$this->database->insert("history")->fields(array(
'uid',
'nid',
'timestamp',
))
->values(array(
'uid' => '1',
'nid' => '1',
'timestamp' => '1421727536',
))->execute();
}
}
#4b9ec8e019d7f6733105db7bc8167268
| komejo/d8demo-dev | web/core/modules/migrate_drupal/src/Tests/Table/d7/History.php | PHP | mit | 1,350 |
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/optable/CombDiacritMarks.js
*
* Copyright (c) 2010-2017 The MathJax Consortium
*
* 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.
*
*/
(function (MML) {
var MO = MML.mo.OPTYPES;
var TEXCLASS = MML.TEXCLASS;
MathJax.Hub.Insert(MML.mo.prototype,{
OPTABLE: {
postfix: {
'\u0311': MO.ACCENT // combining inverted breve
}
}
});
MathJax.Ajax.loadComplete(MML.optableDir+"/CombDiacritMarks.js");
})(MathJax.ElementJax.mml);
| benjaminvialle/Markus | vendor/assets/javascripts/MathJax_lib/jax/element/mml/optable/CombDiacritMarks.js | JavaScript | mit | 1,080 |
/*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.internal.toolkit;
import java.io.*;
import com.sun.javadoc.*;
/**
* The interface for writing field output.
*
* This code is not part of an API.
* It is implementation that is subject to change.
* Do not use it as an API
*
* @author Jamie Ho
* @author Bhavesh Patel (Modified)
* @since 1.5
*/
public interface FieldWriter {
/**
* Get the field details tree header.
*
* @param classDoc the class being documented
* @param memberDetailsTree the content tree representing member details
* @return content tree for the field details header
*/
public Content getFieldDetailsTreeHeader(ClassDoc classDoc,
Content memberDetailsTree);
/**
* Get the field documentation tree header.
*
* @param field the constructor being documented
* @param fieldDetailsTree the content tree representing field details
* @return content tree for the field documentation header
*/
public Content getFieldDocTreeHeader(FieldDoc field,
Content fieldDetailsTree);
/**
* Get the signature for the given field.
*
* @param field the field being documented
* @return content tree for the field signature
*/
public Content getSignature(FieldDoc field);
/**
* Add the deprecated output for the given field.
*
* @param field the field being documented
* @param fieldDocTree content tree to which the deprecated information will be added
*/
public void addDeprecated(FieldDoc field, Content fieldDocTree);
/**
* Add the comments for the given field.
*
* @param field the field being documented
* @param fieldDocTree the content tree to which the comments will be added
*/
public void addComments(FieldDoc field, Content fieldDocTree);
/**
* Add the tags for the given field.
*
* @param field the field being documented
* @param fieldDocTree the content tree to which the tags will be added
*/
public void addTags(FieldDoc field, Content fieldDocTree);
/**
* Get the field details tree.
*
* @param memberDetailsTree the content tree representing member details
* @return content tree for the field details
*/
public Content getFieldDetails(Content memberDetailsTree);
/**
* Get the field documentation.
*
* @param fieldDocTree the content tree representing field documentation
* @param isLastContent true if the content to be added is the last content
* @return content tree for the field documentation
*/
public Content getFieldDoc(Content fieldDocTree, boolean isLastContent);
/**
* Close the writer.
*/
public void close() throws IOException;
}
| rokn/Count_Words_2015 | testing/openjdk/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/FieldWriter.java | Java | mit | 3,997 |
package com.flyco.dialog.widget;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.flyco.dialog.listener.OnBtnLeftClickL;
import com.flyco.dialog.listener.OnBtnRightClickL;
import com.flyco.dialog.utils.CornerUtils;
import com.flyco.dialog.widget.base.BaseDialog;
/**
* Dialog like Material Design Dialog
*/
public class MaterialDialog extends BaseDialog {
/**
* container
*/
private LinearLayout ll_container;
/***
* title
*/
private TextView tv_title;
/**
* content
*/
private TextView tv_content;
/**
* btn container
*/
private LinearLayout ll_btns;
/**
* left btn
*/
private TextView tv_btn_left;
/**
* right btn
*/
private TextView tv_btn_right;
/**
* title content(标题)
*/
private String title = "温馨提示";
/**
* title textcolor(标题颜色)
*/
private int titleTextColor = Color.parseColor("#DE000000");
/**
* title textsize(标题字体大小,单位sp)
*/
private float titleTextSize_SP = 22f;
/**
* enable title show(是否显示标题)
*/
private boolean isTitleShow = true;
/**
* content text
*/
private String content;
/**
* show gravity of content(正文内容显示位置)
*/
private int contentGravity = Gravity.CENTER_VERTICAL;
/**
* content textcolor(正文字体颜色)
*/
private int contentTextColor = Color.parseColor("#8a000000");
/**
* content textsize(正文字体大小)
*/
private float contentTextSize_SP = 16f;
/**
* btn textcolor(按钮字体颜色)
*/
private int leftBtnTextColor = Color.parseColor("#383838");
private int rightBtnTextColor = Color.parseColor("#468ED0");
/**
* btn textsize(按钮字体大小)
*/
private float leftBtnTextSize_SP = 15f;
private float rightBtnTextSize_SP = 15f;
/**
* btn press color(按钮点击颜色)
*/
private int btnPressColor = Color.parseColor("#E3E3E3");// #85D3EF,#ffcccccc,#E3E3E3
/**
* left btn text(左按钮内容)
*/
private String btnLeftText = "取消";
/**
* right btn text(右按钮内容)
*/
private String btnRightText = "确定";
/**
* corner radius,dp(圆角程度,单位dp)
*/
private float cornerRadius_DP = 3;
/**
* background color(背景颜色)
*/
private int bgColor = Color.parseColor("#ffffff");
/**
* left btn click listener(左按钮接口)
*/
private OnBtnLeftClickL onBtnLeftClickL;
/**
* right btn click listener(右按钮接口)
*/
private OnBtnRightClickL onBtnRightClickL;
public MaterialDialog(Context context) {
super(context);
}
@Override
public View onCreateView() {
widthScale(0.88f);
ll_container = new LinearLayout(context);
ll_container.setOrientation(LinearLayout.VERTICAL);
/** title */
tv_title = new TextView(context);
tv_title.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
ll_container.addView(tv_title);
/** content */
tv_content = new TextView(context);
tv_content.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
ll_container.addView(tv_content);
/** btns */
ll_btns = new LinearLayout(context);
ll_btns.setOrientation(LinearLayout.HORIZONTAL);
ll_btns.setGravity(Gravity.RIGHT);
tv_btn_left = new TextView(context);
tv_btn_left.setGravity(Gravity.CENTER);
tv_btn_left.setPadding(dp2px(15), dp2px(10), dp2px(15), dp2px(10));
ll_btns.addView(tv_btn_left);
tv_btn_right = new TextView(context);
tv_btn_right.setGravity(Gravity.CENTER);
tv_btn_right.setPadding(dp2px(15), dp2px(10), dp2px(15), dp2px(10));
ll_btns.addView(tv_btn_right);
ll_container.addView(ll_btns);
return ll_container;
}
@Override
public boolean setUiBeforShow() {
float radius = dp2px(cornerRadius_DP);
/** title */
tv_title.setGravity(Gravity.CENTER_VERTICAL);
tv_title.setPadding(dp2px(20), dp2px(20), dp2px(20), dp2px(0));
tv_title.setVisibility(isTitleShow ? View.VISIBLE : View.GONE);
tv_title.setText(TextUtils.isEmpty(title) ? "温馨提示" : title);
tv_title.setTextColor(titleTextColor);
tv_title.setTextSize(TypedValue.COMPLEX_UNIT_SP, titleTextSize_SP);
/** content */
tv_content.setPadding(dp2px(20), dp2px(20), dp2px(20), dp2px(20));
tv_content.setGravity(contentGravity);
tv_content.setText(content);
tv_content.setTextColor(contentTextColor);
tv_content.setTextSize(TypedValue.COMPLEX_UNIT_SP, contentTextSize_SP);
tv_content.setLineSpacing(0, 1.3f);
/** btns */
ll_btns.setPadding(dp2px(20), dp2px(0), dp2px(10), isTitleShow ? dp2px(10) : dp2px(0));
tv_btn_left.setText(btnLeftText);
tv_btn_right.setText(btnRightText);
tv_btn_left.setTextColor(leftBtnTextColor);
tv_btn_right.setTextColor(rightBtnTextColor);
tv_btn_left.setTextSize(TypedValue.COMPLEX_UNIT_SP, leftBtnTextSize_SP);
tv_btn_right.setTextSize(TypedValue.COMPLEX_UNIT_SP, rightBtnTextSize_SP);
/**set background color and corner radius */
ll_container.setBackgroundDrawable(CornerUtils.cornerDrawable(bgColor, radius));
tv_btn_left.setBackgroundDrawable(CornerUtils.btnSelector(0, bgColor, btnPressColor, 0));
tv_btn_right.setBackgroundDrawable(CornerUtils.btnSelector(0, bgColor, btnPressColor, 1));
tv_btn_left.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onBtnLeftClickL != null) {
onBtnLeftClickL.onBtnLeftClick();
}
}
});
tv_btn_right.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onBtnRightClickL != null) {
onBtnRightClickL.onBtnRightClick();
}
}
});
return false;
}
// --->属性设置
/**
* set title text(设置标题内容)
*
* @param title
* @return MaterialDialog
*/
public MaterialDialog title(String title) {
this.title = title;
return this;
}
/**
* set title textcolor(设置标题字体颜色)
*
* @param titleTextColor
* @return MaterialDialog
*/
public MaterialDialog titleTextColor(int titleTextColor) {
this.titleTextColor = titleTextColor;
return this;
}
/**
* set title textsize(设置标题字体大小)
*
* @param titleTextSize_SP
* @return MaterialDialog
*/
public MaterialDialog titleTextSize(float titleTextSize_SP) {
this.titleTextSize_SP = titleTextSize_SP;
return this;
}
/**
* enable title show(设置标题是否显示)
*
* @param isTitleShow
* @return MaterialDialog
*/
public MaterialDialog isTitleShow(boolean isTitleShow) {
this.isTitleShow = isTitleShow;
return this;
}
/**
* set content text(设置正文内容)
*
* @param content
* @return MaterialDialog
*/
public MaterialDialog content(String content) {
this.content = content;
return this;
}
/**
* set content gravity(设置正文内容,显示位置)
*
* @param contentGravity
* @return MaterialDialog
*/
public MaterialDialog contentGravity(int contentGravity) {
this.contentGravity = contentGravity;
return this;
}
/**
* set content textcolor(设置正文字体颜色)
*
* @param contentTextColor
* @return MaterialDialog
*/
public MaterialDialog contentTextColor(int contentTextColor) {
this.contentTextColor = contentTextColor;
return this;
}
/**
* set content textsize(设置正文字体大小,单位sp)
*
* @param contentTextSize_SP
* @return MaterialDialog
*/
public MaterialDialog contentTextSize(float contentTextSize_SP) {
this.contentTextSize_SP = contentTextSize_SP;
return this;
}
/**
* set btn text(设置按钮文字内容)
*
* @param btnLeftText
* @param btnRightText
* @return MaterialDialog
*/
public MaterialDialog btnText(String btnLeftText, String btnRightText) {
this.btnLeftText = btnLeftText;
this.btnRightText = btnRightText;
return this;
}
/**
* set btn textcolor(设置按钮字体颜色)
*
* @param leftBtnTextColor
* @param rightBtnTextColor
* @return MaterialDialog
*/
public MaterialDialog btnTextColor(int leftBtnTextColor, int rightBtnTextColor) {
this.leftBtnTextColor = leftBtnTextColor;
this.rightBtnTextColor = rightBtnTextColor;
return this;
}
/**
* set btn textsize(设置字体大小,单位sp)
*
* @param leftBtnTextSize_SP
* @param rightBtnTextSize_SP
* @return MaterialDialog
*/
public MaterialDialog btnTextSize(float leftBtnTextSize_SP, float rightBtnTextSize_SP) {
this.leftBtnTextSize_SP = leftBtnTextSize_SP;
this.rightBtnTextSize_SP = rightBtnTextSize_SP;
return this;
}
/**
* set btn press color(设置按钮点击颜色)
*
* @param btnPressColor
* @return MaterialDialog
*/
public MaterialDialog btnPressColor(int btnPressColor) {
this.btnPressColor = btnPressColor;
return this;
}
/**
* set leftbtn click listener(设置左侧按钮监听事件)
*
* @param onBtnLeftClickL
*/
public void setOnBtnLeftClickL(OnBtnLeftClickL onBtnLeftClickL) {
this.onBtnLeftClickL = onBtnLeftClickL;
}
/**
* set rightbtn click listener(设置右侧按钮监听事件)
*
* @param onBtnRightClickL
*/
public void setOnBtnRightClickL(OnBtnRightClickL onBtnRightClickL) {
this.onBtnRightClickL = onBtnRightClickL;
}
/**
* set corner radius (设置圆角程度)
*
* @param cornerRadius_DP
* @return MaterialDialog
*/
public MaterialDialog cornerRadius(float cornerRadius_DP) {
this.cornerRadius_DP = cornerRadius_DP;
return this;
}
/**
* set backgroud color(设置背景色)
*
* @param bgColor
* @return MaterialDialog
*/
public MaterialDialog bgColor(int bgColor) {
this.bgColor = bgColor;
return this;
}
}
| mkodekar/FlycoDialog_Master | FlycoDialog_Lib/src/main/java/com/flyco/dialog/widget/MaterialDialog.java | Java | mit | 11,600 |
# (c) 2020, Felix Fontein <felix@fontein.de>
#
# 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/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
def add_internal_fqcns(names):
'''
Given a sequence of action/module names, returns a list of these names
with the same names with the prefixes `ansible.builtin.` and
`ansible.legacy.` added for all names that are not already FQCNs.
'''
result = []
for name in names:
result.append(name)
if '.' not in name:
result.append('ansible.builtin.%s' % name)
result.append('ansible.legacy.%s' % name)
return result
| dmsimard/ansible | lib/ansible/utils/fqcn.py | Python | gpl-3.0 | 1,268 |
// Copyright ©2015 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mat
import (
"math"
"gonum.org/v1/gonum/blas"
"gonum.org/v1/gonum/blas/blas64"
)
var (
symDense *SymDense
_ Matrix = symDense
_ Symmetric = symDense
_ RawSymmetricer = symDense
_ MutableSymmetric = symDense
)
const (
badSymTriangle = "mat: blas64.Symmetric not upper"
badSymCap = "mat: bad capacity for SymDense"
)
// SymDense is a symmetric matrix that uses dense storage. SymDense
// matrices are stored in the upper triangle.
type SymDense struct {
mat blas64.Symmetric
cap int
}
// Symmetric represents a symmetric matrix (where the element at {i, j} equals
// the element at {j, i}). Symmetric matrices are always square.
type Symmetric interface {
Matrix
// Symmetric returns the number of rows/columns in the matrix.
Symmetric() int
}
// A RawSymmetricer can return a view of itself as a BLAS Symmetric matrix.
type RawSymmetricer interface {
RawSymmetric() blas64.Symmetric
}
// A MutableSymmetric can set elements of a symmetric matrix.
type MutableSymmetric interface {
Symmetric
SetSym(i, j int, v float64)
}
// NewSymDense creates a new Symmetric matrix with n rows and columns. If data == nil,
// a new slice is allocated for the backing slice. If len(data) == n*n, data is
// used as the backing slice, and changes to the elements of the returned SymDense
// will be reflected in data. If neither of these is true, NewSymDense will panic.
// NewSymDense will panic if n is zero.
//
// The data must be arranged in row-major order, i.e. the (i*c + j)-th
// element in the data slice is the {i, j}-th element in the matrix.
// Only the values in the upper triangular portion of the matrix are used.
func NewSymDense(n int, data []float64) *SymDense {
if n <= 0 {
if n == 0 {
panic(ErrZeroLength)
}
panic("mat: negative dimension")
}
if data != nil && n*n != len(data) {
panic(ErrShape)
}
if data == nil {
data = make([]float64, n*n)
}
return &SymDense{
mat: blas64.Symmetric{
N: n,
Stride: n,
Data: data,
Uplo: blas.Upper,
},
cap: n,
}
}
// Dims returns the number of rows and columns in the matrix.
func (s *SymDense) Dims() (r, c int) {
return s.mat.N, s.mat.N
}
// Caps returns the number of rows and columns in the backing matrix.
func (s *SymDense) Caps() (r, c int) {
return s.cap, s.cap
}
// T returns the receiver, the transpose of a symmetric matrix.
func (s *SymDense) T() Matrix {
return s
}
// Symmetric implements the Symmetric interface and returns the number of rows
// and columns in the matrix.
func (s *SymDense) Symmetric() int {
return s.mat.N
}
// RawSymmetric returns the matrix as a blas64.Symmetric. The returned
// value must be stored in upper triangular format.
func (s *SymDense) RawSymmetric() blas64.Symmetric {
return s.mat
}
// SetRawSymmetric sets the underlying blas64.Symmetric used by the receiver.
// Changes to elements in the receiver following the call will be reflected
// in the input.
//
// The supplied Symmetric must use blas.Upper storage format.
func (s *SymDense) SetRawSymmetric(mat blas64.Symmetric) {
if mat.Uplo != blas.Upper {
panic(badSymTriangle)
}
s.mat = mat
}
// Reset zeros the dimensions of the matrix so that it can be reused as the
// receiver of a dimensionally restricted operation.
//
// See the Reseter interface for more information.
func (s *SymDense) Reset() {
// N and Stride must be zeroed in unison.
s.mat.N, s.mat.Stride = 0, 0
s.mat.Data = s.mat.Data[:0]
}
// Zero sets all of the matrix elements to zero.
func (s *SymDense) Zero() {
for i := 0; i < s.mat.N; i++ {
zero(s.mat.Data[i*s.mat.Stride+i : i*s.mat.Stride+s.mat.N])
}
}
// IsZero returns whether the receiver is zero-sized. Zero-sized matrices can be the
// receiver for size-restricted operations. SymDense matrices can be zeroed using Reset.
func (s *SymDense) IsZero() bool {
// It must be the case that m.Dims() returns
// zeros in this case. See comment in Reset().
return s.mat.N == 0
}
// reuseAs resizes an empty matrix to a n×n matrix,
// or checks that a non-empty matrix is n×n.
func (s *SymDense) reuseAs(n int) {
if n == 0 {
panic(ErrZeroLength)
}
if s.mat.N > s.cap {
panic(badSymCap)
}
if s.IsZero() {
s.mat = blas64.Symmetric{
N: n,
Stride: n,
Data: use(s.mat.Data, n*n),
Uplo: blas.Upper,
}
s.cap = n
return
}
if s.mat.Uplo != blas.Upper {
panic(badSymTriangle)
}
if s.mat.N != n {
panic(ErrShape)
}
}
func (s *SymDense) isolatedWorkspace(a Symmetric) (w *SymDense, restore func()) {
n := a.Symmetric()
if n == 0 {
panic(ErrZeroLength)
}
w = getWorkspaceSym(n, false)
return w, func() {
s.CopySym(w)
putWorkspaceSym(w)
}
}
// DiagView returns the diagonal as a matrix backed by the original data.
func (s *SymDense) DiagView() Diagonal {
n := s.mat.N
return &DiagDense{
mat: blas64.Vector{
N: n,
Inc: s.mat.Stride + 1,
Data: s.mat.Data[:(n-1)*s.mat.Stride+n],
},
}
}
func (s *SymDense) AddSym(a, b Symmetric) {
n := a.Symmetric()
if n != b.Symmetric() {
panic(ErrShape)
}
s.reuseAs(n)
if a, ok := a.(RawSymmetricer); ok {
if b, ok := b.(RawSymmetricer); ok {
amat, bmat := a.RawSymmetric(), b.RawSymmetric()
if s != a {
s.checkOverlap(generalFromSymmetric(amat))
}
if s != b {
s.checkOverlap(generalFromSymmetric(bmat))
}
for i := 0; i < n; i++ {
btmp := bmat.Data[i*bmat.Stride+i : i*bmat.Stride+n]
stmp := s.mat.Data[i*s.mat.Stride+i : i*s.mat.Stride+n]
for j, v := range amat.Data[i*amat.Stride+i : i*amat.Stride+n] {
stmp[j] = v + btmp[j]
}
}
return
}
}
s.checkOverlapMatrix(a)
s.checkOverlapMatrix(b)
for i := 0; i < n; i++ {
stmp := s.mat.Data[i*s.mat.Stride : i*s.mat.Stride+n]
for j := i; j < n; j++ {
stmp[j] = a.At(i, j) + b.At(i, j)
}
}
}
func (s *SymDense) CopySym(a Symmetric) int {
n := a.Symmetric()
n = min(n, s.mat.N)
if n == 0 {
return 0
}
switch a := a.(type) {
case RawSymmetricer:
amat := a.RawSymmetric()
if amat.Uplo != blas.Upper {
panic(badSymTriangle)
}
for i := 0; i < n; i++ {
copy(s.mat.Data[i*s.mat.Stride+i:i*s.mat.Stride+n], amat.Data[i*amat.Stride+i:i*amat.Stride+n])
}
default:
for i := 0; i < n; i++ {
stmp := s.mat.Data[i*s.mat.Stride : i*s.mat.Stride+n]
for j := i; j < n; j++ {
stmp[j] = a.At(i, j)
}
}
}
return n
}
// SymRankOne performs a symetric rank-one update to the matrix a and stores
// the result in the receiver
// s = a + alpha * x * x'
func (s *SymDense) SymRankOne(a Symmetric, alpha float64, x Vector) {
n, c := x.Dims()
if a.Symmetric() != n || c != 1 {
panic(ErrShape)
}
s.reuseAs(n)
if s != a {
if rs, ok := a.(RawSymmetricer); ok {
s.checkOverlap(generalFromSymmetric(rs.RawSymmetric()))
}
s.CopySym(a)
}
xU, _ := untranspose(x)
if rv, ok := xU.(RawVectorer); ok {
xmat := rv.RawVector()
s.checkOverlap((&VecDense{mat: xmat}).asGeneral())
blas64.Syr(alpha, xmat, s.mat)
return
}
for i := 0; i < n; i++ {
for j := i; j < n; j++ {
s.set(i, j, s.at(i, j)+alpha*x.AtVec(i)*x.AtVec(j))
}
}
}
// SymRankK performs a symmetric rank-k update to the matrix a and stores the
// result into the receiver. If a is zero, see SymOuterK.
// s = a + alpha * x * x'
func (s *SymDense) SymRankK(a Symmetric, alpha float64, x Matrix) {
n := a.Symmetric()
r, _ := x.Dims()
if r != n {
panic(ErrShape)
}
xMat, aTrans := untranspose(x)
var g blas64.General
if rm, ok := xMat.(RawMatrixer); ok {
g = rm.RawMatrix()
} else {
g = DenseCopyOf(x).mat
aTrans = false
}
if a != s {
if rs, ok := a.(RawSymmetricer); ok {
s.checkOverlap(generalFromSymmetric(rs.RawSymmetric()))
}
s.reuseAs(n)
s.CopySym(a)
}
t := blas.NoTrans
if aTrans {
t = blas.Trans
}
blas64.Syrk(t, alpha, g, 1, s.mat)
}
// SymOuterK calculates the outer product of x with itself and stores
// the result into the receiver. It is equivalent to the matrix
// multiplication
// s = alpha * x * x'.
// In order to update an existing matrix, see SymRankOne.
func (s *SymDense) SymOuterK(alpha float64, x Matrix) {
n, _ := x.Dims()
switch {
case s.IsZero():
s.mat = blas64.Symmetric{
N: n,
Stride: n,
Data: useZeroed(s.mat.Data, n*n),
Uplo: blas.Upper,
}
s.cap = n
s.SymRankK(s, alpha, x)
case s.mat.Uplo != blas.Upper:
panic(badSymTriangle)
case s.mat.N == n:
if s == x {
w := getWorkspaceSym(n, true)
w.SymRankK(w, alpha, x)
s.CopySym(w)
putWorkspaceSym(w)
} else {
switch r := x.(type) {
case RawMatrixer:
s.checkOverlap(r.RawMatrix())
case RawSymmetricer:
s.checkOverlap(generalFromSymmetric(r.RawSymmetric()))
case RawTriangular:
s.checkOverlap(generalFromTriangular(r.RawTriangular()))
}
// Only zero the upper triangle.
for i := 0; i < n; i++ {
ri := i * s.mat.Stride
zero(s.mat.Data[ri+i : ri+n])
}
s.SymRankK(s, alpha, x)
}
default:
panic(ErrShape)
}
}
// RankTwo performs a symmmetric rank-two update to the matrix a and stores
// the result in the receiver
// m = a + alpha * (x * y' + y * x')
func (s *SymDense) RankTwo(a Symmetric, alpha float64, x, y Vector) {
n := s.mat.N
xr, xc := x.Dims()
if xr != n || xc != 1 {
panic(ErrShape)
}
yr, yc := y.Dims()
if yr != n || yc != 1 {
panic(ErrShape)
}
if s != a {
if rs, ok := a.(RawSymmetricer); ok {
s.checkOverlap(generalFromSymmetric(rs.RawSymmetric()))
}
}
var xmat, ymat blas64.Vector
fast := true
xU, _ := untranspose(x)
if rv, ok := xU.(RawVectorer); ok {
xmat = rv.RawVector()
s.checkOverlap((&VecDense{mat: xmat}).asGeneral())
} else {
fast = false
}
yU, _ := untranspose(y)
if rv, ok := yU.(RawVectorer); ok {
ymat = rv.RawVector()
s.checkOverlap((&VecDense{mat: ymat}).asGeneral())
} else {
fast = false
}
if s != a {
if rs, ok := a.(RawSymmetricer); ok {
s.checkOverlap(generalFromSymmetric(rs.RawSymmetric()))
}
s.reuseAs(n)
s.CopySym(a)
}
if fast {
if s != a {
s.reuseAs(n)
s.CopySym(a)
}
blas64.Syr2(alpha, xmat, ymat, s.mat)
return
}
for i := 0; i < n; i++ {
s.reuseAs(n)
for j := i; j < n; j++ {
s.set(i, j, a.At(i, j)+alpha*(x.AtVec(i)*y.AtVec(j)+y.AtVec(i)*x.AtVec(j)))
}
}
}
// ScaleSym multiplies the elements of a by f, placing the result in the receiver.
func (s *SymDense) ScaleSym(f float64, a Symmetric) {
n := a.Symmetric()
s.reuseAs(n)
if a, ok := a.(RawSymmetricer); ok {
amat := a.RawSymmetric()
if s != a {
s.checkOverlap(generalFromSymmetric(amat))
}
for i := 0; i < n; i++ {
for j := i; j < n; j++ {
s.mat.Data[i*s.mat.Stride+j] = f * amat.Data[i*amat.Stride+j]
}
}
return
}
for i := 0; i < n; i++ {
for j := i; j < n; j++ {
s.mat.Data[i*s.mat.Stride+j] = f * a.At(i, j)
}
}
}
// SubsetSym extracts a subset of the rows and columns of the matrix a and stores
// the result in-place into the receiver. The resulting matrix size is
// len(set)×len(set). Specifically, at the conclusion of SubsetSym,
// s.At(i, j) equals a.At(set[i], set[j]). Note that the supplied set does not
// have to be a strict subset, dimension repeats are allowed.
func (s *SymDense) SubsetSym(a Symmetric, set []int) {
n := len(set)
na := a.Symmetric()
s.reuseAs(n)
var restore func()
if a == s {
s, restore = s.isolatedWorkspace(a)
defer restore()
}
if a, ok := a.(RawSymmetricer); ok {
raw := a.RawSymmetric()
if s != a {
s.checkOverlap(generalFromSymmetric(raw))
}
for i := 0; i < n; i++ {
ssub := s.mat.Data[i*s.mat.Stride : i*s.mat.Stride+n]
r := set[i]
rsub := raw.Data[r*raw.Stride : r*raw.Stride+na]
for j := i; j < n; j++ {
c := set[j]
if r <= c {
ssub[j] = rsub[c]
} else {
ssub[j] = raw.Data[c*raw.Stride+r]
}
}
}
return
}
for i := 0; i < n; i++ {
for j := i; j < n; j++ {
s.mat.Data[i*s.mat.Stride+j] = a.At(set[i], set[j])
}
}
}
// SliceSym returns a new Matrix that shares backing data with the receiver.
// The returned matrix starts at {i,i} of the receiver and extends k-i rows
// and columns. The final row and column in the resulting matrix is k-1.
// SliceSym panics with ErrIndexOutOfRange if the slice is outside the
// capacity of the receiver.
func (s *SymDense) SliceSym(i, k int) Symmetric {
sz := s.cap
if i < 0 || sz < i || k < i || sz < k {
panic(ErrIndexOutOfRange)
}
v := *s
v.mat.Data = s.mat.Data[i*s.mat.Stride+i : (k-1)*s.mat.Stride+k]
v.mat.N = k - i
v.cap = s.cap - i
return &v
}
// Trace returns the trace of the matrix.
func (s *SymDense) Trace() float64 {
// TODO(btracey): could use internal asm sum routine.
var v float64
for i := 0; i < s.mat.N; i++ {
v += s.mat.Data[i*s.mat.Stride+i]
}
return v
}
// GrowSym returns the receiver expanded by n rows and n columns. If the
// dimensions of the expanded matrix are outside the capacity of the receiver
// a new allocation is made, otherwise not. Note that the receiver itself is
// not modified during the call to GrowSquare.
func (s *SymDense) GrowSym(n int) Symmetric {
if n < 0 {
panic(ErrIndexOutOfRange)
}
if n == 0 {
return s
}
var v SymDense
n += s.mat.N
if n > s.cap {
v.mat = blas64.Symmetric{
N: n,
Stride: n,
Uplo: blas.Upper,
Data: make([]float64, n*n),
}
v.cap = n
// Copy elements, including those not currently visible. Use a temporary
// structure to avoid modifying the receiver.
var tmp SymDense
tmp.mat = blas64.Symmetric{
N: s.cap,
Stride: s.mat.Stride,
Data: s.mat.Data,
Uplo: s.mat.Uplo,
}
tmp.cap = s.cap
v.CopySym(&tmp)
return &v
}
v.mat = blas64.Symmetric{
N: n,
Stride: s.mat.Stride,
Uplo: blas.Upper,
Data: s.mat.Data[:(n-1)*s.mat.Stride+n],
}
v.cap = s.cap
return &v
}
// PowPSD computes a^pow where a is a positive symmetric definite matrix.
//
// PowPSD returns an error if the matrix is not not positive symmetric definite
// or the Eigendecomposition is not successful.
func (s *SymDense) PowPSD(a Symmetric, pow float64) error {
dim := a.Symmetric()
s.reuseAs(dim)
var eigen EigenSym
ok := eigen.Factorize(a, true)
if !ok {
return ErrFailedEigen
}
values := eigen.Values(nil)
for i, v := range values {
if v <= 0 {
return ErrNotPSD
}
values[i] = math.Pow(v, pow)
}
u := eigen.VectorsTo(nil)
s.SymOuterK(values[0], u.ColView(0))
var v VecDense
for i := 1; i < dim; i++ {
v.ColViewOf(u, i)
s.SymRankOne(s, values[i], &v)
}
return nil
}
| zhangxiaoyu-zidif/kubernetes | vendor/gonum.org/v1/gonum/mat/symmetric.go | GO | apache-2.0 | 14,638 |
class Company
include Mongoid::Document
embeds_many :staffs
end
| kcdragon/mongoid | spec/app/models/company.rb | Ruby | mit | 69 |
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. 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.
*
* ***** END LICENSE BLOCK ***** */
define('ace/theme/dreamweaver', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) {
exports.isDark = false;
exports.cssClass = "ace-dreamweaver";
exports.cssText = ".ace-dreamweaver .ace_gutter {\
background: #e8e8e8;\
color: #333;\
}\
.ace-dreamweaver .ace_print-margin {\
width: 1px;\
background: #e8e8e8;\
}\
.ace-dreamweaver {\
background-color: #FFFFFF;\
}\
.ace-dreamweaver .ace_fold {\
background-color: #757AD8;\
}\
.ace-dreamweaver .ace_cursor {\
color: black;\
}\
.ace-dreamweaver .ace_invisible {\
color: rgb(191, 191, 191);\
}\
.ace-dreamweaver .ace_storage,\
.ace-dreamweaver .ace_keyword {\
color: blue;\
}\
.ace-dreamweaver .ace_constant.ace_buildin {\
color: rgb(88, 72, 246);\
}\
.ace-dreamweaver .ace_constant.ace_language {\
color: rgb(88, 92, 246);\
}\
.ace-dreamweaver .ace_constant.ace_library {\
color: rgb(6, 150, 14);\
}\
.ace-dreamweaver .ace_invalid {\
background-color: rgb(153, 0, 0);\
color: white;\
}\
.ace-dreamweaver .ace_support.ace_function {\
color: rgb(60, 76, 114);\
}\
.ace-dreamweaver .ace_support.ace_constant {\
color: rgb(6, 150, 14);\
}\
.ace-dreamweaver .ace_support.ace_type,\
.ace-dreamweaver .ace_support.ace_class {\
color: #009;\
}\
.ace-dreamweaver .ace_support.ace_php_tag {\
color: #f00;\
}\
.ace-dreamweaver .ace_keyword.ace_operator {\
color: rgb(104, 118, 135);\
}\
.ace-dreamweaver .ace_string {\
color: #00F;\
}\
.ace-dreamweaver .ace_comment {\
color: rgb(76, 136, 107);\
}\
.ace-dreamweaver .ace_comment.ace_doc {\
color: rgb(0, 102, 255);\
}\
.ace-dreamweaver .ace_comment.ace_doc.ace_tag {\
color: rgb(128, 159, 191);\
}\
.ace-dreamweaver .ace_constant.ace_numeric {\
color: rgb(0, 0, 205);\
}\
.ace-dreamweaver .ace_variable {\
color: #06F\
}\
.ace-dreamweaver .ace_xml-pe {\
color: rgb(104, 104, 91);\
}\
.ace-dreamweaver .ace_entity.ace_name.ace_function {\
color: #00F;\
}\
.ace-dreamweaver .ace_heading {\
color: rgb(12, 7, 255);\
}\
.ace-dreamweaver .ace_list {\
color:rgb(185, 6, 144);\
}\
.ace-dreamweaver .ace_marker-layer .ace_selection {\
background: rgb(181, 213, 255);\
}\
.ace-dreamweaver .ace_marker-layer .ace_step {\
background: rgb(252, 255, 0);\
}\
.ace-dreamweaver .ace_marker-layer .ace_stack {\
background: rgb(164, 229, 101);\
}\
.ace-dreamweaver .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgb(192, 192, 192);\
}\
.ace-dreamweaver .ace_marker-layer .ace_active-line {\
background: rgba(0, 0, 0, 0.07);\
}\
.ace-dreamweaver .ace_marker-layer .ace_selected-word {\
background: rgb(250, 250, 255);\
border: 1px solid rgb(200, 200, 250);\
}\
.ace-dreamweaver .ace_meta.ace_tag {\
color:#009;\
}\
.ace-dreamweaver .ace_meta.ace_tag.ace_anchor {\
color:#060;\
}\
.ace-dreamweaver .ace_meta.ace_tag.ace_form {\
color:#F90;\
}\
.ace-dreamweaver .ace_meta.ace_tag.ace_image {\
color:#909;\
}\
.ace-dreamweaver .ace_meta.ace_tag.ace_script {\
color:#900;\
}\
.ace-dreamweaver .ace_meta.ace_tag.ace_style {\
color:#909;\
}\
.ace-dreamweaver .ace_meta.ace_tag.ace_table {\
color:#099;\
}\
.ace-dreamweaver .ace_string.ace_regex {\
color: rgb(255, 0, 0)\
}\
.ace-dreamweaver .ace_indent-guide {\
background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\
}";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
| tancredi/draw | www/js/vendor/ace/theme-dreamweaver.js | JavaScript | mit | 5,077 |
// Copyright (C) 2001-2014 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 "1.h"
#include <list>
int main()
{
operations01<std::list<int> >();
return 0;
}
| xinchoubiology/gcc | libstdc++-v3/testsuite/23_containers/list/operations/1.cc | C++ | gpl-2.0 | 859 |
// Copyright (C) 2010-2014 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/>.
//
// { dg-require-debug-mode "" }
// { dg-do run { xfail *-*-* } }
#include <vector>
#include <debug/checks.h>
void test01()
{
__gnu_test::check_construct3<std::vector<int> >();
}
int main()
{
test01();
return 0;
}
| sudosurootdev/gcc | libstdc++-v3/testsuite/23_containers/vector/debug/construct3_neg.cc | C++ | gpl-2.0 | 992 |
//
// detail/posix_signal_blocker.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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 BOOST_ASIO_DETAIL_POSIX_SIGNAL_BLOCKER_HPP
#define BOOST_ASIO_DETAIL_POSIX_SIGNAL_BLOCKER_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#if defined(BOOST_ASIO_HAS_PTHREADS)
#include <csignal>
#include <pthread.h>
#include <signal.h>
#include <boost/asio/detail/noncopyable.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace detail {
class posix_signal_blocker
: private noncopyable
{
public:
// Constructor blocks all signals for the calling thread.
posix_signal_blocker()
: blocked_(false)
{
sigset_t new_mask;
sigfillset(&new_mask);
blocked_ = (pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask_) == 0);
}
// Destructor restores the previous signal mask.
~posix_signal_blocker()
{
if (blocked_)
pthread_sigmask(SIG_SETMASK, &old_mask_, 0);
}
// Block all signals for the calling thread.
void block()
{
if (!blocked_)
{
sigset_t new_mask;
sigfillset(&new_mask);
blocked_ = (pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask_) == 0);
}
}
// Restore the previous signal mask.
void unblock()
{
if (blocked_)
blocked_ = (pthread_sigmask(SIG_SETMASK, &old_mask_, 0) != 0);
}
private:
// Have signals been blocked.
bool blocked_;
// The previous signal mask.
sigset_t old_mask_;
};
} // namespace detail
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // defined(BOOST_ASIO_HAS_PTHREADS)
#endif // BOOST_ASIO_DETAIL_POSIX_SIGNAL_BLOCKER_HPP
| jack8z/TODOP | third_party/boost_1_65_1/boost/asio/detail/posix_signal_blocker.hpp | C++ | gpl-2.0 | 1,975 |
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
/*======
This file is part of PerconaFT.
Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved.
PerconaFT is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2,
as published by the Free Software Foundation.
PerconaFT 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 PerconaFT. If not, see <http://www.gnu.org/licenses/>.
----------------------------------------
PerconaFT is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License, version 3,
as published by the Free Software Foundation.
PerconaFT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with PerconaFT. If not, see <http://www.gnu.org/licenses/>.
======= */
#ident "Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved."
#include "test.h"
static TOKUTXN const null_txn = 0;
static void test0 (void) {
FT_HANDLE t;
int r;
CACHETABLE ct;
const char *fname = TOKU_TEST_FILENAME;
if (verbose) printf("%s:%d test0\n", __FILE__, __LINE__);
toku_cachetable_create(&ct, 0, ZERO_LSN, nullptr);
if (verbose) printf("%s:%d test0\n", __FILE__, __LINE__);
unlink(fname);
r = toku_open_ft_handle(fname, 1, &t, 1024, 256, TOKU_DEFAULT_COMPRESSION_METHOD, ct, null_txn, toku_builtin_compare_fun);
assert(r==0);
//printf("%s:%d test0\n", __FILE__, __LINE__);
//printf("%s:%d n_items_malloced=%lld\n", __FILE__, __LINE__, n_items_malloced);
r = toku_close_ft_handle_nolsn(t, 0); assert(r==0);
//printf("%s:%d n_items_malloced=%lld\n", __FILE__, __LINE__, n_items_malloced);
toku_cachetable_close(&ct);
}
int
test_main (int argc , const char *argv[]) {
default_parse_args(argc, argv);
if (verbose) printf("test0 A\n");
test0();
if (verbose) printf("test0 B\n");
test0(); /* Make sure it works twice. */
if (verbose) printf("test0 ok\n");
return 0;
}
| ChengXiaoZ/MariaDBserver | storage/tokudb/PerconaFT/ft/tests/ft-test0.cc | C++ | gpl-2.0 | 2,689 |
<?php
/**
* @package Joomla.Plugin
* @subpackage System.remember
*
* @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* Joomla! System Remember Me Plugin
*
* @package Joomla.Plugin
* @subpackage System.remember
* @since 1.5
*/
class PlgSystemRemember extends JPlugin
{
/**
* Application object.
*
* @var JApplicationCms
* @since 3.2
*/
protected $app;
/**
* Remember me method to run onAfterInitialise
* Only purpose is to initialise the login authentication process if a cookie is present
*
* @return boolean
*
* @since 1.5
* @throws InvalidArgumentException
*/
public function onAfterInitialise()
{
// No remember me for admin.
if ($this->app->isAdmin())
{
return false;
}
// Check for a cookie if user is not logged in
if (JFactory::getUser()->get('guest'))
{
$cookieName = JUserHelper::getShortHashedUserAgent();
// Check for the cookie
if ($this->app->input->cookie->get($cookieName))
{
return $this->app->login(array('username' => ''), array('silent' => true));
}
}
return false;
}
public function onUserLogout($options)
{
// No remember me for admin
if ($this->app->isAdmin())
{
return false;
}
$cookieName = JUserHelper::getShortHashedUserAgent();
// Check for the cookie
if ($this->app->input->cookie->get($cookieName))
{
// Make sure authentication group is loaded to process onUserAfterLogout event
JPluginHelper::importPlugin('authentication');
}
}
}
| bblurock/windwalker-tutorial | plugins/system/remember/remember.php | PHP | gpl-2.0 | 1,659 |
// { dg-do compile }
// 2006-02-04 Edward Smith-Rowland <3dw4rd@verizon.net>
//
// Copyright (C) 2006-2014 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/>.
// 5.2.1.21 sph_bessel
#include <tr1/cmath>
void
test01()
{
float xf = 0.5F;
double xd = 0.5;
long double xl = 0.5L;
unsigned int n = 0;
std::tr1::sph_bessel(n, xf);
std::tr1::sph_besself(n, xf);
std::tr1::sph_bessel(n, xd);
std::tr1::sph_bessel(n, xl);
std::tr1::sph_bessell(n, xl);
return;
}
| xinchoubiology/gcc | libstdc++-v3/testsuite/tr1/5_numerical_facilities/special_functions/21_sph_bessel/compile.cc | C++ | gpl-2.0 | 1,169 |
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_config import cfg
from oslo_log import log as logging
# Import extensions to pull in osapi_compute_extension CONF option used below.
from nova.tests.functional import integrated_helpers
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
class ExtensionsTest(integrated_helpers._IntegratedTestBase):
_api_version = 'v2'
def _get_flags(self):
f = super(ExtensionsTest, self)._get_flags()
f['osapi_compute_extension'] = CONF.osapi_compute_extension[:]
f['osapi_compute_extension'].append(
'nova.tests.unit.api.openstack.compute.extensions.'
'foxinsocks.Foxinsocks')
return f
def test_get_foxnsocks(self):
# Simple check that fox-n-socks works.
response = self.api.api_request('/foxnsocks')
foxnsocks = response.content
LOG.debug("foxnsocks: %s" % foxnsocks)
self.assertEqual('Try to say this Mr. Knox, sir...', foxnsocks)
| jeffrey4l/nova | nova/tests/functional/test_extensions.py | Python | apache-2.0 | 1,578 |
/*
* 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.sling.mailarchiveserver.util;
import java.io.PrintStream;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ValueMap;
/**
* Util class to calculate entropy of a letter position in the message subject.
*
* @author bogomolo
*/
@Component
public class SubjectLettersEntropy {
private static final int SAMPLE_LENGTH = 300;
private static final int ALPHABET_LENGTH = 26;
private static final double THRESHOLD = 0.9;
private static final double MAX_THEOR_ENTROPY = -Math.log10(1./ALPHABET_LENGTH);
@Reference
ResourceResolverFactory resourceResolverFactory;
private ResourceResolver resolver = null;
public static SubjectLettersEntropy instance = null;
public SubjectLettersEntropy() {
if (instance == null) {
instance = this;
}
}
int[][] count = new int[SAMPLE_LENGTH][ALPHABET_LENGTH];
double[] entropy = new double[SAMPLE_LENGTH];
int messages = 0;
public void calculateEntropyAndPrint(PrintStream out) {
try {
if (resourceResolverFactory == null) {
System.out.println("resourceResolverFactory is NULL");
}
resolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
String root = "/content/mailarchiveserver/archive"; // /domain/project/list/t/th/thread/message
Resource main = resolver.getResource(root);
iterate(main, 6);
int[] sum = new int[SAMPLE_LENGTH];
for (int i = 0; i < sum.length; i++) {
for (int j = 0; j < ALPHABET_LENGTH; j++) {
sum[i] += count[i][j];
}
}
for (int i = 0; i < sum.length; i++) {
for (int j = 0; j < ALPHABET_LENGTH; j++) {
if (count[i][j] > 0) {
double num = count[i][j]/1./sum[i];
entropy[i] += - num * Math.log10(num);
}
}
}
System.out.println(String.format("%s\t%s\t%s", "charAt","entropy", "sum"));
for (int i = 0; i < sum.length; i++) {
if (entropy[i] >= MAX_THEOR_ENTROPY*THRESHOLD || sum[i] >= messages*THRESHOLD)
System.out.println(String.format("%d\t%.3f\t%d", i, entropy[i], sum[i]));
}
out.println("Messages #: "+messages);
} catch (LoginException e) {
e.printStackTrace();
}
}
private void countLetters(Resource r) {
messages++;
ValueMap properties = r.adaptTo(ValueMap.class);
String subj = properties.get("Subject", (String) null);
for (int i = 0; i < Math.min(subj.length(), SAMPLE_LENGTH); i++) {
Character c = Character.toLowerCase(subj.charAt(i));
if (c.toString().matches("[a-z]")) {
count[i][c-'a']++;
}
}
}
private void iterate(Resource r, int lvl) {
for (Resource child : r.getChildren()) {
if (lvl == 0) {
countLetters(child);
} else {
iterate(child, lvl-1);
}
}
}
}
| dulvac/sling | samples/mail-archive/server/src/test/java/org/apache/sling/mailarchiveserver/util/SubjectLettersEntropy.java | Java | apache-2.0 | 3,776 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.platform.plugin;
import org.apache.ignite.plugin.IgnitePlugin;
/**
* Test plugin.
*/
class PlatformTestPlugin implements IgnitePlugin {
// No-op.
}
| irudyak/ignite | modules/extdata/platform/src/test/java/org/apache/ignite/platform/plugin/PlatformTestPlugin.java | Java | apache-2.0 | 986 |
///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Mathematics (glm.g-truc.net)
///
/// Copyright (c) 2005 - 2015 G-Truc Creation (www.g-truc.net)
/// 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.
///
/// Restrictions:
/// By making use of the Software for military purposes, you choose to make
/// a Bunny unhappy.
///
/// 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.
///
/// @ref gtx_matrix_decompose
/// @file glm/gtx/matrix_decompose.hpp
/// @date 2014-08-29 / 2014-08-29
/// @author Christophe Riccio
///
/// @see core (dependence)
///
/// @defgroup gtx_matrix_decompose GLM_GTX_matrix_decompose
/// @ingroup gtx
///
/// @brief Decomposes a model matrix to translations, rotation and scale components
///
/// <glm/gtx/matrix_decompose.hpp> need to be included to use these functionalities.
///////////////////////////////////////////////////////////////////////////////////
#pragma once
// Dependencies
#include "../mat4x4.hpp"
#include "../vec3.hpp"
#include "../vec4.hpp"
#include "../geometric.hpp"
#include "../gtc/quaternion.hpp"
#include "../gtc/matrix_transform.hpp"
#if(defined(GLM_MESSAGES) && !defined(GLM_EXT_INCLUDED))
# pragma message("GLM: GLM_GTX_matrix_decompose extension included")
#endif
namespace glm
{
/// @addtogroup gtx_matrix_decompose
/// @{
/// Decomposes a model matrix to translations, rotation and scale components
/// @see gtx_matrix_decompose
template <typename T, precision P>
GLM_FUNC_DECL bool decompose(
tmat4x4<T, P> const & modelMatrix,
tvec3<T, P> & scale, tquat<T, P> & orientation, tvec3<T, P> & translation, tvec3<T, P> & skew, tvec4<T, P> & perspective);
/// @}
}//namespace glm
#include "matrix_decompose.inl"
| DevRaptor/OpenGL_tutorial | visual_libs/glm/glm/gtx/matrix_decompose.hpp | C++ | mit | 2,715 |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.svn.svnkit;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.SvnConfiguration;
import org.jetbrains.idea.svn.SvnHttpAuthMethodsDefaultChecker;
import org.jetbrains.idea.svn.SvnVcs;
import org.jetbrains.idea.svn.auth.SvnAuthenticationManager;
import org.jetbrains.idea.svn.svnkit.lowLevel.PrimitivePool;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.internal.util.jna.SVNJNAUtil;
import org.tmatesoft.svn.core.internal.wc.admin.SVNAdminArea14;
import org.tmatesoft.svn.core.internal.wc.admin.SVNAdminAreaFactory;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.*;
import org.tmatesoft.svn.util.SVNDebugLog;
/**
* @author Konstantin Kolosovsky.
*/
public class SvnKitManager {
private static final Logger LOG = SvnVcs.wrapLogger(Logger.getInstance(SvnKitManager.class));
@NonNls public static final String LOG_PARAMETER_NAME = "javasvn.log";
@NonNls public static final String TRACE_NATIVE_CALLS = "javasvn.log.native";
@NonNls public static final String SVNKIT_HTTP_SSL_PROTOCOLS = "svnkit.http.sslProtocols";
@Nullable private static String ourExplicitlySetSslProtocols;
@NotNull private final SvnVcs myVcs;
@NotNull private final Project myProject;
@NotNull private final SvnConfiguration myConfiguration;
static {
System.setProperty("svnkit.log.native.calls", "true");
final SvnKitDebugLogger
logger = new SvnKitDebugLogger(Boolean.getBoolean(LOG_PARAMETER_NAME), Boolean.getBoolean(TRACE_NATIVE_CALLS), LOG);
SVNDebugLog.setDefaultLog(logger);
SVNJNAUtil.setJNAEnabled(true);
SvnHttpAuthMethodsDefaultChecker.check();
SVNAdminAreaFactory.setSelector(new SvnKitAdminAreaFactorySelector());
DAVRepositoryFactory.setup();
SVNRepositoryFactoryImpl.setup();
FSRepositoryFactory.setup();
// non-optimized writing is fast enough on Linux/MacOS, and somewhat more reliable
if (SystemInfo.isWindows) {
SVNAdminArea14.setOptimizedWritingEnabled(true);
}
if (!SVNJNAUtil.isJNAPresent()) {
LOG.warn("JNA is not found by svnkit library");
}
ourExplicitlySetSslProtocols = System.getProperty(SVNKIT_HTTP_SSL_PROTOCOLS);
}
public SvnKitManager(@NotNull SvnVcs vcs) {
myVcs = vcs;
myProject = myVcs.getProject();
myConfiguration = myVcs.getSvnConfiguration();
refreshSSLProperty();
}
@Nullable
public static String getExplicitlySetSslProtocols() {
return ourExplicitlySetSslProtocols;
}
public static boolean isSSLProtocolExplicitlySet() {
return ourExplicitlySetSslProtocols != null;
}
public void refreshSSLProperty() {
if (isSSLProtocolExplicitlySet()) return;
if (SvnConfiguration.SSLProtocols.all.equals(myConfiguration.getSslProtocols())) {
System.clearProperty(SVNKIT_HTTP_SSL_PROTOCOLS);
}
else if (SvnConfiguration.SSLProtocols.sslv3.equals(myConfiguration.getSslProtocols())) {
System.setProperty(SVNKIT_HTTP_SSL_PROTOCOLS, "SSLv3");
}
else if (SvnConfiguration.SSLProtocols.tlsv1.equals(myConfiguration.getSslProtocols())) {
System.setProperty(SVNKIT_HTTP_SSL_PROTOCOLS, "TLSv1");
}
}
public void activate() {
if (SystemInfo.isWindows) {
if (!SVNJNAUtil.isJNAPresent()) {
Notifications.Bus.notify(new Notification(myVcs.getDisplayName(), "Subversion plugin: no JNA",
"A problem with JNA initialization for SVNKit library. Encryption is not available.",
NotificationType.WARNING), myProject);
}
else if (!SVNJNAUtil.isWinCryptEnabled()) {
Notifications.Bus.notify(new Notification(myVcs.getDisplayName(), "Subversion plugin: no encryption",
"A problem with encryption module (Crypt32.dll) initialization for SVNKit library. " +
"Encryption is not available.",
NotificationType.WARNING
), myProject);
}
}
}
@NotNull
public ISVNOptions getSvnOptions() {
return myConfiguration.getOptions();
}
@NotNull
public SVNRepository createRepository(String url) throws SVNException {
return createRepository(SVNURL.parseURIEncoded(url));
}
@NotNull
public SVNRepository createRepository(@NotNull SVNURL url) throws SVNException {
SVNRepository repository = SVNRepositoryFactory.create(url);
repository.setAuthenticationManager(getAuthenticationManager());
repository.setTunnelProvider(getSvnOptions());
return repository;
}
@NotNull
private ISVNRepositoryPool getPool() {
return getPool(getAuthenticationManager());
}
@NotNull
private ISVNRepositoryPool getPool(@NotNull ISVNAuthenticationManager manager) {
if (myProject.isDisposed()) {
throw new ProcessCanceledException();
}
return new PrimitivePool(manager, getSvnOptions());
}
@NotNull
public SVNUpdateClient createUpdateClient() {
return setupClient(new SVNUpdateClient(getPool(), getSvnOptions()));
}
@NotNull
public SVNUpdateClient createUpdateClient(@NotNull ISVNAuthenticationManager manager) {
return setupClient(new SVNUpdateClient(getPool(manager), getSvnOptions()), manager);
}
@NotNull
public SVNStatusClient createStatusClient() {
SVNStatusClient client = new SVNStatusClient(getPool(), getSvnOptions());
client.setIgnoreExternals(false);
return setupClient(client);
}
@NotNull
public SVNWCClient createWCClient() {
return setupClient(new SVNWCClient(getPool(), getSvnOptions()));
}
@NotNull
public SVNWCClient createWCClient(@NotNull ISVNAuthenticationManager manager) {
return setupClient(new SVNWCClient(getPool(manager), getSvnOptions()), manager);
}
@NotNull
public SVNCopyClient createCopyClient() {
return setupClient(new SVNCopyClient(getPool(), getSvnOptions()));
}
@NotNull
public SVNMoveClient createMoveClient() {
return setupClient(new SVNMoveClient(getPool(), getSvnOptions()));
}
@NotNull
public SVNLogClient createLogClient() {
return setupClient(new SVNLogClient(getPool(), getSvnOptions()));
}
@NotNull
public SVNLogClient createLogClient(@NotNull ISVNAuthenticationManager manager) {
return setupClient(new SVNLogClient(getPool(manager), getSvnOptions()), manager);
}
@NotNull
public SVNCommitClient createCommitClient() {
return setupClient(new SVNCommitClient(getPool(), getSvnOptions()));
}
@NotNull
public SVNDiffClient createDiffClient() {
return setupClient(new SVNDiffClient(getPool(), getSvnOptions()));
}
@NotNull
public SVNChangelistClient createChangelistClient() {
return setupClient(new SVNChangelistClient(getPool(), getSvnOptions()));
}
@NotNull
private SvnAuthenticationManager getAuthenticationManager() {
return myConfiguration.getAuthenticationManager(myVcs);
}
@NotNull
private <T extends SVNBasicClient> T setupClient(@NotNull T client) {
return setupClient(client, getAuthenticationManager());
}
@NotNull
private static <T extends SVNBasicClient> T setupClient(@NotNull T client, @NotNull ISVNAuthenticationManager manager) {
client.getOperationsFactory().setAuthenticationManager(manager);
return client;
}
}
| akosyakov/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/svnkit/SvnKitManager.java | Java | apache-2.0 | 8,785 |
/**
* Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior
* University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package org.openflow.protocol.statistics;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.jboss.netty.buffer.ChannelBuffer;
/**
* Represents an ofp_queue_stats structure
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public class OFQueueStatisticsReply implements OFStatistics {
protected short portNumber;
protected int queueId;
protected long transmitBytes;
protected long transmitPackets;
protected long transmitErrors;
/**
* @return the portNumber
*/
public short getPortNumber() {
return portNumber;
}
/**
* @param portNumber the portNumber to set
*/
public void setPortNumber(short portNumber) {
this.portNumber = portNumber;
}
/**
* @return the queueId
*/
public int getQueueId() {
return queueId;
}
/**
* @param queueId the queueId to set
*/
public void setQueueId(int queueId) {
this.queueId = queueId;
}
/**
* @return the transmitBytes
*/
public long getTransmitBytes() {
return transmitBytes;
}
/**
* @param transmitBytes the transmitBytes to set
*/
public void setTransmitBytes(long transmitBytes) {
this.transmitBytes = transmitBytes;
}
/**
* @return the transmitPackets
*/
public long getTransmitPackets() {
return transmitPackets;
}
/**
* @param transmitPackets the transmitPackets to set
*/
public void setTransmitPackets(long transmitPackets) {
this.transmitPackets = transmitPackets;
}
/**
* @return the transmitErrors
*/
public long getTransmitErrors() {
return transmitErrors;
}
/**
* @param transmitErrors the transmitErrors to set
*/
public void setTransmitErrors(long transmitErrors) {
this.transmitErrors = transmitErrors;
}
@Override
@JsonIgnore
public int getLength() {
return 32;
}
@Override
public void readFrom(ChannelBuffer data) {
this.portNumber = data.readShort();
data.readShort(); // pad
this.queueId = data.readInt();
this.transmitBytes = data.readLong();
this.transmitPackets = data.readLong();
this.transmitErrors = data.readLong();
}
@Override
public void writeTo(ChannelBuffer data) {
data.writeShort(this.portNumber);
data.writeShort((short) 0); // pad
data.writeInt(this.queueId);
data.writeLong(this.transmitBytes);
data.writeLong(this.transmitPackets);
data.writeLong(this.transmitErrors);
}
@Override
public int hashCode() {
final int prime = 439;
int result = 1;
result = prime * result + portNumber;
result = prime * result + queueId;
result = prime * result
+ (int) (transmitBytes ^ (transmitBytes >>> 32));
result = prime * result
+ (int) (transmitErrors ^ (transmitErrors >>> 32));
result = prime * result
+ (int) (transmitPackets ^ (transmitPackets >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof OFQueueStatisticsReply)) {
return false;
}
OFQueueStatisticsReply other = (OFQueueStatisticsReply) obj;
if (portNumber != other.portNumber) {
return false;
}
if (queueId != other.queueId) {
return false;
}
if (transmitBytes != other.transmitBytes) {
return false;
}
if (transmitErrors != other.transmitErrors) {
return false;
}
if (transmitPackets != other.transmitPackets) {
return false;
}
return true;
}
}
| alsmadi/CSCI-6617 | src/main/java/org/openflow/protocol/statistics/OFQueueStatisticsReply.java | Java | apache-2.0 | 4,637 |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// GraphCycles provides incremental cycle detection on a dynamic
// graph using the following algorithm:
//
// A dynamic topological sort algorithm for directed acyclic graphs
// David J. Pearce, Paul H. J. Kelly
// Journal of Experimental Algorithmics (JEA) JEA Homepage archive
// Volume 11, 2006, Article No. 1.7
//
// Brief summary of the algorithm:
//
// (1) Maintain a rank for each node that is consistent
// with the topological sort of the graph. I.e., path from x to y
// implies rank[x] < rank[y].
// (2) When a new edge (x->y) is inserted, do nothing if rank[x] < rank[y].
// (3) Otherwise: adjust ranks in the neighborhood of x and y.
#include "tensorflow/compiler/jit/graphcycles/graphcycles.h"
#include <algorithm>
#include <unordered_set>
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/platform/logging.h"
namespace tensorflow {
namespace {
typedef std::unordered_set<int32> NodeSet;
template <typename T>
struct VecStruct {
typedef gtl::InlinedVector<T, 4> type;
};
template <typename T>
using Vec = typename VecStruct<T>::type;
struct Node {
Node() : in(4), out(4) {} // Small hashtables for in/out edges
int32 rank; // rank number assigned by Pearce-Kelly algorithm
bool visited; // Temporary marker used by depth-first-search
void* data; // User-supplied data
NodeSet in; // List of immediate predecessor nodes in graph
NodeSet out; // List of immediate successor nodes in graph
};
} // namespace
struct GraphCycles::Rep {
Vec<Node*> nodes_;
Vec<int32> free_nodes_; // Indices for unused entries in nodes_
// Temporary state.
Vec<int32> deltaf_; // Results of forward DFS
Vec<int32> deltab_; // Results of backward DFS
Vec<int32> list_; // All nodes to reprocess
Vec<int32> merged_; // Rank values to assign to list_ entries
Vec<int32> stack_; // Emulates recursion stack when doing depth first search
};
GraphCycles::GraphCycles() : rep_(new Rep) {}
GraphCycles::~GraphCycles() {
for (Vec<Node*>::size_type i = 0; i < rep_->nodes_.size(); i++) {
delete rep_->nodes_[i];
}
delete rep_;
}
bool GraphCycles::CheckInvariants() const {
Rep* r = rep_;
NodeSet ranks; // Set of ranks seen so far.
for (Vec<Node*>::size_type x = 0; x < r->nodes_.size(); x++) {
Node* nx = r->nodes_[x];
if (nx->visited) {
LOG(FATAL) << "Did not clear visited marker on node " << x;
}
if (!ranks.insert(nx->rank).second) {
LOG(FATAL) << "Duplicate occurrence of rank " << nx->rank;
}
for (auto y : nx->out) {
Node* ny = r->nodes_[y];
if (nx->rank >= ny->rank) {
LOG(FATAL) << "Edge " << x << "->" << y << " has bad rank assignment "
<< nx->rank << "->" << ny->rank;
}
}
}
return true;
}
int32 GraphCycles::NewNode() {
if (rep_->free_nodes_.empty()) {
Node* n = new Node;
n->visited = false;
n->data = NULL;
n->rank = rep_->nodes_.size();
rep_->nodes_.push_back(n);
return n->rank;
} else {
// Preserve preceding rank since the set of ranks in use must be
// a permutation of [0,rep_->nodes_.size()-1].
int32 r = rep_->free_nodes_.back();
rep_->nodes_[r]->data = NULL;
rep_->free_nodes_.pop_back();
return r;
}
}
void GraphCycles::RemoveNode(int32 node) {
Node* x = rep_->nodes_[node];
for (auto y : x->out) {
rep_->nodes_[y]->in.erase(node);
}
for (auto y : x->in) {
rep_->nodes_[y]->out.erase(node);
}
x->in.clear();
x->out.clear();
rep_->free_nodes_.push_back(node);
}
void* GraphCycles::GetNodeData(int32 node) const {
return rep_->nodes_[node]->data;
}
void GraphCycles::SetNodeData(int32 node, void* data) {
rep_->nodes_[node]->data = data;
}
bool GraphCycles::HasEdge(int32 x, int32 y) const {
return rep_->nodes_[x]->out.find(y) != rep_->nodes_[x]->out.end();
}
void GraphCycles::RemoveEdge(int32 x, int32 y) {
rep_->nodes_[x]->out.erase(y);
rep_->nodes_[y]->in.erase(x);
// No need to update the rank assignment since a previous valid
// rank assignment remains valid after an edge deletion.
}
static bool ForwardDFS(GraphCycles::Rep* r, int32 n, int32 upper_bound);
static void BackwardDFS(GraphCycles::Rep* r, int32 n, int32 lower_bound);
static void Reorder(GraphCycles::Rep* r);
static void Sort(const Vec<Node*>&, Vec<int32>* delta);
static void MoveToList(GraphCycles::Rep* r, Vec<int32>* src, Vec<int32>* dst);
static void ClearVisitedBits(GraphCycles::Rep* r, const Vec<int32>& nodes);
bool GraphCycles::InsertEdge(int32 x, int32 y) {
if (x == y) return false;
Rep* r = rep_;
Node* nx = r->nodes_[x];
if (!nx->out.insert(y).second) {
// Edge already exists.
return true;
}
Node* ny = r->nodes_[y];
ny->in.insert(x);
if (nx->rank <= ny->rank) {
// New edge is consistent with existing rank assignment.
return true;
}
// Current rank assignments are incompatible with the new edge. Recompute.
// We only need to consider nodes that fall in the range [ny->rank,nx->rank].
if (!ForwardDFS(r, y, nx->rank)) {
// Found a cycle. Undo the insertion and tell caller.
nx->out.erase(y);
ny->in.erase(x);
// Since we do not call Reorder() on this path, clear any visited
// markers left by ForwardDFS.
ClearVisitedBits(r, r->deltaf_);
return false;
}
BackwardDFS(r, x, ny->rank);
Reorder(r);
return true;
}
static bool ForwardDFS(GraphCycles::Rep* r, int32 n, int32 upper_bound) {
// Avoid recursion since stack space might be limited.
// We instead keep a stack of nodes to visit.
r->deltaf_.clear();
r->stack_.clear();
r->stack_.push_back(n);
while (!r->stack_.empty()) {
n = r->stack_.back();
r->stack_.pop_back();
Node* nn = r->nodes_[n];
if (nn->visited) continue;
nn->visited = true;
r->deltaf_.push_back(n);
for (auto w : nn->out) {
Node* nw = r->nodes_[w];
if (nw->rank == upper_bound) {
return false; // Cycle
}
if (!nw->visited && nw->rank < upper_bound) {
r->stack_.push_back(w);
}
}
}
return true;
}
static void BackwardDFS(GraphCycles::Rep* r, int32 n, int32 lower_bound) {
r->deltab_.clear();
r->stack_.clear();
r->stack_.push_back(n);
while (!r->stack_.empty()) {
n = r->stack_.back();
r->stack_.pop_back();
Node* nn = r->nodes_[n];
if (nn->visited) continue;
nn->visited = true;
r->deltab_.push_back(n);
for (auto w : nn->in) {
Node* nw = r->nodes_[w];
if (!nw->visited && lower_bound < nw->rank) {
r->stack_.push_back(w);
}
}
}
}
static void Reorder(GraphCycles::Rep* r) {
Sort(r->nodes_, &r->deltab_);
Sort(r->nodes_, &r->deltaf_);
// Adds contents of delta lists to list_ (backwards deltas first).
r->list_.clear();
MoveToList(r, &r->deltab_, &r->list_);
MoveToList(r, &r->deltaf_, &r->list_);
// Produce sorted list of all ranks that will be reassigned.
r->merged_.resize(r->deltab_.size() + r->deltaf_.size());
std::merge(r->deltab_.begin(), r->deltab_.end(), r->deltaf_.begin(),
r->deltaf_.end(), r->merged_.begin());
// Assign the ranks in order to the collected list.
for (Vec<int32>::size_type i = 0; i < r->list_.size(); i++) {
r->nodes_[r->list_[i]]->rank = r->merged_[i];
}
}
static void Sort(const Vec<Node*>& nodes, Vec<int32>* delta) {
struct ByRank {
const Vec<Node*>* nodes;
bool operator()(int32 a, int32 b) const {
return (*nodes)[a]->rank < (*nodes)[b]->rank;
}
};
ByRank cmp;
cmp.nodes = &nodes;
std::sort(delta->begin(), delta->end(), cmp);
}
static void MoveToList(GraphCycles::Rep* r, Vec<int32>* src, Vec<int32>* dst) {
for (Vec<int32>::size_type i = 0; i < src->size(); i++) {
int32 w = (*src)[i];
(*src)[i] = r->nodes_[w]->rank; // Replace src entry with its rank
r->nodes_[w]->visited = false; // Prepare for future DFS calls
dst->push_back(w);
}
}
static void ClearVisitedBits(GraphCycles::Rep* r, const Vec<int32>& nodes) {
for (Vec<int32>::size_type i = 0; i < nodes.size(); i++) {
r->nodes_[nodes[i]]->visited = false;
}
}
int GraphCycles::FindPath(int32 x, int32 y, int max_path_len,
int32 path[]) const {
// Forward depth first search starting at x until we hit y.
// As we descend into a node, we push it onto the path.
// As we leave a node, we remove it from the path.
int path_len = 0;
Rep* r = rep_;
NodeSet seen;
r->stack_.clear();
r->stack_.push_back(x);
while (!r->stack_.empty()) {
int32 n = r->stack_.back();
r->stack_.pop_back();
if (n < 0) {
// Marker to indicate that we are leaving a node
path_len--;
continue;
}
if (path_len < max_path_len) {
path[path_len] = n;
}
path_len++;
r->stack_.push_back(-1); // Will remove tentative path entry
if (n == y) {
return path_len;
}
for (auto w : r->nodes_[n]->out) {
if (seen.insert(w).second) {
r->stack_.push_back(w);
}
}
}
return 0;
}
bool GraphCycles::IsReachable(int32 x, int32 y) const {
return FindPath(x, y, 0, NULL) > 0;
}
bool GraphCycles::IsReachableNonConst(int32 x, int32 y) {
if (x == y) return true;
Rep* r = rep_;
Node* nx = r->nodes_[x];
Node* ny = r->nodes_[y];
if (nx->rank >= ny->rank) {
// x cannot reach y since it is after it in the topological ordering
return false;
}
// See if x can reach y using a DFS search that is limited to y's rank
bool reachable = !ForwardDFS(r, x, ny->rank);
// Clear any visited markers left by ForwardDFS.
ClearVisitedBits(r, r->deltaf_);
return reachable;
}
bool GraphCycles::ContractEdge(int32 a, int32 b) {
CHECK(HasEdge(a, b));
RemoveEdge(a, b);
if (IsReachableNonConst(a, b)) {
// Restore the graph to its original state.
InsertEdge(a, b);
return false;
}
Node* nb = rep_->nodes_[b];
std::unordered_set<int32> out = std::move(nb->out);
std::unordered_set<int32> in = std::move(nb->in);
for (auto y : out) {
rep_->nodes_[y]->in.erase(b);
}
for (auto y : in) {
rep_->nodes_[y]->out.erase(b);
}
rep_->free_nodes_.push_back(b);
for (auto y : out) {
InsertEdge(a, y);
}
for (auto y : in) {
InsertEdge(y, a);
}
return true;
}
std::unordered_set<int32> GraphCycles::Successors(int32 node) {
return rep_->nodes_[node]->out;
}
} // namespace tensorflow
| wangyum/tensorflow | tensorflow/compiler/jit/graphcycles/graphcycles.cc | C++ | apache-2.0 | 11,105 |
function WPATH(s) {
var index = s.lastIndexOf("/");
var path = -1 === index ? "tony.section/" + s : s.substring(0, index) + "/tony.section/" + s.substring(index + 1);
return path;
}
module.exports = []; | brentonhouse/brentonhouse.alloy | test/apps/testing/ALOY-833/_generated/mobileweb/alloy/widgets/tony.section/styles/widget.js | JavaScript | apache-2.0 | 215 |
require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../../spec_helper')
describe "/<%= table_name %>/edit.<%= default_file_extension %>" do
include <%= controller_class_name %>Helper
before(:each) do
assigns[:<%= file_name %>] = @<%= file_name %> = stub_model(<%= class_name %>,
:new_record? => false<%= attributes.empty? ? '' : ',' %>
<% attributes.each_with_index do |attribute, attribute_index| -%><% unless attribute.name =~ /_id/ || [:datetime, :timestamp, :time, :date].index(attribute.type) -%>
:<%= attribute.name %> => <%= attribute.default_value %><%= attribute_index == attributes.length - 1 ? '' : ','%>
<% end -%><% end -%>
)
end
it "should render edit form" do
render "/<%= table_name %>/edit.<%= default_file_extension %>"
response.should have_tag("form[action=#{<%= file_name %>_path(@<%= file_name %>)}][method=post]") do
<% for attribute in attributes -%><% unless attribute.name =~ /_id/ || [:datetime, :timestamp, :time, :date].index(attribute.type) -%>
with_tag('<%= attribute.input_type -%>#<%= file_name %>_<%= attribute.name %>[name=?]', "<%= file_name %>[<%= attribute.name %>]")
<% end -%><% end -%>
end
end
end
| tapn2it/attic-antiques | vendor/spree/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/edit_erb_spec.rb | Ruby | bsd-3-clause | 1,232 |
import { errorObject } from './errorObject';
let tryCatchTarget: Function;
function tryCatcher(this: any): any {
try {
return tryCatchTarget.apply(this, arguments);
} catch (e) {
errorObject.e = e;
return errorObject;
}
}
export function tryCatch<T extends Function>(fn: T): T {
tryCatchTarget = fn;
return <any>tryCatcher;
};
| mo-norant/FinHeartBel | website/node_modules/rxjs/src/util/tryCatch.ts | TypeScript | gpl-3.0 | 352 |
<TS language="kk" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Create a new address</source>
<translation>Жаңа адрес енгізу</translation>
</message>
<message>
<source>&New</source>
<translation>Жаңа</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Таңдаған адресті тізімнен жою</translation>
</message>
<message>
<source>C&lose</source>
<translation>Жабу</translation>
</message>
<message>
<source>&Export</source>
<translation>Экспорт</translation>
</message>
<message>
<source>&Delete</source>
<translation>Жою</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Enter passphrase</source>
<translation>Құпия сөзді енгізу</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Жаңа құпия сөзі</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Жаңа құпия сөзді қайта енгізу</translation>
</message>
</context>
<context>
<name>BanTableModel</name>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>&Transactions</source>
<translation>&Транзакциялар</translation>
</message>
<message>
<source>E&xit</source>
<translation>Шығу</translation>
</message>
<message>
<source>&Options...</source>
<translation>Параметрлері</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>Әмиянды жасыру</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>Құпия сөзді өзгерту</translation>
</message>
<message>
<source>&Send</source>
<translation>Жіберу</translation>
</message>
<message>
<source>&Receive</source>
<translation>Алу</translation>
</message>
<message>
<source>&File</source>
<translation>Файл</translation>
</message>
<message>
<source>&Help</source>
<translation>Көмек</translation>
</message>
<message>
<source>%1 behind</source>
<translation>%1 қалмады</translation>
</message>
<message>
<source>Error</source>
<translation>қате</translation>
</message>
<message>
<source>Warning</source>
<translation>Ескерту</translation>
</message>
<message>
<source>Information</source>
<translation>Информация</translation>
</message>
<message>
<source>Up to date</source>
<translation>Жаңартылған</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Amount:</source>
<translation>Саны</translation>
</message>
<message>
<source>Fee:</source>
<translation>Комиссия</translation>
</message>
<message>
<source>Dust:</source>
<translation>Шаң</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Комиссия алу кейін</translation>
</message>
<message>
<source>Amount</source>
<translation>Саны</translation>
</message>
<message>
<source>Date</source>
<translation>Күні</translation>
</message>
<message>
<source>Confirmations</source>
<translation>Растау саны</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Растық</translation>
</message>
</context>
<context>
<name>CreateWalletActivity</name>
</context>
<context>
<name>CreateWalletDialog</name>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>&Label</source>
<translation>таңба</translation>
</message>
<message>
<source>&Address</source>
<translation>Адрес</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
</context>
<context>
<name>HelpMessageDialog</name>
</context>
<context>
<name>Intro</name>
<message>
<source>Bitcoin</source>
<translation>Биткоин</translation>
</message>
<message>
<source>Error</source>
<translation>қате</translation>
</message>
</context>
<context>
<name>ModalOverlay</name>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OpenWalletActivity</name>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>W&allet</source>
<translation>Әмиян</translation>
</message>
<message>
<source>Error</source>
<translation>қате</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
</context>
<context>
<name>PSBTOperationsDialog</name>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>Саны</translation>
</message>
<message>
<source>%1 and %2</source>
<translation>%1 немесе %2</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>&Information</source>
<translation>Информация</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Amount:</source>
<translation>Саны</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>Amount:</source>
<translation>Саны</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>Күні</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Amount:</source>
<translation>Саны</translation>
</message>
<message>
<source>Fee:</source>
<translation>Комиссия:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Комиссия алу кейін:</translation>
</message>
<message>
<source>Dust:</source>
<translation>Шаң</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>Саны</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Date</source>
<translation>Күні</translation>
</message>
<message>
<source>Amount</source>
<translation>Саны</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>Күні</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>Confirmed</source>
<translation>Растық</translation>
</message>
<message>
<source>Date</source>
<translation>Күні</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletController</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
</context>
<context>
<name>WalletView</name>
<message>
<source>&Export</source>
<translation>Экспорт</translation>
</message>
<message>
<source>Error</source>
<translation>қате</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<source>Transaction amount too small</source>
<translation>Транзакция өте кішкентай</translation>
</message>
<message>
<source>Transaction too large</source>
<translation>Транзакция өте үлкен</translation>
</message>
</context>
</TS> | sstone/bitcoin | src/qt/locale/bitcoin_kk.ts | TypeScript | mit | 9,201 |
require 'rubygems/command'
##
# Installs RubyGems itself. This command is ordinarily only available from a
# RubyGems checkout or tarball.
class Gem::Commands::SetupCommand < Gem::Command
HISTORY_HEADER = /^===\s*[\d.]+\s*\/\s*\d{4}-\d{2}-\d{2}\s*$/
VERSION_MATCHER = /^===\s*([\d.]+)\s*\/\s*\d{4}-\d{2}-\d{2}\s*$/
def initialize
require 'tmpdir'
super 'setup', 'Install RubyGems',
:format_executable => true, :document => %w[ri],
:site_or_vendor => 'sitelibdir',
:destdir => '', :prefix => '', :previous_version => ''
add_option '--previous-version=VERSION',
'Previous version of rubygems',
'Used for changelog processing' do |version, options|
options[:previous_version] = version
end
add_option '--prefix=PREFIX',
'Prefix path for installing RubyGems',
'Will not affect gem repository location' do |prefix, options|
options[:prefix] = File.expand_path prefix
end
add_option '--destdir=DESTDIR',
'Root directory to install RubyGems into',
'Mainly used for packaging RubyGems' do |destdir, options|
options[:destdir] = File.expand_path destdir
end
add_option '--[no-]vendor',
'Install into vendorlibdir not sitelibdir' do |vendor, options|
options[:site_or_vendor] = vendor ? 'vendorlibdir' : 'sitelibdir'
end
add_option '--[no-]format-executable',
'Makes `gem` match ruby',
'If ruby is ruby18, gem will be gem18' do |value, options|
options[:format_executable] = value
end
add_option '--[no-]document [TYPES]', Array,
'Generate documentation for RubyGems.',
'List the documentation types you wish to',
'generate. For example: rdoc,ri' do |value, options|
options[:document] = case value
when nil then %w[rdoc ri]
when false then []
else value
end
end
add_option '--[no-]rdoc',
'Generate RDoc documentation for RubyGems' do |value, options|
if value then
options[:document] << 'rdoc'
else
options[:document].delete 'rdoc'
end
options[:document].uniq!
end
add_option '--[no-]ri',
'Generate RI documentation for RubyGems' do |value, options|
if value then
options[:document] << 'ri'
else
options[:document].delete 'ri'
end
options[:document].uniq!
end
@verbose = nil
end
def check_ruby_version
required_version = Gem::Requirement.new '>= 1.8.7'
unless required_version.satisfied_by? Gem.ruby_version then
alert_error "Expected Ruby version #{required_version}, is #{Gem.ruby_version}"
terminate_interaction 1
end
end
def defaults_str # :nodoc:
"--format-executable --document ri"
end
def description # :nodoc:
<<-EOF
Installs RubyGems itself.
RubyGems installs RDoc for itself in GEM_HOME. By default this is:
#{Gem.dir}
If you prefer a different directory, set the GEM_HOME environment variable.
RubyGems will install the gem command with a name matching ruby's
prefix and suffix. If ruby was installed as `ruby18`, gem will be
installed as `gem18`.
By default, this RubyGems will install gem as:
#{Gem.default_exec_format % 'gem'}
EOF
end
def execute
@verbose = Gem.configuration.really_verbose
install_destdir = options[:destdir]
unless install_destdir.empty? then
ENV['GEM_HOME'] ||= File.join(install_destdir,
Gem.default_dir.gsub(/^[a-zA-Z]:/, ''))
end
check_ruby_version
require 'fileutils'
if Gem.configuration.really_verbose then
extend FileUtils::Verbose
else
extend FileUtils
end
lib_dir, bin_dir = make_destination_dirs install_destdir
install_lib lib_dir
install_executables bin_dir
remove_old_bin_files bin_dir
remove_old_lib_files lib_dir
say "RubyGems #{Gem::VERSION} installed"
uninstall_old_gemcutter
documentation_success = install_rdoc
say
if @verbose then
say "-" * 78
say
end
if options[:previous_version].empty?
options[:previous_version] = Gem::VERSION.sub(/[0-9]+$/, '0')
end
options[:previous_version] = Gem::Version.new(options[:previous_version])
show_release_notes
say
say "-" * 78
say
say "RubyGems installed the following executables:"
say @bin_file_names.map { |name| "\t#{name}\n" }
say
unless @bin_file_names.grep(/#{File::SEPARATOR}gem$/) then
say "If `gem` was installed by a previous RubyGems installation, you may need"
say "to remove it by hand."
say
end
if documentation_success
if options[:document].include? 'rdoc' then
say "Rdoc documentation was installed. You may now invoke:"
say " gem server"
say "and then peruse beautifully formatted documentation for your gems"
say "with your web browser."
say "If you do not wish to install this documentation in the future, use the"
say "--no-document flag, or set it as the default in your ~/.gemrc file. See"
say "'gem help env' for details."
say
end
if options[:document].include? 'ri' then
say "Ruby Interactive (ri) documentation was installed. ri is kind of like man "
say "pages for ruby libraries. You may access it like this:"
say " ri Classname"
say " ri Classname.class_method"
say " ri Classname#instance_method"
say "If you do not wish to install this documentation in the future, use the"
say "--no-document flag, or set it as the default in your ~/.gemrc file. See"
say "'gem help env' for details."
say
end
end
end
def install_executables(bin_dir)
say "Installing gem executable" if @verbose
@bin_file_names = []
Dir.chdir 'bin' do
bin_files = Dir['*']
bin_files.delete 'update_rubygems'
bin_files.each do |bin_file|
bin_file_formatted = if options[:format_executable] then
Gem.default_exec_format % bin_file
else
bin_file
end
dest_file = File.join bin_dir, bin_file_formatted
bin_tmp_file = File.join Dir.tmpdir, "#{bin_file}.#{$$}"
begin
bin = File.readlines bin_file
bin[0] = "#!#{Gem.ruby}\n"
File.open bin_tmp_file, 'w' do |fp|
fp.puts bin.join
end
install bin_tmp_file, dest_file, :mode => 0755
@bin_file_names << dest_file
ensure
rm bin_tmp_file
end
next unless Gem.win_platform?
begin
bin_cmd_file = File.join Dir.tmpdir, "#{bin_file}.bat"
File.open bin_cmd_file, 'w' do |file|
file.puts <<-TEXT
@ECHO OFF
IF NOT "%~f0" == "~f0" GOTO :WinNT
@"#{File.basename(Gem.ruby).chomp('"')}" "#{dest_file}" %1 %2 %3 %4 %5 %6 %7 %8 %9
GOTO :EOF
:WinNT
@"#{File.basename(Gem.ruby).chomp('"')}" "%~dpn0" %*
TEXT
end
install bin_cmd_file, "#{dest_file}.bat", :mode => 0755
ensure
rm bin_cmd_file
end
end
end
end
def install_file file, dest_dir
dest_file = File.join dest_dir, file
dest_dir = File.dirname dest_file
mkdir_p dest_dir unless File.directory? dest_dir
install file, dest_file, :mode => 0644
end
def install_lib(lib_dir)
say "Installing RubyGems" if @verbose
lib_files = rb_files_in 'lib'
pem_files = pem_files_in 'lib'
Dir.chdir 'lib' do
lib_files.each do |lib_file|
install_file lib_file, lib_dir
end
pem_files.each do |pem_file|
install_file pem_file, lib_dir
end
end
end
def install_rdoc
gem_doc_dir = File.join Gem.dir, 'doc'
rubygems_name = "rubygems-#{Gem::VERSION}"
rubygems_doc_dir = File.join gem_doc_dir, rubygems_name
begin
Gem.ensure_gem_subdirectories Gem.dir
rescue SystemCallError
# ignore
end
if File.writable? gem_doc_dir and
(not File.exist? rubygems_doc_dir or
File.writable? rubygems_doc_dir) then
say "Removing old RubyGems RDoc and ri" if @verbose
Dir[File.join(Gem.dir, 'doc', 'rubygems-[0-9]*')].each do |dir|
rm_rf dir
end
require 'rubygems/rdoc'
fake_spec = Gem::Specification.new 'rubygems', Gem::VERSION
def fake_spec.full_gem_path
File.expand_path '../../../..', __FILE__
end
generate_ri = options[:document].include? 'ri'
generate_rdoc = options[:document].include? 'rdoc'
rdoc = Gem::RDoc.new fake_spec, generate_rdoc, generate_ri
rdoc.generate
return true
elsif @verbose then
say "Skipping RDoc generation, #{gem_doc_dir} not writable"
say "Set the GEM_HOME environment variable if you want RDoc generated"
end
return false
end
def make_destination_dirs(install_destdir)
lib_dir, bin_dir = Gem.default_rubygems_dirs
unless lib_dir
lib_dir, bin_dir = generate_default_dirs(install_destdir)
end
mkdir_p lib_dir
mkdir_p bin_dir
return lib_dir, bin_dir
end
def generate_default_dirs(install_destdir)
prefix = options[:prefix]
site_or_vendor = options[:site_or_vendor]
if prefix.empty? then
lib_dir = RbConfig::CONFIG[site_or_vendor]
bin_dir = RbConfig::CONFIG['bindir']
else
# Apple installed RubyGems into libdir, and RubyGems <= 1.1.0 gets
# confused about installation location, so switch back to
# sitelibdir/vendorlibdir.
if defined?(APPLE_GEM_HOME) and
# just in case Apple and RubyGems don't get this patched up proper.
(prefix == RbConfig::CONFIG['libdir'] or
# this one is important
prefix == File.join(RbConfig::CONFIG['libdir'], 'ruby')) then
lib_dir = RbConfig::CONFIG[site_or_vendor]
bin_dir = RbConfig::CONFIG['bindir']
else
lib_dir = File.join prefix, 'lib'
bin_dir = File.join prefix, 'bin'
end
end
unless install_destdir.empty? then
lib_dir = File.join install_destdir, lib_dir.gsub(/^[a-zA-Z]:/, '')
bin_dir = File.join install_destdir, bin_dir.gsub(/^[a-zA-Z]:/, '')
end
[lib_dir, bin_dir]
end
def pem_files_in dir
Dir.chdir dir do
Dir[File.join('**', '*pem')]
end
end
def rb_files_in dir
Dir.chdir dir do
Dir[File.join('**', '*rb')]
end
end
def remove_old_bin_files(bin_dir)
old_bin_files = {
'gem_mirror' => 'gem mirror',
'gem_server' => 'gem server',
'gemlock' => 'gem lock',
'gemri' => 'ri',
'gemwhich' => 'gem which',
'index_gem_repository.rb' => 'gem generate_index',
}
old_bin_files.each do |old_bin_file, new_name|
old_bin_path = File.join bin_dir, old_bin_file
next unless File.exist? old_bin_path
deprecation_message = "`#{old_bin_file}` has been deprecated. Use `#{new_name}` instead."
File.open old_bin_path, 'w' do |fp|
fp.write <<-EOF
#!#{Gem.ruby}
abort "#{deprecation_message}"
EOF
end
next unless Gem.win_platform?
File.open "#{old_bin_path}.bat", 'w' do |fp|
fp.puts %{@ECHO.#{deprecation_message}}
end
end
end
def remove_old_lib_files lib_dir
rubygems_dir = File.join lib_dir, 'rubygems'
lib_files = rb_files_in 'lib/rubygems'
old_lib_files = rb_files_in rubygems_dir
to_remove = old_lib_files - lib_files
to_remove.delete_if do |file|
file.start_with? 'defaults'
end
Dir.chdir rubygems_dir do
to_remove.each do |file|
FileUtils.rm_f file
warn "unable to remove old file #{file} please remove it by hand" if
File.exist? file
end
end
end
def show_release_notes
release_notes = File.join Dir.pwd, 'History.txt'
release_notes =
if File.exist? release_notes then
history = File.read release_notes
history.force_encoding Encoding::UTF_8 if
Object.const_defined? :Encoding
history = history.sub(/^# coding:.*?(?=^=)/m, '')
text = history.split(HISTORY_HEADER)
text.shift # correct an off-by-one generated by split
version_lines = history.scan(HISTORY_HEADER)
versions = history.scan(VERSION_MATCHER).flatten.map do |x|
Gem::Version.new(x)
end
history_string = ""
until versions.length == 0 or
versions.shift < options[:previous_version] do
history_string += version_lines.shift + text.shift
end
history_string
else
"Oh-no! Unable to find release notes!"
end
say release_notes
end
def uninstall_old_gemcutter
require 'rubygems/uninstaller'
ui = Gem::Uninstaller.new('gemcutter', :all => true, :ignore => true,
:version => '< 0.4')
ui.uninstall
rescue Gem::InstallError
end
end
| jmatbastos/rbenv | versions/2.2.3/lib/ruby/2.2.0/rubygems/commands/setup_command.rb | Ruby | mit | 13,277 |
// This file is part of Notepad++ project
// Copyright (C)2003 Don HO <don.h@free.fr>
//
// 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.
//
// Note that the GPL places important restrictions on "derived works", yet
// it does not provide a detailed definition of that term. To avoid
// misunderstandings, we consider an application to constitute a
// "derivative work" for the purpose of this license if it does any of the
// following:
// 1. Integrates source code from Notepad++.
// 2. Integrates/includes/aggregates Notepad++ into a proprietary executable
// installer, such as those produced by InstallShield.
// 3. Links to a library or executes a program that does any of the above.
//
// 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., 675 Mass Ave, Cambridge, MA 02139, USA.
#include <vector>
#include <algorithm>
#include <Shlobj.h>
#include <uxtheme.h>
#include "columnEditor.h"
#include "ScintillaEditView.h"
void ColumnEditorDlg::init(HINSTANCE hInst, HWND hPere, ScintillaEditView **ppEditView)
{
Window::init(hInst, hPere);
if (!ppEditView)
throw std::runtime_error("StaticDialog::init : ppEditView is null.");
_ppEditView = ppEditView;
}
void ColumnEditorDlg::display(bool toShow) const
{
Window::display(toShow);
if (toShow)
::SetFocus(::GetDlgItem(_hSelf, ID_GOLINE_EDIT));
}
INT_PTR CALLBACK ColumnEditorDlg::run_dlgProc(UINT message, WPARAM wParam, LPARAM)
{
switch (message)
{
case WM_INITDIALOG :
{
switchTo(activeText);
::SendDlgItemMessage(_hSelf, IDC_COL_DEC_RADIO, BM_SETCHECK, TRUE, 0);
goToCenter();
NppParameters *pNppParam = NppParameters::getInstance();
ETDTProc enableDlgTheme = (ETDTProc)pNppParam->getEnableThemeDlgTexture();
if (enableDlgTheme)
{
enableDlgTheme(_hSelf, ETDT_ENABLETAB);
redraw();
}
return TRUE;
}
case WM_COMMAND :
{
switch (wParam)
{
case IDCANCEL : // Close
display(false);
return TRUE;
case IDOK :
{
(*_ppEditView)->execute(SCI_BEGINUNDOACTION);
const int stringSize = 1024;
TCHAR str[stringSize];
bool isTextMode = (BST_CHECKED == ::SendDlgItemMessage(_hSelf, IDC_COL_TEXT_RADIO, BM_GETCHECK, 0, 0));
if (isTextMode)
{
::SendDlgItemMessage(_hSelf, IDC_COL_TEXT_EDIT, WM_GETTEXT, stringSize, (LPARAM)str);
display(false);
if ((*_ppEditView)->execute(SCI_SELECTIONISRECTANGLE) || (*_ppEditView)->execute(SCI_GETSELECTIONS) > 1)
{
ColumnModeInfos colInfos = (*_ppEditView)->getColumnModeSelectInfo();
std::sort(colInfos.begin(), colInfos.end(), SortInPositionOrder());
(*_ppEditView)->columnReplace(colInfos, str);
std::sort(colInfos.begin(), colInfos.end(), SortInSelectOrder());
(*_ppEditView)->setMultiSelections(colInfos);
}
else
{
int cursorPos = (*_ppEditView)->execute(SCI_GETCURRENTPOS);
int cursorCol = (*_ppEditView)->execute(SCI_GETCOLUMN, cursorPos);
int cursorLine = (*_ppEditView)->execute(SCI_LINEFROMPOSITION, cursorPos);
int endPos = (*_ppEditView)->execute(SCI_GETLENGTH);
int endLine = (*_ppEditView)->execute(SCI_LINEFROMPOSITION, endPos);
int lineAllocatedLen = 1024;
TCHAR *line = new TCHAR[lineAllocatedLen];
for (int i = cursorLine ; i <= endLine ; ++i)
{
int lineBegin = (*_ppEditView)->execute(SCI_POSITIONFROMLINE, i);
int lineEnd = (*_ppEditView)->execute(SCI_GETLINEENDPOSITION, i);
int lineEndCol = (*_ppEditView)->execute(SCI_GETCOLUMN, lineEnd);
int lineLen = lineEnd - lineBegin + 1;
if (lineLen > lineAllocatedLen)
{
delete [] line;
line = new TCHAR[lineLen];
}
(*_ppEditView)->getGenericText(line, lineLen, lineBegin, lineEnd);
generic_string s2r(line);
if (lineEndCol < cursorCol)
{
generic_string s_space(cursorCol - lineEndCol, ' ');
s2r.append(s_space);
s2r.append(str);
}
else
{
int posAbs2Start = (*_ppEditView)->execute(SCI_FINDCOLUMN, i, cursorCol);
int posRelative2Start = posAbs2Start - lineBegin;
s2r.insert(posRelative2Start, str);
}
(*_ppEditView)->replaceTarget(s2r.c_str(), lineBegin, lineEnd);
}
delete [] line;
}
}
else
{
int initialNumber = ::GetDlgItemInt(_hSelf, IDC_COL_INITNUM_EDIT, NULL, TRUE);
int increaseNumber = ::GetDlgItemInt(_hSelf, IDC_COL_INCREASENUM_EDIT, NULL, TRUE);
int repeat = ::GetDlgItemInt(_hSelf, IDC_COL_REPEATNUM_EDIT, NULL, TRUE);
if (repeat == 0)
{
repeat = 1; // Without this we might get an infinite loop while calculating the set "numbers" below.
}
UCHAR format = getFormat();
display(false);
if ((*_ppEditView)->execute(SCI_SELECTIONISRECTANGLE) || (*_ppEditView)->execute(SCI_GETSELECTIONS) > 1)
{
ColumnModeInfos colInfos = (*_ppEditView)->getColumnModeSelectInfo();
std::sort(colInfos.begin(), colInfos.end(), SortInPositionOrder());
(*_ppEditView)->columnReplace(colInfos, initialNumber, increaseNumber, repeat, format);
std::sort(colInfos.begin(), colInfos.end(), SortInSelectOrder());
(*_ppEditView)->setMultiSelections(colInfos);
}
else
{
int cursorPos = (*_ppEditView)->execute(SCI_GETCURRENTPOS);
int cursorCol = (*_ppEditView)->execute(SCI_GETCOLUMN, cursorPos);
int cursorLine = (*_ppEditView)->execute(SCI_LINEFROMPOSITION, cursorPos);
int endPos = (*_ppEditView)->execute(SCI_GETLENGTH);
int endLine = (*_ppEditView)->execute(SCI_LINEFROMPOSITION, endPos);
// Compute the numbers to be placed at each column.
std::vector<int> numbers;
{
int curNumber = initialNumber;
const unsigned int kiMaxSize = 1 + (unsigned int)endLine - (unsigned int)cursorLine;
while (numbers.size() < kiMaxSize)
{
for (int i = 0; i < repeat; i++)
{
numbers.push_back(curNumber);
if (numbers.size() >= kiMaxSize)
{
break;
}
}
curNumber += increaseNumber;
}
}
assert(numbers.size() > 0);
int lineAllocatedLen = 1024;
TCHAR *line = new TCHAR[lineAllocatedLen];
UCHAR f = format & MASK_FORMAT;
bool isZeroLeading = (MASK_ZERO_LEADING & format) != 0;
int base = 10;
if (f == BASE_16)
base = 16;
else if (f == BASE_08)
base = 8;
else if (f == BASE_02)
base = 2;
int endNumber = *numbers.rbegin();
int nbEnd = getNbDigits(endNumber, base);
int nbInit = getNbDigits(initialNumber, base);
int nb = max(nbInit, nbEnd);
for (int i = cursorLine ; i <= endLine ; ++i)
{
int lineBegin = (*_ppEditView)->execute(SCI_POSITIONFROMLINE, i);
int lineEnd = (*_ppEditView)->execute(SCI_GETLINEENDPOSITION, i);
int lineEndCol = (*_ppEditView)->execute(SCI_GETCOLUMN, lineEnd);
int lineLen = lineEnd - lineBegin + 1;
if (lineLen > lineAllocatedLen)
{
delete [] line;
line = new TCHAR[lineLen];
}
(*_ppEditView)->getGenericText(line, lineLen, lineBegin, lineEnd);
generic_string s2r(line);
//
// Calcule generic_string
//
int2str(str, stringSize, numbers.at(i - cursorLine), base, nb, isZeroLeading);
if (lineEndCol < cursorCol)
{
generic_string s_space(cursorCol - lineEndCol, ' ');
s2r.append(s_space);
s2r.append(str);
}
else
{
int posAbs2Start = (*_ppEditView)->execute(SCI_FINDCOLUMN, i, cursorCol);
int posRelative2Start = posAbs2Start - lineBegin;
s2r.insert(posRelative2Start, str);
}
(*_ppEditView)->replaceTarget(s2r.c_str(), lineBegin, lineEnd);
}
delete [] line;
}
}
(*_ppEditView)->execute(SCI_ENDUNDOACTION);
(*_ppEditView)->getFocus();
return TRUE;
}
case IDC_COL_TEXT_RADIO :
case IDC_COL_NUM_RADIO :
{
switchTo((wParam == IDC_COL_TEXT_RADIO)? activeText : activeNumeric);
return TRUE;
}
default :
{
switch (HIWORD(wParam))
{
case EN_SETFOCUS :
case BN_SETFOCUS :
//updateLinesNumbers();
return TRUE;
default :
return TRUE;
}
break;
}
}
}
default :
return FALSE;
}
//return FALSE;
}
void ColumnEditorDlg::switchTo(bool toText)
{
HWND hText = ::GetDlgItem(_hSelf, IDC_COL_TEXT_EDIT);
::EnableWindow(hText, toText);
::EnableWindow(::GetDlgItem(_hSelf, IDC_COL_TEXT_GRP_STATIC), toText);
::SendDlgItemMessage(_hSelf, IDC_COL_TEXT_RADIO, BM_SETCHECK, toText, 0);
HWND hNum = ::GetDlgItem(_hSelf, IDC_COL_INITNUM_EDIT);
::SendDlgItemMessage(_hSelf, IDC_COL_NUM_RADIO, BM_SETCHECK, !toText, 0);
::EnableWindow(::GetDlgItem(_hSelf, IDC_COL_NUM_GRP_STATIC), !toText);
::EnableWindow(::GetDlgItem(_hSelf, IDC_COL_INITNUM_STATIC), !toText);
::EnableWindow(hNum, !toText);
::EnableWindow(::GetDlgItem(_hSelf, IDC_COL_INCRNUM_STATIC), !toText);
::EnableWindow(::GetDlgItem(_hSelf, IDC_COL_INCREASENUM_EDIT), !toText);
::EnableWindow(::GetDlgItem(_hSelf, IDC_COL_REPEATNUM_STATIC), !toText);
::EnableWindow(::GetDlgItem(_hSelf, IDC_COL_REPEATNUM_EDIT), !toText);
::EnableWindow(::GetDlgItem(_hSelf, IDC_COL_FORMAT_GRP_STATIC), !toText);
::EnableWindow(::GetDlgItem(_hSelf, IDC_COL_DEC_RADIO), !toText);
::EnableWindow(::GetDlgItem(_hSelf, IDC_COL_HEX_RADIO), !toText);
::EnableWindow(::GetDlgItem(_hSelf, IDC_COL_OCT_RADIO), !toText);
::EnableWindow(::GetDlgItem(_hSelf, IDC_COL_BIN_RADIO), !toText);
::EnableWindow(::GetDlgItem(_hSelf, IDC_COL_LEADZERO_CHECK), !toText);
::SetFocus(toText?hText:hNum);
}
UCHAR ColumnEditorDlg::getFormat()
{
bool isLeadingZeros = (BST_CHECKED == ::SendDlgItemMessage(_hSelf, IDC_COL_LEADZERO_CHECK, BM_GETCHECK, 0, 0));
UCHAR f = 0; // Dec by default
if (BST_CHECKED == ::SendDlgItemMessage(_hSelf, IDC_COL_HEX_RADIO, BM_GETCHECK, 0, 0))
f = 1;
else if (BST_CHECKED == ::SendDlgItemMessage(_hSelf, IDC_COL_OCT_RADIO, BM_GETCHECK, 0, 0))
f = 2;
else if (BST_CHECKED == ::SendDlgItemMessage(_hSelf, IDC_COL_BIN_RADIO, BM_GETCHECK, 0, 0))
f = 3;
return (f | (isLeadingZeros?MASK_ZERO_LEADING:0));
}
| firstblade/notepad-plus-plus | PowerEditor/src/ScitillaComponent/columnEditor.cpp | C++ | gpl-2.0 | 11,483 |
# -*- coding: utf-8 -*-
# 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.
require File.expand_path("storm", File.dirname(__FILE__))
$words = ["nathan", "mike", "jackson", "golda", "bertels人"]
def random_word
$words[rand($words.length)]
end
class TesterSpout < Storm::Spout
attr_accessor :uid, :pending
def open(conf, context)
emit ['spout initializing']
self.pending = {}
self.uid = 0
end
def nextTuple
sleep 0.5
word = random_word
id = self.uid += 1
self.pending[id] = word
emit [word], :id => id
end
def ack(id)
self.pending.delete(id)
end
def fail(id)
word = self.pending[id]
log "emitting " + word + " on fail"
emit [word], :id => id
end
end
TesterSpout.new.run
| mrknmc/storm-mc | storm-multicore/src/dev/resources/tester_spout.rb | Ruby | apache-2.0 | 1,476 |
package v1
import (
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// SchemeGroupVersion is group version used to register these objects
var SchemeGroupVersion = schema.GroupVersion{Group: "", Version: "v1"}
var (
SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
AddToScheme = SchemeBuilder.AddToScheme
)
// Adds the list of known types to api.Scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&BuildDefaultsConfig{},
)
return nil
}
func (obj *BuildDefaultsConfig) GetObjectKind() schema.ObjectKind { return &obj.TypeMeta }
| cdrage/kedge | vendor/github.com/openshift/origin/pkg/build/controller/build/defaults/api/v1/register.go | GO | apache-2.0 | 627 |
/*
Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/J is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors.
There are special exceptions to the terms and conditions of the GPLv2 as it is applied to
this software, see the FOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
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., 51 Franklin St, Fifth
Floor, Boston, MA 02110-1301 USA
*/
package com.mysql.jdbc.exceptions;
import java.sql.SQLException;
public class MySQLTransientException extends SQLException {
static final long serialVersionUID = -1885878228558607563L;
public MySQLTransientException(String reason, String SQLState, int vendorCode) {
super(reason, SQLState, vendorCode);
}
public MySQLTransientException(String reason, String SQLState) {
super(reason, SQLState);
}
public MySQLTransientException(String reason) {
super(reason);
}
public MySQLTransientException() {
super();
}
}
| swankjesse/mysql-connector-j | src/com/mysql/jdbc/exceptions/MySQLTransientException.java | Java | gpl-2.0 | 1,682 |
#!/usr/bin/env python
"""Show python and pip versions."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import sys
import warnings
warnings.simplefilter('ignore') # avoid python version deprecation warnings when using newer pip dependencies
try:
import pip
except ImportError:
pip = None
print(sys.version)
if pip:
print('pip %s from %s' % (pip.__version__, os.path.dirname(pip.__file__)))
| thnee/ansible | test/lib/ansible_test/_util/controller/tools/versions.py | Python | gpl-3.0 | 460 |
/*
Copyright 2020 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 internal_test
import (
"testing"
"time"
"k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal"
)
func TestAtMostEvery(t *testing.T) {
duration := time.Second
delay := 179 * time.Millisecond
atMostEvery := internal.NewAtMostEvery(delay)
count := 0
exit := time.NewTicker(duration)
tick := time.NewTicker(2 * time.Millisecond)
defer exit.Stop()
defer tick.Stop()
done := false
for !done {
select {
case <-exit.C:
done = true
case <-tick.C:
atMostEvery.Do(func() {
count++
})
}
}
if expected := int(duration/delay) + 1; count != expected {
t.Fatalf("Function called %d times, should have been called exactly %d times", count, expected)
}
}
| Miciah/origin | vendor/k8s.io/kubernetes/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal/atmostevery_test.go | GO | apache-2.0 | 1,269 |
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Note: the example only works with the code within the same release/branch.
package main
import (
"fmt"
"time"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
//
// Uncomment to load all auth plugins
// _ "k8s.io/client-go/plugin/pkg/client/auth
//
// Or uncomment to load specific auth plugins
// _ "k8s.io/client-go/plugin/pkg/client/auth/azure"
// _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
// _ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
// _ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
)
func main() {
// creates the in-cluster config
config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
for {
pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
// Examples for error handling:
// - Use helper functions like e.g. errors.IsNotFound()
// - And/or cast to StatusError and use its properties like e.g. ErrStatus.Message
_, err = clientset.CoreV1().Pods("default").Get("example-xxxxx", metav1.GetOptions{})
if errors.IsNotFound(err) {
fmt.Printf("Pod not found\n")
} else if statusError, isStatus := err.(*errors.StatusError); isStatus {
fmt.Printf("Error getting pod %v\n", statusError.ErrStatus.Message)
} else if err != nil {
panic(err.Error())
} else {
fmt.Printf("Found pod\n")
}
time.Sleep(10 * time.Second)
}
}
| Stackdriver/heapster | vendor/k8s.io/kubernetes/staging/src/k8s.io/client-go/examples/in-cluster-client-configuration/main.go | GO | apache-2.0 | 2,228 |
//
// StanfordCoreNLP -- a suite of NLP tools
// Copyright (c) 2009-2010 The Board of Trustees of
// The Leland Stanford Junior University. All Rights Reserved.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// For more information, bug reports, fixes, contact:
// Christopher Manning
// Dept of Computer Science, Gates 1A
// Stanford CA 94305-9010
// USA
//
package edu.stanford.nlp.dcoref;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.stanford.nlp.classify.LogisticClassifier;
import edu.stanford.nlp.ie.machinereading.domains.ace.AceReader;
import edu.stanford.nlp.ie.machinereading.structure.EntityMention;
import edu.stanford.nlp.ie.machinereading.structure.MachineReadingAnnotations;
import edu.stanford.nlp.io.RuntimeIOException;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.stats.ClassicCounter;
import edu.stanford.nlp.stats.Counter;
import edu.stanford.nlp.semgraph.SemanticGraphCoreAnnotations;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.trees.TreeCoreAnnotations;
import edu.stanford.nlp.util.CoreMap;
import edu.stanford.nlp.util.Generics;
/**
* Extracts {@code <COREF>} mentions from a file annotated in ACE format (ACE2004, ACE2005).
*
* @author Heeyoung Lee
*/
public class ACEMentionExtractor extends MentionExtractor {
private AceReader aceReader;
private String corpusPath;
protected int fileIndex = 0;
protected String[] files;
private static final Logger logger = SieveCoreferenceSystem.logger;
private static class EntityComparator implements Comparator<EntityMention> {
@Override
public int compare(EntityMention m1, EntityMention m2){
if(m1.getExtentTokenStart() > m2.getExtentTokenStart()) return 1;
else if(m1.getExtentTokenStart() < m2.getExtentTokenStart()) return -1;
else if(m1.getExtentTokenEnd() > m2.getExtentTokenEnd()) return -1;
else if(m1.getExtentTokenEnd() < m2.getExtentTokenEnd()) return 1;
else return 0;
}
}
public ACEMentionExtractor(Dictionaries dict, Properties props, Semantics semantics) throws Exception {
super(dict, semantics);
stanfordProcessor = loadStanfordProcessor(props);
if(props.containsKey(Constants.ACE2004_PROP)) {
corpusPath = props.getProperty(Constants.ACE2004_PROP);
aceReader = new AceReader(stanfordProcessor, false, "ACE2004");
}
else if(props.containsKey(Constants.ACE2005_PROP)) {
corpusPath = props.getProperty(Constants.ACE2005_PROP);
aceReader = new AceReader(stanfordProcessor, false);
}
aceReader.setLoggerLevel(Level.INFO);
if(corpusPath.charAt(corpusPath.length()-1)!= File.separatorChar) corpusPath+= File.separatorChar;
files = new File(corpusPath).list();
}
public ACEMentionExtractor(Dictionaries dict, Properties props, Semantics semantics,
LogisticClassifier<String, String> singletonModel) throws Exception {
this(dict, props, semantics);
singletonPredictor = singletonModel;
}
public void resetDocs() {
super.resetDocs();
fileIndex = 0;
}
public Document nextDoc() throws Exception {
List<List<CoreLabel>> allWords = new ArrayList<List<CoreLabel>>();
List<List<Mention>> allGoldMentions = new ArrayList<List<Mention>>();
List<List<Mention>> allPredictedMentions;
List<Tree> allTrees = new ArrayList<Tree>();
Annotation anno;
try {
String filename="";
while(files.length > fileIndex){
if(files[fileIndex].contains("apf.xml")) {
filename = files[fileIndex];
fileIndex++;
break;
}
else {
fileIndex++;
filename="";
}
}
if(files.length <= fileIndex && filename.equals("")) return null;
anno = aceReader.parse(corpusPath+filename);
stanfordProcessor.annotate(anno);
List<CoreMap> sentences = anno.get(CoreAnnotations.SentencesAnnotation.class);
for (CoreMap s : sentences){
int i = 1;
for(CoreLabel w : s.get(CoreAnnotations.TokensAnnotation.class)){
w.set(CoreAnnotations.IndexAnnotation.class, i++);
if(!w.containsKey(CoreAnnotations.UtteranceAnnotation.class)) {
w.set(CoreAnnotations.UtteranceAnnotation.class, 0);
}
}
allTrees.add(s.get(TreeCoreAnnotations.TreeAnnotation.class));
allWords.add(s.get(CoreAnnotations.TokensAnnotation.class));
EntityComparator comparator = new EntityComparator();
extractGoldMentions(s, allGoldMentions, comparator);
}
if(Constants.USE_GOLD_MENTIONS) allPredictedMentions = allGoldMentions;
else allPredictedMentions = mentionFinder.extractPredictedMentions(anno, maxID, dictionaries);
printRawDoc(sentences, allGoldMentions, filename, true);
printRawDoc(sentences, allPredictedMentions, filename, false);
} catch (IOException e) {
throw new RuntimeIOException(e);
}
return arrange(anno, allWords, allTrees, allPredictedMentions, allGoldMentions, true);
}
private void extractGoldMentions(CoreMap s, List<List<Mention>> allGoldMentions, EntityComparator comparator) {
List<Mention> goldMentions = new ArrayList<Mention>();
allGoldMentions.add(goldMentions);
List<EntityMention> goldMentionList = s.get(MachineReadingAnnotations.EntityMentionsAnnotation.class);
List<CoreLabel> words = s.get(CoreAnnotations.TokensAnnotation.class);
TreeSet<EntityMention> treeForSortGoldMentions = new TreeSet<EntityMention>(comparator);
if(goldMentionList!=null) treeForSortGoldMentions.addAll(goldMentionList);
if(!treeForSortGoldMentions.isEmpty()){
for(EntityMention e : treeForSortGoldMentions){
Mention men = new Mention();
men.dependency = s.get(SemanticGraphCoreAnnotations.CollapsedDependenciesAnnotation.class);
men.startIndex = e.getExtentTokenStart();
men.endIndex = e.getExtentTokenEnd();
String[] parseID = e.getObjectId().split("-");
men.mentionID = Integer.parseInt(parseID[parseID.length-1]);
String[] parseCorefID = e.getCorefID().split("-E");
men.goldCorefClusterID = Integer.parseInt(parseCorefID[parseCorefID.length-1]);
men.originalRef = -1;
for(int j=allGoldMentions.size()-1 ; j>=0 ; j--){
List<Mention> l = allGoldMentions.get(j);
for(int k=l.size()-1 ; k>=0 ; k--){
Mention m = l.get(k);
if(men.goldCorefClusterID == m.goldCorefClusterID){
men.originalRef = m.mentionID;
}
}
}
goldMentions.add(men);
if(men.mentionID > maxID) maxID = men.mentionID;
// set ner type
for(int j = e.getExtentTokenStart() ; j < e.getExtentTokenEnd() ; j++){
CoreLabel word = words.get(j);
String ner = e.getType() +"-"+ e.getSubType();
if(Constants.USE_GOLD_NE){
word.set(CoreAnnotations.EntityTypeAnnotation.class, e.getMentionType());
if(e.getMentionType().equals("NAM")) word.set(CoreAnnotations.NamedEntityTagAnnotation.class, ner);
}
}
}
}
}
private static void printRawDoc(List<CoreMap> sentences, List<List<Mention>> allMentions, String filename, boolean gold) throws FileNotFoundException {
StringBuilder doc = new StringBuilder();
int previousOffset = 0;
Counter<Integer> mentionCount = new ClassicCounter<Integer>();
for(List<Mention> l : allMentions) {
for(Mention m : l) {
mentionCount.incrementCount(m.goldCorefClusterID);
}
}
for(int i = 0 ; i<sentences.size(); i++) {
CoreMap sentence = sentences.get(i);
List<Mention> mentions = allMentions.get(i);
String[] tokens = sentence.get(CoreAnnotations.TextAnnotation.class).split(" ");
String sent = "";
List<CoreLabel> t = sentence.get(CoreAnnotations.TokensAnnotation.class);
if(previousOffset+2 < t.get(0).get(CoreAnnotations.CharacterOffsetBeginAnnotation.class)) sent += "\n";
previousOffset = t.get(t.size()-1).get(CoreAnnotations.CharacterOffsetEndAnnotation.class);
Counter<Integer> startCounts = new ClassicCounter<Integer>();
Counter<Integer> endCounts = new ClassicCounter<Integer>();
Map<Integer, Set<Integer>> endID = Generics.newHashMap();
for (Mention m : mentions) {
startCounts.incrementCount(m.startIndex);
endCounts.incrementCount(m.endIndex);
if(!endID.containsKey(m.endIndex)) endID.put(m.endIndex, Generics.<Integer>newHashSet());
endID.get(m.endIndex).add(m.goldCorefClusterID);
}
for (int j = 0 ; j < tokens.length; j++){
if(endID.containsKey(j)) {
for(Integer id : endID.get(j)){
if(mentionCount.getCount(id)!=1 && gold) sent += "]_"+id;
else sent += "]";
}
}
for (int k = 0 ; k < startCounts.getCount(j) ; k++) {
if(!sent.endsWith("[")) sent += " ";
sent += "[";
}
sent += " ";
sent = sent + tokens[j];
}
for(int k = 0 ; k <endCounts.getCount(tokens.length); k++) {
sent += "]";
}
sent += "\n";
doc.append(sent);
}
if (gold) logger.fine("New DOC: (GOLD MENTIONS) ==================================================");
else logger.fine("New DOC: (Predicted Mentions) ==================================================");
logger.fine(doc.toString());
}
}
| heeyounglee/hcoref | src/edu/stanford/nlp/dcoref/ACEMentionExtractor.java | Java | gpl-2.0 | 10,488 |
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Core\Event\Hook;
use Thelia\Core\Event\ActionEvent;
use Thelia\Model\Hook;
/**
* Class HookEvent
* @package Thelia\Core\Event\Hook
* @author Julien Chanséaume <jchanseaume@openstudio.fr>
*/
class HookEvent extends ActionEvent
{
public $hook = null;
public function __construct(Hook $hook = null)
{
$this->hook = $hook;
}
public function hasHook()
{
return ! is_null($this->hook);
}
public function getHook()
{
return $this->hook;
}
public function setHook(Hook $hook)
{
$this->hook = $hook;
return $this;
}
}
| amirlionor/mythelia | vendor/thelia/core/lib/Thelia/Core/Event/Hook/HookEvent.php | PHP | lgpl-3.0 | 1,517 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.snapshots;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.Version;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.xcontent.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static java.util.Collections.*;
/**
* Represent information about snapshot
*/
public class Snapshot implements Comparable<Snapshot>, ToXContent, FromXContentBuilder<Snapshot> {
private final String name;
private final Version version;
private final SnapshotState state;
private final String reason;
private final List<String> indices;
private final long startTime;
private final long endTime;
private final int totalShard;
private final int successfulShards;
private final List<SnapshotShardFailure> shardFailures;
private final static List<SnapshotShardFailure> NO_FAILURES = Collections.emptyList();
public final static Snapshot PROTO = new Snapshot();
private Snapshot(String name, List<String> indices, SnapshotState state, String reason, Version version, long startTime, long endTime,
int totalShard, int successfulShards, List<SnapshotShardFailure> shardFailures) {
assert name != null;
assert indices != null;
assert state != null;
assert shardFailures != null;
this.name = name;
this.indices = indices;
this.state = state;
this.reason = reason;
this.version = version;
this.startTime = startTime;
this.endTime = endTime;
this.totalShard = totalShard;
this.successfulShards = successfulShards;
this.shardFailures = shardFailures;
}
public Snapshot(String name, List<String> indices, long startTime) {
this(name, indices, SnapshotState.IN_PROGRESS, null, Version.CURRENT, startTime, 0L, 0, 0, NO_FAILURES);
}
public Snapshot(String name, List<String> indices, long startTime, String reason, long endTime,
int totalShard, List<SnapshotShardFailure> shardFailures) {
this(name, indices, snapshotState(reason, shardFailures), reason, Version.CURRENT,
startTime, endTime, totalShard, totalShard - shardFailures.size(), shardFailures);
}
/**
* Special constructor for the prototype object
*/
private Snapshot() {
this("", (List<String>) EMPTY_LIST, 0);
}
private static SnapshotState snapshotState(String reason, List<SnapshotShardFailure> shardFailures) {
if (reason == null) {
if (shardFailures.isEmpty()) {
return SnapshotState.SUCCESS;
} else {
return SnapshotState.PARTIAL;
}
} else {
return SnapshotState.FAILED;
}
}
/**
* Returns snapshot name
*
* @return snapshot name
*/
public String name() {
return name;
}
/**
* Returns current snapshot state
*
* @return snapshot state
*/
public SnapshotState state() {
return state;
}
/**
* Returns reason for complete snapshot failure
*
* @return snapshot failure reason
*/
public String reason() {
return reason;
}
/**
* Returns version of Elasticsearch that was used to create this snapshot
*
* @return Elasticsearch version
*/
public Version version() {
return version;
}
/**
* Returns indices that were included into this snapshot
*
* @return list of indices
*/
public List<String> indices() {
return indices;
}
/**
* Returns time when snapshot started
*
* @return snapshot start time
*/
public long startTime() {
return startTime;
}
/**
* Returns time when snapshot ended
* <p>
* Can be 0L if snapshot is still running
*
* @return snapshot end time
*/
public long endTime() {
return endTime;
}
/**
* Returns total number of shards that were snapshotted
*
* @return number of shards
*/
public int totalShard() {
return totalShard;
}
/**
* Returns total number of shards that were successfully snapshotted
*
* @return number of successful shards
*/
public int successfulShards() {
return successfulShards;
}
/**
* Returns shard failures
*/
public List<SnapshotShardFailure> shardFailures() {
return shardFailures;
}
/**
* Compares two snapshots by their start time
*
* @param o other snapshot
* @return the value {@code 0} if snapshots were created at the same time;
* a value less than {@code 0} if this snapshot was created before snapshot {@code o}; and
* a value greater than {@code 0} if this snapshot was created after snapshot {@code o};
*/
@Override
public int compareTo(Snapshot o) {
return Long.compare(startTime, o.startTime);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Snapshot that = (Snapshot) o;
if (startTime != that.startTime) return false;
if (!name.equals(that.name)) return false;
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + (int) (startTime ^ (startTime >>> 32));
return result;
}
@Override
public Snapshot fromXContent(XContentParser parser, ParseFieldMatcher parseFieldMatcher) throws IOException {
return fromXContent(parser);
}
static final class Fields {
static final XContentBuilderString SNAPSHOT = new XContentBuilderString("snapshot");
static final XContentBuilderString NAME = new XContentBuilderString("name");
static final XContentBuilderString VERSION_ID = new XContentBuilderString("version_id");
static final XContentBuilderString INDICES = new XContentBuilderString("indices");
static final XContentBuilderString STATE = new XContentBuilderString("state");
static final XContentBuilderString REASON = new XContentBuilderString("reason");
static final XContentBuilderString START_TIME = new XContentBuilderString("start_time");
static final XContentBuilderString END_TIME = new XContentBuilderString("end_time");
static final XContentBuilderString TOTAL_SHARDS = new XContentBuilderString("total_shards");
static final XContentBuilderString SUCCESSFUL_SHARDS = new XContentBuilderString("successful_shards");
static final XContentBuilderString FAILURES = new XContentBuilderString("failures");
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
builder.startObject(Fields.SNAPSHOT);
builder.field(Fields.NAME, name);
builder.field(Fields.VERSION_ID, version.id);
builder.startArray(Fields.INDICES);
for (String index : indices) {
builder.value(index);
}
builder.endArray();
builder.field(Fields.STATE, state);
if (reason != null) {
builder.field(Fields.REASON, reason);
}
builder.field(Fields.START_TIME, startTime);
builder.field(Fields.END_TIME, endTime);
builder.field(Fields.TOTAL_SHARDS, totalShard);
builder.field(Fields.SUCCESSFUL_SHARDS, successfulShards);
builder.startArray(Fields.FAILURES);
for (SnapshotShardFailure shardFailure : shardFailures) {
builder.startObject();
shardFailure.toXContent(builder, params);
builder.endObject();
}
builder.endArray();
builder.endObject();
return builder;
}
public static Snapshot fromXContent(XContentParser parser) throws IOException {
String name = null;
Version version = Version.CURRENT;
SnapshotState state = SnapshotState.IN_PROGRESS;
String reason = null;
List<String> indices = Collections.emptyList();
long startTime = 0;
long endTime = 0;
int totalShard = 0;
int successfulShards = 0;
List<SnapshotShardFailure> shardFailures = NO_FAILURES;
if (parser.currentToken() == null) { // fresh parser? move to the first token
parser.nextToken();
}
if (parser.currentToken() == XContentParser.Token.START_OBJECT) { // on a start object move to next token
parser.nextToken();
}
XContentParser.Token token;
if ((token = parser.nextToken()) == XContentParser.Token.START_OBJECT) {
String currentFieldName = parser.currentName();
if ("snapshot".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
token = parser.nextToken();
if (token.isValue()) {
if ("name".equals(currentFieldName)) {
name = parser.text();
} else if ("state".equals(currentFieldName)) {
state = SnapshotState.valueOf(parser.text());
} else if ("reason".equals(currentFieldName)) {
reason = parser.text();
} else if ("start_time".equals(currentFieldName)) {
startTime = parser.longValue();
} else if ("end_time".equals(currentFieldName)) {
endTime = parser.longValue();
} else if ("total_shards".equals(currentFieldName)) {
totalShard = parser.intValue();
} else if ("successful_shards".equals(currentFieldName)) {
successfulShards = parser.intValue();
} else if ("version_id".equals(currentFieldName)) {
version = Version.fromId(parser.intValue());
}
} else if (token == XContentParser.Token.START_ARRAY) {
if ("indices".equals(currentFieldName)) {
ArrayList<String> indicesArray = new ArrayList<>();
while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
indicesArray.add(parser.text());
}
indices = Collections.unmodifiableList(indicesArray);
} else if ("failures".equals(currentFieldName)) {
ArrayList<SnapshotShardFailure> shardFailureArrayList = new ArrayList<>();
while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
shardFailureArrayList.add(SnapshotShardFailure.fromXContent(parser));
}
shardFailures = Collections.unmodifiableList(shardFailureArrayList);
} else {
// It was probably created by newer version - ignoring
parser.skipChildren();
}
} else if (token == XContentParser.Token.START_OBJECT) {
// It was probably created by newer version - ignoring
parser.skipChildren();
}
}
}
}
} else {
throw new ElasticsearchParseException("unexpected token [" + token + "]");
}
return new Snapshot(name, indices, state, reason, version, startTime, endTime, totalShard, successfulShards, shardFailures);
}
}
| Rygbee/elasticsearch | core/src/main/java/org/elasticsearch/snapshots/Snapshot.java | Java | apache-2.0 | 13,099 |
var isArray = Array.isArray;
var isPathValue = require("./is-path-value");
var isJsonGraphEnvelope = require("./is-json-graph-envelope");
var isJsonEnvelope = require("./is-json-envelope");
var pathSyntax = require("falcor-path-syntax");
/**
*
* @param {Object} allowedInput - allowedInput is a map of input styles
* that are allowed
* @private
*/
module.exports = function validateInput(args, allowedInput, method) {
for (var i = 0, len = args.length; i < len; ++i) {
var arg = args[i];
var valid = false;
// Path
if (isArray(arg) && allowedInput.path) {
valid = true;
}
// Path Syntax
else if (typeof arg === "string" && allowedInput.pathSyntax) {
valid = true;
}
// Path Value
else if (isPathValue(arg) && allowedInput.pathValue) {
arg.path = pathSyntax.fromPath(arg.path);
valid = true;
}
// jsonGraph {jsonGraph: { ... }, paths: [ ... ]}
else if (isJsonGraphEnvelope(arg) && allowedInput.jsonGraph) {
valid = true;
}
// json env {json: {...}}
else if (isJsonEnvelope(arg) && allowedInput.json) {
valid = true;
}
// selector functions
else if (typeof arg === "function" &&
i + 1 === len &&
allowedInput.selector) {
valid = true;
}
if (!valid) {
return new Error("Unrecognized argument " + (typeof arg) + " [" + String(arg) + "] " + "to Model#" + method + "");
}
}
return true;
};
| michaelbpaulson/falcor-1 | lib/support/validate-input.js | JavaScript | apache-2.0 | 1,615 |
cask 'hostr' do
version '0.8.0'
sha256 '89e8b6a4d0168fb05520ff9ac1f69d378dade59a883034aaa549398c039faeed'
url "https://hostr.co/apps/mac/Hostr-#{version}.zip"
appcast 'https://hostr.co/updaters/mac.xml'
name 'Hostr'
homepage 'https://hostr.co/'
app 'Hostr.app'
end
| jawshooah/homebrew-cask | Casks/hostr.rb | Ruby | bsd-2-clause | 281 |
///////////////////////////////////////////////////////////////////////////////
// Name: src/unix/glx11.cpp
// Purpose: code common to all X11-based wxGLCanvas implementations
// Author: Vadim Zeitlin
// Created: 2007-04-15
// Copyright: (c) 2007 Vadim Zeitlin <vadim@wxwindows.org>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// for compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#if wxUSE_GLCANVAS
#ifndef WX_PRECOMP
#include "wx/log.h"
#endif //WX_PRECOMP
#include "wx/glcanvas.h"
// IRIX headers call this differently
#ifdef __SGI__
#ifndef GLX_SAMPLE_BUFFERS_ARB
#define GLX_SAMPLE_BUFFERS_ARB GLX_SAMPLE_BUFFERS_SGIS
#endif
#ifndef GLX_SAMPLES_ARB
#define GLX_SAMPLES_ARB GLX_SAMPLES_SGIS
#endif
#endif // __SGI__
// ----------------------------------------------------------------------------
// define possibly missing XGL constants and types
// ----------------------------------------------------------------------------
#ifndef GLX_NONE_EXT
#define GLX_NONE_EXT 0x8000
#endif
#ifndef GLX_ARB_multisample
#define GLX_ARB_multisample
#define GLX_SAMPLE_BUFFERS_ARB 100000
#define GLX_SAMPLES_ARB 100001
#endif
#ifndef GLX_EXT_visual_rating
#define GLX_EXT_visual_rating
#define GLX_VISUAL_CAVEAT_EXT 0x20
#define GLX_NONE_EXT 0x8000
#define GLX_SLOW_VISUAL_EXT 0x8001
#define GLX_NON_CONFORMANT_VISUAL_EXT 0x800D
#endif
#ifndef GLX_EXT_visual_info
#define GLX_EXT_visual_info
#define GLX_X_VISUAL_TYPE_EXT 0x22
#define GLX_DIRECT_COLOR_EXT 0x8003
#endif
#ifndef GLX_ARB_framebuffer_sRGB
#define GLX_ARB_framebuffer_sRGB
#define GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20B2
#endif
/* Typedef for the GL 3.0 context creation function */
typedef GLXContext(*PFNGLXCREATECONTEXTATTRIBSARBPROC)
(Display * dpy, GLXFBConfig config, GLXContext share_context,
Bool direct, const int *attrib_list);
#ifndef GLX_ARB_create_context
#define GLX_ARB_create_context
#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
#define GLX_CONTEXT_FLAGS_ARB 0x2094
#define GLX_CONTEXT_DEBUG_BIT_ARB 0x0001
#define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x0002
#endif
#ifndef GLX_ARB_create_context_profile
#define GLX_ARB_create_context_profile
#define GLX_CONTEXT_PROFILE_MASK_ARB 0x9126
#define GLX_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
#define GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
#endif
#ifndef GLX_ARB_create_context_robustness
#define GLX_ARB_create_context_robustness
#define GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB 0x00000004
#define GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB 0x8256
#define GLX_NO_RESET_NOTIFICATION_ARB 0x8261
#define GLX_LOSE_CONTEXT_ON_RESET_ARB 0x8252
#endif
#ifndef GLX_ARB_robustness_application_isolation
#define GLX_ARB_robustness_application_isolation
#define GLX_CONTEXT_RESET_ISOLATION_BIT_ARB 0x00000008
#endif
#ifndef GLX_ARB_robustness_share_group_isolation
#define GLX_ARB_robustness_share_group_isolation
#endif
#ifndef GLX_ARB_context_flush_control
#define GLX_ARB_context_flush_control
#define GLX_CONTEXT_RELEASE_BEHAVIOR_ARB 0x2097
#define GLX_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB 0
#define GLX_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB 0x2098
#endif
#ifndef GLX_EXT_create_context_es2_profile
#define GLX_EXT_create_context_es2_profile
#define GLX_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000004
#endif
#ifndef GLX_EXT_create_context_es_profile
#define GLX_EXT_create_context_es_profile
#define GLX_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000004
#endif
// ----------------------------------------------------------------------------
// wxGLContextAttrs: OpenGL rendering context attributes
// ----------------------------------------------------------------------------
// GLX specific values
wxGLContextAttrs& wxGLContextAttrs::CoreProfile()
{
AddAttribBits(GLX_CONTEXT_PROFILE_MASK_ARB,
GLX_CONTEXT_CORE_PROFILE_BIT_ARB);
SetNeedsARB();
return *this;
}
wxGLContextAttrs& wxGLContextAttrs::MajorVersion(int val)
{
if ( val > 0 )
{
AddAttribute(GLX_CONTEXT_MAJOR_VERSION_ARB);
AddAttribute(val);
if ( val >= 3 )
SetNeedsARB();
}
return *this;
}
wxGLContextAttrs& wxGLContextAttrs::MinorVersion(int val)
{
if ( val >= 0 )
{
AddAttribute(GLX_CONTEXT_MINOR_VERSION_ARB);
AddAttribute(val);
}
return *this;
}
wxGLContextAttrs& wxGLContextAttrs::CompatibilityProfile()
{
AddAttribBits(GLX_CONTEXT_PROFILE_MASK_ARB,
GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB);
SetNeedsARB();
return *this;
}
wxGLContextAttrs& wxGLContextAttrs::ForwardCompatible()
{
AddAttribBits(GLX_CONTEXT_FLAGS_ARB,
GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB);
SetNeedsARB();
return *this;
}
wxGLContextAttrs& wxGLContextAttrs::ES2()
{
AddAttribBits(GLX_CONTEXT_PROFILE_MASK_ARB,
GLX_CONTEXT_ES2_PROFILE_BIT_EXT);
SetNeedsARB();
return *this;
}
wxGLContextAttrs& wxGLContextAttrs::DebugCtx()
{
AddAttribBits(GLX_CONTEXT_FLAGS_ARB,
GLX_CONTEXT_DEBUG_BIT_ARB);
SetNeedsARB();
return *this;
}
wxGLContextAttrs& wxGLContextAttrs::Robust()
{
AddAttribBits(GLX_CONTEXT_FLAGS_ARB,
GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB);
SetNeedsARB();
return *this;
}
wxGLContextAttrs& wxGLContextAttrs::NoResetNotify()
{
AddAttribute(GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB);
AddAttribute(GLX_NO_RESET_NOTIFICATION_ARB);
SetNeedsARB();
return *this;
}
wxGLContextAttrs& wxGLContextAttrs::LoseOnReset()
{
AddAttribute(GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB);
AddAttribute(GLX_LOSE_CONTEXT_ON_RESET_ARB);
SetNeedsARB();
return *this;
}
wxGLContextAttrs& wxGLContextAttrs::ResetIsolation()
{
AddAttribBits(GLX_CONTEXT_FLAGS_ARB,
GLX_CONTEXT_RESET_ISOLATION_BIT_ARB);
SetNeedsARB();
return *this;
}
wxGLContextAttrs& wxGLContextAttrs::ReleaseFlush(int val)
{
AddAttribute(GLX_CONTEXT_RELEASE_BEHAVIOR_ARB);
if ( val == 1 )
AddAttribute(GLX_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB);
else
AddAttribute(GLX_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB);
SetNeedsARB();
return *this;
}
wxGLContextAttrs& wxGLContextAttrs::PlatformDefaults()
{
renderTypeRGBA = true;
x11Direct = true;
return *this;
}
void wxGLContextAttrs::EndList()
{
AddAttribute(None);
}
// ----------------------------------------------------------------------------
// wxGLAttributes: Visual/FBconfig attributes
// ----------------------------------------------------------------------------
// GLX specific values
// Different versions of GLX API use rather different attributes lists, see
// the following URLs:
//
// - <= 1.2: http://www.opengl.org/sdk/docs/man/xhtml/glXChooseVisual.xml
// - >= 1.3: http://www.opengl.org/sdk/docs/man/xhtml/glXChooseFBConfig.xml
//
// Notice in particular that
// - GLX_RGBA is boolean attribute in the old version of the API but a
// value of GLX_RENDER_TYPE in the new one
// - Boolean attributes such as GLX_DOUBLEBUFFER don't take values in the
// old version but must be followed by True or False in the new one.
wxGLAttributes& wxGLAttributes::RGBA()
{
if ( wxGLCanvasX11::GetGLXVersion() >= 13 )
AddAttribBits(GLX_RENDER_TYPE, GLX_RGBA_BIT);
else
AddAttribute(GLX_RGBA);
return *this;
}
wxGLAttributes& wxGLAttributes::BufferSize(int val)
{
if ( val >= 0 )
{
AddAttribute(GLX_BUFFER_SIZE);
AddAttribute(val);
}
return *this;
}
wxGLAttributes& wxGLAttributes::Level(int val)
{
AddAttribute(GLX_LEVEL);
AddAttribute(val);
return *this;
}
wxGLAttributes& wxGLAttributes::DoubleBuffer()
{
AddAttribute(GLX_DOUBLEBUFFER);
if ( wxGLCanvasX11::GetGLXVersion() >= 13 )
AddAttribute(True);
return *this;
}
wxGLAttributes& wxGLAttributes::Stereo()
{
AddAttribute(GLX_STEREO);
if ( wxGLCanvasX11::GetGLXVersion() >= 13 )
AddAttribute(True);
return *this;
}
wxGLAttributes& wxGLAttributes::AuxBuffers(int val)
{
if ( val >= 0 )
{
AddAttribute(GLX_AUX_BUFFERS);
AddAttribute(val);
}
return *this;
}
wxGLAttributes& wxGLAttributes::MinRGBA(int mRed, int mGreen, int mBlue, int mAlpha)
{
if ( mRed >= 0)
{
AddAttribute(GLX_RED_SIZE);
AddAttribute(mRed);
}
if ( mGreen >= 0)
{
AddAttribute(GLX_GREEN_SIZE);
AddAttribute(mGreen);
}
if ( mBlue >= 0)
{
AddAttribute(GLX_BLUE_SIZE);
AddAttribute(mBlue);
}
if ( mAlpha >= 0)
{
AddAttribute(GLX_ALPHA_SIZE);
AddAttribute(mAlpha);
}
return *this;
}
wxGLAttributes& wxGLAttributes::Depth(int val)
{
if ( val >= 0 )
{
AddAttribute(GLX_DEPTH_SIZE);
AddAttribute(val);
}
return *this;
}
wxGLAttributes& wxGLAttributes::Stencil(int val)
{
if ( val >= 0 )
{
AddAttribute(GLX_STENCIL_SIZE);
AddAttribute(val);
}
return *this;
}
wxGLAttributes& wxGLAttributes::MinAcumRGBA(int mRed, int mGreen, int mBlue, int mAlpha)
{
if ( mRed >= 0)
{
AddAttribute(GLX_ACCUM_RED_SIZE);
AddAttribute(mRed);
}
if ( mGreen >= 0)
{
AddAttribute(GLX_ACCUM_GREEN_SIZE);
AddAttribute(mGreen);
}
if ( mBlue >= 0)
{
AddAttribute(GLX_ACCUM_BLUE_SIZE);
AddAttribute(mBlue);
}
if ( mAlpha >= 0)
{
AddAttribute(GLX_ACCUM_ALPHA_SIZE);
AddAttribute(mAlpha);
}
return *this;
}
wxGLAttributes& wxGLAttributes::SampleBuffers(int val)
{
#ifdef GLX_SAMPLE_BUFFERS_ARB
if ( val >= 0 && wxGLCanvasX11::IsGLXMultiSampleAvailable() )
{
AddAttribute(GLX_SAMPLE_BUFFERS_ARB);
AddAttribute(val);
}
#endif
return *this;
}
wxGLAttributes& wxGLAttributes::Samplers(int val)
{
#ifdef GLX_SAMPLES_ARB
if ( val >= 0 && wxGLCanvasX11::IsGLXMultiSampleAvailable() )
{
AddAttribute(GLX_SAMPLES_ARB);
AddAttribute(val);
}
#endif
return *this;
}
wxGLAttributes& wxGLAttributes::FrameBuffersRGB()
{
AddAttribute(GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB);
AddAttribute(True);
return *this;
}
void wxGLAttributes::EndList()
{
AddAttribute(None);
}
wxGLAttributes& wxGLAttributes::PlatformDefaults()
{
// No GLX specific values
return *this;
}
wxGLAttributes& wxGLAttributes::Defaults()
{
RGBA().DoubleBuffer();
if ( wxGLCanvasX11::GetGLXVersion() < 13 )
Depth(1).MinRGBA(1, 1, 1, 0);
else
Depth(16).SampleBuffers(1).Samplers(4);
return *this;
}
// ============================================================================
// wxGLContext implementation
// ============================================================================
// Need this X error handler for the case context creation fails
static bool g_ctxErrorOccurred = false;
static int CTXErrorHandler( Display* WXUNUSED(dpy), XErrorEvent* WXUNUSED(ev) )
{
g_ctxErrorOccurred = true;
return 0;
}
wxIMPLEMENT_CLASS(wxGLContext, wxObject);
wxGLContext::wxGLContext(wxGLCanvas *win,
const wxGLContext *other,
const wxGLContextAttrs *ctxAttrs)
: m_glContext(NULL)
{
const int* contextAttribs = NULL;
Bool x11Direct = True;
int renderType = GLX_RGBA_TYPE;
bool needsARB = false;
if ( ctxAttrs )
{
contextAttribs = ctxAttrs->GetGLAttrs();
x11Direct = ctxAttrs->x11Direct;
renderType = ctxAttrs->renderTypeRGBA ? GLX_RGBA_TYPE : GLX_COLOR_INDEX_TYPE;
needsARB = ctxAttrs->NeedsARB();
}
else if ( win->GetGLCTXAttrs().GetGLAttrs() )
{
// If OpenGL context parameters were set at wxGLCanvas ctor, get them now
contextAttribs = win->GetGLCTXAttrs().GetGLAttrs();
x11Direct = win->GetGLCTXAttrs().x11Direct;
renderType = win->GetGLCTXAttrs().renderTypeRGBA ? GLX_RGBA_TYPE : GLX_COLOR_INDEX_TYPE;
needsARB = win->GetGLCTXAttrs().NeedsARB();
}
// else use GPU driver defaults and x11Direct renderType ones
m_isOk = false;
Display* dpy = wxGetX11Display();
XVisualInfo *vi = win->GetXVisualInfo();
wxCHECK_RET( vi, "invalid visual for OpenGL" );
// We need to create a temporary context to get the
// glXCreateContextAttribsARB function
GLXContext tempContext = glXCreateContext(dpy, vi, NULL,
win->GetGLCTXAttrs().x11Direct );
wxCHECK_RET(tempContext, "glXCreateContext failed" );
PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB
= (PFNGLXCREATECONTEXTATTRIBSARBPROC)
glXGetProcAddress((GLubyte *)"glXCreateContextAttribsARB");
glXDestroyContext( dpy, tempContext );
// The preferred way is using glXCreateContextAttribsARB, even for old context
if ( !glXCreateContextAttribsARB && needsARB ) // OpenGL 3 context creation
{
wxLogMessage(_("OpenGL 3.0 or later is not supported by the OpenGL driver."));
return;
}
// Install a X error handler, so as to the app doesn't exit (without
// even a warning) if GL >= 3.0 context creation fails
g_ctxErrorOccurred = false;
int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&CTXErrorHandler);
if ( glXCreateContextAttribsARB )
{
GLXFBConfig *fbc = win->GetGLXFBConfig();
wxCHECK_RET( fbc, "Invalid GLXFBConfig for OpenGL" );
m_glContext = glXCreateContextAttribsARB( dpy, fbc[0],
other ? other->m_glContext : None,
x11Direct, contextAttribs );
}
else if ( wxGLCanvas::GetGLXVersion() >= 13 )
{
GLXFBConfig *fbc = win->GetGLXFBConfig();
wxCHECK_RET( fbc, "Invalid GLXFBConfig for OpenGL" );
m_glContext = glXCreateNewContext( dpy, fbc[0], renderType,
other ? other->m_glContext : None,
x11Direct );
}
else // GLX <= 1.2
{
m_glContext = glXCreateContext( dpy, vi,
other ? other->m_glContext : None,
x11Direct );
}
// Sync to ensure any errors generated are processed.
XSync( dpy, False );
if ( g_ctxErrorOccurred || !m_glContext )
wxLogMessage(_("Couldn't create OpenGL context"));
else
m_isOk = true;
// Restore old error handler
XSetErrorHandler( oldHandler );
}
wxGLContext::~wxGLContext()
{
if ( !m_glContext )
return;
if ( m_glContext == glXGetCurrentContext() )
MakeCurrent(None, NULL);
glXDestroyContext( wxGetX11Display(), m_glContext );
}
bool wxGLContext::SetCurrent(const wxGLCanvas& win) const
{
if ( !m_glContext )
return false;
const Window xid = win.GetXWindow();
wxCHECK2_MSG( xid, return false, wxT("window must be shown") );
return MakeCurrent(xid, m_glContext);
}
// wrapper around glXMakeContextCurrent/glXMakeCurrent depending on GLX
// version
/* static */
bool wxGLContext::MakeCurrent(GLXDrawable drawable, GLXContext context)
{
if (wxGLCanvas::GetGLXVersion() >= 13)
return glXMakeContextCurrent( wxGetX11Display(), drawable, drawable, context);
else // GLX <= 1.2 doesn't have glXMakeContextCurrent()
return glXMakeCurrent( wxGetX11Display(), drawable, context);
}
// ============================================================================
// wxGLCanvasX11 implementation
// ============================================================================
// ----------------------------------------------------------------------------
// initialization methods and dtor
// ----------------------------------------------------------------------------
wxGLCanvasX11::wxGLCanvasX11()
{
m_fbc = NULL;
m_vi = NULL;
}
bool wxGLCanvasX11::InitVisual(const wxGLAttributes& dispAttrs)
{
bool ret = InitXVisualInfo(dispAttrs, &m_fbc, &m_vi);
if ( !ret )
{
wxFAIL_MSG("Failed to get a XVisualInfo for the requested attributes.");
}
return ret;
}
wxGLCanvasX11::~wxGLCanvasX11()
{
if ( m_fbc && m_fbc != ms_glFBCInfo )
XFree(m_fbc);
if ( m_vi && m_vi != ms_glVisualInfo )
XFree(m_vi);
}
// ----------------------------------------------------------------------------
// working with GL attributes
// ----------------------------------------------------------------------------
/* static */
bool wxGLCanvasBase::IsExtensionSupported(const char *extension)
{
Display * const dpy = wxGetX11Display();
return IsExtensionInList(glXQueryExtensionsString(dpy, DefaultScreen(dpy)),
extension);
}
/* static */
bool wxGLCanvasX11::IsGLXMultiSampleAvailable()
{
static int s_isMultiSampleAvailable = -1;
if ( s_isMultiSampleAvailable == -1 )
s_isMultiSampleAvailable = IsExtensionSupported("GLX_ARB_multisample");
return s_isMultiSampleAvailable != 0;
}
/* static */
bool wxGLCanvasX11::InitXVisualInfo(const wxGLAttributes& dispAttrs,
GLXFBConfig** pFBC,
XVisualInfo** pXVisual)
{
// GLX_XX attributes
const int* attrsListGLX = dispAttrs.GetGLAttrs();
if ( !attrsListGLX )
{
wxFAIL_MSG("wxGLAttributes object is empty.");
return false;
}
Display* dpy = wxGetX11Display();
if ( GetGLXVersion() >= 13 )
{
int returned;
*pFBC = glXChooseFBConfig(dpy, DefaultScreen(dpy), attrsListGLX, &returned);
if ( *pFBC )
{
// Use the first good match
*pXVisual = glXGetVisualFromFBConfig(wxGetX11Display(), **pFBC);
if ( !*pXVisual )
{
XFree(*pFBC);
*pFBC = NULL;
}
}
}
else // GLX <= 1.2
{
*pFBC = NULL;
*pXVisual = glXChooseVisual(dpy, DefaultScreen(dpy),
wx_const_cast(int*, attrsListGLX) );
}
return *pXVisual != NULL;
}
/* static */
bool wxGLCanvasBase::IsDisplaySupported(const wxGLAttributes& dispAttrs)
{
GLXFBConfig *fbc = NULL;
XVisualInfo *vi = NULL;
bool isSupported = wxGLCanvasX11::InitXVisualInfo(dispAttrs, &fbc, &vi);
if ( fbc )
XFree(fbc);
if ( vi )
XFree(vi);
return isSupported;
}
/* static */
bool wxGLCanvasBase::IsDisplaySupported(const int *attribList)
{
wxGLAttributes dispAttrs;
ParseAttribList(attribList, dispAttrs);
return IsDisplaySupported(dispAttrs);
}
// ----------------------------------------------------------------------------
// default visual management
// ----------------------------------------------------------------------------
XVisualInfo *wxGLCanvasX11::ms_glVisualInfo = NULL;
GLXFBConfig *wxGLCanvasX11::ms_glFBCInfo = NULL;
/* static */
bool wxGLCanvasX11::InitDefaultVisualInfo(const int *attribList)
{
FreeDefaultVisualInfo();
wxGLAttributes dispAttrs;
ParseAttribList(attribList, dispAttrs);
return InitXVisualInfo(dispAttrs, &ms_glFBCInfo, &ms_glVisualInfo);
}
/* static */
void wxGLCanvasX11::FreeDefaultVisualInfo()
{
if ( ms_glFBCInfo )
{
XFree(ms_glFBCInfo);
ms_glFBCInfo = NULL;
}
if ( ms_glVisualInfo )
{
XFree(ms_glVisualInfo);
ms_glVisualInfo = NULL;
}
}
// ----------------------------------------------------------------------------
// other GL methods
// ----------------------------------------------------------------------------
/* static */
int wxGLCanvasX11::GetGLXVersion()
{
static int s_glxVersion = 0;
if ( s_glxVersion == 0 )
{
// check the GLX version
int glxMajorVer, glxMinorVer;
bool ok = glXQueryVersion(wxGetX11Display(), &glxMajorVer, &glxMinorVer);
wxASSERT_MSG( ok, wxT("GLX version not found") );
if (!ok)
s_glxVersion = 10; // 1.0 by default
else
s_glxVersion = glxMajorVer*10 + glxMinorVer;
}
return s_glxVersion;
}
bool wxGLCanvasX11::SwapBuffers()
{
const Window xid = GetXWindow();
wxCHECK2_MSG( xid, return false, wxT("window must be shown") );
glXSwapBuffers(wxGetX11Display(), xid);
return true;
}
bool wxGLCanvasX11::IsShownOnScreen() const
{
return GetXWindow() && wxGLCanvasBase::IsShownOnScreen();
}
#endif // wxUSE_GLCANVAS
| adouble42/nemesis-current | wxWidgets-3.1.0/src/unix/glx11.cpp | C++ | bsd-2-clause | 21,265 |
/*
* Copyright (C) 2008-2015 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 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, see <http://www.gnu.org/licenses/>.
*/
#include "WoWRealmPackets.h"
#include "Session.h"
#include <boost/lexical_cast.hpp>
#include <boost/asio/ip/address.hpp>
std::string Battlenet::WoWRealm::ListSubscribeRequest::ToString() const
{
return "Battlenet::WoWRealm::ListSubscribeRequest";
}
void Battlenet::WoWRealm::ListSubscribeRequest::CallHandler(Session* session)
{
session->HandleListSubscribeRequest(*this);
}
std::string Battlenet::WoWRealm::ListUnsubscribe::ToString() const
{
return "Battlenet::WoWRealm::ListUnsubscribe";
}
void Battlenet::WoWRealm::ListUnsubscribe::CallHandler(Session* session)
{
session->HandleListUnsubscribe(*this);
}
void Battlenet::WoWRealm::JoinRequestV2::Read()
{
ClientSeed = _stream.Read<uint32>(32);
_stream.Read<uint32>(20);
Realm.Region = _stream.Read<uint8>(8);
_stream.Read<uint16>(12);
Realm.Battlegroup = _stream.Read<uint8>(8);
Realm.Index = _stream.Read<uint32>(32);
}
std::string Battlenet::WoWRealm::JoinRequestV2::ToString() const
{
std::ostringstream stream;
stream << "Battlenet::WoWRealm::JoinRequestV2 ClientSeed " << ClientSeed << " Region " << uint32(Realm.Region) << " Battlegroup " << uint32(Realm.Battlegroup) << " Index " << Realm.Index;
return stream.str().c_str();
}
void Battlenet::WoWRealm::JoinRequestV2::CallHandler(Session* session)
{
session->HandleJoinRequestV2(*this);
}
Battlenet::WoWRealm::ListSubscribeResponse::~ListSubscribeResponse()
{
for (ServerPacket* realmData : RealmData)
delete realmData;
}
void Battlenet::WoWRealm::ListSubscribeResponse::Write()
{
_stream.Write(Response, 1);
if (Response == SUCCESS)
{
_stream.Write(CharacterCounts.size(), 7);
for (CharacterCountEntry const& entry : CharacterCounts)
{
_stream.Write(entry.Realm.Region, 8);
_stream.Write(0, 12);
_stream.Write(entry.Realm.Battlegroup, 8);
_stream.Write(entry.Realm.Index, 32);
_stream.Write(entry.CharacterCount, 16);
}
for (ServerPacket* realmData : RealmData)
{
realmData->Write();
_stream.WriteBytes(realmData->GetData(), realmData->GetSize());
}
}
else
_stream.Write(ResponseCode, 8);
}
std::string Battlenet::WoWRealm::ListSubscribeResponse::ToString() const
{
std::ostringstream stream;
stream << "Battlenet::WoWRealm::ListSubscribeResponse";
if (Response == SUCCESS)
{
stream << " Realms " << CharacterCounts.size();
for (CharacterCountEntry const& entry : CharacterCounts)
stream << std::endl << "Region " << uint32(entry.Realm.Region) << " Battlegroup " << uint32(entry.Realm.Region) << " Index " << entry.Realm.Index << " Characters " << entry.CharacterCount;
for (ServerPacket* realmData : RealmData)
stream << std::endl << realmData->ToString();
}
else
stream << " Failure";
return stream.str().c_str();
}
void Battlenet::WoWRealm::ListUpdate::Write()
{
_stream.Write(UpdateState, 1);
if (UpdateState == UPDATE)
{
_stream.Write(Timezone, 32);
_stream.WriteFloat(Population);
_stream.Write(Lock, 8);
_stream.Write(0, 19);
_stream.Write(Type + -std::numeric_limits<int32>::min(), 32);
_stream.WriteString(Name, 10);
_stream.Write(!Version.empty(), 1);
if (!Version.empty())
{
_stream.WriteString(Version, 5);
_stream.Write(Id.Build, 32);
boost::asio::ip::address_v4::bytes_type ip = Address.address().to_v4().to_bytes();
uint16 port = Address.port();
EndianConvertReverse(ip);
EndianConvertReverse(port);
_stream.WriteBytes(ip.data(), 4);
_stream.WriteBytes(&port, 2);
}
_stream.Write(Flags, 8);
}
_stream.Write(Id.Region, 8);
_stream.Write(0, 12);
_stream.Write(Id.Battlegroup, 8);
_stream.Write(Id.Index, 32);
}
std::string Battlenet::WoWRealm::ListUpdate::ToString() const
{
std::ostringstream stream;
stream << "Battlenet::WoWRealm::ListUpdate";
if (UpdateState == UPDATE)
{
stream << " Timezone: " << Timezone << " Population: " << Population << " Lock: " << uint32(Lock) << " Type: " << Type << " Name: " << Name
<< " Flags: " << uint32(Flags) << " Region: " << uint32(Id.Region) << " Battlegroup: " << uint32(Id.Battlegroup) << " Index: " << Id.Index;
if (!Version.empty())
stream << " Version: " << Version;
}
else
stream << " Delete realm [Region: " << uint32(Id.Region) << " Battlegroup : " << uint32(Id.Battlegroup) << " Index : " << Id.Index << "]";
return stream.str().c_str();
}
void Battlenet::WoWRealm::ToonReady::Write()
{
_stream.Write(Realm.Region, 8);
_stream.WriteFourCC(Game);
uint32 realmAddress = ((Realm.Battlegroup << 16) & 0xFF0000) | uint16(Realm.Index);
_stream.Write(realmAddress, 32);
_stream.WriteString(Name, 7, -2);
_stream.WriteSkip(21);
_stream.Write(0, 64); // Unknown
_stream.Write(0, 32); // Unknown
_stream.Write(Guid, 64);
_stream.Write(realmAddress, 32);
_stream.Write(Realm.Region, 8);
_stream.WriteFourCC(Game);
}
std::string Battlenet::WoWRealm::ToonReady::ToString() const
{
std::ostringstream stream;
stream << "Battlenet::WoWRealm::ToonReady" << " Game: " << Game
<< ", Region: " << uint32(Realm.Region) << ", Battlegroup: " << uint32(Realm.Battlegroup) << ", Index: " << Realm.Index
<< ", Guid: " << Guid << ", Name: " << Name;
return stream.str().c_str();
}
void Battlenet::WoWRealm::JoinResponseV2::Write()
{
_stream.Write(Response, 1);
if (Response == SUCCESS)
{
_stream.Write(ServerSeed, 32);
_stream.Write(IPv4.size(), 5);
for (tcp::endpoint const& addr : IPv4)
{
boost::asio::ip::address_v4::bytes_type ip = addr.address().to_v4().to_bytes();
uint16 port = addr.port();
EndianConvertReverse(port);
_stream.WriteBytes(ip.data(), 4);
_stream.WriteBytes(&port, 2);
}
_stream.Write(IPv6.size(), 5);
for (tcp::endpoint const& addr : IPv6)
{
boost::asio::ip::address_v6::bytes_type ip = addr.address().to_v6().to_bytes();
uint16 port = addr.port();
EndianConvertReverse(port);
_stream.WriteBytes(ip.data(), 16);
_stream.WriteBytes(&port, 2);
}
}
else
_stream.Write(ResponseCode, 8);
}
std::string Battlenet::WoWRealm::JoinResponseV2::ToString() const
{
std::ostringstream stream;
stream << "Battlenet::WoWRealm::JoinResponseV2";
if (Response == SUCCESS)
{
stream << " ServerSeed " << ServerSeed << " IPv4 Addresses " << IPv4.size() << " IPv6 Addresses " << IPv6.size();
for (tcp::endpoint const& addr : IPv4)
stream << std::endl << "Battlenet::WoWRealm::JoinResponseV2::Address " << boost::lexical_cast<std::string>(addr);
for (tcp::endpoint const& addr : IPv6)
stream << std::endl << "Battlenet::WoWRealm::JoinResponseV2::Address " << boost::lexical_cast<std::string>(addr);
}
else
stream << " Failure";
return stream.str().c_str();
}
| Helias/TrinityCore | src/server/bnetserver/Packets/WoWRealmPackets.cpp | C++ | gpl-2.0 | 8,063 |
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package resource
import (
"fmt"
"log"
"strings"
"sigs.k8s.io/kustomize/api/filters/patchstrategicmerge"
"sigs.k8s.io/kustomize/api/ifc"
"sigs.k8s.io/kustomize/api/internal/utils"
"sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/kustomize/kyaml/kio"
"sigs.k8s.io/kustomize/kyaml/resid"
kyaml "sigs.k8s.io/kustomize/kyaml/yaml"
"sigs.k8s.io/yaml"
)
// Resource is an RNode, representing a Kubernetes Resource Model object,
// paired with metadata used by kustomize.
type Resource struct {
kyaml.RNode
options *types.GenArgs
refBy []resid.ResId
refVarNames []string
}
var BuildAnnotations = []string{
utils.BuildAnnotationPreviousKinds,
utils.BuildAnnotationPreviousNames,
utils.BuildAnnotationPrefixes,
utils.BuildAnnotationSuffixes,
utils.BuildAnnotationPreviousNamespaces,
utils.BuildAnnotationAllowNameChange,
utils.BuildAnnotationAllowKindChange,
}
func (r *Resource) ResetRNode(incoming *Resource) {
r.RNode = *incoming.Copy()
}
func (r *Resource) GetGvk() resid.Gvk {
return resid.GvkFromNode(&r.RNode)
}
func (r *Resource) Hash(h ifc.KustHasher) (string, error) {
return h.Hash(&r.RNode)
}
func (r *Resource) SetGvk(gvk resid.Gvk) {
r.SetKind(gvk.Kind)
r.SetApiVersion(gvk.ApiVersion())
}
// ResCtx is an interface describing the contextual added
// kept kustomize in the context of each Resource object.
// Currently mainly the name prefix and name suffix are added.
type ResCtx interface {
AddNamePrefix(p string)
AddNameSuffix(s string)
GetNamePrefixes() []string
GetNameSuffixes() []string
}
// ResCtxMatcher returns true if two Resources are being
// modified in the same kustomize context.
type ResCtxMatcher func(ResCtx) bool
// DeepCopy returns a new copy of resource
func (r *Resource) DeepCopy() *Resource {
rc := &Resource{
RNode: *r.Copy(),
}
rc.copyKustomizeSpecificFields(r)
return rc
}
// CopyMergeMetaDataFieldsFrom copies everything but the non-metadata in
// the resource.
// TODO: move to RNode, use GetMeta to improve performance.
// Must remove the kustomize bit at the end.
func (r *Resource) CopyMergeMetaDataFieldsFrom(other *Resource) error {
if err := r.SetLabels(
mergeStringMaps(other.GetLabels(), r.GetLabels())); err != nil {
return fmt.Errorf("copyMerge cannot set labels - %w", err)
}
if err := r.SetAnnotations(
mergeStringMaps(other.GetAnnotations(), r.GetAnnotations())); err != nil {
return fmt.Errorf("copyMerge cannot set annotations - %w", err)
}
if err := r.SetName(other.GetName()); err != nil {
return fmt.Errorf("copyMerge cannot set name - %w", err)
}
if err := r.SetNamespace(other.GetNamespace()); err != nil {
return fmt.Errorf("copyMerge cannot set namespace - %w", err)
}
r.copyKustomizeSpecificFields(other)
return nil
}
func (r *Resource) copyKustomizeSpecificFields(other *Resource) {
r.options = other.options
r.refBy = other.copyRefBy()
r.refVarNames = copyStringSlice(other.refVarNames)
}
func (r *Resource) MergeDataMapFrom(o *Resource) {
r.SetDataMap(mergeStringMaps(o.GetDataMap(), r.GetDataMap()))
}
func (r *Resource) MergeBinaryDataMapFrom(o *Resource) {
r.SetBinaryDataMap(mergeStringMaps(o.GetBinaryDataMap(), r.GetBinaryDataMap()))
}
func (r *Resource) ErrIfNotEquals(o *Resource) error {
meYaml, err := r.AsYAML()
if err != nil {
return err
}
otherYaml, err := o.AsYAML()
if err != nil {
return err
}
if !r.ReferencesEqual(o) {
return fmt.Errorf(
`unequal references - self:
%sreferenced by: %s
--- other:
%sreferenced by: %s
`, meYaml, r.GetRefBy(), otherYaml, o.GetRefBy())
}
if string(meYaml) != string(otherYaml) {
return fmt.Errorf(`--- self:
%s
--- other:
%s
`, meYaml, otherYaml)
}
return nil
}
func (r *Resource) ReferencesEqual(other *Resource) bool {
setSelf := make(map[resid.ResId]bool)
setOther := make(map[resid.ResId]bool)
for _, ref := range other.refBy {
setOther[ref] = true
}
for _, ref := range r.refBy {
if _, ok := setOther[ref]; !ok {
return false
}
setSelf[ref] = true
}
return len(setSelf) == len(setOther)
}
func (r *Resource) copyRefBy() []resid.ResId {
if r.refBy == nil {
return nil
}
s := make([]resid.ResId, len(r.refBy))
copy(s, r.refBy)
return s
}
func copyStringSlice(s []string) []string {
if s == nil {
return nil
}
c := make([]string, len(s))
copy(c, s)
return c
}
// Implements ResCtx AddNamePrefix
func (r *Resource) AddNamePrefix(p string) {
r.appendCsvAnnotation(utils.BuildAnnotationPrefixes, p)
}
// Implements ResCtx AddNameSuffix
func (r *Resource) AddNameSuffix(s string) {
r.appendCsvAnnotation(utils.BuildAnnotationSuffixes, s)
}
func (r *Resource) appendCsvAnnotation(name, value string) {
if value == "" {
return
}
annotations := r.GetAnnotations()
if existing, ok := annotations[name]; ok {
annotations[name] = existing + "," + value
} else {
annotations[name] = value
}
if err := r.SetAnnotations(annotations); err != nil {
panic(err)
}
}
// Implements ResCtx GetNamePrefixes
func (r *Resource) GetNamePrefixes() []string {
return r.getCsvAnnotation(utils.BuildAnnotationPrefixes)
}
// Implements ResCtx GetNameSuffixes
func (r *Resource) GetNameSuffixes() []string {
return r.getCsvAnnotation(utils.BuildAnnotationSuffixes)
}
func (r *Resource) getCsvAnnotation(name string) []string {
annotations := r.GetAnnotations()
if _, ok := annotations[name]; !ok {
return nil
}
return strings.Split(annotations[name], ",")
}
// PrefixesSuffixesEquals is conceptually doing the same task
// as OutermostPrefixSuffix but performs a deeper comparison
// of the suffix and prefix slices.
func (r *Resource) PrefixesSuffixesEquals(o ResCtx) bool {
return utils.SameEndingSubSlice(r.GetNamePrefixes(), o.GetNamePrefixes()) &&
utils.SameEndingSubSlice(r.GetNameSuffixes(), o.GetNameSuffixes())
}
// RemoveBuildAnnotations removes annotations created by the build process.
// These are internal-only to kustomize, added to the data pipeline to
// track name changes so name references can be fixed.
func (r *Resource) RemoveBuildAnnotations() {
annotations := r.GetAnnotations()
if len(annotations) == 0 {
return
}
for _, a := range BuildAnnotations {
delete(annotations, a)
}
if err := r.SetAnnotations(annotations); err != nil {
panic(err)
}
}
func (r *Resource) setPreviousId(ns string, n string, k string) *Resource {
r.appendCsvAnnotation(utils.BuildAnnotationPreviousNames, n)
r.appendCsvAnnotation(utils.BuildAnnotationPreviousNamespaces, ns)
r.appendCsvAnnotation(utils.BuildAnnotationPreviousKinds, k)
return r
}
// AllowNameChange allows name changes to the resource.
func (r *Resource) AllowNameChange() {
annotations := r.GetAnnotations()
annotations[utils.BuildAnnotationAllowNameChange] = utils.Allowed
if err := r.SetAnnotations(annotations); err != nil {
panic(err)
}
}
func (r *Resource) NameChangeAllowed() bool {
annotations := r.GetAnnotations()
v, ok := annotations[utils.BuildAnnotationAllowNameChange]
return ok && v == utils.Allowed
}
// AllowKindChange allows kind changes to the resource.
func (r *Resource) AllowKindChange() {
annotations := r.GetAnnotations()
annotations[utils.BuildAnnotationAllowKindChange] = utils.Allowed
if err := r.SetAnnotations(annotations); err != nil {
panic(err)
}
}
func (r *Resource) KindChangeAllowed() bool {
annotations := r.GetAnnotations()
v, ok := annotations[utils.BuildAnnotationAllowKindChange]
return ok && v == utils.Allowed
}
// String returns resource as JSON.
func (r *Resource) String() string {
bs, err := r.MarshalJSON()
if err != nil {
return "<" + err.Error() + ">"
}
return strings.TrimSpace(string(bs)) + r.options.String()
}
// AsYAML returns the resource in Yaml form.
// Easier to read than JSON.
func (r *Resource) AsYAML() ([]byte, error) {
json, err := r.MarshalJSON()
if err != nil {
return nil, err
}
return yaml.JSONToYAML(json)
}
// MustYaml returns YAML or panics.
func (r *Resource) MustYaml() string {
yml, err := r.AsYAML()
if err != nil {
log.Fatal(err)
}
return string(yml)
}
// SetOptions updates the generator options for the resource.
func (r *Resource) SetOptions(o *types.GenArgs) {
r.options = o
}
// Behavior returns the behavior for the resource.
func (r *Resource) Behavior() types.GenerationBehavior {
return r.options.Behavior()
}
// NeedHashSuffix returns true if a resource content
// hash should be appended to the name of the resource.
func (r *Resource) NeedHashSuffix() bool {
return r.options != nil && r.options.ShouldAddHashSuffixToName()
}
// OrgId returns the original, immutable ResId for the resource.
// This doesn't have to be unique in a ResMap.
func (r *Resource) OrgId() resid.ResId {
ids := r.PrevIds()
if len(ids) > 0 {
return ids[0]
}
return r.CurId()
}
// PrevIds returns a list of ResIds that includes every
// previous ResId the resource has had through all of its
// GVKN transformations, in the order that it had that ID.
// I.e. the oldest ID is first.
// The returned array does not include the resource's current
// ID. If there are no previous IDs, this will return nil.
func (r *Resource) PrevIds() []resid.ResId {
prevIds, err := utils.PrevIds(&r.RNode)
if err != nil {
// this should never happen
panic(err)
}
return prevIds
}
// StorePreviousId stores the resource's current ID via build annotations.
func (r *Resource) StorePreviousId() {
id := r.CurId()
r.setPreviousId(id.EffectiveNamespace(), id.Name, id.Kind)
}
// CurId returns a ResId for the resource using the
// mutable parts of the resource.
// This should be unique in any ResMap.
func (r *Resource) CurId() resid.ResId {
return resid.NewResIdWithNamespace(
r.GetGvk(), r.GetName(), r.GetNamespace())
}
// GetRefBy returns the ResIds that referred to current resource
func (r *Resource) GetRefBy() []resid.ResId {
return r.refBy
}
// AppendRefBy appends a ResId into the refBy list
func (r *Resource) AppendRefBy(id resid.ResId) {
r.refBy = append(r.refBy, id)
}
// GetRefVarNames returns vars that refer to current resource
func (r *Resource) GetRefVarNames() []string {
return r.refVarNames
}
// AppendRefVarName appends a name of a var into the refVar list
func (r *Resource) AppendRefVarName(variable types.Var) {
r.refVarNames = append(r.refVarNames, variable.Name)
}
// ApplySmPatch applies the provided strategic merge patch.
func (r *Resource) ApplySmPatch(patch *Resource) error {
n, ns, k := r.GetName(), r.GetNamespace(), r.GetKind()
if patch.NameChangeAllowed() || patch.KindChangeAllowed() {
r.StorePreviousId()
}
if err := r.ApplyFilter(patchstrategicmerge.Filter{
Patch: &patch.RNode,
}); err != nil {
return err
}
if r.IsNilOrEmpty() {
return nil
}
if !patch.KindChangeAllowed() {
r.SetKind(k)
}
if !patch.NameChangeAllowed() {
r.SetName(n)
}
r.SetNamespace(ns)
return nil
}
func (r *Resource) ApplyFilter(f kio.Filter) error {
l, err := f.Filter([]*kyaml.RNode{&r.RNode})
if len(l) == 0 {
// The node was deleted, which means the entire resource
// must be deleted. Signal that via the following:
r.SetYNode(nil)
}
return err
}
func mergeStringMaps(maps ...map[string]string) map[string]string {
result := map[string]string{}
for _, m := range maps {
for key, value := range m {
result[key] = value
}
}
return result
}
| dereknex/kubernetes | vendor/sigs.k8s.io/kustomize/api/resource/resource.go | GO | apache-2.0 | 11,359 |
// @target:es6
export default class {
static z: string = "Foo";
} | weswigham/TypeScript | tests/cases/conformance/es6/classDeclaration/exportDefaultClassWithStaticPropertyAssignmentsInES6.ts | TypeScript | apache-2.0 | 72 |
/* Copyright 2018 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/platform/mutex.h"
#include <chrono>
#include <condition_variable>
#include "nsync_cv.h"
#include "nsync_mu.h"
namespace tensorflow {
// Check that the external_mu_space struct used to reserve space for the mutex
// in tensorflow::mutex is big enough.
static_assert(sizeof(nsync::nsync_mu) <= sizeof(mutex::external_mu_space),
"tensorflow::mutex::external_mu_space needs to be bigger");
// Cast a pointer to mutex::external_mu_space to a pointer to the mutex mutex
// representation. This is done so that the header files for nsync_mu do not
// need to be included in every file that uses tensorflow's mutex.
static inline nsync::nsync_mu *mu_cast(mutex::external_mu_space *mu) {
return reinterpret_cast<nsync::nsync_mu *>(mu);
}
mutex::mutex() { nsync::nsync_mu_init(mu_cast(&mu_)); }
void mutex::lock() { nsync::nsync_mu_lock(mu_cast(&mu_)); }
bool mutex::try_lock() { return nsync::nsync_mu_trylock(mu_cast(&mu_)) != 0; };
void mutex::unlock() { nsync::nsync_mu_unlock(mu_cast(&mu_)); }
void mutex::lock_shared() { nsync::nsync_mu_rlock(mu_cast(&mu_)); }
bool mutex::try_lock_shared() {
return nsync::nsync_mu_rtrylock(mu_cast(&mu_)) != 0;
};
void mutex::unlock_shared() { nsync::nsync_mu_runlock(mu_cast(&mu_)); }
// Check that the external_cv_space struct used to reserve space for the
// condition variable in tensorflow::condition_variable is big enough.
static_assert(
sizeof(nsync::nsync_cv) <= sizeof(condition_variable::external_cv_space),
"tensorflow::condition_variable::external_cv_space needs to be bigger");
// Cast a pointer to mutex::external_cv_space to a pointer to the condition
// variable representation. This is done so that the header files for nsync_mu
// do not need to be included in every file that uses tensorflow's
// condition_variable.
static inline nsync::nsync_cv *cv_cast(
condition_variable::external_cv_space *cv) {
return reinterpret_cast<nsync::nsync_cv *>(cv);
}
condition_variable::condition_variable() {
nsync::nsync_cv_init(cv_cast(&cv_));
}
void condition_variable::wait(mutex_lock &lock) {
nsync::nsync_cv_wait(cv_cast(&cv_), mu_cast(&lock.mutex()->mu_));
}
std::cv_status condition_variable::wait_until_system_clock(
mutex_lock &lock,
const std::chrono::system_clock::time_point timeout_time) {
int r = nsync::nsync_cv_wait_with_deadline(
cv_cast(&cv_), mu_cast(&lock.mutex()->mu_), timeout_time, nullptr);
return r ? std::cv_status::timeout : std::cv_status::no_timeout;
}
void condition_variable::notify_one() { nsync::nsync_cv_signal(cv_cast(&cv_)); }
void condition_variable::notify_all() {
nsync::nsync_cv_broadcast(cv_cast(&cv_));
}
} // namespace tensorflow
| kevin-coder/tensorflow-fork | tensorflow/core/platform/default/mutex.cc | C++ | apache-2.0 | 3,384 |
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// singleton.cpp
//
// Copyright (c) 201 5 Robert Ramey, Indiana University (garcia@osl.iu.edu)
// 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)
//
// it marks our code with proper attributes as being exported when
// we're compiling it while marking it import when just the headers
// is being included.
#define BOOST_SERIALIZATION_SOURCE
#include <boost/serialization/config.hpp>
#include <boost/serialization/singleton.hpp>
namespace boost {
namespace serialization {
bool & singleton_module::get_lock(){
static bool lock = false;
return lock;
}
BOOST_SERIALIZATION_DECL void singleton_module::lock(){
get_lock() = true;
}
BOOST_SERIALIZATION_DECL void singleton_module::unlock(){
get_lock() = false;
}
BOOST_SERIALIZATION_DECL bool singleton_module::is_locked() {
return get_lock();
}
} // namespace serialization
} // namespace boost
| bureau14/qdb-benchmark | thirdparty/boost/libs/serialization/src/singleton.cpp | C++ | bsd-2-clause | 1,085 |
<?php
class Swift_Plugins_PopBeforeSmtpPluginTest extends \PHPUnit_Framework_TestCase
{
public function testPluginConnectsToPop3HostBeforeTransportStarts()
{
$connection = $this->_createConnection();
$connection->expects($this->once())
->method('connect');
$plugin = $this->_createPlugin('pop.host.tld', 110);
$plugin->setConnection($connection);
$transport = $this->_createTransport();
$evt = $this->_createTransportChangeEvent($transport);
$plugin->beforeTransportStarted($evt);
}
public function testPluginDisconnectsFromPop3HostBeforeTransportStarts()
{
$connection = $this->_createConnection();
$connection->expects($this->once())
->method('disconnect');
$plugin = $this->_createPlugin('pop.host.tld', 110);
$plugin->setConnection($connection);
$transport = $this->_createTransport();
$evt = $this->_createTransportChangeEvent($transport);
$plugin->beforeTransportStarted($evt);
}
public function testPluginDoesNotConnectToSmtpIfBoundToDifferentTransport()
{
$connection = $this->_createConnection();
$connection->expects($this->never())
->method('disconnect');
$connection->expects($this->never())
->method('connect');
$smtp = $this->_createTransport();
$plugin = $this->_createPlugin('pop.host.tld', 110);
$plugin->setConnection($connection);
$plugin->bindSmtp($smtp);
$transport = $this->_createTransport();
$evt = $this->_createTransportChangeEvent($transport);
$plugin->beforeTransportStarted($evt);
}
public function testPluginCanBindToSpecificTransport()
{
$connection = $this->_createConnection();
$connection->expects($this->once())
->method('connect');
$smtp = $this->_createTransport();
$plugin = $this->_createPlugin('pop.host.tld', 110);
$plugin->setConnection($connection);
$plugin->bindSmtp($smtp);
$evt = $this->_createTransportChangeEvent($smtp);
$plugin->beforeTransportStarted($evt);
}
private function _createTransport()
{
return $this->getMockBuilder('Swift_Transport')->getMock();
}
private function _createTransportChangeEvent($transport)
{
$evt = $this->getMockBuilder('Swift_Events_TransportChangeEvent')
->disableOriginalConstructor()
->getMock();
$evt->expects($this->any())
->method('getSource')
->will($this->returnValue($transport));
$evt->expects($this->any())
->method('getTransport')
->will($this->returnValue($transport));
return $evt;
}
public function _createConnection()
{
return $this->getMockBuilder('Swift_Plugins_Pop_Pop3Connection')->getMock();
}
public function _createPlugin($host, $port, $crypto = null)
{
return new Swift_Plugins_PopBeforeSmtpPlugin($host, $port, $crypto);
}
}
| aloha1003/poseitech_assignment | workspace/assignment/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/PopBeforeSmtpPluginTest.php | PHP | mit | 3,143 |
#! /usr/bin/env ruby
#
# System User Percentage Metric Plugin
#
# DESCRIPTION:
# Produces Graphite output of sum of %CPU over all processes by user.
# E.g., if user joe is running two processes, each using 10% CPU, and
# jane is running one process using 50% CPU, output will be:
#
# joe 20.0 (timestamp)
# jane 50.0 (timestamp)
#
# OUTPUT:
# Graphite metric data.
#
# PLATFORMS:
# Linux, BSD, OS X
#
# DEPENDENCIES:
# gem: sensu-plugin
# gem: socket
#
# USAGE:
# ./user-pct-usage-metrics.rb --ignore_inactive true
# NOTES:
#
# LICENSE:
# John VanDyk <sensu@sysarchitects.com>
# Released under the same terms as Sensu (the MIT license); see LICENSE
# for details.
#
require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'sensu-plugin/metric/cli'
require 'socket'
class UserPercent < Sensu::Plugin::Metric::CLI::Graphite
option :scheme,
description: 'Metric naming scheme prepended to .username',
long: '--scheme SCHEME',
default: "#{Socket.gethostname}.user_percent"
option :ignore_inactive,
description: 'Boolean. If true, ignore users using 0% CPU',
long: '--ignore_inactive',
default: true
option :uid,
description: 'Boolean. If true, uses uid instead of username',
long: '--uid',
default: false
def run
timestamp = Time.now.to_i
usertype = config[:uid] ? 'uid' : 'user'
pslist = `ps -A -o #{usertype}= -o %cpu= -o %mem=`
users = {}
pslist.lines.each do |line|
user, cpu, mem = line.split
users[user] = {} unless users[user]
h = { 'cpu' => cpu.to_f, 'mem' => mem.to_f }
users[user] = users[user].merge(h) { |_key, oldval, newval| newval + oldval }
end
if config[:ignore_inactive]
users.delete_if { |_key, value| value == 0 }
end
users.each do |user, h|
h.each do |key, value|
output [config[:scheme], user].join(".#{key}."), value, timestamp
end
end
ok
end
end
| intoximeters/sensu-community-plugins | plugins/system/user-pct-usage-metrics.rb | Ruby | mit | 1,983 |
export type from 'test';
| wcjohnson/babylon-lightscript | test/fixtures/experimental/export-extensions/default-type-without-flow/actual.js | JavaScript | mit | 25 |
// PR c++/66543
// { dg-do compile { target c++14 } }
// { dg-options "-Wunused-but-set-variable" }
int main() {
auto f = []() { };
[=](auto) {
using Foo = decltype(f());
};
}
| selmentdev/selment-toolchain | source/gcc-latest/gcc/testsuite/g++.dg/warn/Wunused-var-24.C | C++ | gpl-3.0 | 187 |
/**
* Secure Hash Algorithm with a 1024-bit block size implementation.
*
* This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For
* SHA-256 (block size 512 bits), see sha256.js.
*
* See FIPS 180-4 for details.
*
* @author Dave Longley
*
* Copyright (c) 2014-2015 Digital Bazaar, Inc.
*/
(function() {
/* ########## Begin module implementation ########## */
function initModule(forge) {
var sha512 = forge.sha512 = forge.sha512 || {};
forge.md = forge.md || {};
forge.md.algorithms = forge.md.algorithms || {};
// SHA-512
forge.md.sha512 = forge.md.algorithms.sha512 = sha512;
// SHA-384
var sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {};
sha384.create = function() {
return sha512.create('SHA-384');
};
forge.md.sha384 = forge.md.algorithms.sha384 = sha384;
// SHA-512/256
forge.sha512.sha256 = forge.sha512.sha256 || {
create: function() {
return sha512.create('SHA-512/256');
}
};
forge.md['sha512/256'] = forge.md.algorithms['sha512/256'] =
forge.sha512.sha256;
// SHA-512/224
forge.sha512.sha224 = forge.sha512.sha224 || {
create: function() {
return sha512.create('SHA-512/224');
}
};
forge.md['sha512/224'] = forge.md.algorithms['sha512/224'] =
forge.sha512.sha224;
/**
* Creates a SHA-2 message digest object.
*
* @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224,
* SHA-512/256).
*
* @return a message digest object.
*/
sha512.create = function(algorithm) {
// do initialization as necessary
if(!_initialized) {
_init();
}
if(typeof algorithm === 'undefined') {
algorithm = 'SHA-512';
}
if(!(algorithm in _states)) {
throw new Error('Invalid SHA-512 algorithm: ' + algorithm);
}
// SHA-512 state contains eight 64-bit integers (each as two 32-bit ints)
var _state = _states[algorithm];
var _h = null;
// input buffer
var _input = forge.util.createBuffer();
// used for 64-bit word storage
var _w = new Array(80);
for(var wi = 0; wi < 80; ++wi) {
_w[wi] = new Array(2);
}
// message digest object
var md = {
// SHA-512 => sha512
algorithm: algorithm.replace('-', '').toLowerCase(),
blockLength: 128,
digestLength: 64,
// 56-bit length of message so far (does not including padding)
messageLength: 0,
// true message length
fullMessageLength: null,
// size of message length in bytes
messageLengthSize: 16
};
/**
* Starts the digest.
*
* @return this digest object.
*/
md.start = function() {
// up to 56-bit message length for convenience
md.messageLength = 0;
// full message length (set md.messageLength128 for backwards-compatibility)
md.fullMessageLength = md.messageLength128 = [];
var int32s = md.messageLengthSize / 4;
for(var i = 0; i < int32s; ++i) {
md.fullMessageLength.push(0);
}
_input = forge.util.createBuffer();
_h = new Array(_state.length);
for(var i = 0; i < _state.length; ++i) {
_h[i] = _state[i].slice(0);
}
return md;
};
// start digest automatically for first time
md.start();
/**
* Updates the digest with the given message input. The given input can
* treated as raw input (no encoding will be applied) or an encoding of
* 'utf8' maybe given to encode the input using UTF-8.
*
* @param msg the message input to update with.
* @param encoding the encoding to use (default: 'raw', other: 'utf8').
*
* @return this digest object.
*/
md.update = function(msg, encoding) {
if(encoding === 'utf8') {
msg = forge.util.encodeUtf8(msg);
}
// update message length
var len = msg.length;
md.messageLength += len;
len = [(len / 0x100000000) >>> 0, len >>> 0];
for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {
md.fullMessageLength[i] += len[1];
len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);
md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;
len[0] = ((len[1] / 0x100000000) >>> 0);
}
// add bytes to input buffer
_input.putBytes(msg);
// process bytes
_update(_h, _w, _input);
// compact input buffer every 2K or if empty
if(_input.read > 2048 || _input.length() === 0) {
_input.compact();
}
return md;
};
/**
* Produces the digest.
*
* @return a byte buffer containing the digest value.
*/
md.digest = function() {
/* Note: Here we copy the remaining bytes in the input buffer and
add the appropriate SHA-512 padding. Then we do the final update
on a copy of the state so that if the user wants to get
intermediate digests they can do so. */
/* Determine the number of bytes that must be added to the message
to ensure its length is congruent to 896 mod 1024. In other words,
the data to be digested must be a multiple of 1024 bits (or 128 bytes).
This data includes the message, some padding, and the length of the
message. Since the length of the message will be encoded as 16 bytes (128
bits), that means that the last segment of the data must have 112 bytes
(896 bits) of message and padding. Therefore, the length of the message
plus the padding must be congruent to 896 mod 1024 because
1024 - 128 = 896.
In order to fill up the message length it must be filled with
padding that begins with 1 bit followed by all 0 bits. Padding
must *always* be present, so if the message length is already
congruent to 896 mod 1024, then 1024 padding bits must be added. */
var finalBlock = forge.util.createBuffer();
finalBlock.putBytes(_input.bytes());
// compute remaining size to be digested (include message length size)
var remaining = (
md.fullMessageLength[md.fullMessageLength.length - 1] +
md.messageLengthSize);
// add padding for overflow blockSize - overflow
// _padding starts with 1 byte with first bit is set (byte value 128), then
// there may be up to (blockSize - 1) other pad bytes
var overflow = remaining & (md.blockLength - 1);
finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));
// serialize message length in bits in big-endian order; since length
// is stored in bytes we multiply by 8 and add carry from next int
var messageLength = forge.util.createBuffer();
var next, carry;
var bits = md.fullMessageLength[0] * 8;
for(var i = 0; i < md.fullMessageLength.length; ++i) {
next = md.fullMessageLength[i + 1] * 8;
carry = (next / 0x100000000) >>> 0;
bits += carry;
finalBlock.putInt32(bits >>> 0);
bits = next;
}
var h = new Array(_h.length);
for(var i = 0; i < _h.length; ++i) {
h[i] = _h[i].slice(0);
}
_update(h, _w, finalBlock);
var rval = forge.util.createBuffer();
var hlen;
if(algorithm === 'SHA-512') {
hlen = h.length;
} else if(algorithm === 'SHA-384') {
hlen = h.length - 2;
} else {
hlen = h.length - 4;
}
for(var i = 0; i < hlen; ++i) {
rval.putInt32(h[i][0]);
if(i !== hlen - 1 || algorithm !== 'SHA-512/224') {
rval.putInt32(h[i][1]);
}
}
return rval;
};
return md;
};
// sha-512 padding bytes not initialized yet
var _padding = null;
var _initialized = false;
// table of constants
var _k = null;
// initial hash states
var _states = null;
/**
* Initializes the constant tables.
*/
function _init() {
// create padding
_padding = String.fromCharCode(128);
_padding += forge.util.fillString(String.fromCharCode(0x00), 128);
// create K table for SHA-512
_k = [
[0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd],
[0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc],
[0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019],
[0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118],
[0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe],
[0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2],
[0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1],
[0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694],
[0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3],
[0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65],
[0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483],
[0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5],
[0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210],
[0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4],
[0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725],
[0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70],
[0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926],
[0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df],
[0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8],
[0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b],
[0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001],
[0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30],
[0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910],
[0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8],
[0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53],
[0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8],
[0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb],
[0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3],
[0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60],
[0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec],
[0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9],
[0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b],
[0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207],
[0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178],
[0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6],
[0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b],
[0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493],
[0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c],
[0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a],
[0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817]
];
// initial hash states
_states = {};
_states['SHA-512'] = [
[0x6a09e667, 0xf3bcc908],
[0xbb67ae85, 0x84caa73b],
[0x3c6ef372, 0xfe94f82b],
[0xa54ff53a, 0x5f1d36f1],
[0x510e527f, 0xade682d1],
[0x9b05688c, 0x2b3e6c1f],
[0x1f83d9ab, 0xfb41bd6b],
[0x5be0cd19, 0x137e2179]
];
_states['SHA-384'] = [
[0xcbbb9d5d, 0xc1059ed8],
[0x629a292a, 0x367cd507],
[0x9159015a, 0x3070dd17],
[0x152fecd8, 0xf70e5939],
[0x67332667, 0xffc00b31],
[0x8eb44a87, 0x68581511],
[0xdb0c2e0d, 0x64f98fa7],
[0x47b5481d, 0xbefa4fa4]
];
_states['SHA-512/256'] = [
[0x22312194, 0xFC2BF72C],
[0x9F555FA3, 0xC84C64C2],
[0x2393B86B, 0x6F53B151],
[0x96387719, 0x5940EABD],
[0x96283EE2, 0xA88EFFE3],
[0xBE5E1E25, 0x53863992],
[0x2B0199FC, 0x2C85B8AA],
[0x0EB72DDC, 0x81C52CA2]
];
_states['SHA-512/224'] = [
[0x8C3D37C8, 0x19544DA2],
[0x73E19966, 0x89DCD4D6],
[0x1DFAB7AE, 0x32FF9C82],
[0x679DD514, 0x582F9FCF],
[0x0F6D2B69, 0x7BD44DA8],
[0x77E36F73, 0x04C48942],
[0x3F9D85A8, 0x6A1D36C8],
[0x1112E6AD, 0x91D692A1]
];
// now initialized
_initialized = true;
}
/**
* Updates a SHA-512 state with the given byte buffer.
*
* @param s the SHA-512 state to update.
* @param w the array to use to store words.
* @param bytes the byte buffer to update with.
*/
function _update(s, w, bytes) {
// consume 512 bit (128 byte) chunks
var t1_hi, t1_lo;
var t2_hi, t2_lo;
var s0_hi, s0_lo;
var s1_hi, s1_lo;
var ch_hi, ch_lo;
var maj_hi, maj_lo;
var a_hi, a_lo;
var b_hi, b_lo;
var c_hi, c_lo;
var d_hi, d_lo;
var e_hi, e_lo;
var f_hi, f_lo;
var g_hi, g_lo;
var h_hi, h_lo;
var i, hi, lo, w2, w7, w15, w16;
var len = bytes.length();
while(len >= 128) {
// the w array will be populated with sixteen 64-bit big-endian words
// and then extended into 64 64-bit words according to SHA-512
for(i = 0; i < 16; ++i) {
w[i][0] = bytes.getInt32() >>> 0;
w[i][1] = bytes.getInt32() >>> 0;
}
for(; i < 80; ++i) {
// for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x)
w2 = w[i - 2];
hi = w2[0];
lo = w2[1];
// high bits
t1_hi = (
((hi >>> 19) | (lo << 13)) ^ // ROTR 19
((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29)
(hi >>> 6)) >>> 0; // SHR 6
// low bits
t1_lo = (
((hi << 13) | (lo >>> 19)) ^ // ROTR 19
((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29)
((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6
// for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x)
w15 = w[i - 15];
hi = w15[0];
lo = w15[1];
// high bits
t2_hi = (
((hi >>> 1) | (lo << 31)) ^ // ROTR 1
((hi >>> 8) | (lo << 24)) ^ // ROTR 8
(hi >>> 7)) >>> 0; // SHR 7
// low bits
t2_lo = (
((hi << 31) | (lo >>> 1)) ^ // ROTR 1
((hi << 24) | (lo >>> 8)) ^ // ROTR 8
((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7
// sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow)
w7 = w[i - 7];
w16 = w[i - 16];
lo = (t1_lo + w7[1] + t2_lo + w16[1]);
w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] +
((lo / 0x100000000) >>> 0)) >>> 0;
w[i][1] = lo >>> 0;
}
// initialize hash value for this chunk
a_hi = s[0][0];
a_lo = s[0][1];
b_hi = s[1][0];
b_lo = s[1][1];
c_hi = s[2][0];
c_lo = s[2][1];
d_hi = s[3][0];
d_lo = s[3][1];
e_hi = s[4][0];
e_lo = s[4][1];
f_hi = s[5][0];
f_lo = s[5][1];
g_hi = s[6][0];
g_lo = s[6][1];
h_hi = s[7][0];
h_lo = s[7][1];
// round function
for(i = 0; i < 80; ++i) {
// Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e)
s1_hi = (
((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14
((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18
((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9)
s1_lo = (
((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14
((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18
((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9)
// Ch(e, f, g) (optimized the same way as SHA-1)
ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0;
ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0;
// Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a)
s0_hi = (
((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28
((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2)
((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7)
s0_lo = (
((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28
((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2)
((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7)
// Maj(a, b, c) (optimized the same way as SHA-1)
maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0;
maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0;
// main algorithm
// t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow)
lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]);
t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] +
((lo / 0x100000000) >>> 0)) >>> 0;
t1_lo = lo >>> 0;
// t2 = s0 + maj modulo 2^64 (carry lo overflow)
lo = s0_lo + maj_lo;
t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
t2_lo = lo >>> 0;
h_hi = g_hi;
h_lo = g_lo;
g_hi = f_hi;
g_lo = f_lo;
f_hi = e_hi;
f_lo = e_lo;
// e = (d + t1) modulo 2^64 (carry lo overflow)
lo = d_lo + t1_lo;
e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
e_lo = lo >>> 0;
d_hi = c_hi;
d_lo = c_lo;
c_hi = b_hi;
c_lo = b_lo;
b_hi = a_hi;
b_lo = a_lo;
// a = (t1 + t2) modulo 2^64 (carry lo overflow)
lo = t1_lo + t2_lo;
a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
a_lo = lo >>> 0;
}
// update hash state (additional modulo 2^64)
lo = s[0][1] + a_lo;
s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
s[0][1] = lo >>> 0;
lo = s[1][1] + b_lo;
s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
s[1][1] = lo >>> 0;
lo = s[2][1] + c_lo;
s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
s[2][1] = lo >>> 0;
lo = s[3][1] + d_lo;
s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
s[3][1] = lo >>> 0;
lo = s[4][1] + e_lo;
s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
s[4][1] = lo >>> 0;
lo = s[5][1] + f_lo;
s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
s[5][1] = lo >>> 0;
lo = s[6][1] + g_lo;
s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
s[6][1] = lo >>> 0;
lo = s[7][1] + h_lo;
s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
s[7][1] = lo >>> 0;
len -= 128;
}
}
} // end module implementation
/* ########## Begin module wrapper ########## */
var name = 'sha512';
if(typeof define !== 'function') {
// NodeJS -> AMD
if(typeof module === 'object' && module.exports) {
var nodeJS = true;
define = function(ids, factory) {
factory(require, module);
};
} else {
// <script>
if(typeof forge === 'undefined') {
forge = {};
}
return initModule(forge);
}
}
// AMD
var deps;
var defineFunc = function(require, module) {
module.exports = function(forge) {
var mods = deps.map(function(dep) {
return require(dep);
}).concat(initModule);
// handle circular dependencies
forge = forge || {};
forge.defined = forge.defined || {};
if(forge.defined[name]) {
return forge[name];
}
forge.defined[name] = true;
for(var i = 0; i < mods.length; ++i) {
mods[i](forge);
}
return forge[name];
};
};
var tmpDefine = define;
define = function(ids, factory) {
deps = (typeof ids === 'string') ? factory.slice(2) : ids.slice(2);
if(nodeJS) {
delete define;
return tmpDefine.apply(null, Array.prototype.slice.call(arguments, 0));
}
define = tmpDefine;
return define.apply(null, Array.prototype.slice.call(arguments, 0));
};
define(['require', 'module', './util'], function() {
defineFunc.apply(null, Array.prototype.slice.call(arguments, 0));
});
})();
| unki/thallium | public/resources/forge/js/sha512.js | JavaScript | agpl-3.0 | 18,329 |
// Copyright 2015 go-dockerclient authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package docker
import (
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"strings"
"testing"
)
func TestAuthConfigurationSearchPath(t *testing.T) {
t.Parallel()
var testData = []struct {
dockerConfigEnv string
homeEnv string
expectedPaths []string
}{
{"", "", []string{}},
{"", "home", []string{path.Join("home", ".docker", "config.json"), path.Join("home", ".dockercfg")}},
{"docker_config", "", []string{path.Join("docker_config", "config.json")}},
{"a", "b", []string{path.Join("a", "config.json"), path.Join("b", ".docker", "config.json"), path.Join("b", ".dockercfg")}},
}
for _, tt := range testData {
paths := cfgPaths(tt.dockerConfigEnv, tt.homeEnv)
if got, want := strings.Join(paths, ","), strings.Join(tt.expectedPaths, ","); got != want {
t.Errorf("cfgPaths: wrong result. Want: %s. Got: %s", want, got)
}
}
}
func TestAuthConfigurationsFromFile(t *testing.T) {
t.Parallel()
tmpDir, err := ioutil.TempDir("", "go-dockerclient-auth-test")
if err != nil {
t.Errorf("Unable to create temporary directory for TestAuthConfigurationsFromFile: %s", err)
}
defer os.RemoveAll(tmpDir)
authString := base64.StdEncoding.EncodeToString([]byte("user:pass"))
content := fmt.Sprintf("{\"auths\":{\"foo\": {\"auth\": \"%s\"}}}", authString)
configFile := path.Join(tmpDir, "docker_config")
if err = ioutil.WriteFile(configFile, []byte(content), 0600); err != nil {
t.Errorf("Error writing auth config for TestAuthConfigurationsFromFile: %s", err)
}
auths, err := NewAuthConfigurationsFromFile(configFile)
if err != nil {
t.Errorf("Error calling NewAuthConfigurationsFromFile: %s", err)
}
if _, hasKey := auths.Configs["foo"]; !hasKey {
t.Errorf("Returned auths did not include expected auth key foo")
}
}
func TestAuthLegacyConfig(t *testing.T) {
t.Parallel()
auth := base64.StdEncoding.EncodeToString([]byte("user:pa:ss"))
read := strings.NewReader(fmt.Sprintf(`{"docker.io":{"auth":"%s","email":"user@example.com"}}`, auth))
ac, err := NewAuthConfigurations(read)
if err != nil {
t.Error(err)
}
c, ok := ac.Configs["docker.io"]
if !ok {
t.Error("NewAuthConfigurations: Expected Configs to contain docker.io")
}
if got, want := c.Email, "user@example.com"; got != want {
t.Errorf(`AuthConfigurations.Configs["docker.io"].Email: wrong result. Want %q. Got %q`, want, got)
}
if got, want := c.Username, "user"; got != want {
t.Errorf(`AuthConfigurations.Configs["docker.io"].Username: wrong result. Want %q. Got %q`, want, got)
}
if got, want := c.Password, "pa:ss"; got != want {
t.Errorf(`AuthConfigurations.Configs["docker.io"].Password: wrong result. Want %q. Got %q`, want, got)
}
if got, want := c.ServerAddress, "docker.io"; got != want {
t.Errorf(`AuthConfigurations.Configs["docker.io"].ServerAddress: wrong result. Want %q. Got %q`, want, got)
}
}
func TestAuthBadConfig(t *testing.T) {
t.Parallel()
auth := base64.StdEncoding.EncodeToString([]byte("userpass"))
read := strings.NewReader(fmt.Sprintf(`{"docker.io":{"auth":"%s","email":"user@example.com"}}`, auth))
ac, err := NewAuthConfigurations(read)
if err != ErrCannotParseDockercfg {
t.Errorf("Incorrect error returned %v\n", err)
}
if ac != nil {
t.Errorf("Invalid auth configuration returned, should be nil %v\n", ac)
}
}
func TestAuthAndOtherFields(t *testing.T) {
t.Parallel()
auth := base64.StdEncoding.EncodeToString([]byte("user:pass"))
read := strings.NewReader(fmt.Sprintf(`{
"auths":{"docker.io":{"auth":"%s","email":"user@example.com"}},
"detachKeys": "ctrl-e,e",
"HttpHeaders": { "MyHeader": "MyValue" }}`, auth))
ac, err := NewAuthConfigurations(read)
if err != nil {
t.Error(err)
}
c, ok := ac.Configs["docker.io"]
if !ok {
t.Error("NewAuthConfigurations: Expected Configs to contain docker.io")
}
if got, want := c.Email, "user@example.com"; got != want {
t.Errorf(`AuthConfigurations.Configs["docker.io"].Email: wrong result. Want %q. Got %q`, want, got)
}
if got, want := c.Username, "user"; got != want {
t.Errorf(`AuthConfigurations.Configs["docker.io"].Username: wrong result. Want %q. Got %q`, want, got)
}
if got, want := c.Password, "pass"; got != want {
t.Errorf(`AuthConfigurations.Configs["docker.io"].Password: wrong result. Want %q. Got %q`, want, got)
}
if got, want := c.ServerAddress, "docker.io"; got != want {
t.Errorf(`AuthConfigurations.Configs["docker.io"].ServerAddress: wrong result. Want %q. Got %q`, want, got)
}
}
func TestAuthConfig(t *testing.T) {
t.Parallel()
auth := base64.StdEncoding.EncodeToString([]byte("user:pass"))
read := strings.NewReader(fmt.Sprintf(`{"auths":{"docker.io":{"auth":"%s","email":"user@example.com"}}}`, auth))
ac, err := NewAuthConfigurations(read)
if err != nil {
t.Error(err)
}
c, ok := ac.Configs["docker.io"]
if !ok {
t.Error("NewAuthConfigurations: Expected Configs to contain docker.io")
}
if got, want := c.Email, "user@example.com"; got != want {
t.Errorf(`AuthConfigurations.Configs["docker.io"].Email: wrong result. Want %q. Got %q`, want, got)
}
if got, want := c.Username, "user"; got != want {
t.Errorf(`AuthConfigurations.Configs["docker.io"].Username: wrong result. Want %q. Got %q`, want, got)
}
if got, want := c.Password, "pass"; got != want {
t.Errorf(`AuthConfigurations.Configs["docker.io"].Password: wrong result. Want %q. Got %q`, want, got)
}
if got, want := c.ServerAddress, "docker.io"; got != want {
t.Errorf(`AuthConfigurations.Configs["docker.io"].ServerAddress: wrong result. Want %q. Got %q`, want, got)
}
}
func TestAuthCheck(t *testing.T) {
t.Parallel()
fakeRT := &FakeRoundTripper{status: http.StatusOK}
client := newTestClient(fakeRT)
if _, err := client.AuthCheck(nil); err == nil {
t.Fatalf("expected error on nil auth config")
}
// test good auth
if _, err := client.AuthCheck(&AuthConfiguration{}); err != nil {
t.Fatal(err)
}
*fakeRT = FakeRoundTripper{status: http.StatusUnauthorized}
if _, err := client.AuthCheck(&AuthConfiguration{}); err == nil {
t.Fatal("expected failure from unauthorized auth")
}
}
| dobbymoodge/origin | vendor/github.com/fsouza/go-dockerclient/auth_test.go | GO | apache-2.0 | 6,257 |
/////////////////////////////////////////////////////////////////////////////
// Name: src/common/stdstream.cpp
// Purpose: Implementation of std::istream and std::ostream derived
// wrappers for wxInputStream and wxOutputStream
// Author: Jonathan Liu <net147@gmail.com>
// Created: 2009-05-02
// Copyright: (c) 2009 Jonathan Liu
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ==========================================================================
// Declarations
// ==========================================================================
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_STREAMS && wxUSE_STD_IOSTREAM
#ifndef WX_PRECOMP
#endif
#include "wx/stdstream.h"
#include <ios>
#include <istream>
#include <ostream>
#include <streambuf>
// ==========================================================================
// Helpers
// ==========================================================================
namespace
{
bool
IosSeekDirToWxSeekMode(std::ios_base::seekdir way,
wxSeekMode& seekMode)
{
switch ( way )
{
case std::ios_base::beg:
seekMode = wxFromStart;
break;
case std::ios_base::cur:
seekMode = wxFromCurrent;
break;
case std::ios_base::end:
seekMode = wxFromEnd;
break;
default:
return false;
}
return true;
}
} // anonymous namespace
// ==========================================================================
// wxStdInputStreamBuffer
// ==========================================================================
wxStdInputStreamBuffer::wxStdInputStreamBuffer(wxInputStream& stream) :
m_stream(stream), m_lastChar(EOF)
{
}
std::streambuf *
wxStdInputStreamBuffer::setbuf(char *WXUNUSED(s),
std::streamsize WXUNUSED(n))
{
return NULL;
}
std::streampos
wxStdInputStreamBuffer::seekoff(std::streamoff off,
std::ios_base::seekdir way,
std::ios_base::openmode which)
{
wxSeekMode seekMode;
if ( !IosSeekDirToWxSeekMode(way, seekMode) )
return -1;
if ( !(which & std::ios_base::in) )
return -1;
off_t newPos = m_stream.SeekI((off_t) off, seekMode);
if ( newPos != wxInvalidOffset )
return (std::streampos) newPos;
else
return -1;
}
std::streampos
wxStdInputStreamBuffer::seekpos(std::streampos sp,
std::ios_base::openmode which)
{
if ( !(which & std::ios_base::in) )
return -1;
off_t newPos = m_stream.SeekI((off_t) sp);
if ( newPos != wxInvalidOffset )
return (std::streampos) newPos;
else
return -1;
}
std::streamsize
wxStdInputStreamBuffer::showmanyc()
{
if ( m_stream.CanRead() && (off_t) m_stream.GetSize() > m_stream.TellI() )
return m_stream.GetSize() - m_stream.TellI();
else
return 0;
}
std::streamsize
wxStdInputStreamBuffer::xsgetn(char *s, std::streamsize n)
{
m_stream.Read((void *) s, (size_t) n);
std::streamsize read = m_stream.LastRead();
if ( read > 0 )
m_lastChar = (unsigned char) s[read - 1];
return read;
}
int
wxStdInputStreamBuffer::underflow()
{
int ch = m_stream.GetC();
if ( m_stream.LastRead() == 1 )
{
m_stream.Ungetch((char) ch);
return ch;
}
else
{
return EOF;
}
}
int
wxStdInputStreamBuffer::uflow()
{
int ch = m_stream.GetC();
if ( m_stream.LastRead() == 1 )
{
m_lastChar = ch;
return ch;
}
else
{
return EOF;
}
}
int
wxStdInputStreamBuffer::pbackfail(int c)
{
if ( c == EOF )
{
if ( m_lastChar == EOF )
return EOF;
c = m_lastChar;
m_lastChar = EOF;
}
return m_stream.Ungetch((char) c) ? c : EOF;
}
// ==========================================================================
// wxStdOutputStreamBuffer
// ==========================================================================
wxStdOutputStreamBuffer::wxStdOutputStreamBuffer(wxOutputStream& stream) :
m_stream(stream)
{
}
std::streambuf *
wxStdOutputStreamBuffer::setbuf(char *WXUNUSED(s),
std::streamsize WXUNUSED(n))
{
return NULL;
}
std::streampos
wxStdOutputStreamBuffer::seekoff(std::streamoff off,
std::ios_base::seekdir way,
std::ios_base::openmode which)
{
wxSeekMode seekMode;
if ( !IosSeekDirToWxSeekMode(way, seekMode) )
return -1;
if ( !(which & std::ios_base::out) )
return -1;
off_t newPos = m_stream.SeekO((off_t) off, seekMode);
if ( newPos != wxInvalidOffset )
return (std::streampos) newPos;
else
return -1;
}
std::streampos
wxStdOutputStreamBuffer::seekpos(std::streampos sp,
std::ios_base::openmode which)
{
if ( !(which & std::ios_base::out) )
return -1;
off_t newPos = m_stream.SeekO((off_t) sp);
if ( newPos != wxInvalidOffset )
return (std::streampos) newPos;
else
return -1;
}
std::streamsize
wxStdOutputStreamBuffer::xsputn(const char *s,
std::streamsize n)
{
m_stream.Write((const void *) s, (size_t) n);
return (std::streamsize) m_stream.LastWrite();
}
int
wxStdOutputStreamBuffer::overflow(int c)
{
m_stream.PutC(c);
return m_stream.IsOk() ? c : EOF;
}
// ==========================================================================
// wxStdInputStream and wxStdOutputStream
// ==========================================================================
wxStdInputStream::wxStdInputStream(wxInputStream& stream) :
std::istream(NULL), m_streamBuffer(stream)
{
std::ios::init(&m_streamBuffer);
}
wxStdOutputStream::wxStdOutputStream(wxOutputStream& stream) :
std::ostream(NULL), m_streamBuffer(stream)
{
std::ios::init(&m_streamBuffer);
}
#endif // wxUSE_STREAMS && wxUSE_STD_IOSTREAM
| adouble42/nemesis-current | wxWidgets-3.1.0/src/common/stdstream.cpp | C++ | bsd-2-clause | 6,258 |
void cphisto(){
TFile * f = new TFile("histos.root") ;
TList * l=(TList*)f->Get("histESD") ;
cout << l->GetSize() << endl ;
TFile fout("sum.root","recreate") ;
for(Int_t i=0;i<l->GetSize();i++){
l->At(i)->Write() ;
}
fout.Close() ;
}
| akubera/AliPhysics | PWGGA/PHOSTasks/PHOSCalib/cphisto.C | C++ | bsd-3-clause | 255 |
//
// iWeb - navbar.js
// Copyright (c) 2007-2008 Apple Inc. All rights reserved.
//
var NavBar=Class.create(Widget,{widgetIdentifier:"com-apple-iweb-widget-NavBar",initialize:function($super,instanceID,widgetPath,sharedPath,sitePath,preferences,runningInApp)
{if(instanceID)
{$super(instanceID,widgetPath,sharedPath,sitePath,preferences,runningInApp);if(!this.preferenceForKey("useStaticFeed")&&this.preferenceForKey("dotMacAccount"))
{var depthPrefix=this.preferenceForKey("path-to-root");if(!depthPrefix||depthPrefix=="")
depthPrefix="./";this.xml_feed=depthPrefix+"?webdav-method=truthget&depth=infinity&ns=iweb&filterby=in-navbar";}
else
{this.xml_feed="feed.xml";if(this.sitePath)
{this.xml_feed=this.sitePath+"/"+this.xml_feed;}}
this.changedPreferenceForKey("navbar-css");this.regenerate();}},regenerate:function()
{new Ajax.Request(this.xml_feed,{method:'get',onSuccess:this.populateNavItems.bind(this)});return true;},getStyleElement:function(key)
{if(!this.styleElement)
{var head=document.getElementsByTagName("head")[0];if(head)
{var newElement=document.createElement("style");newElement.type="text/css";head.appendChild(newElement);this.styleElement=newElement;}}
return this.styleElement;},substWidgetPath:function(text)
{var result=text.replace(/\$WIDGET_PATH/gm,this.widgetPath);return result;},addCSSSelectorPrefix:function(text)
{var prefix="div#"+this.instanceID+" ";text=text.replace(/\/\*[^*]*\*+([^/][^*]*\*+)*\//gm,"");text=text.replace(/(^\s*|\}\s*)([^{]+)({[^}]*})/gm,function(match,beforeSelectorList,selectorList,propertyList){var result=beforeSelectorList;var selectors=selectorList.split(",");for(var i=0;i<selectors.length;i++){result+=prefix+selectors[i];if(i+1<selectors.length)result+=",";}
result+=propertyList;return result;});return text;},changedPreferenceForKey:function(key)
{if(key=="navbar-css")
{var text=this.preferenceForKey(key);if(!text)
{text="";}
text=this.substWidgetPath(text);text=this.addCSSSelectorPrefix(text);var styleElement=this.getStyleElement();if(styleElement)
{if(!windowsInternetExplorer)
{var node=document.createTextNode(text);if(node)
{while(styleElement.hasChildNodes())
{styleElement.removeChild(styleElement.firstChild);}
styleElement.appendChild(node);}}
else
{styleElement.styleSheet.cssText=text;}}}},populateNavItems:function(req)
{var items;var feedRoot=ajaxGetDocumentElement(req);if(feedRoot){var parsedFeed=this.getAtomFeedItems(feedRoot);var items=parsedFeed.resultArray;var currentPageGUID=null;var isCollectionPage="NO";var curPagePat=null;if(this.runningInApp)
curPagePat=/\.#current#.$/;else
{currentPageGUID=this.preferenceForKey("current-page-GUID");isCollectionPage=this.preferenceForKey("isCollectionPage");}
var navDiv=this.div("navbar-list");var navBgDiv=navDiv.parentNode;$(navBgDiv).ensureHasLayoutForIE();while(navDiv.firstChild){navDiv.removeChild(navDiv.firstChild);}
var depthPrefix=this.preferenceForKey("path-to-root");if(!depthPrefix||depthPrefix=="")
depthPrefix="./";for(var x=0;x<items.length;x++){var navItem=document.createElement("li");var anchor=document.createElement("a");var title=items[x].title;var pageGUID=items[x].GUID;title=title.replace(/ /g,"\u00a0")+" ";var url=items[x].url;if(!this.runningInApp&&!url.match(/^http:/i))
url=depthPrefix+url;var inAppCurPage=this.runningInApp&&curPagePat.exec(unescape(new String(url)));if(inAppCurPage)
{url=url.replace(curPagePat,"");}
if(pageGUID==currentPageGUID||inAppCurPage){navItem.className='current-page';if(!this.runningInApp&&isCollectionPage!="YES"){url="";}}
else
navItem.className='noncurrent-page';anchor.setAttribute("href",url);anchor.appendChild(document.createTextNode(title));navItem.appendChild(anchor);navDiv.appendChild(navItem);}
if(this.preferences&&this.preferences.postNotification){this.preferences.postNotification("BLWidgetIsSafeToDrawNotification",1);}}},getAtomFeedItems:function(feedNode)
{var results=new Array;var pageOrder=new Array;if(feedNode)
{var generator="";var generatorElt=getFirstElementByTagName(feedNode,"generator");if(generatorElt&&generatorElt.firstChild){generator=allData(generatorElt);}
var pageGUIDs,pageGUIDsElt;for(var entryElt=feedNode.firstChild;entryElt;entryElt=entryElt.nextSibling){var isInNavbarElt=null;if(!pageGUIDs&&(pageGUIDsElt=findChild(entryElt,"site-navbar","urn:iweb:"))){pageGUIDs=allData(pageGUIDsElt).split(",");for(var x=0;x<pageGUIDs.length;x++){var pageGUID=pageGUIDs[x];pageOrder[""+pageGUID]=x;}}
if(entryElt.nodeName=="entry"&&(isInNavbarElt=findChild(entryElt,"in-navbar","urn:iweb:"))){if(!isInNavbarElt)
continue;var pageGUID="";if(isInNavbarElt.firstChild){pageGUID=""+allData(isInNavbarElt);}else{iWLog("no navBarElt child");}
if(pageGUID=="navbar-sort")
continue;var title="";var titleElt=findChild(entryElt,"title","urn:iweb:");if(!titleElt){iWLog("No iWeb title");titleElt=findChild(entryElt,"title");}
if(titleElt&&titleElt.firstChild){title=allData(titleElt);}
var linkElt=getFirstElementByTagName(entryElt,'link');url=linkElt.getAttribute("href");if(!url&&linkElement.firstChild){url=allData(linkElement);}
results[results.length]={title:title,url:url,GUID:pageGUID};}}}
if(pageGUIDs){results=$(results).reject(function(result){return(pageOrder[result.GUID]===undefined);});results.sort(function(lhs,rhs){return pageOrder[lhs.GUID]-pageOrder[rhs.GUID];});}
return{resultArray:results};},onload:function()
{},onunload:function()
{}});function findChild(element,nodeName,namespace)
{var child;for(child=element.firstChild;child;child=child.nextSibling){if(child.localName==nodeName||child.baseName==nodeName){if(!namespace){return child;}
var childNameSpace=child.namespaceURI;if(childNameSpace==namespace){return child;}}}
return null;}
function getFirstElementByTagName(node,tag_name){var elements=node.getElementsByTagName(tag_name);if(elements.length){return elements[0];}
else{return findChild(node,tag_name);}}
function allData(node)
{node=node.firstChild;var data=node.data;while((node=node.nextSibling)){data+=node.data;}
return data;}
| vrdmr/vrdmr.github.io | www/Scripts/Widgets/Navbar/navbar.js | JavaScript | mit | 5,986 |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 1997-2009 Oracle. All rights reserved.
*
* $Id$
*/
package com.sleepycat.db;
import com.sleepycat.db.internal.DbEnv;
/**
Thrown if the version of the Berkeley DB library doesn't match the version that created
the database environment.
*/
public class VersionMismatchException extends DatabaseException {
/* package */ VersionMismatchException(final String s,
final int errno,
final DbEnv dbenv) {
super(s, errno, dbenv);
}
}
| mxrrow/zaicoin | src/deps/db/java/src/com/sleepycat/db/VersionMismatchException.java | Java | mit | 597 |
package stream
import (
"io"
"sync"
"golang.org/x/net/context"
"github.com/Sirupsen/logrus"
"github.com/docker/docker/pkg/promise"
)
var defaultEscapeSequence = []byte{16, 17} // ctrl-p, ctrl-q
// DetachError is special error which returned in case of container detach.
type DetachError struct{}
func (DetachError) Error() string {
return "detached from container"
}
// AttachConfig is the config struct used to attach a client to a stream's stdio
type AttachConfig struct {
// Tells the attach copier that the stream's stdin is a TTY and to look for
// escape sequences in stdin to detach from the stream.
// When true the escape sequence is not passed to the underlying stream
TTY bool
// Specifies the detach keys the client will be using
// Only useful when `TTY` is true
DetachKeys []byte
// CloseStdin signals that once done, stdin for the attached stream should be closed
// For example, this would close the attached container's stdin.
CloseStdin bool
// UseStd* indicate whether the client has requested to be connected to the
// given stream or not. These flags are used instead of checking Std* != nil
// at points before the client streams Std* are wired up.
UseStdin, UseStdout, UseStderr bool
// CStd* are the streams directly connected to the container
CStdin io.WriteCloser
CStdout, CStderr io.ReadCloser
// Provide client streams to wire up to
Stdin io.ReadCloser
Stdout, Stderr io.Writer
}
// AttachStreams attaches the container's streams to the AttachConfig
func (c *Config) AttachStreams(cfg *AttachConfig) {
if cfg.UseStdin {
cfg.CStdin = c.StdinPipe()
}
if cfg.UseStdout {
cfg.CStdout = c.StdoutPipe()
}
if cfg.UseStderr {
cfg.CStderr = c.StderrPipe()
}
}
// CopyStreams starts goroutines to copy data in and out to/from the container
func (c *Config) CopyStreams(ctx context.Context, cfg *AttachConfig) chan error {
var (
wg sync.WaitGroup
errors = make(chan error, 3)
)
if cfg.Stdin != nil {
wg.Add(1)
}
if cfg.Stdout != nil {
wg.Add(1)
}
if cfg.Stderr != nil {
wg.Add(1)
}
// Connect stdin of container to the attach stdin stream.
go func() {
if cfg.Stdin == nil {
return
}
logrus.Debug("attach: stdin: begin")
var err error
if cfg.TTY {
_, err = copyEscapable(cfg.CStdin, cfg.Stdin, cfg.DetachKeys)
} else {
_, err = io.Copy(cfg.CStdin, cfg.Stdin)
}
if err == io.ErrClosedPipe {
err = nil
}
if err != nil {
logrus.Errorf("attach: stdin: %s", err)
errors <- err
}
if cfg.CloseStdin && !cfg.TTY {
cfg.CStdin.Close()
} else {
// No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr
if cfg.CStdout != nil {
cfg.CStdout.Close()
}
if cfg.CStderr != nil {
cfg.CStderr.Close()
}
}
logrus.Debug("attach: stdin: end")
wg.Done()
}()
attachStream := func(name string, stream io.Writer, streamPipe io.ReadCloser) {
if stream == nil {
return
}
logrus.Debugf("attach: %s: begin", name)
_, err := io.Copy(stream, streamPipe)
if err == io.ErrClosedPipe {
err = nil
}
if err != nil {
logrus.Errorf("attach: %s: %v", name, err)
errors <- err
}
// Make sure stdin gets closed
if cfg.Stdin != nil {
cfg.Stdin.Close()
}
streamPipe.Close()
logrus.Debugf("attach: %s: end", name)
wg.Done()
}
go attachStream("stdout", cfg.Stdout, cfg.CStdout)
go attachStream("stderr", cfg.Stderr, cfg.CStderr)
return promise.Go(func() error {
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
case <-ctx.Done():
// close all pipes
if cfg.CStdin != nil {
cfg.CStdin.Close()
}
if cfg.CStdout != nil {
cfg.CStdout.Close()
}
if cfg.CStderr != nil {
cfg.CStderr.Close()
}
<-done
}
close(errors)
for err := range errors {
if err != nil {
return err
}
}
return nil
})
}
// ttyProxy is used only for attaches with a TTY. It is used to proxy
// stdin keypresses from the underlying reader and look for the passed in
// escape key sequence to signal a detach.
type ttyProxy struct {
escapeKeys []byte
escapeKeyPos int
r io.Reader
}
func (r *ttyProxy) Read(buf []byte) (int, error) {
nr, err := r.r.Read(buf)
preserve := func() {
// this preserves the original key presses in the passed in buffer
nr += r.escapeKeyPos
preserve := make([]byte, 0, r.escapeKeyPos+len(buf))
preserve = append(preserve, r.escapeKeys[:r.escapeKeyPos]...)
preserve = append(preserve, buf...)
r.escapeKeyPos = 0
copy(buf[0:nr], preserve)
}
if nr != 1 || err != nil {
if r.escapeKeyPos > 0 {
preserve()
}
return nr, err
}
if buf[0] != r.escapeKeys[r.escapeKeyPos] {
if r.escapeKeyPos > 0 {
preserve()
}
return nr, nil
}
if r.escapeKeyPos == len(r.escapeKeys)-1 {
return 0, DetachError{}
}
// Looks like we've got an escape key, but we need to match again on the next
// read.
// Store the current escape key we found so we can look for the next one on
// the next read.
// Since this is an escape key, make sure we don't let the caller read it
// If later on we find that this is not the escape sequence, we'll add the
// keys back
r.escapeKeyPos++
return nr - r.escapeKeyPos, nil
}
func copyEscapable(dst io.Writer, src io.ReadCloser, keys []byte) (written int64, err error) {
if len(keys) == 0 {
keys = defaultEscapeSequence
}
pr := &ttyProxy{escapeKeys: keys, r: src}
defer src.Close()
return io.Copy(dst, pr)
}
| Originate/exosphere | vendor/github.com/moby/moby/container/stream/attach.go | GO | mit | 5,521 |
app.controller('LayersOverlaysMarkersNestedController', ['$scope', 'leafletData','$timeout',
function ($scope, leafletData, $timeout) {
var _map;
leafletData.getMap().then(function(map){
_map = map;
});
angular.extend($scope, {
eraseMarkers: function(){
$scope.markers = {
cars: {
m1: {
lat: 42.20133,
lng: 2.19110,
message: "I'm a car"
}
}
};
//$scope.$apply();
leafletData.getMarkers().then(function(lmarkers) {
$scope.hasM1 = _map.hasLayer(lmarkers.m1);
$scope.hasM2 = _map.hasLayer(lmarkers.m2);
});
$timeout(function(){
leafletData.getMarkers().then(function(lmarkers){
$scope.lMarkers = Object.keys(lmarkers);
$scope.hasM1 = _map.hasLayer(lmarkers.m1);
$scope.hasM2 = _map.hasLayer(lmarkers.m2);
});
},1000);
},
lMarkers:{},
ripoll: {
lat: 42.20133,
lng: 2.19110,
zoom: 11
},
layers: {
baselayers: {
osm: {
name: 'OpenStreetMap',
type: 'xyz',
url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
layerOptions: {
subdomains: ['a', 'b', 'c'],
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
continuousWorld: true
}
},
cycle: {
name: 'OpenCycleMap',
type: 'xyz',
url: 'http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png',
layerOptions: {
subdomains: ['a', 'b', 'c'],
attribution: '© <a href="http://www.opencyclemap.org/copyright">OpenCycleMap</a> contributors - © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
continuousWorld: true
}
}
},
overlays: {
hillshade: {
name: 'Hillshade Europa',
type: 'wms',
url: 'http://129.206.228.72/cached/hillshade',
visible: true,
layerOptions: {
layers: 'europe_wms:hs_srtm_europa',
format: 'image/png',
opacity: 0.25,
attribution: 'Hillshade layer by GIScience http://www.osm-wms.de',
crs: L.CRS.EPSG900913
}
},
fire: {
name: 'OpenFireMap',
type: 'xyz',
url: 'http://openfiremap.org/hytiles/{z}/{x}/{y}.png',
layerOptions: {
attribution: '© <a href="http://www.openfiremap.org">OpenFireMap</a> contributors - © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
continuousWorld: true
}
},
cars: {
name: 'Cars',
type: 'group',
visible: true
},
bikes: {
name: 'Bicycles',
type: 'group',
visible: false
},
runners:{
name: 'Runners',
type: 'group',
visible: false
}
}
},
markers: {
cars: {
m1: {
lat: 42.20133,
lng: 2.19110,
message: "I'm a car"
},
m2: {
lat: 42.21133,
lng: 2.18110,
message: "I'm a car"
}
},
bikes: {
m3: {
lat: 42.19133,
lng: 2.18110,
layer: 'bikes',
message: 'A bike!!'
},
m4: {
lat: 42.3,
lng: 2.16110,
layer: 'bikes'
}
},
runners: {
m5: {
lat: 42.1,
lng: 2.16910
},
m6: {
lat: 42.15,
lng: 2.17110
}
}
}
});
}]); | ronnpang1/otocopy | www/lib/angular-leaflet-directive-master/examples/js/controllers/LayersOverlaysMarkersNestedController.js | JavaScript | mit | 6,000 |
<?php
/**
* @package Joomla.Site
* @subpackage Layout
*
* @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('JPATH_BASE') or die;
$id = empty($displayData['id']) ? '' : (' id="' . $displayData['id'] . '"');
$target = empty($displayData['target']) ? '' : (' target="' . $displayData['target'] . '"');
$onclick = empty($displayData['onclick']) ? '' : (' onclick="' . $displayData['onclick'] . '"');
$title = empty($displayData['title']) ? '' : (' title="' . $this->escape($displayData['title']) . '"');
$text = empty($displayData['text']) ? '' : ('<span>' . $displayData['text'] . '</span>')
?>
<div class="row-fluid"<?php echo $id; ?>>
<div class="span12">
<a href="<?php echo $displayData['link']; ?>"<?php echo $target . $onclick . $title; ?>>
<span class="icon-<?php echo $displayData['image']; ?>" aria-hidden="true"></span> <?php echo $text; ?>
</a>
</div>
</div>
| vyelamanchili/v4ecc | sites/ranjeesh/layouts/joomla/quickicons/icon.php | PHP | gpl-2.0 | 1,027 |
// Copyright 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 "chrome/browser/ui/views/frame/browser_view_layout.h"
#include "base/observer_list.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/find_bar/find_bar.h"
#include "chrome/browser/ui/find_bar/find_bar_controller.h"
#include "chrome/browser/ui/search/search_model.h"
#include "chrome/browser/ui/views/bookmarks/bookmark_bar_view.h"
#include "chrome/browser/ui/views/download/download_shelf_view.h"
#include "chrome/browser/ui/views/frame/browser_view_layout_delegate.h"
#include "chrome/browser/ui/views/frame/contents_layout_manager.h"
#include "chrome/browser/ui/views/frame/immersive_mode_controller.h"
#include "chrome/browser/ui/views/frame/top_container_view.h"
#include "chrome/browser/ui/views/fullscreen_exit_bubble_views.h"
#include "chrome/browser/ui/views/infobars/infobar_container_view.h"
#include "chrome/browser/ui/views/tabs/tab_strip.h"
#include "components/web_modal/web_contents_modal_dialog_host.h"
#include "ui/base/hit_test.h"
#include "ui/gfx/point.h"
#include "ui/gfx/scrollbar_size.h"
#include "ui/gfx/size.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/client_view.h"
using views::View;
using web_modal::WebContentsModalDialogHost;
using web_modal::ModalDialogHostObserver;
namespace {
// The visible height of the shadow above the tabs. Clicks in this area are
// treated as clicks to the frame, rather than clicks to the tab.
const int kTabShadowSize = 2;
// The number of pixels the constrained window should overlap the bottom
// of the omnibox.
const int kConstrainedWindowOverlap = 3;
// Combines View::ConvertPointToTarget and View::HitTest for a given |point|.
// Converts |point| from |src| to |dst| and hit tests it against |dst|. The
// converted |point| can then be retrieved and used for additional tests.
bool ConvertedHitTest(views::View* src, views::View* dst, gfx::Point* point) {
DCHECK(src);
DCHECK(dst);
DCHECK(point);
views::View::ConvertPointToTarget(src, dst, point);
return dst->HitTestPoint(*point);
}
} // namespace
class BrowserViewLayout::WebContentsModalDialogHostViews
: public WebContentsModalDialogHost {
public:
explicit WebContentsModalDialogHostViews(
BrowserViewLayout* browser_view_layout)
: browser_view_layout_(browser_view_layout) {
}
virtual ~WebContentsModalDialogHostViews() {
FOR_EACH_OBSERVER(ModalDialogHostObserver,
observer_list_,
OnHostDestroying());
}
void NotifyPositionRequiresUpdate() {
FOR_EACH_OBSERVER(ModalDialogHostObserver,
observer_list_,
OnPositionRequiresUpdate());
}
virtual gfx::Point GetDialogPosition(const gfx::Size& size) OVERRIDE {
views::View* view = browser_view_layout_->contents_container_;
gfx::Rect content_area = view->ConvertRectToWidget(view->GetLocalBounds());
const int middle_x = content_area.x() + content_area.width() / 2;
const int top = browser_view_layout_->web_contents_modal_dialog_top_y_;
return gfx::Point(middle_x - size.width() / 2, top);
}
virtual gfx::Size GetMaximumDialogSize() OVERRIDE {
views::View* view = browser_view_layout_->contents_container_;
gfx::Rect content_area = view->ConvertRectToWidget(view->GetLocalBounds());
const int top = browser_view_layout_->web_contents_modal_dialog_top_y_;
return gfx::Size(content_area.width(), content_area.bottom() - top);
}
private:
virtual gfx::NativeView GetHostView() const OVERRIDE {
gfx::NativeWindow window =
browser_view_layout_->browser()->window()->GetNativeWindow();
return views::Widget::GetWidgetForNativeWindow(window)->GetNativeView();
}
// Add/remove observer.
virtual void AddObserver(ModalDialogHostObserver* observer) OVERRIDE {
observer_list_.AddObserver(observer);
}
virtual void RemoveObserver(ModalDialogHostObserver* observer) OVERRIDE {
observer_list_.RemoveObserver(observer);
}
BrowserViewLayout* const browser_view_layout_;
ObserverList<ModalDialogHostObserver> observer_list_;
DISALLOW_COPY_AND_ASSIGN(WebContentsModalDialogHostViews);
};
// static
const int BrowserViewLayout::kToolbarTabStripVerticalOverlap = 3;
////////////////////////////////////////////////////////////////////////////////
// BrowserViewLayout, public:
BrowserViewLayout::BrowserViewLayout()
: browser_(NULL),
browser_view_(NULL),
top_container_(NULL),
tab_strip_(NULL),
toolbar_(NULL),
bookmark_bar_(NULL),
infobar_container_(NULL),
contents_container_(NULL),
contents_layout_manager_(NULL),
download_shelf_(NULL),
immersive_mode_controller_(NULL),
dialog_host_(new WebContentsModalDialogHostViews(this)),
web_contents_modal_dialog_top_y_(-1) {}
BrowserViewLayout::~BrowserViewLayout() {
}
void BrowserViewLayout::Init(
BrowserViewLayoutDelegate* delegate,
Browser* browser,
views::ClientView* browser_view,
views::View* top_container,
TabStrip* tab_strip,
views::View* toolbar,
InfoBarContainerView* infobar_container,
views::View* contents_container,
ContentsLayoutManager* contents_layout_manager,
ImmersiveModeController* immersive_mode_controller) {
delegate_.reset(delegate);
browser_ = browser;
browser_view_ = browser_view;
top_container_ = top_container;
tab_strip_ = tab_strip;
toolbar_ = toolbar;
infobar_container_ = infobar_container;
contents_container_ = contents_container;
contents_layout_manager_ = contents_layout_manager;
immersive_mode_controller_ = immersive_mode_controller;
}
WebContentsModalDialogHost*
BrowserViewLayout::GetWebContentsModalDialogHost() {
return dialog_host_.get();
}
gfx::Size BrowserViewLayout::GetMinimumSize() {
gfx::Size tabstrip_size(
browser()->SupportsWindowFeature(Browser::FEATURE_TABSTRIP) ?
tab_strip_->GetMinimumSize() : gfx::Size());
gfx::Size toolbar_size(
(browser()->SupportsWindowFeature(Browser::FEATURE_TOOLBAR) ||
browser()->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR)) ?
toolbar_->GetMinimumSize() : gfx::Size());
if (tabstrip_size.height() && toolbar_size.height())
toolbar_size.Enlarge(0, -kToolbarTabStripVerticalOverlap);
gfx::Size bookmark_bar_size;
if (bookmark_bar_ &&
bookmark_bar_->visible() &&
browser()->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR)) {
bookmark_bar_size = bookmark_bar_->GetMinimumSize();
bookmark_bar_size.Enlarge(0, -bookmark_bar_->GetToolbarOverlap());
}
gfx::Size infobar_container_size(infobar_container_->GetMinimumSize());
// TODO: Adjust the minimum height for the find bar.
gfx::Size contents_size(contents_container_->GetMinimumSize());
int min_height = delegate_->GetTopInsetInBrowserView() +
tabstrip_size.height() + toolbar_size.height() +
bookmark_bar_size.height() + infobar_container_size.height() +
contents_size.height();
int widths[] = {
tabstrip_size.width(),
toolbar_size.width(),
bookmark_bar_size.width(),
infobar_container_size.width(),
contents_size.width() };
int min_width = *std::max_element(&widths[0], &widths[arraysize(widths)]);
return gfx::Size(min_width, min_height);
}
gfx::Rect BrowserViewLayout::GetFindBarBoundingBox() const {
// This function returns the area the Find Bar can be laid out within. This
// basically implies the "user-perceived content area" of the browser
// window excluding the vertical scrollbar. The "user-perceived content area"
// excludes the detached bookmark bar (in the New Tab case) and any infobars
// since they are not _visually_ connected to the Toolbar.
// First determine the bounding box of the content area in Widget
// coordinates.
gfx::Rect bounding_box = contents_container_->ConvertRectToWidget(
contents_container_->GetLocalBounds());
gfx::Rect top_container_bounds = top_container_->ConvertRectToWidget(
top_container_->GetLocalBounds());
int find_bar_y = 0;
if (immersive_mode_controller_->IsEnabled() &&
!immersive_mode_controller_->IsRevealed()) {
// Position the find bar exactly below the top container. In immersive
// fullscreen, when the top-of-window views are not revealed, only the
// miniature immersive style tab strip is visible. Do not overlap the
// find bar and the tab strip.
find_bar_y = top_container_bounds.bottom();
} else {
// Position the find bar 1 pixel above the bottom of the top container
// so that it occludes the border between the content area and the top
// container and looks connected to the top container.
find_bar_y = top_container_bounds.bottom() - 1;
}
// Grow the height of |bounding_box| by the height of any elements between
// the top container and |contents_container_| such as the detached bookmark
// bar and any infobars.
int height_delta = bounding_box.y() - find_bar_y;
bounding_box.set_y(find_bar_y);
bounding_box.set_height(std::max(0, bounding_box.height() + height_delta));
// Finally decrease the width of the bounding box by the width of
// the vertical scroll bar.
int scrollbar_width = gfx::scrollbar_size();
bounding_box.set_width(std::max(0, bounding_box.width() - scrollbar_width));
if (base::i18n::IsRTL())
bounding_box.set_x(bounding_box.x() + scrollbar_width);
return bounding_box;
}
int BrowserViewLayout::NonClientHitTest(const gfx::Point& point) {
// Since the TabStrip only renders in some parts of the top of the window,
// the un-obscured area is considered to be part of the non-client caption
// area of the window. So we need to treat hit-tests in these regions as
// hit-tests of the titlebar.
views::View* parent = browser_view_->parent();
gfx::Point point_in_browser_view_coords(point);
views::View::ConvertPointToTarget(
parent, browser_view_, &point_in_browser_view_coords);
gfx::Point test_point(point);
// Determine if the TabStrip exists and is capable of being clicked on. We
// might be a popup window without a TabStrip.
if (delegate_->IsTabStripVisible()) {
// See if the mouse pointer is within the bounds of the TabStrip.
if (ConvertedHitTest(parent, tab_strip_, &test_point)) {
if (tab_strip_->IsPositionInWindowCaption(test_point))
return HTCAPTION;
return HTCLIENT;
}
// The top few pixels of the TabStrip are a drop-shadow - as we're pretty
// starved of dragable area, let's give it to window dragging (this also
// makes sense visually).
views::Widget* widget = browser_view_->GetWidget();
if (!(widget->IsMaximized() || widget->IsFullscreen()) &&
(point_in_browser_view_coords.y() <
(tab_strip_->y() + kTabShadowSize))) {
// We return HTNOWHERE as this is a signal to our containing
// NonClientView that it should figure out what the correct hit-test
// code is given the mouse position...
return HTNOWHERE;
}
}
// If the point's y coordinate is below the top of the toolbar and otherwise
// within the bounds of this view, the point is considered to be within the
// client area.
gfx::Rect bv_bounds = browser_view_->bounds();
bv_bounds.Offset(0, toolbar_->y());
bv_bounds.set_height(bv_bounds.height() - toolbar_->y());
if (bv_bounds.Contains(point))
return HTCLIENT;
// If the point's y coordinate is above the top of the toolbar, but not
// over the tabstrip (per previous checking in this function), then we
// consider it in the window caption (e.g. the area to the right of the
// tabstrip underneath the window controls). However, note that we DO NOT
// return HTCAPTION here, because when the window is maximized the window
// controls will fall into this space (since the BrowserView is sized to
// entire size of the window at that point), and the HTCAPTION value will
// cause the window controls not to work. So we return HTNOWHERE so that the
// caller will hit-test the window controls before finally falling back to
// HTCAPTION.
bv_bounds = browser_view_->bounds();
bv_bounds.set_height(toolbar_->y());
if (bv_bounds.Contains(point))
return HTNOWHERE;
// If the point is somewhere else, delegate to the default implementation.
return browser_view_->views::ClientView::NonClientHitTest(point);
}
//////////////////////////////////////////////////////////////////////////////
// BrowserViewLayout, views::LayoutManager implementation:
void BrowserViewLayout::Layout(views::View* browser_view) {
vertical_layout_rect_ = browser_view->GetLocalBounds();
int top = delegate_->GetTopInsetInBrowserView();
top = LayoutTabStripRegion(top);
if (delegate_->IsTabStripVisible()) {
int x = tab_strip_->GetMirroredX() +
browser_view_->GetMirroredX() +
delegate_->GetThemeBackgroundXInset();
int y = browser_view_->y() + delegate_->GetTopInsetInBrowserView();
tab_strip_->SetBackgroundOffset(gfx::Point(x, y));
}
top = LayoutToolbar(top);
top = LayoutBookmarkAndInfoBars(top, browser_view->y());
// Top container requires updated toolbar and bookmark bar to compute bounds.
UpdateTopContainerBounds();
int bottom = LayoutDownloadShelf(browser_view->height());
// Treat a detached bookmark bar as if the web contents container is shifted
// upwards and overlaps it.
int active_top_margin = GetContentsOffsetForBookmarkBar();
contents_layout_manager_->SetActiveTopMargin(active_top_margin);
top -= active_top_margin;
LayoutContentsContainerView(top, bottom);
// This must be done _after_ we lay out the WebContents since this
// code calls back into us to find the bounding box the find bar
// must be laid out within, and that code depends on the
// TabContentsContainer's bounds being up to date.
if (browser()->HasFindBarController()) {
browser()->GetFindBarController()->find_bar()->MoveWindowIfNecessary(
gfx::Rect(), true);
}
// Adjust the fullscreen exit bubble bounds for |top_container_|'s new bounds.
// This makes the fullscreen exit bubble look like it animates with
// |top_container_| in immersive fullscreen.
FullscreenExitBubbleViews* fullscreen_exit_bubble =
delegate_->GetFullscreenExitBubble();
if (fullscreen_exit_bubble)
fullscreen_exit_bubble->RepositionIfVisible();
// Adjust any hosted dialogs if the browser's dialog hosting bounds changed.
const gfx::Rect dialog_bounds(dialog_host_->GetDialogPosition(gfx::Size()),
dialog_host_->GetMaximumDialogSize());
if (latest_dialog_bounds_ != dialog_bounds) {
latest_dialog_bounds_ = dialog_bounds;
dialog_host_->NotifyPositionRequiresUpdate();
}
}
// Return the preferred size which is the size required to give each
// children their respective preferred size.
gfx::Size BrowserViewLayout::GetPreferredSize(const views::View* host) const {
return gfx::Size();
}
//////////////////////////////////////////////////////////////////////////////
// BrowserViewLayout, private:
int BrowserViewLayout::LayoutTabStripRegion(int top) {
if (!delegate_->IsTabStripVisible()) {
tab_strip_->SetVisible(false);
tab_strip_->SetBounds(0, 0, 0, 0);
return top;
}
// This retrieves the bounds for the tab strip based on whether or not we show
// anything to the left of it, like the incognito avatar.
gfx::Rect tabstrip_bounds(delegate_->GetBoundsForTabStripInBrowserView());
tab_strip_->SetVisible(true);
tab_strip_->SetBoundsRect(tabstrip_bounds);
return tabstrip_bounds.bottom();
}
int BrowserViewLayout::LayoutToolbar(int top) {
int browser_view_width = vertical_layout_rect_.width();
bool toolbar_visible = delegate_->IsToolbarVisible();
int y = top;
y -= (toolbar_visible && delegate_->IsTabStripVisible()) ?
kToolbarTabStripVerticalOverlap : 0;
int height = toolbar_visible ? toolbar_->GetPreferredSize().height() : 0;
toolbar_->SetVisible(toolbar_visible);
toolbar_->SetBounds(vertical_layout_rect_.x(), y, browser_view_width, height);
return y + height;
}
int BrowserViewLayout::LayoutBookmarkAndInfoBars(int top, int browser_view_y) {
web_contents_modal_dialog_top_y_ =
top + browser_view_y - kConstrainedWindowOverlap;
if (bookmark_bar_) {
// If we're showing the Bookmark bar in detached style, then we
// need to show any Info bar _above_ the Bookmark bar, since the
// Bookmark bar is styled to look like it's part of the page.
if (bookmark_bar_->IsDetached()) {
web_contents_modal_dialog_top_y_ =
top + browser_view_y - kConstrainedWindowOverlap;
return LayoutBookmarkBar(LayoutInfoBar(top));
}
// Otherwise, Bookmark bar first, Info bar second.
top = std::max(toolbar_->bounds().bottom(), LayoutBookmarkBar(top));
}
return LayoutInfoBar(top);
}
int BrowserViewLayout::LayoutBookmarkBar(int top) {
int y = top;
if (!delegate_->IsBookmarkBarVisible()) {
bookmark_bar_->SetVisible(false);
// TODO(jamescook): Don't change the bookmark bar height when it is
// invisible, so we can use its height for layout even in that state.
bookmark_bar_->SetBounds(0, y, browser_view_->width(), 0);
return y;
}
bookmark_bar_->set_infobar_visible(InfobarVisible());
int bookmark_bar_height = bookmark_bar_->GetPreferredSize().height();
y -= bookmark_bar_->GetToolbarOverlap();
bookmark_bar_->SetBounds(vertical_layout_rect_.x(),
y,
vertical_layout_rect_.width(),
bookmark_bar_height);
// Set visibility after setting bounds, as the visibility update uses the
// bounds to determine if the mouse is hovering over a button.
bookmark_bar_->SetVisible(true);
return y + bookmark_bar_height;
}
int BrowserViewLayout::LayoutInfoBar(int top) {
// In immersive fullscreen, the infobar always starts near the top of the
// screen, just under the "light bar" rectangular stripes.
if (immersive_mode_controller_->IsEnabled()) {
top = browser_view_->y();
if (!immersive_mode_controller_->ShouldHideTabIndicators())
top += TabStrip::GetImmersiveHeight();
}
// Raise the |infobar_container_| by its vertical overlap.
infobar_container_->SetVisible(InfobarVisible());
int height;
int overlapped_top = top - infobar_container_->GetVerticalOverlap(&height);
infobar_container_->SetBounds(vertical_layout_rect_.x(),
overlapped_top,
vertical_layout_rect_.width(),
height);
return overlapped_top + height;
}
void BrowserViewLayout::LayoutContentsContainerView(int top, int bottom) {
// |contents_container_| contains web page contents and devtools.
// See browser_view.h for details.
gfx::Rect contents_container_bounds(vertical_layout_rect_.x(),
top,
vertical_layout_rect_.width(),
std::max(0, bottom - top));
contents_container_->SetBoundsRect(contents_container_bounds);
}
void BrowserViewLayout::UpdateTopContainerBounds() {
// Set the bounds of the top container view such that it is tall enough to
// fully show all of its children. In particular, the bottom of the bookmark
// bar can be above the bottom of the toolbar while the bookmark bar is
// animating. The top container view is positioned relative to the top of the
// client view instead of relative to GetTopInsetInBrowserView() because the
// top container view paints parts of the frame (title, window controls)
// during an immersive fullscreen reveal.
int height = 0;
for (int i = 0; i < top_container_->child_count(); ++i) {
views::View* child = top_container_->child_at(i);
if (!child->visible())
continue;
int child_bottom = child->bounds().bottom();
if (child_bottom > height)
height = child_bottom;
}
// Ensure that the top container view reaches the topmost view in the
// ClientView because the bounds of the top container view are used in
// layout and we assume that this is the case.
height = std::max(height, delegate_->GetTopInsetInBrowserView());
gfx::Rect top_container_bounds(vertical_layout_rect_.width(), height);
// If the immersive mode controller is animating the top container, it may be
// partly offscreen.
top_container_bounds.set_y(
immersive_mode_controller_->GetTopContainerVerticalOffset(
top_container_bounds.size()));
top_container_->SetBoundsRect(top_container_bounds);
}
int BrowserViewLayout::GetContentsOffsetForBookmarkBar() {
// If the bookmark bar is hidden or attached to the omnibox the web contents
// will appear directly underneath it and does not need an offset.
if (!bookmark_bar_ ||
!delegate_->IsBookmarkBarVisible() ||
!bookmark_bar_->IsDetached()) {
return 0;
}
// Offset for the detached bookmark bar.
return bookmark_bar_->height() -
bookmark_bar_->GetFullyDetachedToolbarOverlap();
}
int BrowserViewLayout::LayoutDownloadShelf(int bottom) {
if (delegate_->DownloadShelfNeedsLayout()) {
bool visible = browser()->SupportsWindowFeature(
Browser::FEATURE_DOWNLOADSHELF);
DCHECK(download_shelf_);
int height = visible ? download_shelf_->GetPreferredSize().height() : 0;
download_shelf_->SetVisible(visible);
download_shelf_->SetBounds(vertical_layout_rect_.x(), bottom - height,
vertical_layout_rect_.width(), height);
download_shelf_->Layout();
bottom -= height;
}
return bottom;
}
bool BrowserViewLayout::InfobarVisible() const {
// Cast to a views::View to access GetPreferredSize().
views::View* infobar_container = infobar_container_;
// NOTE: Can't check if the size IsEmpty() since it's always 0-width.
return browser_->SupportsWindowFeature(Browser::FEATURE_INFOBAR) &&
(infobar_container->GetPreferredSize().height() != 0);
}
| s20121035/rk3288_android5.1_repo | external/chromium_org/chrome/browser/ui/views/frame/browser_view_layout.cc | C++ | gpl-3.0 | 22,355 |
// PR libgomp/69555
// { dg-do run }
__attribute__((noinline, noclone)) void
f1 (int y)
{
int a[y - 2];
int (&c)[y - 2] = a;
for (int i = 0; i < y - 2; i++)
c[i] = i + 4;
#pragma omp target firstprivate (c)
{
for (int i = 0; i < y - 2; i++)
{
if (c[i] != i + 4)
__builtin_abort ();
c[i] = i + 9;
}
asm volatile ("" : : "r" (&c[0]) : "memory");
for (int i = 0; i < y - 2; i++)
if (c[i] != i + 9)
__builtin_abort ();
}
for (int i = 0; i < y - 2; i++)
if (c[i] != i + 4)
__builtin_abort ();
}
__attribute__((noinline, noclone)) void
f2 (int y)
{
int a[y - 2];
int (&c)[y - 2] = a;
for (int i = 0; i < y - 2; i++)
c[i] = i + 4;
#pragma omp target private (c)
{
for (int i = 0; i < y - 2; i++)
c[i] = i + 9;
asm volatile ("" : : "r" (&c[0]) : "memory");
for (int i = 0; i < y - 2; i++)
if (c[i] != i + 9)
__builtin_abort ();
}
for (int i = 0; i < y - 2; i++)
if (c[i] != i + 4)
__builtin_abort ();
}
int
main ()
{
f1 (6);
f2 (6);
return 0;
}
| selmentdev/selment-toolchain | source/gcc-latest/libgomp/testsuite/libgomp.c++/pr69555-2.C | C++ | gpl-3.0 | 1,065 |
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Authors: keith.ray@gmail.com (Keith Ray)
#include <gtest/internal/gtest-filepath.h>
#include <gtest/internal/gtest-port.h>
#include <stdlib.h>
#ifdef _WIN32_WCE
#include <windows.h>
#elif GTEST_OS_WINDOWS
#include <direct.h>
#include <io.h>
#include <sys/stat.h>
#elif GTEST_OS_SYMBIAN
// Symbian OpenC has PATH_MAX in sys/syslimits.h
#include <sys/syslimits.h>
#include <unistd.h>
#else
#include <limits.h>
#include <sys/stat.h> // NOLINT
#include <unistd.h> // NOLINT
#include <climits> // Some Linux distributions define PATH_MAX here.
#endif // _WIN32_WCE or _WIN32
#if GTEST_OS_WINDOWS
#define GTEST_PATH_MAX_ _MAX_PATH
#elif defined(PATH_MAX)
#define GTEST_PATH_MAX_ PATH_MAX
#elif defined(_XOPEN_PATH_MAX)
#define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
#else
#define GTEST_PATH_MAX_ _POSIX_PATH_MAX
#endif // GTEST_OS_WINDOWS
#include <gtest/internal/gtest-string.h>
namespace testing {
namespace internal {
#if GTEST_OS_WINDOWS
const char kPathSeparator = '\\';
const char kPathSeparatorString[] = "\\";
#ifdef _WIN32_WCE
// Windows CE doesn't have a current directory. You should not use
// the current directory in tests on Windows CE, but this at least
// provides a reasonable fallback.
const char kCurrentDirectoryString[] = "\\";
// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
const DWORD kInvalidFileAttributes = 0xffffffff;
#else
const char kCurrentDirectoryString[] = ".\\";
#endif // _WIN32_WCE
#else
const char kPathSeparator = '/';
const char kPathSeparatorString[] = "/";
const char kCurrentDirectoryString[] = "./";
#endif // GTEST_OS_WINDOWS
// Returns the current working directory, or "" if unsuccessful.
FilePath FilePath::GetCurrentDir() {
#ifdef _WIN32_WCE
// Windows CE doesn't have a current directory, so we just return
// something reasonable.
return FilePath(kCurrentDirectoryString);
#elif GTEST_OS_WINDOWS
char cwd[GTEST_PATH_MAX_ + 1] = {};
return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
#else
char cwd[GTEST_PATH_MAX_ + 1] = {};
return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
#endif
}
// Returns a copy of the FilePath with the case-insensitive extension removed.
// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
// FilePath("dir/file"). If a case-insensitive extension is not
// found, returns a copy of the original FilePath.
FilePath FilePath::RemoveExtension(const char* extension) const {
String dot_extension(String::Format(".%s", extension));
if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) {
return FilePath(String(pathname_.c_str(), pathname_.GetLength() - 4));
}
return *this;
}
// Returns a copy of the FilePath with the directory part removed.
// Example: FilePath("path/to/file").RemoveDirectoryName() returns
// FilePath("file"). If there is no directory part ("just_a_file"), it returns
// the FilePath unmodified. If there is no file part ("just_a_dir/") it
// returns an empty FilePath ("").
// On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath FilePath::RemoveDirectoryName() const {
const char* const last_sep = strrchr(c_str(), kPathSeparator);
return last_sep ? FilePath(String(last_sep + 1)) : *this;
}
// RemoveFileName returns the directory path with the filename removed.
// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
// On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath FilePath::RemoveFileName() const {
const char* const last_sep = strrchr(c_str(), kPathSeparator);
return FilePath(last_sep ? String(c_str(), last_sep + 1 - c_str())
: String(kCurrentDirectoryString));
}
// Helper functions for naming files in a directory for xml output.
// Given directory = "dir", base_name = "test", number = 0,
// extension = "xml", returns "dir/test.xml". If number is greater
// than zero (e.g., 12), returns "dir/test_12.xml".
// On Windows platform, uses \ as the separator rather than /.
FilePath FilePath::MakeFileName(const FilePath& directory,
const FilePath& base_name,
int number,
const char* extension) {
const FilePath file_name(
(number == 0) ?
String::Format("%s.%s", base_name.c_str(), extension) :
String::Format("%s_%d.%s", base_name.c_str(), number, extension));
return ConcatPaths(directory, file_name);
}
// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
// On Windows, uses \ as the separator rather than /.
FilePath FilePath::ConcatPaths(const FilePath& directory,
const FilePath& relative_path) {
if (directory.IsEmpty())
return relative_path;
const FilePath dir(directory.RemoveTrailingPathSeparator());
return FilePath(String::Format("%s%c%s", dir.c_str(), kPathSeparator,
relative_path.c_str()));
}
// Returns true if pathname describes something findable in the file-system,
// either a file, directory, or whatever.
bool FilePath::FileOrDirectoryExists() const {
#if GTEST_OS_WINDOWS
#ifdef _WIN32_WCE
LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
const DWORD attributes = GetFileAttributes(unicode);
delete [] unicode;
return attributes != kInvalidFileAttributes;
#else
struct _stat file_stat = {};
return _stat(pathname_.c_str(), &file_stat) == 0;
#endif // _WIN32_WCE
#else
struct stat file_stat = {};
return stat(pathname_.c_str(), &file_stat) == 0;
#endif // GTEST_OS_WINDOWS
}
// Returns true if pathname describes a directory in the file-system
// that exists.
bool FilePath::DirectoryExists() const {
bool result = false;
#if GTEST_OS_WINDOWS
// Don't strip off trailing separator if path is a root directory on
// Windows (like "C:\\").
const FilePath& path(IsRootDirectory() ? *this :
RemoveTrailingPathSeparator());
#ifdef _WIN32_WCE
LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
const DWORD attributes = GetFileAttributes(unicode);
delete [] unicode;
if ((attributes != kInvalidFileAttributes) &&
(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
result = true;
}
#else
struct _stat file_stat = {};
result = _stat(path.c_str(), &file_stat) == 0 &&
(_S_IFDIR & file_stat.st_mode) != 0;
#endif // _WIN32_WCE
#else
struct stat file_stat = {};
result = stat(pathname_.c_str(), &file_stat) == 0 &&
S_ISDIR(file_stat.st_mode);
#endif // GTEST_OS_WINDOWS
return result;
}
// Returns true if pathname describes a root directory. (Windows has one
// root directory per disk drive.)
bool FilePath::IsRootDirectory() const {
#if GTEST_OS_WINDOWS
// TODO(wan@google.com): on Windows a network share like
// \\server\share can be a root directory, although it cannot be the
// current directory. Handle this properly.
return pathname_.GetLength() == 3 && IsAbsolutePath();
#else
return pathname_ == kPathSeparatorString;
#endif
}
// Returns true if pathname describes an absolute path.
bool FilePath::IsAbsolutePath() const {
const char* const name = pathname_.c_str();
#if GTEST_OS_WINDOWS
return pathname_.GetLength() >= 3 &&
((name[0] >= 'a' && name[0] <= 'z') ||
(name[0] >= 'A' && name[0] <= 'Z')) &&
name[1] == ':' &&
name[2] == kPathSeparator;
#else
return name[0] == kPathSeparator;
#endif
}
// Returns a pathname for a file that does not currently exist. The pathname
// will be directory/base_name.extension or
// directory/base_name_<number>.extension if directory/base_name.extension
// already exists. The number will be incremented until a pathname is found
// that does not already exist.
// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
// There could be a race condition if two or more processes are calling this
// function at the same time -- they could both pick the same filename.
FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
const FilePath& base_name,
const char* extension) {
FilePath full_pathname;
int number = 0;
do {
full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
} while (full_pathname.FileOrDirectoryExists());
return full_pathname;
}
// Returns true if FilePath ends with a path separator, which indicates that
// it is intended to represent a directory. Returns false otherwise.
// This does NOT check that a directory (or file) actually exists.
bool FilePath::IsDirectory() const {
return pathname_.EndsWith(kPathSeparatorString);
}
// Create directories so that path exists. Returns true if successful or if
// the directories already exist; returns false if unable to create directories
// for any reason.
bool FilePath::CreateDirectoriesRecursively() const {
if (!this->IsDirectory()) {
return false;
}
if (pathname_.GetLength() == 0 || this->DirectoryExists()) {
return true;
}
const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
return parent.CreateDirectoriesRecursively() && this->CreateFolder();
}
// Create the directory so that path exists. Returns true if successful or
// if the directory already exists; returns false if unable to create the
// directory for any reason, including if the parent directory does not
// exist. Not named "CreateDirectory" because that's a macro on Windows.
bool FilePath::CreateFolder() const {
#if GTEST_OS_WINDOWS
#ifdef _WIN32_WCE
FilePath removed_sep(this->RemoveTrailingPathSeparator());
LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
int result = CreateDirectory(unicode, NULL) ? 0 : -1;
delete [] unicode;
#else
int result = _mkdir(pathname_.c_str());
#endif // !WIN32_WCE
#else
int result = mkdir(pathname_.c_str(), 0777);
#endif // _WIN32
if (result == -1) {
return this->DirectoryExists(); // An error is OK if the directory exists.
}
return true; // No error.
}
// If input name has a trailing separator character, remove it and return the
// name, otherwise return the name string unmodified.
// On Windows platform, uses \ as the separator, other platforms use /.
FilePath FilePath::RemoveTrailingPathSeparator() const {
return pathname_.EndsWith(kPathSeparatorString)
? FilePath(String(pathname_.c_str(), pathname_.GetLength() - 1))
: *this;
}
// Normalize removes any redundant separators that might be in the pathname.
// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
// redundancies that might be in a pathname involving "." or "..".
void FilePath::Normalize() {
if (pathname_.c_str() == NULL) {
pathname_ = "";
return;
}
const char* src = pathname_.c_str();
char* const dest = new char[pathname_.GetLength() + 1];
char* dest_ptr = dest;
memset(dest_ptr, 0, pathname_.GetLength() + 1);
while (*src != '\0') {
*dest_ptr++ = *src;
if (*src != kPathSeparator)
src++;
else
while (*src == kPathSeparator)
src++;
}
*dest_ptr = '\0';
pathname_ = dest;
delete[] dest;
}
} // namespace internal
} // namespace testing
| SciAps/android-external-gtest | src/gtest-filepath.cc | C++ | bsd-3-clause | 12,929 |
using System;
namespace umbraco.interfaces
{
/// <summary>
/// The IDataType is a interface used for adding a new Data type to the umbraco backoffice.
/// It consists of IdataEditor which provides the Editing UI, the IDataPrevalue which provides prevalues and th their editing UI
/// And finally it contains IData which manages the actual data in the Data Type
/// </summary>
[Obsolete("IDataType is obsolete and is no longer used, it will be removed from the codebase in future versions")]
public interface IDataType
{
/// <summary>
/// Gets the id.
/// </summary>
/// <value>The id.</value>
Guid Id {get;}
/// <summary>
/// Gets the name of the data type.
/// </summary>
/// <value>The name of the data type.</value>
string DataTypeName{get;}
/// <summary>
/// Gets the data editor.
/// </summary>
/// <value>The data editor.</value>
IDataEditor DataEditor{get;}
/// <summary>
/// Gets the prevalue editor.
/// </summary>
/// <value>The prevalue editor.</value>
IDataPrevalue PrevalueEditor {get;}
/// <summary>
/// Gets the data.
/// </summary>
/// <value>The data.</value>
IData Data{get;}
/// <summary>
/// Gets or sets the data type definition id.
/// </summary>
/// <value>The data type definition id.</value>
int DataTypeDefinitionId {set; get;}
}
}
| Nicholas-Westby/Umbraco-CMS | src/umbraco.interfaces/IDataType.cs | C# | mit | 1,525 |
<?php
/**
* @file
* Definition of Drupal\system\Tests\Theme\ThemeEarlyInitializationTest.
*/
namespace Drupal\system\Tests\Theme;
use Drupal\simpletest\WebTestBase;
/**
* Tests that the theme system can be correctly initialized early in the page
* request.
*
* @group Theme
*/
class ThemeEarlyInitializationTest extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('theme_test');
/**
* Test that the theme system can generate output in a request listener.
*/
function testRequestListener() {
$this->drupalGet('theme-test/request-listener');
// Verify that themed output generated in the request listener appears.
$this->assertRaw('Themed output generated in a KernelEvents::REQUEST listener');
// Verify that the default theme's CSS still appears even though the theme
// system was initialized early.
$this->assertRaw('classy/css/layout.css');
}
}
| casivaagustin/drupalcon-mentoring | src/core/modules/system/src/Tests/Theme/ThemeEarlyInitializationTest.php | PHP | mit | 958 |
'use strict';
// TODO(matsko): use caching here to speed things up for detection
// TODO(matsko): add documentation
// by the time...
var $$AnimateJsProvider = ['$animateProvider', /** @this */ function($animateProvider) {
this.$get = ['$injector', '$$AnimateRunner', '$$jqLite',
function($injector, $$AnimateRunner, $$jqLite) {
var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
// $animateJs(element, 'enter');
return function(element, event, classes, options) {
var animationClosed = false;
// the `classes` argument is optional and if it is not used
// then the classes will be resolved from the element's className
// property as well as options.addClass/options.removeClass.
if (arguments.length === 3 && isObject(classes)) {
options = classes;
classes = null;
}
options = prepareAnimationOptions(options);
if (!classes) {
classes = element.attr('class') || '';
if (options.addClass) {
classes += ' ' + options.addClass;
}
if (options.removeClass) {
classes += ' ' + options.removeClass;
}
}
var classesToAdd = options.addClass;
var classesToRemove = options.removeClass;
// the lookupAnimations function returns a series of animation objects that are
// matched up with one or more of the CSS classes. These animation objects are
// defined via the module.animation factory function. If nothing is detected then
// we don't return anything which then makes $animation query the next driver.
var animations = lookupAnimations(classes);
var before, after;
if (animations.length) {
var afterFn, beforeFn;
if (event === 'leave') {
beforeFn = 'leave';
afterFn = 'afterLeave'; // TODO(matsko): get rid of this
} else {
beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1);
afterFn = event;
}
if (event !== 'enter' && event !== 'move') {
before = packageAnimations(element, event, options, animations, beforeFn);
}
after = packageAnimations(element, event, options, animations, afterFn);
}
// no matching animations
if (!before && !after) return;
function applyOptions() {
options.domOperation();
applyAnimationClasses(element, options);
}
function close() {
animationClosed = true;
applyOptions();
applyAnimationStyles(element, options);
}
var runner;
return {
$$willAnimate: true,
end: function() {
if (runner) {
runner.end();
} else {
close();
runner = new $$AnimateRunner();
runner.complete(true);
}
return runner;
},
start: function() {
if (runner) {
return runner;
}
runner = new $$AnimateRunner();
var closeActiveAnimations;
var chain = [];
if (before) {
chain.push(function(fn) {
closeActiveAnimations = before(fn);
});
}
if (chain.length) {
chain.push(function(fn) {
applyOptions();
fn(true);
});
} else {
applyOptions();
}
if (after) {
chain.push(function(fn) {
closeActiveAnimations = after(fn);
});
}
runner.setHost({
end: function() {
endAnimations();
},
cancel: function() {
endAnimations(true);
}
});
$$AnimateRunner.chain(chain, onComplete);
return runner;
function onComplete(success) {
close(success);
runner.complete(success);
}
function endAnimations(cancelled) {
if (!animationClosed) {
(closeActiveAnimations || noop)(cancelled);
onComplete(cancelled);
}
}
}
};
function executeAnimationFn(fn, element, event, options, onDone) {
var args;
switch (event) {
case 'animate':
args = [element, options.from, options.to, onDone];
break;
case 'setClass':
args = [element, classesToAdd, classesToRemove, onDone];
break;
case 'addClass':
args = [element, classesToAdd, onDone];
break;
case 'removeClass':
args = [element, classesToRemove, onDone];
break;
default:
args = [element, onDone];
break;
}
args.push(options);
var value = fn.apply(fn, args);
if (value) {
if (isFunction(value.start)) {
value = value.start();
}
if (value instanceof $$AnimateRunner) {
value.done(onDone);
} else if (isFunction(value)) {
// optional onEnd / onCancel callback
return value;
}
}
return noop;
}
function groupEventedAnimations(element, event, options, animations, fnName) {
var operations = [];
forEach(animations, function(ani) {
var animation = ani[fnName];
if (!animation) return;
// note that all of these animations will run in parallel
operations.push(function() {
var runner;
var endProgressCb;
var resolved = false;
var onAnimationComplete = function(rejected) {
if (!resolved) {
resolved = true;
(endProgressCb || noop)(rejected);
runner.complete(!rejected);
}
};
runner = new $$AnimateRunner({
end: function() {
onAnimationComplete();
},
cancel: function() {
onAnimationComplete(true);
}
});
endProgressCb = executeAnimationFn(animation, element, event, options, function(result) {
var cancelled = result === false;
onAnimationComplete(cancelled);
});
return runner;
});
});
return operations;
}
function packageAnimations(element, event, options, animations, fnName) {
var operations = groupEventedAnimations(element, event, options, animations, fnName);
if (operations.length === 0) {
var a, b;
if (fnName === 'beforeSetClass') {
a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass');
b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass');
} else if (fnName === 'setClass') {
a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass');
b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass');
}
if (a) {
operations = operations.concat(a);
}
if (b) {
operations = operations.concat(b);
}
}
if (operations.length === 0) return;
// TODO(matsko): add documentation
return function startAnimation(callback) {
var runners = [];
if (operations.length) {
forEach(operations, function(animateFn) {
runners.push(animateFn());
});
}
if (runners.length) {
$$AnimateRunner.all(runners, callback);
} else {
callback();
}
return function endFn(reject) {
forEach(runners, function(runner) {
if (reject) {
runner.cancel();
} else {
runner.end();
}
});
};
};
}
};
function lookupAnimations(classes) {
classes = isArray(classes) ? classes : classes.split(' ');
var matches = [], flagMap = {};
for (var i = 0; i < classes.length; i++) {
var klass = classes[i],
animationFactory = $animateProvider.$$registeredAnimations[klass];
if (animationFactory && !flagMap[klass]) {
matches.push($injector.get(animationFactory));
flagMap[klass] = true;
}
}
return matches;
}
}];
}];
| Aremyst/angular.js | src/ngAnimate/animateJs.js | JavaScript | mit | 8,632 |
/**
* Copyright (c) 2010-2016 by the respective copyright holders.
*
* 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.ecobee.messages;
import java.text.SimpleDateFormat;
import java.util.Properties;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.openhab.binding.ecobee.internal.EcobeeException;
/**
* Base class for all Ecobee API requests.
*
* @author John Cocula
* @since 1.7.0
*/
public abstract class AbstractRequest extends AbstractMessage implements Request {
protected static final String HTTP_GET = "GET";
protected static final String HTTP_POST = "POST";
protected static final String API_BASE_URL = "https://api.ecobee.com/";
protected static final Properties HTTP_HEADERS;
protected static int HTTP_REQUEST_TIMEOUT = 20000;
protected static final ObjectMapper JSON = new ObjectMapper();
static {
HTTP_HEADERS = new Properties();
HTTP_HEADERS.put("Content-Type", "application/json;charset=UTF-8");
HTTP_HEADERS.put("User-Agent", "ecobee-openhab-api/1.0");
// do not serialize null values
JSON.setSerializationInclusion(Inclusion.NON_NULL);
// *most* dates in the JSON are in this format
JSON.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
public static void setHttpRequestTimeout(int timeout) {
HTTP_REQUEST_TIMEOUT = timeout;
}
protected final RuntimeException newException(final String message, final Exception cause, final String url,
final String json) {
if (cause instanceof JsonMappingException) {
return new EcobeeException("Could not parse JSON from URL '" + url + "': " + json, cause);
}
return new EcobeeException(message, cause);
}
}
| theoweiss/openhab | bundles/binding/org.openhab.binding.ecobee/src/main/java/org/openhab/binding/ecobee/messages/AbstractRequest.java | Java | epl-1.0 | 2,111 |
// { dg-options "-Wno-deprecated" }
// { dg-do compile }
// Copyright (C) 2004, 2007, 2009 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/>.
// This file tests explicit instantiation of library containers
#include <hash_map>
template class __gnu_cxx::hash_map<int, char>;
| SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/libstdc++-v3/testsuite/backward/hash_map/requirements/explicit_instantiation.cc | C++ | gpl-2.0 | 963 |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.core.util;
import java.util.prefs.Preferences;
import org.apache.commons.lang.StringUtils;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.metastore.api.IMetaStore;
import org.w3c.dom.Node;
/**
* @author <a href="mailto:thomas.hoedl@aschauer-edv.at">Thomas Hoedl(asc042)</a>
*
*/
public class StringPluginProperty extends KeyValue<String> implements PluginProperty {
/**
* Serial version UID.
*/
private static final long serialVersionUID = -2990345692552430357L;
/**
* Constructor. Value is null.
*
* @param key
* key to set.
* @throws IllegalArgumentException
* if key is invalid.
*/
public StringPluginProperty( final String key ) throws IllegalArgumentException {
super( key, DEFAULT_STRING_VALUE );
}
/**
* {@inheritDoc}
*
* @see at.aschauer.commons.pentaho.plugin.PluginProperty#evaluate()
*/
public boolean evaluate() {
return StringUtils.isNotBlank( this.getValue() );
}
/**
* {@inheritDoc}
*
* @see at.aschauer.commons.pentaho.plugin.PluginProperty#appendXml(java.lang.StringBuilder)
*/
public void appendXml( final StringBuilder builder ) {
builder.append( XMLHandler.addTagValue( this.getKey(), this.getValue() ) );
}
/**
* {@inheritDoc}
*
* @see at.aschauer.commons.pentaho.plugin.PluginProperty#loadXml(org.w3c.dom.Node)
*/
public void loadXml( final Node node ) {
final String value = XMLHandler.getTagValue( node, this.getKey() );
this.setValue( value );
}
/**
* {@inheritDoc}
*
* @see at.aschauer.commons.pentaho.plugin.PluginProperty#readFromRepositoryStep(org.pentaho.di.repository.Repository,
* long)
*/
public void readFromRepositoryStep( final Repository repository, final IMetaStore metaStore,
final ObjectId stepId ) throws KettleException {
final String value = repository.getStepAttributeString( stepId, this.getKey() );
this.setValue( value );
}
/**
* {@inheritDoc}
*
* @see at.aschauer.commons.pentaho.plugin.PluginProperty#saveToPreferences(java.util.prefs.Preferences)
*/
public void saveToPreferences( final Preferences node ) {
node.put( this.getKey(), this.getValue() );
}
/**
* {@inheritDoc}
*
* @see at.aschauer.commons.pentaho.plugin.PluginProperty#readFromPreferences(java.util.prefs.Preferences)
*/
public void readFromPreferences( final Preferences node ) {
this.setValue( node.get( this.getKey(), this.getValue() ) );
}
/**
* {@inheritDoc}
*
* @see at.aschauer.commons.pentaho.plugin.PluginProperty#saveToRepositoryStep(org.pentaho.di.repository.Repository,
* long, long)
*/
public void saveToRepositoryStep( final Repository repository, final IMetaStore metaStore,
final ObjectId transformationId, final ObjectId stepId ) throws KettleException {
repository.saveStepAttribute( transformationId, stepId, this.getKey(), this.getValue() );
}
}
| ivanpogodin/pentaho-kettle | engine/src/org/pentaho/di/core/util/StringPluginProperty.java | Java | apache-2.0 | 4,028 |
// Copyright (c) 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 "tools/gn/operators.h"
#include "base/strings/string_number_conversions.h"
#include "tools/gn/err.h"
#include "tools/gn/parse_tree.h"
#include "tools/gn/scope.h"
#include "tools/gn/token.h"
#include "tools/gn/value.h"
namespace {
const char kSourcesName[] = "sources";
// Applies the sources assignment filter from the given scope to each element
// of source (can be a list or a string), appending it to dest if it doesn't
// match.
void AppendFilteredSourcesToValue(const Scope* scope,
const Value& source,
Value* dest) {
const PatternList* filter = scope->GetSourcesAssignmentFilter();
if (source.type() == Value::STRING) {
if (!filter || filter->is_empty() ||
!filter->MatchesValue(source))
dest->list_value().push_back(source);
return;
}
if (source.type() != Value::LIST) {
// Any non-list and non-string being added to a list can just get appended,
// we're not going to filter it.
dest->list_value().push_back(source);
return;
}
const std::vector<Value>& source_list = source.list_value();
if (!filter || filter->is_empty()) {
// No filter, append everything.
for (size_t i = 0; i < source_list.size(); i++)
dest->list_value().push_back(source_list[i]);
return;
}
// Note: don't reserve() the dest vector here since that actually hurts
// the allocation pattern when the build script is doing multiple small
// additions.
for (size_t i = 0; i < source_list.size(); i++) {
if (!filter->MatchesValue(source_list[i]))
dest->list_value().push_back(source_list[i]);
}
}
Value GetValueOrFillError(const BinaryOpNode* op_node,
const ParseNode* node,
const char* name,
Scope* scope,
Err* err) {
Value value = node->Execute(scope, err);
if (err->has_error())
return Value();
if (value.type() == Value::NONE) {
*err = Err(op_node->op(),
"Operator requires a value.",
"This thing on the " + std::string(name) +
" does not evaluate to a value.");
err->AppendRange(node->GetRange());
return Value();
}
return value;
}
void RemoveMatchesFromList(const BinaryOpNode* op_node,
Value* list,
const Value& to_remove,
Err* err) {
std::vector<Value>& v = list->list_value();
switch (to_remove.type()) {
case Value::BOOLEAN:
case Value::INTEGER: // Filter out the individual int/string.
case Value::STRING: {
bool found_match = false;
for (size_t i = 0; i < v.size(); /* nothing */) {
if (v[i] == to_remove) {
found_match = true;
v.erase(v.begin() + i);
} else {
i++;
}
}
if (!found_match) {
*err = Err(to_remove.origin()->GetRange(), "Item not found",
"You were trying to remove " + to_remove.ToString(true) +
"\nfrom the list but it wasn't there.");
}
break;
}
case Value::LIST: // Filter out each individual thing.
for (size_t i = 0; i < to_remove.list_value().size(); i++) {
// TODO(brettw) if the nested item is a list, we may want to search
// for the literal list rather than remote the items in it.
RemoveMatchesFromList(op_node, list, to_remove.list_value()[i], err);
if (err->has_error())
return;
}
break;
default:
break;
}
}
// Assignment -----------------------------------------------------------------
// We return a null value from this rather than the result of doing the append.
// See ValuePlusEquals for rationale.
Value ExecuteEquals(Scope* scope,
const BinaryOpNode* op_node,
const Token& left,
const Value& right,
Err* err) {
const Value* old_value = scope->GetValue(left.value(), false);
if (old_value) {
// Throw an error when overwriting a nonempty list with another nonempty
// list item. This is to detect the case where you write
// defines = ["FOO"]
// and you overwrote inherited ones, when instead you mean to append:
// defines += ["FOO"]
if (old_value->type() == Value::LIST &&
!old_value->list_value().empty() &&
right.type() == Value::LIST &&
!right.list_value().empty()) {
*err = Err(op_node->left()->GetRange(), "Replacing nonempty list.",
std::string("This overwrites a previously-defined nonempty list ") +
"(length " +
base::IntToString(static_cast<int>(old_value->list_value().size()))
+ ").");
err->AppendSubErr(Err(*old_value, "for previous definition",
"with another one (length " +
base::IntToString(static_cast<int>(right.list_value().size())) +
"). Did you mean " +
"\"+=\" to append instead? If you\nreally want to do this, do\n " +
left.value().as_string() + " = []\nbefore reassigning."));
return Value();
}
}
if (err->has_error())
return Value();
if (right.type() == Value::LIST && left.value() == kSourcesName) {
// Assigning to sources, filter the list. Here we do the filtering and
// copying in one step to save an extra list copy (the lists may be
// long).
Value* set_value = scope->SetValue(left.value(),
Value(op_node, Value::LIST), op_node);
set_value->list_value().reserve(right.list_value().size());
AppendFilteredSourcesToValue(scope, right, set_value);
} else {
// Normal value set, just copy it.
scope->SetValue(left.value(), right, op_node->right());
}
return Value();
}
// allow_type_conversion indicates if we're allowed to change the type of the
// left value. This is set to true when doing +, and false when doing +=.
//
// Note that we return Value() from here, which is different than C++. This
// means you can't do clever things like foo = [ bar += baz ] to simultaneously
// append to and use a value. This is basically never needed in out build
// scripts and is just as likely an error as the intended behavior, and it also
// involves a copy of the value when it's returned. Many times we're appending
// to large lists, and copying the value to discard it for the next statement
// is very wasteful.
void ValuePlusEquals(const Scope* scope,
const BinaryOpNode* op_node,
const Token& left_token,
Value* left,
const Value& right,
bool allow_type_conversion,
Err* err) {
switch (left->type()) {
// Left-hand-side int.
case Value::INTEGER:
switch (right.type()) {
case Value::INTEGER: // int + int -> addition.
left->int_value() += right.int_value();
return;
case Value::STRING: // int + string -> string concat.
if (allow_type_conversion) {
*left = Value(op_node,
base::Int64ToString(left->int_value()) + right.string_value());
return;
}
break;
default:
break;
}
break;
// Left-hand-side string.
case Value::STRING:
switch (right.type()) {
case Value::INTEGER: // string + int -> string concat.
left->string_value().append(base::Int64ToString(right.int_value()));
return;
case Value::STRING: // string + string -> string contat.
left->string_value().append(right.string_value());
return;
default:
break;
}
break;
// Left-hand-side list.
case Value::LIST:
switch (right.type()) {
case Value::LIST: // list + list -> list concat.
if (left_token.value() == kSourcesName) {
// Filter additions through the assignment filter.
AppendFilteredSourcesToValue(scope, right, left);
} else {
// Normal list concat.
for (size_t i = 0; i < right.list_value().size(); i++)
left->list_value().push_back(right.list_value()[i]);
}
return;
default:
*err = Err(op_node->op(), "Incompatible types to add.",
"To append a single item to a list do \"foo += [ bar ]\".");
return;
}
default:
break;
}
*err = Err(op_node->op(), "Incompatible types to add.",
std::string("I see a ") + Value::DescribeType(left->type()) + " and a " +
Value::DescribeType(right.type()) + ".");
}
Value ExecutePlusEquals(Scope* scope,
const BinaryOpNode* op_node,
const Token& left,
const Value& right,
Err* err) {
// We modify in-place rather than doing read-modify-write to avoid
// copying large lists.
Value* left_value =
scope->GetValueForcedToCurrentScope(left.value(), op_node);
if (!left_value) {
*err = Err(left, "Undefined variable for +=.",
"I don't have something with this name in scope now.");
return Value();
}
ValuePlusEquals(scope, op_node, left, left_value, right, false, err);
left_value->set_origin(op_node);
scope->MarkUnused(left.value());
return Value();
}
// We return a null value from this rather than the result of doing the append.
// See ValuePlusEquals for rationale.
void ValueMinusEquals(const BinaryOpNode* op_node,
Value* left,
const Value& right,
bool allow_type_conversion,
Err* err) {
switch (left->type()) {
// Left-hand-side int.
case Value::INTEGER:
switch (right.type()) {
case Value::INTEGER: // int - int -> subtraction.
left->int_value() -= right.int_value();
return;
default:
break;
}
break;
// Left-hand-side string.
case Value::STRING:
break; // All are errors.
// Left-hand-side list.
case Value::LIST:
if (right.type() != Value::LIST) {
*err = Err(op_node->op(), "Incompatible types to subtract.",
"To remove a single item from a list do \"foo -= [ bar ]\".");
} else {
RemoveMatchesFromList(op_node, left, right, err);
}
return;
default:
break;
}
*err = Err(op_node->op(), "Incompatible types to subtract.",
std::string("I see a ") + Value::DescribeType(left->type()) + " and a " +
Value::DescribeType(right.type()) + ".");
}
Value ExecuteMinusEquals(Scope* scope,
const BinaryOpNode* op_node,
const Token& left,
const Value& right,
Err* err) {
Value* left_value =
scope->GetValueForcedToCurrentScope(left.value(), op_node);
if (!left_value) {
*err = Err(left, "Undefined variable for -=.",
"I don't have something with this name in scope now.");
return Value();
}
ValueMinusEquals(op_node, left_value, right, false, err);
left_value->set_origin(op_node);
scope->MarkUnused(left.value());
return Value();
}
// Plus/Minus -----------------------------------------------------------------
Value ExecutePlus(Scope* scope,
const BinaryOpNode* op_node,
const Value& left,
const Value& right,
Err* err) {
Value ret = left;
ValuePlusEquals(scope, op_node, Token(), &ret, right, true, err);
ret.set_origin(op_node);
return ret;
}
Value ExecuteMinus(Scope* scope,
const BinaryOpNode* op_node,
const Value& left,
const Value& right,
Err* err) {
Value ret = left;
ValueMinusEquals(op_node, &ret, right, true, err);
ret.set_origin(op_node);
return ret;
}
// Comparison -----------------------------------------------------------------
Value ExecuteEqualsEquals(Scope* scope,
const BinaryOpNode* op_node,
const Value& left,
const Value& right,
Err* err) {
if (left == right)
return Value(op_node, true);
return Value(op_node, false);
}
Value ExecuteNotEquals(Scope* scope,
const BinaryOpNode* op_node,
const Value& left,
const Value& right,
Err* err) {
// Evaluate in terms of ==.
Value result = ExecuteEqualsEquals(scope, op_node, left, right, err);
result.boolean_value() = !result.boolean_value();
return result;
}
Value FillNeedsTwoIntegersError(const BinaryOpNode* op_node,
const Value& left,
const Value& right,
Err* err) {
*err = Err(op_node, "Comparison requires two integers.",
"This operator can only compare two integers.");
err->AppendRange(left.origin()->GetRange());
err->AppendRange(right.origin()->GetRange());
return Value();
}
Value ExecuteLessEquals(Scope* scope,
const BinaryOpNode* op_node,
const Value& left,
const Value& right,
Err* err) {
if (left.type() != Value::INTEGER || right.type() != Value::INTEGER)
return FillNeedsTwoIntegersError(op_node, left, right, err);
return Value(op_node, left.int_value() <= right.int_value());
}
Value ExecuteGreaterEquals(Scope* scope,
const BinaryOpNode* op_node,
const Value& left,
const Value& right,
Err* err) {
if (left.type() != Value::INTEGER || right.type() != Value::INTEGER)
return FillNeedsTwoIntegersError(op_node, left, right, err);
return Value(op_node, left.int_value() >= right.int_value());
}
Value ExecuteGreater(Scope* scope,
const BinaryOpNode* op_node,
const Value& left,
const Value& right,
Err* err) {
if (left.type() != Value::INTEGER || right.type() != Value::INTEGER)
return FillNeedsTwoIntegersError(op_node, left, right, err);
return Value(op_node, left.int_value() > right.int_value());
}
Value ExecuteLess(Scope* scope,
const BinaryOpNode* op_node,
const Value& left,
const Value& right,
Err* err) {
if (left.type() != Value::INTEGER || right.type() != Value::INTEGER)
return FillNeedsTwoIntegersError(op_node, left, right, err);
return Value(op_node, left.int_value() < right.int_value());
}
// Binary ----------------------------------------------------------------------
Value ExecuteOr(Scope* scope,
const BinaryOpNode* op_node,
const ParseNode* left_node,
const ParseNode* right_node,
Err* err) {
Value left = GetValueOrFillError(op_node, left_node, "left", scope, err);
if (err->has_error())
return Value();
if (left.type() != Value::BOOLEAN) {
*err = Err(op_node->left(), "Left side of || operator is not a boolean.",
"Type is \"" + std::string(Value::DescribeType(left.type())) +
"\" instead.");
return Value();
}
if (left.boolean_value())
return Value(op_node, left.boolean_value());
Value right = GetValueOrFillError(op_node, right_node, "right", scope, err);
if (err->has_error())
return Value();
if (right.type() != Value::BOOLEAN) {
*err = Err(op_node->right(), "Right side of || operator is not a boolean.",
"Type is \"" + std::string(Value::DescribeType(right.type())) +
"\" instead.");
return Value();
}
return Value(op_node, left.boolean_value() || right.boolean_value());
}
Value ExecuteAnd(Scope* scope,
const BinaryOpNode* op_node,
const ParseNode* left_node,
const ParseNode* right_node,
Err* err) {
Value left = GetValueOrFillError(op_node, left_node, "left", scope, err);
if (err->has_error())
return Value();
if (left.type() != Value::BOOLEAN) {
*err = Err(op_node->left(), "Left side of && operator is not a boolean.",
"Type is \"" + std::string(Value::DescribeType(left.type())) +
"\" instead.");
return Value();
}
if (!left.boolean_value())
return Value(op_node, left.boolean_value());
Value right = GetValueOrFillError(op_node, right_node, "right", scope, err);
if (err->has_error())
return Value();
if (right.type() != Value::BOOLEAN) {
*err = Err(op_node->right(), "Right side of && operator is not a boolean.",
"Type is \"" + std::string(Value::DescribeType(right.type())) +
"\" instead.");
return Value();
}
return Value(op_node, left.boolean_value() && right.boolean_value());
}
} // namespace
// ----------------------------------------------------------------------------
bool IsUnaryOperator(const Token& token) {
return token.type() == Token::BANG;
}
bool IsBinaryOperator(const Token& token) {
return token.type() == Token::EQUAL ||
token.type() == Token::PLUS ||
token.type() == Token::MINUS ||
token.type() == Token::PLUS_EQUALS ||
token.type() == Token::MINUS_EQUALS ||
token.type() == Token::EQUAL_EQUAL ||
token.type() == Token::NOT_EQUAL ||
token.type() == Token::LESS_EQUAL ||
token.type() == Token::GREATER_EQUAL ||
token.type() == Token::LESS_THAN ||
token.type() == Token::GREATER_THAN ||
token.type() == Token::BOOLEAN_AND ||
token.type() == Token::BOOLEAN_OR;
}
bool IsFunctionCallArgBeginScoper(const Token& token) {
return token.type() == Token::LEFT_PAREN;
}
bool IsFunctionCallArgEndScoper(const Token& token) {
return token.type() == Token::RIGHT_PAREN;
}
bool IsScopeBeginScoper(const Token& token) {
return token.type() == Token::LEFT_BRACE;
}
bool IsScopeEndScoper(const Token& token) {
return token.type() == Token::RIGHT_BRACE;
}
Value ExecuteUnaryOperator(Scope* scope,
const UnaryOpNode* op_node,
const Value& expr,
Err* err) {
DCHECK(op_node->op().type() == Token::BANG);
if (expr.type() != Value::BOOLEAN) {
*err = Err(op_node, "Operand of ! operator is not a boolean.",
"Type is \"" + std::string(Value::DescribeType(expr.type())) +
"\" instead.");
return Value();
}
// TODO(scottmg): Why no unary minus?
return Value(op_node, !expr.boolean_value());
}
Value ExecuteBinaryOperator(Scope* scope,
const BinaryOpNode* op_node,
const ParseNode* left,
const ParseNode* right,
Err* err) {
const Token& op = op_node->op();
// First handle the ones that take an lvalue.
if (op.type() == Token::EQUAL ||
op.type() == Token::PLUS_EQUALS ||
op.type() == Token::MINUS_EQUALS) {
const IdentifierNode* left_id = left->AsIdentifier();
if (!left_id) {
*err = Err(op, "Operator requires a lvalue.",
"This thing on the left is not an identifier.");
err->AppendRange(left->GetRange());
return Value();
}
const Token& dest = left_id->value();
Value right_value = right->Execute(scope, err);
if (err->has_error())
return Value();
if (right_value.type() == Value::NONE) {
*err = Err(op, "Operator requires a rvalue.",
"This thing on the right does not evaluate to a value.");
err->AppendRange(right->GetRange());
return Value();
}
if (op.type() == Token::EQUAL)
return ExecuteEquals(scope, op_node, dest, right_value, err);
if (op.type() == Token::PLUS_EQUALS)
return ExecutePlusEquals(scope, op_node, dest, right_value, err);
if (op.type() == Token::MINUS_EQUALS)
return ExecuteMinusEquals(scope, op_node, dest, right_value, err);
NOTREACHED();
return Value();
}
// ||, &&. Passed the node instead of the value so that they can avoid
// evaluating the RHS on early-out.
if (op.type() == Token::BOOLEAN_OR)
return ExecuteOr(scope, op_node, left, right, err);
if (op.type() == Token::BOOLEAN_AND)
return ExecuteAnd(scope, op_node, left, right, err);
Value left_value = GetValueOrFillError(op_node, left, "left", scope, err);
if (err->has_error())
return Value();
Value right_value = GetValueOrFillError(op_node, right, "right", scope, err);
if (err->has_error())
return Value();
// +, -.
if (op.type() == Token::MINUS)
return ExecuteMinus(scope, op_node, left_value, right_value, err);
if (op.type() == Token::PLUS)
return ExecutePlus(scope, op_node, left_value, right_value, err);
// Comparisons.
if (op.type() == Token::EQUAL_EQUAL)
return ExecuteEqualsEquals(scope, op_node, left_value, right_value, err);
if (op.type() == Token::NOT_EQUAL)
return ExecuteNotEquals(scope, op_node, left_value, right_value, err);
if (op.type() == Token::GREATER_EQUAL)
return ExecuteGreaterEquals(scope, op_node, left_value, right_value, err);
if (op.type() == Token::LESS_EQUAL)
return ExecuteLessEquals(scope, op_node, left_value, right_value, err);
if (op.type() == Token::GREATER_THAN)
return ExecuteGreater(scope, op_node, left_value, right_value, err);
if (op.type() == Token::LESS_THAN)
return ExecuteLess(scope, op_node, left_value, right_value, err);
return Value();
}
| GladeRom/android_external_chromium_org | tools/gn/operators.cc | C++ | bsd-3-clause | 21,965 |
# Copyright 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.
import re
from telemetry.core import web_contents
def UrlToExtensionId(url):
return re.match(r"(chrome-extension://)([^/]+)", url).group(2)
class ExtensionPage(web_contents.WebContents):
"""Represents an extension page in the browser"""
def __init__(self, inspector_backend, backend_list):
super(ExtensionPage, self).__init__(inspector_backend, backend_list)
self.url = inspector_backend.url
self.extension_id = UrlToExtensionId(self.url)
def Reload(self):
"""Reloading an extension page is used as a workaround for an extension
binding bug for old versions of Chrome (crbug.com/263162). After Navigate
returns, we are guaranteed that the inspected page is in the correct state.
"""
self._inspector_backend.Navigate(self.url, None, 10)
| 7kbird/chrome | tools/telemetry/telemetry/core/extension_page.py | Python | bsd-3-clause | 946 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Tests\Constraints;
use Symfony\Component\Intl\Util\IntlTestHelper;
use Symfony\Component\Validator\Constraints\Currency;
use Symfony\Component\Validator\Constraints\CurrencyValidator;
use Symfony\Component\Validator\Validation;
class CurrencyValidatorTest extends AbstractConstraintValidatorTest
{
protected function setUp()
{
IntlTestHelper::requireFullIntl($this);
parent::setUp();
}
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new CurrencyValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Currency());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Currency());
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new Currency());
}
/**
* @dataProvider getValidCurrencies
*/
public function testValidCurrencies($currency)
{
$this->validator->validate($currency, new Currency());
$this->assertNoViolation();
}
/**
* @dataProvider getValidCurrencies
**/
public function testValidCurrenciesWithCountrySpecificLocale($currency)
{
\Locale::setDefault('en_GB');
$this->validator->validate($currency, new Currency());
$this->assertNoViolation();
}
public function getValidCurrencies()
{
return array(
array('EUR'),
array('USD'),
array('SIT'),
array('AUD'),
array('CAD'),
);
}
/**
* @dataProvider getInvalidCurrencies
*/
public function testInvalidCurrencies($currency)
{
$constraint = new Currency(array(
'message' => 'myMessage'
));
$this->validator->validate($currency, $constraint);
$this->assertViolation('myMessage', array(
'{{ value }}' => '"'.$currency.'"',
));
}
public function getInvalidCurrencies()
{
return array(
array('EN'),
array('foobar'),
);
}
}
| TonnyORG/ScioTest1 | vendor/symfony/validator/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php | PHP | mit | 2,676 |
# Copyright 2011 Red Hat, Inc.
# Copyright 2003 Brent Fox <bfox@redhat.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; 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., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# Authors:
# Miroslav Suchy <msuchy@redhat.com>
import sys
sys.path.append("/usr/share/rhn")
from up2date_client import rhnreg, rhnregGui, rhnserver
import gtk
import gettext
_ = lambda x: gettext.ldgettext("rhn-client-tools", x)
gtk.glade.bindtextdomain("rhn-client-tools")
from firstboot.module import Module
from firstboot.constants import RESULT_SUCCESS, RESULT_FAILURE, RESULT_JUMP
class moduleClass(Module):
def __init__(self):
Module.__init__(self)
self.priority = 108.6
self.sidebarTitle = _("Select operating system release")
self.title = _("Select operating system release")
self.chooseChannel = FirstbootChooseChannelPage()
def needsNetwork(self):
return True
def apply(self, interface, testing=False):
if testing:
return RESULT_SUCCESS
self.chooseChannel.chooseChannelPageApply()
return RESULT_SUCCESS
def createScreen(self):
self.vbox = gtk.VBox(spacing=5)
self.vbox.pack_start(self.chooseChannel.chooseChannelPageVbox(), True, True)
def initializeUI(self):
# populate capability - needef for EUSsupported
s = rhnserver.RhnServer()
s.capabilities.validate()
# this populate zstream channels as side effect
self.chooseChannel.chooseChannelShouldBeShown()
self.chooseChannel.chooseChannelPagePrepare()
def shouldAppear(self):
return not rhnreg.registered()
class FirstbootChooseChannelPage(rhnregGui.ChooseChannelPage):
pass
| lhellebr/spacewalk | client/rhel/rhn-client-tools/src/firstboot-legacy-rhel5/rhn_choose_channel.py | Python | gpl-2.0 | 2,255 |
"""
=======================
MNIST dataset benchmark
=======================
Benchmark on the MNIST dataset. The dataset comprises 70,000 samples
and 784 features. Here, we consider the task of predicting
10 classes - digits from 0 to 9 from their raw images. By contrast to the
covertype dataset, the feature space is homogenous.
Example of output :
[..]
Classification performance:
===========================
Classifier train-time test-time error-rate
------------------------------------------------------------
MLP_adam 53.46s 0.11s 0.0224
Nystroem-SVM 112.97s 0.92s 0.0228
MultilayerPerceptron 24.33s 0.14s 0.0287
ExtraTrees 42.99s 0.57s 0.0294
RandomForest 42.70s 0.49s 0.0318
SampledRBF-SVM 135.81s 0.56s 0.0486
LinearRegression-SAG 16.67s 0.06s 0.0824
CART 20.69s 0.02s 0.1219
dummy 0.00s 0.01s 0.8973
"""
from __future__ import division, print_function
# Author: Issam H. Laradji
# Arnaud Joly <arnaud.v.joly@gmail.com>
# License: BSD 3 clause
import os
from time import time
import argparse
import numpy as np
from sklearn.datasets import fetch_mldata
from sklearn.datasets import get_data_home
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.dummy import DummyClassifier
from sklearn.externals.joblib import Memory
from sklearn.kernel_approximation import Nystroem
from sklearn.kernel_approximation import RBFSampler
from sklearn.metrics import zero_one_loss
from sklearn.pipeline import make_pipeline
from sklearn.svm import LinearSVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.utils import check_array
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
# Memoize the data extraction and memory map the resulting
# train / test splits in readonly mode
memory = Memory(os.path.join(get_data_home(), 'mnist_benchmark_data'),
mmap_mode='r')
@memory.cache
def load_data(dtype=np.float32, order='F'):
"""Load the data, then cache and memmap the train/test split"""
######################################################################
# Load dataset
print("Loading dataset...")
data = fetch_mldata('MNIST original')
X = check_array(data['data'], dtype=dtype, order=order)
y = data["target"]
# Normalize features
X = X / 255
# Create train-test split (as [Joachims, 2006])
print("Creating train-test split...")
n_train = 60000
X_train = X[:n_train]
y_train = y[:n_train]
X_test = X[n_train:]
y_test = y[n_train:]
return X_train, X_test, y_train, y_test
ESTIMATORS = {
"dummy": DummyClassifier(),
'CART': DecisionTreeClassifier(),
'ExtraTrees': ExtraTreesClassifier(n_estimators=100),
'RandomForest': RandomForestClassifier(n_estimators=100),
'Nystroem-SVM': make_pipeline(
Nystroem(gamma=0.015, n_components=1000), LinearSVC(C=100)),
'SampledRBF-SVM': make_pipeline(
RBFSampler(gamma=0.015, n_components=1000), LinearSVC(C=100)),
'LogisticRegression-SAG': LogisticRegression(solver='sag', tol=1e-1,
C=1e4),
'LogisticRegression-SAGA': LogisticRegression(solver='saga', tol=1e-1,
C=1e4),
'MultilayerPerceptron': MLPClassifier(
hidden_layer_sizes=(100, 100), max_iter=400, alpha=1e-4,
solver='sgd', learning_rate_init=0.2, momentum=0.9, verbose=1,
tol=1e-4, random_state=1),
'MLP-adam': MLPClassifier(
hidden_layer_sizes=(100, 100), max_iter=400, alpha=1e-4,
solver='adam', learning_rate_init=0.001, verbose=1,
tol=1e-4, random_state=1)
}
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--classifiers', nargs="+",
choices=ESTIMATORS, type=str,
default=['ExtraTrees', 'Nystroem-SVM'],
help="list of classifiers to benchmark.")
parser.add_argument('--n-jobs', nargs="?", default=1, type=int,
help="Number of concurrently running workers for "
"models that support parallelism.")
parser.add_argument('--order', nargs="?", default="C", type=str,
choices=["F", "C"],
help="Allow to choose between fortran and C ordered "
"data")
parser.add_argument('--random-seed', nargs="?", default=0, type=int,
help="Common seed used by random number generator.")
args = vars(parser.parse_args())
print(__doc__)
X_train, X_test, y_train, y_test = load_data(order=args["order"])
print("")
print("Dataset statistics:")
print("===================")
print("%s %d" % ("number of features:".ljust(25), X_train.shape[1]))
print("%s %d" % ("number of classes:".ljust(25), np.unique(y_train).size))
print("%s %s" % ("data type:".ljust(25), X_train.dtype))
print("%s %d (size=%dMB)" % ("number of train samples:".ljust(25),
X_train.shape[0], int(X_train.nbytes / 1e6)))
print("%s %d (size=%dMB)" % ("number of test samples:".ljust(25),
X_test.shape[0], int(X_test.nbytes / 1e6)))
print()
print("Training Classifiers")
print("====================")
error, train_time, test_time = {}, {}, {}
for name in sorted(args["classifiers"]):
print("Training %s ... " % name, end="")
estimator = ESTIMATORS[name]
estimator_params = estimator.get_params()
estimator.set_params(**{p: args["random_seed"]
for p in estimator_params
if p.endswith("random_state")})
if "n_jobs" in estimator_params:
estimator.set_params(n_jobs=args["n_jobs"])
time_start = time()
estimator.fit(X_train, y_train)
train_time[name] = time() - time_start
time_start = time()
y_pred = estimator.predict(X_test)
test_time[name] = time() - time_start
error[name] = zero_one_loss(y_test, y_pred)
print("done")
print()
print("Classification performance:")
print("===========================")
print("{0: <24} {1: >10} {2: >11} {3: >12}"
"".format("Classifier ", "train-time", "test-time", "error-rate"))
print("-" * 60)
for name in sorted(args["classifiers"], key=error.get):
print("{0: <23} {1: >10.2f}s {2: >10.2f}s {3: >12.4f}"
"".format(name, train_time[name], test_time[name], error[name]))
print()
| Titan-C/scikit-learn | benchmarks/bench_mnist.py | Python | bsd-3-clause | 6,977 |
require 'rails_helper'
describe Authentication, :type => :model do
let(:authentication) {FactoryGirl.build(:authentication)}
skip "add some examples to (or delete) #{__FILE__}"
# todo: check loading of oath_data and default_scope
end
| usmanajmal3/Testing | spec/models/authentication_spec.rb | Ruby | mit | 241 |
package com.intellij.structuralsearch.plugin;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.structuralsearch.plugin.ui.Configuration;
import com.intellij.structuralsearch.plugin.ui.SearchContext;
import com.intellij.structuralsearch.plugin.ui.SearchDialog;
public class StructuralSearchAction extends AnAction {
/** Handles IDEA action event
* @param event the event of action
*/
public void actionPerformed(AnActionEvent event) {
triggerAction(null, SearchContext.buildFromDataContext(event.getDataContext()));
}
public static void triggerAction(Configuration config, SearchContext searchContext) {
final Project project = searchContext.getProject();
if (project == null) {
return;
}
PsiDocumentManager.getInstance(project).commitAllDocuments();
//StructuralSearchPlugin.getInstance(searchContext.getProject());
final SearchDialog searchDialog = new SearchDialog(searchContext);
if (config!=null) {
searchDialog.setUseLastConfiguration(true);
searchDialog.setValuesFromConfig(config);
}
searchDialog.show();
}
/** Updates the state of the action
* @param event the action event
*/
public void update(AnActionEvent event) {
final Presentation presentation = event.getPresentation();
final DataContext context = event.getDataContext();
final Project project = CommonDataKeys.PROJECT.getData(context);
final StructuralSearchPlugin plugin = project==null ? null:StructuralSearchPlugin.getInstance( project );
if (plugin == null || plugin.isSearchInProgress() || plugin.isDialogVisible()) {
presentation.setEnabled( false );
} else {
presentation.setEnabled( true );
}
super.update(event);
}
}
| caot/intellij-community | platform/structuralsearch/source/com/intellij/structuralsearch/plugin/StructuralSearchAction.java | Java | apache-2.0 | 1,839 |
<?php
/**
* @package Joomla.UnitTest
* @subpackage Linkedin
*
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
require_once JPATH_PLATFORM . '/joomla/linkedin/people.php';
/**
* Test class for JLinkedinPeople.
*
* @package Joomla.UnitTest
* @subpackage Linkedin
* @since 13.1
*/
class JLinkedinPeopleTest extends TestCase
{
/**
* @var JRegistry Options for the Linkedin object.
* @since 13.1
*/
protected $options;
/**
* @var JHttp Mock http object.
* @since 13.1
*/
protected $client;
/**
* @var JInput The input object to use in retrieving GET/POST data.
* @since 13.1
*/
protected $input;
/**
* @var JLinkedinPeople Object under test.
* @since 13.1
*/
protected $object;
/**
* @var JLinkedinOAuth Authentication object for the Twitter object.
* @since 13.1
*/
protected $oauth;
/**
* @var string Sample JSON string.
* @since 13.1
*/
protected $sampleString = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
/**
* @var string Sample JSON string used to access out of network profiles.
* @since 13.1
*/
protected $outString = '{"headers": { "_total": 1, "values": [{ "name": "x-li-auth-token",
"value": "NAME_SEARCH:-Ogn" }] }, "url": "/v1/people/oAFz-3CZyv"}';
/**
* @var string Sample JSON error message.
* @since 13.1
*/
protected $errorString = '{"errorCode":401, "message": "Generic error"}';
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*
* @return void
*/
protected function setUp()
{
parent::setUp();
$_SERVER['HTTP_HOST'] = 'example.com';
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0';
$_SERVER['REQUEST_URI'] = '/index.php';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$key = "app_key";
$secret = "app_secret";
$my_url = "http://127.0.0.1/gsoc/joomla-platform/linkedin_test.php";
$this->options = new JRegistry;
$this->input = new JInput;
$this->client = $this->getMock('JHttp', array('get', 'post', 'delete', 'put'));
$this->oauth = new JLinkedinOauth($this->options, $this->client, $this->input);
$this->oauth->setToken(array('key' => $key, 'secret' => $secret));
$this->object = new JLinkedinPeople($this->options, $this->client, $this->oauth);
$this->options->set('consumer_key', $key);
$this->options->set('consumer_secret', $secret);
$this->options->set('callback', $my_url);
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*
* @return void
*/
protected function tearDown()
{
}
/**
* Provides test data for request format detection.
*
* @return array
*
* @since 13.1
*/
public function seedIdUrl()
{
// Member ID or url
return array(
array('lcnIwDU0S6', null),
array(null, 'http://www.linkedin.com/in/dianaprajescu'),
array(null, null)
);
}
/**
* Tests the getProfile method
*
* @param string $id Member id of the profile you want.
* @param string $url The public profile URL.
*
* @return void
*
* @dataProvider seedIdUrl
* @since 13.1
*/
public function testGetProfile($id, $url)
{
$fields = '(id,first-name,last-name)';
$language = 'en-US';
// Set request parameters.
$data['format'] = 'json';
$path = '/v1/people/';
if ($url)
{
$path .= 'url=' . $this->oauth->safeEncode($url) . ':public';
$type = 'public';
}
else
{
$type = 'standard';
}
if ($id)
{
$path .= 'id=' . $id;
}
elseif (!$url)
{
$path .= '~';
}
$path .= ':' . $fields;
$header = array('Accept-Language' => $language);
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->sampleString;
$path = $this->oauth->toUrl($path, $data);
$this->client->expects($this->once())
->method('get', $header)
->with($path)
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->getProfile($id, $url, $fields, $type, $language),
$this->equalTo(json_decode($this->sampleString))
);
}
/**
* Tests the getProfile method - failure
*
* @param string $id Member id of the profile you want.
* @param string $url The public profile URL.
*
* @return void
*
* @dataProvider seedIdUrl
* @since 13.1
* @expectedException DomainException
*/
public function testGetProfileFailure($id, $url)
{
$fields = '(id,first-name,last-name)';
$language = 'en-US';
// Set request parameters.
$data['format'] = 'json';
$path = '/v1/people/';
if ($url)
{
$path .= 'url=' . $this->oauth->safeEncode($url) . ':public';
$type = 'public';
}
else
{
$type = 'standard';
}
if ($id)
{
$path .= 'id=' . $id;
}
elseif (!$url)
{
$path .= '~';
}
$path .= ':' . $fields;
$header = array('Accept-Language' => $language);
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$path = $this->oauth->toUrl($path, $data);
$this->client->expects($this->once())
->method('get', $header)
->with($path)
->will($this->returnValue($returnData));
$this->object->getProfile($id, $url, $fields, $type, $language);
}
/**
* Tests the getConnections method
*
* @return void
*
* @since 13.1
*/
public function testGetConnections()
{
$fields = '(id,first-name,last-name)';
$start = 1;
$count = 50;
$modified = 'new';
$modified_since = '1267401600000';
// Set request parameters.
$data['format'] = 'json';
$data['start'] = $start;
$data['count'] = $count;
$data['modified'] = $modified;
$data['modified-since'] = $modified_since;
$path = '/v1/people/~/connections';
$path .= ':' . $fields;
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->sampleString;
$path = $this->oauth->toUrl($path, $data);
$this->client->expects($this->once())
->method('get')
->with($path)
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->getConnections($fields, $start, $count, $modified, $modified_since),
$this->equalTo(json_decode($this->sampleString))
);
}
/**
* Tests the getConnections method - failure
*
* @return void
*
* @since 13.1
* @expectedException DomainException
*/
public function testGetConnectionsFailure()
{
$fields = '(id,first-name,last-name)';
$start = 1;
$count = 50;
$modified = 'new';
$modified_since = '1267401600000';
// Set request parameters.
$data['format'] = 'json';
$data['start'] = $start;
$data['count'] = $count;
$data['modified'] = $modified;
$data['modified-since'] = $modified_since;
$path = '/v1/people/~/connections';
$path .= ':' . $fields;
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$path = $this->oauth->toUrl($path, $data);
$this->client->expects($this->once())
->method('get')
->with($path)
->will($this->returnValue($returnData));
$this->object->getConnections($fields, $start, $count, $modified, $modified_since);
}
/**
* Provides test data for request format detection.
*
* @return array
*
* @since 13.1
*/
public function seedFields()
{
// Fields
return array(
array('(people:(id,first-name,last-name,api-standard-profile-request))'),
array('(people:(id,first-name,last-name))')
);
}
/**
* Tests the search method
*
* @param string $fields Request fields beyond the default ones. provide 'api-standard-profile-request' field for out of network profiles.
*
* @return void
*
* @dataProvider seedFields
* @since 13.1
*/
public function testSearch($fields)
{
$keywords = 'Princess';
$first_name = 'Clair';
$last_name = 'Standish';
$company_name = 'Smth';
$current_company = true;
$title = 'developer';
$current_title = true;
$school_name = 'Shermer High School';
$current_school = true;
$country_code = 'us';
$postal_code = 12345;
$distance = 500;
$facets = 'location,industry,network,language,current-company,past-company,school';
$facet = array('us-84', 47, 'F', 'en', 1006, 1028, 2345);
$start = 1;
$count = 50;
$sort = 'distance';
// Set request parameters.
$data['format'] = 'json';
$data['keywords'] = $keywords;
$data['first-name'] = $first_name;
$data['last-name'] = $last_name;
$data['company-name'] = $company_name;
$data['current-company'] = $current_company;
$data['title'] = $title;
$data['current-title'] = $current_title;
$data['school-name'] = $school_name;
$data['current-school'] = $current_school;
$data['country-code'] = $country_code;
$data['postal-code'] = $postal_code;
$data['distance'] = $distance;
$data['facets'] = $facets;
$data['facet'] = array();
$data['facet'][] = 'location,' . $facet[0];
$data['facet'][] = 'industry,' . $facet[1];
$data['facet'][] = 'network,' . $facet[2];
$data['facet'][] = 'language,' . $facet[3];
$data['facet'][] = 'current-company,' . $facet[4];
$data['facet'][] = 'past-company,' . $facet[5];
$data['facet'][] = 'school,' . $facet[6];
$data['start'] = $start;
$data['count'] = $count;
$data['sort'] = $sort;
$path = '/v1/people-search';
$path .= ':' . $fields;
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->sampleString;
$path = $this->oauth->toUrl($path, $data);
if (strpos($fields, 'api-standard-profile-request') === false)
{
$this->client->expects($this->once())
->method('get')
->with($path)
->will($this->returnValue($returnData));
}
else
{
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->outString;
$this->client->expects($this->at(0))
->method('get')
->with($path)
->will($this->returnValue($returnData));
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->sampleString;
$path = '/v1/people/oAFz-3CZyv';
$path = $this->oauth->toUrl($path, $data);
$name = 'x-li-auth-token';
$value = 'NAME_SEARCH:-Ogn';
$header[$name] = $value;
$this->client->expects($this->at(1))
->method('get', $header)
->with($path)
->will($this->returnValue($returnData));
}
$this->assertThat(
$this->object->search(
$fields, $keywords, $first_name, $last_name, $company_name,
$current_company, $title, $current_title, $school_name, $current_school, $country_code,
$postal_code, $distance, $facets, $facet, $start, $count, $sort
),
$this->equalTo(json_decode($this->sampleString))
);
}
/**
* Tests the search method - failure
*
* @return void
*
* @since 13.1
* @expectedException DomainException
*/
public function testSearchFailure()
{
$fields = '(id,first-name,last-name)';
$keywords = 'Princess';
$first_name = 'Clair';
$last_name = 'Standish';
$company_name = 'Smth';
$current_company = true;
$title = 'developer';
$current_title = true;
$school_name = 'Shermer High School';
$current_school = true;
$country_code = 'us';
$postal_code = 12345;
$distance = 500;
$facets = 'location,industry,network,language,current-company,past-company,school';
$facet = array('us-84', 47, 'F', 'en', 1006, 1028, 2345);
$start = 1;
$count = 50;
$sort = 'distance';
// Set request parameters.
$data['format'] = 'json';
$data['keywords'] = $keywords;
$data['first-name'] = $first_name;
$data['last-name'] = $last_name;
$data['company-name'] = $company_name;
$data['current-company'] = $current_company;
$data['title'] = $title;
$data['current-title'] = $current_title;
$data['school-name'] = $school_name;
$data['current-school'] = $current_school;
$data['country-code'] = $country_code;
$data['postal-code'] = $postal_code;
$data['distance'] = $distance;
$data['facets'] = $facets;
$data['facet'] = array();
$data['facet'][] = 'location,' . $facet[0];
$data['facet'][] = 'industry,' . $facet[1];
$data['facet'][] = 'network,' . $facet[2];
$data['facet'][] = 'language,' . $facet[3];
$data['facet'][] = 'current-company,' . $facet[4];
$data['facet'][] = 'past-company,' . $facet[5];
$data['facet'][] = 'school,' . $facet[6];
$data['start'] = $start;
$data['count'] = $count;
$data['sort'] = $sort;
$path = '/v1/people-search';
$path .= ':' . $fields;
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$path = $this->oauth->toUrl($path, $data);
$this->client->expects($this->once())
->method('get')
->with($path)
->will($this->returnValue($returnData));
$this->object->search(
$fields, $keywords, $first_name, $last_name, $company_name,
$current_company, $title, $current_title, $school_name, $current_school, $country_code,
$postal_code, $distance, $facets, $facet, $start, $count, $sort
);
}
}
| Nilaksha/sep_2013 | tests/unit/suites/platform/linkedin/JLinkedinPeopleTest.php | PHP | gpl-2.0 | 13,003 |
/* Copyright (c) 2009 Timothy Wall, All Rights Reserved
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* <p/>
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package com.sun.jna;
import junit.framework.*;
import com.sun.jna.*;
import com.sun.jna.ptr.PointerByReference;
import java.lang.ref.*;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import com.sun.jna.DirectTest.TestInterface;
import com.sun.jna.DirectTest.TestLibrary;
//@SuppressWarnings("unused")
public class PerformanceTest extends TestCase {
public void testEmpty() { }
private static final String BUILDDIR =
System.getProperty("jna.builddir",
"build" + (Platform.is64Bit() ? "-d64" : ""));
private static class JNI {
static {
String path = BUILDDIR + "/native/" + System.mapLibraryName("testlib");;
if (!new File(path).isAbsolute()) {
path = System.getProperty("user.dir") + "/" + path;
}
if (path.endsWith(".jnilib")) {
path = path.replace(".jnilib", ".dylib");
}
System.load(path);
}
private static native double cos(double x);
}
public static void main(java.lang.String[] argList) {
checkPerformance();
}
static class MathLibrary {
public static native double cos(double x);
static {
Native.register(Platform.MATH_LIBRARY_NAME);
}
}
interface MathInterface extends Library {
double cos(double x);
}
static class CLibrary {
public static class size_t extends IntegerType {
public size_t() {
super(Native.POINTER_SIZE);
}
public size_t(long value) {
super(Native.POINTER_SIZE, value);
}
}
public static native Pointer memset(Pointer p, int v, size_t len);
public static native Pointer memset(Pointer p, int v, int len);
public static native Pointer memset(Pointer p, int v, long len);
public static native long memset(long p, int v, long len);
public static native int memset(int p, int v, int len);
public static native int strlen(String s1);
public static native int strlen(Pointer p);
public static native int strlen(byte[] b);
public static native int strlen(Buffer b);
static {
Native.register(Platform.C_LIBRARY_NAME);
}
}
static interface CInterface extends Library {
Pointer memset(Pointer p, int v, int len);
int strlen(String s);
}
// Requires java.library.path include testlib
public static void checkPerformance() {
if (!Platform.HAS_BUFFERS) return;
final int COUNT = 100000;
System.out.println("Checking performance of different access methods (" + COUNT + " iterations)");
final int SIZE = 8*1024;
ByteBuffer b = ByteBuffer.allocateDirect(SIZE);
// Native order is faster
b.order(ByteOrder.nativeOrder());
Pointer pb = Native.getDirectBufferPointer(b);
String mname = Platform.MATH_LIBRARY_NAME;
MathInterface mlib = (MathInterface)
Native.loadLibrary(mname, MathInterface.class);
Function f = NativeLibrary.getInstance(mname).getFunction("cos");
///////////////////////////////////////////
// cos
Object[] args = { new Double(0) };
double dresult;
long start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
dresult = mlib.cos(0d);
}
long delta = System.currentTimeMillis() - start;
System.out.println("cos (JNA interface): " + delta + "ms");
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
dresult = f.invokeDouble(args);
}
delta = System.currentTimeMillis() - start;
System.out.println("cos (JNA function): " + delta + "ms");
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
dresult = MathLibrary.cos(0d);
}
delta = System.currentTimeMillis() - start;
System.out.println("cos (JNA direct): " + delta + "ms");
long types = pb.peer;
long cif;
long resp;
long argv;
if (Native.POINTER_SIZE == 4) {
b.putInt(0, (int)Structure.FFIType.get(double.class).peer);
cif = Native.ffi_prep_cif(0, 1, Structure.FFIType.get(double.class).peer, types);
resp = pb.peer + 4;
argv = pb.peer + 12;
double INPUT = 42;
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
b.putInt(12, (int)pb.peer + 16);
b.putDouble(16, INPUT);
Native.ffi_call(cif, f.peer, resp, argv);
dresult = b.getDouble(4);
}
delta = System.currentTimeMillis() - start;
}
else {
b.putLong(0, Structure.FFIType.get(double.class).peer);
cif = Native.ffi_prep_cif(0, 1, Structure.FFIType.get(double.class).peer, types);
resp = pb.peer + 8;
argv = pb.peer + 16;
double INPUT = 42;
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
b.putLong(16, pb.peer + 24);
b.putDouble(24, INPUT);
Native.ffi_call(cif, f.peer, resp, argv);
dresult = b.getDouble(8);
}
delta = System.currentTimeMillis() - start;
}
System.out.println("cos (JNI ffi): " + delta + "ms");
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
dresult = JNI.cos(0d);
}
delta = System.currentTimeMillis() - start;
System.out.println("cos (JNI): " + delta + "ms");
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
dresult = Math.cos(0d);
}
delta = System.currentTimeMillis() - start;
System.out.println("cos (pure java): " + delta + "ms");
///////////////////////////////////////////
// memset
Pointer presult;
String cname = Platform.C_LIBRARY_NAME;
CInterface clib = (CInterface)
Native.loadLibrary(cname, CInterface.class);
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
presult = clib.memset(null, 0, 0);
}
delta = System.currentTimeMillis() - start;
System.out.println("memset (JNA interface): " + delta + "ms");
f = NativeLibrary.getInstance(cname).getFunction("memset");
args = new Object[] { null, new Integer(0), new Integer(0)};
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
presult = f.invokePointer(args);
}
delta = System.currentTimeMillis() - start;
System.out.println("memset (JNA function): " + delta + "ms");
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
presult = CLibrary.memset((Pointer)null, 0, new CLibrary.size_t(0));
}
delta = System.currentTimeMillis() - start;
System.out.println("memset (JNA direct Pointer/size_t): " + delta + "ms");
start = System.currentTimeMillis();
if (Native.POINTER_SIZE == 4) {
for (int i=0;i < COUNT;i++) {
presult = CLibrary.memset((Pointer)null, 0, 0);
}
}
else {
for (int i=0;i < COUNT;i++) {
presult = CLibrary.memset((Pointer)null, 0, 0L);
}
}
delta = System.currentTimeMillis() - start;
System.out.println("memset (JNA direct Pointer/primitive): " + delta + "ms");
int iresult;
long jresult;
start = System.currentTimeMillis();
if (Native.POINTER_SIZE == 4) {
for (int i=0;i < COUNT;i++) {
iresult = CLibrary.memset(0, 0, 0);
}
}
else {
for (int i=0;i < COUNT;i++) {
jresult = CLibrary.memset(0L, 0, 0L);
}
}
delta = System.currentTimeMillis() - start;
System.out.println("memset (JNA direct primitives): " + delta + "ms");
if (Native.POINTER_SIZE == 4) {
b.putInt(0, (int)Structure.FFIType.get(Pointer.class).peer);
b.putInt(4, (int)Structure.FFIType.get(int.class).peer);
b.putInt(8, (int)Structure.FFIType.get(int.class).peer);
cif = Native.ffi_prep_cif(0, 3, Structure.FFIType.get(Pointer.class).peer, types);
resp = pb.peer + 12;
argv = pb.peer + 16;
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
b.putInt(16, (int)pb.peer + 28);
b.putInt(20, (int)pb.peer + 32);
b.putInt(24, (int)pb.peer + 36);
b.putInt(28, 0);
b.putInt(32, 0);
b.putInt(36, 0);
Native.ffi_call(cif, f.peer, resp, argv);
b.getInt(12);
}
delta = System.currentTimeMillis() - start;
}
else {
b.putLong(0, Structure.FFIType.get(Pointer.class).peer);
b.putLong(8, Structure.FFIType.get(int.class).peer);
b.putLong(16, Structure.FFIType.get(long.class).peer);
cif = Native.ffi_prep_cif(0, 3, Structure.FFIType.get(Pointer.class).peer, types);
resp = pb.peer + 24;
argv = pb.peer + 32;
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
b.putLong(32, pb.peer + 56);
b.putLong(40, pb.peer + 64);
b.putLong(48, pb.peer + 72);
b.putLong(56, 0);
b.putInt(64, 0);
b.putLong(72, 0);
Native.ffi_call(cif, f.peer, resp, argv);
b.getLong(24);
}
delta = System.currentTimeMillis() - start;
}
System.out.println("memset (JNI ffi): " + delta + "ms");
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
Native.setMemory(0L, 0L, (byte)0);
}
delta = System.currentTimeMillis() - start;
System.out.println("memset (JNI): " + delta + "ms");
///////////////////////////////////////////
// strlen
String str = "performance test";
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
iresult = clib.strlen(str);
}
delta = System.currentTimeMillis() - start;
System.out.println("strlen (JNA interface): " + delta + "ms");
f = NativeLibrary.getInstance(cname).getFunction("strlen");
args = new Object[] { str };
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
iresult = f.invokeInt(args);
}
delta = System.currentTimeMillis() - start;
System.out.println("strlen (JNA function): " + delta + "ms");
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
iresult = CLibrary.strlen(str);
}
delta = System.currentTimeMillis() - start;
System.out.println("strlen (JNA direct - String): " + delta + "ms");
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
iresult = CLibrary.strlen(new NativeString(str).getPointer());
}
delta = System.currentTimeMillis() - start;
System.out.println("strlen (JNA direct - Pointer): " + delta + "ms");
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
iresult = CLibrary.strlen(Native.toByteArray(str));
}
delta = System.currentTimeMillis() - start;
System.out.println("strlen (JNA direct - byte[]): " + delta + "ms");
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
byte[] bytes = str.getBytes();
b.position(0);
b.put(bytes);
b.put((byte)0);
iresult = CLibrary.strlen(b);
}
delta = System.currentTimeMillis() - start;
System.out.println("strlen (JNA direct - Buffer): " + delta + "ms");
if (Native.POINTER_SIZE == 4) {
b.putInt(0, (int)Structure.FFIType.get(Pointer.class).peer);
cif = Native.ffi_prep_cif(0, 1, Structure.FFIType.get(int.class).peer, types);
resp = pb.peer + 4;
argv = pb.peer + 8;
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
b.putInt(8, (int)pb.peer + 12);
b.putInt(12, (int)pb.peer + 16);
b.position(16);
// This operation is very expensive!
b.put(str.getBytes());
b.put((byte)0);
Native.ffi_call(cif, f.peer, resp, argv);
iresult = b.getInt(4);
}
delta = System.currentTimeMillis() - start;
}
else {
b.putLong(0, Structure.FFIType.get(Pointer.class).peer);
cif = Native.ffi_prep_cif(0, 1, Structure.FFIType.get(long.class).peer, types);
resp = pb.peer + 8;
argv = pb.peer + 16;
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
b.putLong(16, pb.peer + 24);
b.putLong(24, pb.peer + 32);
b.position(32);
// This operation is very expensive!
b.put(str.getBytes());
b.put((byte)0);
Native.ffi_call(cif, f.peer, resp, argv);
jresult = b.getLong(8);
}
delta = System.currentTimeMillis() - start;
}
System.out.println("strlen (JNI ffi): " + delta + "ms");
///////////////////////////////////////////
// Direct buffer vs. Pointer methods
byte[] bulk = new byte[SIZE];
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
b.putInt(0, 0);
}
delta = System.currentTimeMillis() - start;
System.out.println("direct Buffer write: " + delta + "ms");
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
b.position(0);
b.put(bulk);
}
delta = System.currentTimeMillis() - start;
System.out.println("direct Buffer write (bulk): " + delta + "ms");
Pointer p = new Memory(SIZE);
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
p.setInt(0, 0);
}
delta = System.currentTimeMillis() - start;
System.out.println("Memory write: " + delta + "ms");
start = System.currentTimeMillis();
for (int i=0;i < COUNT;i++) {
p.write(0, bulk, 0, bulk.length);
}
delta = System.currentTimeMillis() - start;
System.out.println("Memory write (bulk): " + delta + "ms");
///////////////////////////////////////////
// Callbacks
TestInterface tlib = (TestInterface)Native.loadLibrary("testlib", TestInterface.class);
start = System.currentTimeMillis();
TestInterface.Int32Callback cb = new TestInterface.Int32Callback() {
public int invoke(int arg1, int arg2) {
return arg1 + arg2;
}
};
tlib.callInt32CallbackRepeatedly(cb, 1, 2, COUNT);
delta = System.currentTimeMillis() - start;
System.out.println("callback (JNA interface): " + delta + "ms");
tlib = new TestLibrary();
start = System.currentTimeMillis();
tlib.callInt32CallbackRepeatedly(cb, 1, 2, COUNT);
delta = System.currentTimeMillis() - start;
System.out.println("callback (JNA direct): " + delta + "ms");
start = System.currentTimeMillis();
TestInterface.NativeLongCallback nlcb = new TestInterface.NativeLongCallback() {
public NativeLong invoke(NativeLong arg1, NativeLong arg2) {
return new NativeLong(arg1.longValue() + arg2.longValue());
}
};
tlib.callLongCallbackRepeatedly(nlcb, new NativeLong(1), new NativeLong(2), COUNT);
delta = System.currentTimeMillis() - start;
System.out.println("callback w/NativeMapped (JNA interface): " + delta + "ms");
tlib = new TestLibrary();
start = System.currentTimeMillis();
tlib.callLongCallbackRepeatedly(nlcb, new NativeLong(1), new NativeLong(2), COUNT);
delta = System.currentTimeMillis() - start;
System.out.println("callback w/NativeMapped (JNA direct): " + delta + "ms");
}
}
| rozdoum/jna | test/com/sun/jna/PerformanceTest.java | Java | lgpl-2.1 | 17,543 |
/*
* 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.spi.loadbalancing.adaptive;
import org.apache.ignite.spi.GridSpiStartStopAbstractTest;
import org.apache.ignite.testframework.junits.spi.GridSpiTest;
/**
* Adaptive load balancing SPI start-stop test.
*/
@SuppressWarnings({"JUnitTestCaseWithNoTests"})
@GridSpiTest(spi = AdaptiveLoadBalancingSpi.class, group = "LoadBalancing SPI")
public class GridAdaptiveLoadBalancingSpiStartStopSelfTest extends
GridSpiStartStopAbstractTest<AdaptiveLoadBalancingSpi> {
// No configs.
} | irudyak/ignite | modules/core/src/test/java/org/apache/ignite/spi/loadbalancing/adaptive/GridAdaptiveLoadBalancingSpiStartStopSelfTest.java | Java | apache-2.0 | 1,314 |